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 material map export
Matt Kissinger9f62e8bd7b5a
diff --git a/dist/agent-run.mjs b/dist/agent-run.mjsindex 06122727..d927cb76 100644--- a/dist/agent-run.mjs+++ b/dist/agent-run.mjs@@ -11857,9 +11857,36 @@ var init_procedural_material_v3 = __esm(() => {};});+// src/cli-output.ts+var init_cli_output = () => {};++// src/material-map-export-node.ts+import sharp from "sharp";+import * as THREE6 from "three";+var MATERIAL_MAP_EXPORT_LIMITS, PREVIEW_CAMERA, SRGB_TO_LINEAR;+var init_material_map_export_node = __esm(() => {+ init_cli_output();+ init_material_library();+ init_procedural_texture();+ init_textures();+ MATERIAL_MAP_EXPORT_LIMITS = Object.freeze({+ minSize: 4,+ maxSize: MATERIAL_LIBRARY_LIMITS.maxMapEdge,+ maxRepeatMeters: 1e5,+ defaultTiles: 3,+ maxTiles: 8,+ maxPreviewMapSize: 1024+ });+ PREVIEW_CAMERA = Object.freeze({ azimuthDeg: 30, elevationDeg: 50 });+ SRGB_TO_LINEAR = Float64Array.from({ length: 256 }, (_, value) => {+ const c = value / 255;+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;+ });+});+// src/material-library-node.tsimport { createHash as createHash6, randomUUID } from "node:crypto";-import sharp from "sharp";+import sharp2 from "sharp";import { DataTexture as DataTexture3 } from "three";function revisionHash(manifest) {const { revisionId: _, ...content } = manifest;@@ -11939,7 +11966,7 @@ async function createMaterialRecordV1(draft) {const compiled = materialPixels(input.procedural, input.derive);if (compiled.spec.usage !== MATERIAL_LIBRARY_USAGE[input.slot])throw new Error("Procedural map usage mismatch");- bytes = new Uint8Array(await sharp(compiled.pixels, {+ bytes = new Uint8Array(await sharp2(compiled.pixels, {raw: { width: compiled.spec.size, height: compiled.spec.size, channels: 4 }}).png({ compressionLevel: 9, adaptiveFiltering: false }).toBuffer());procedural = {@@ -12010,7 +12037,7 @@ async function verifyMaterialRecordV1(record) {const bytes = record.files[map.file];if (digest2(bytes) !== map.sha256)throw new Error(`Material integrity hash mismatch: ${map.file}`);- const { data, info } = await sharp(bytes, {+ const { data, info } = await sharp2(bytes, {limitInputPixels: MATERIAL_LIBRARY_LIMITS.maxRecordPixels,failOn: "warning"}).ensureAlpha().raw().toBuffer({ resolveWithObject: true });@@ -12311,7 +12338,7 @@ function createPinnedMaterialMapPort(records) {const descriptor = describe(resourceId, pin), entry = find(resourceId, pin);if (!descriptor || !entry)throw new Error("Missing verified pinned-library map; approved resources cannot be atlas sources");- const { data, info } = await sharp(entry.record.files[entry.map.file], {+ const { data, info } = await sharp2(entry.record.files[entry.map.file], {limitInputPixels: MATERIAL_LIBRARY_LIMITS.maxRecordPixels,failOn: "warning"}).ensureAlpha().raw().toBuffer({ resolveWithObject: true });@@ -12338,7 +12365,7 @@ async function verifyMaterialRecordContents(record, options) {const bytes = record.files[map.file];if (digest2(bytes) !== map.sha256)throw new Error("Material integrity hash mismatch");- const { data, info } = await sharp(bytes, {+ const { data, info } = await sharp2(bytes, {limitInputPixels: MATERIAL_LIBRARY_LIMITS.maxRecordPixels,failOn: "warning"}).ensureAlpha().raw().toBuffer({ resolveWithObject: true });@@ -12594,7 +12621,7 @@ async function createMaterialRecordV2(draft, options) {const compiled = spec.schemaVersion === 3 ? materialPixelsV3(spec, derive) : materialPixels(spec, derive);const d = compiled.spec.schemaVersion === 3 ? { width: compiled.spec.width, height: compiled.spec.height } : { width: compiled.spec.size, height: compiled.spec.size };pixelHash = digest2(compiled.pixels);- bytes = new Uint8Array(await sharp(compiled.pixels, { raw: { ...d, channels: 4 } }).png({ compressionLevel: 9, adaptiveFiltering: false }).toBuffer());+ bytes = new Uint8Array(await sharp2(compiled.pixels, { raw: { ...d, channels: 4 } }).png({ compressionLevel: 9, adaptiveFiltering: false }).toBuffer());recipe = {kind: "procedural",compilerId: compiled.spec.schemaVersion === 3 ? PROCEDURAL_TEXTURE_V3_COMPILER_ID : "kiln.procedural-texture.v2",@@ -12609,7 +12636,7 @@ async function createMaterialRecordV2(draft, options) {} else if (item.atlas !== undefined) {const compiled = await compileTextureAtlasSpecV1(item.atlas, { resources });pixelHash = compiled.manifest.decodedPixelHash;- bytes = new Uint8Array(await sharp(compiled.pixels, {+ bytes = new Uint8Array(await sharp2(compiled.pixels, {raw: { width: compiled.spec.width, height: compiled.spec.height, channels: 4 }}).png({ compressionLevel: 9, adaptiveFiltering: false }).toBuffer());recipe = {@@ -12624,7 +12651,7 @@ async function createMaterialRecordV2(draft, options) {pins.set(`${r.source.pin.resourceId}/${r.source.pin.revisionId}`, r.source.pin);} else {bytes = item.bytes.slice();- const decoded = await sharp(bytes, {+ const decoded = await sharp2(bytes, {limitInputPixels: MATERIAL_LIBRARY_LIMITS.maxRecordPixels,failOn: "warning"}).ensureAlpha().raw().toBuffer();@@ -12684,7 +12711,8 @@ var init_material_library_node = __esm(() => {init_textures();init_texture_resolver();init_procedural_material_v3();- encoder = { name: "sharp", version: sharp.versions.sharp };+ init_material_map_export_node();+ encoder = { name: "sharp", version: sharp2.versions.sharp };});// src/rebuild-options.ts@@ -12756,7 +12784,7 @@ function declaredSupports(mesh, supports) {var EXTERNAL_SUPPORT_TOLERANCE = 0.02;// src/qa/breadth-evidence.ts-import * as THREE6 from "three";+import * as THREE7 from "three";function record7(value) {return typeof value === "object" && value !== null && !Array.isArray(value);}@@ -12775,7 +12803,7 @@ function isAnimationClip(value) {function localRenderableBox(rootInverse, node) {if (isSpriteNode(node)) {const transform = rootInverse.clone().multiply(node.matrixWorld);- return new THREE6.Box3(new THREE6.Vector3(-0.5, -0.5, -0.0005), new THREE6.Vector3(0.5, 0.5, 0.0005)).applyMatrix4(transform);+ return new THREE7.Box3(new THREE7.Vector3(-0.5, -0.5, -0.0005), new THREE7.Vector3(0.5, 0.5, 0.0005)).applyMatrix4(transform);}if (!isMeshNode(node) || !node.geometry?.isBufferGeometry)return;@@ -12784,11 +12812,11 @@ function localRenderableBox(rootInverse, node) {if (!source || source.isEmpty())return;const transform = rootInverse.clone().multiply(node.matrixWorld);- const result = new THREE6.Box3;+ const result = new THREE7.Box3;for (const x of [source.min.x, source.max.x]) {for (const y of [source.min.y, source.max.y]) {for (const z of [source.min.z, source.max.z]) {- result.expandByPoint(new THREE6.Vector3(x, y, z).applyMatrix4(transform));+ result.expandByPoint(new THREE7.Vector3(x, y, z).applyMatrix4(transform));}}}@@ -12876,10 +12904,10 @@ function isEffectSurface(nodes) {function coverageRatio(boxes, overall) {if (boxes.length === 0 || overall.isEmpty())return 0;- const overallSize = overall.getSize(new THREE6.Vector3);+ const overallSize = overall.getSize(new THREE7.Vector3);const denominator = Math.max(0.000000001, overallSize.x * overallSize.y, overallSize.z * overallSize.y, overallSize.x * overallSize.z);const area = boxes.reduce((sum, box) => {- const size = box.getSize(new THREE6.Vector3);+ const size = box.getSize(new THREE7.Vector3);return sum + Math.max(size.x * size.y, size.z * size.y, size.x * size.z);}, 0);return stable2(Math.min(1, area / denominator));@@ -12888,7 +12916,7 @@ function collectMaterialEvidence(root, intent) {root.updateWorldMatrix(true, true);const inverse = root.matrixWorld.clone().invert();const byMaterial = new Map;- const overall = new THREE6.Box3;+ const overall = new THREE7.Box3;root.traverseVisible((node) => {const box = localRenderableBox(inverse, node);if (!box || !isMeshNode(node) && !isSpriteNode(node))@@ -12913,7 +12941,7 @@ function collectMaterialEvidence(root, intent) {effectSurface: isEffectSurface(value.nodes),alphaMode: mode,alphaData: alphaData(material),- doubleSided: material.side === THREE6.DoubleSide,+ doubleSided: material.side === THREE7.DoubleSide,...mode === "mask" ? { alphaCutoff: standard.alphaTest ?? 0 } : {},screenAreaRatio: coverageRatio(value.boxes, overall),transparentLayers: mode === "blend" ? value.nodes.length : 0,@@ -12941,23 +12969,23 @@ function dominantGeometryAxis(root, mode) {const bounds = node.geometry.boundingBox;if (!bounds || bounds.isEmpty())return;- const size = bounds.getSize(new THREE6.Vector3);+ const size = bounds.getSize(new THREE7.Vector3);const axes = [- { score: size.x, direction: new THREE6.Vector3(1, 0, 0) },- { score: size.y, direction: new THREE6.Vector3(0, 1, 0) },- { score: size.z, direction: new THREE6.Vector3(0, 0, 1) }+ { score: size.x, direction: new THREE7.Vector3(1, 0, 0) },+ { score: size.y, direction: new THREE7.Vector3(0, 1, 0) },+ { score: size.z, direction: new THREE7.Vector3(0, 0, 1) }];const selected = axes.reduce((candidate, value) => mode === "length" ? value.score > candidate.score ? value : candidate : value.score < candidate.score ? value : candidate);const relative = inverse.clone().multiply(node.matrixWorld);const direction = selected.direction.transformDirection(relative);- const score = selected.score * node.getWorldScale(new THREE6.Vector3).length();+ const score = selected.score * node.getWorldScale(new THREE7.Vector3).length();if (!best || (mode === "length" ? score > best.score : score < best.score)) {best = { score, direction };}});if (best)return signedAxis(best.direction);- const overall = new THREE6.Box3;+ const overall = new THREE7.Box3;root.traverseVisible((node) => {const box = localRenderableBox(inverse, node);if (box)@@ -12965,8 +12993,8 @@ function dominantGeometryAxis(root, mode) {});if (overall.isEmpty())return "+X";- const size = overall.getSize(new THREE6.Vector3);- const vector = mode === "length" ? size.x >= size.y && size.x >= size.z ? new THREE6.Vector3(1, 0, 0) : size.y >= size.z ? new THREE6.Vector3(0, 1, 0) : new THREE6.Vector3(0, 0, 1) : size.x <= size.y && size.x <= size.z ? new THREE6.Vector3(1, 0, 0) : size.y <= size.z ? new THREE6.Vector3(0, 1, 0) : new THREE6.Vector3(0, 0, 1);+ const size = overall.getSize(new THREE7.Vector3);+ const vector = mode === "length" ? size.x >= size.y && size.x >= size.z ? new THREE7.Vector3(1, 0, 0) : size.y >= size.z ? new THREE7.Vector3(0, 1, 0) : new THREE7.Vector3(0, 0, 1) : size.x <= size.y && size.x <= size.z ? new THREE7.Vector3(1, 0, 0) : size.y <= size.z ? new THREE7.Vector3(0, 1, 0) : new THREE7.Vector3(0, 0, 1);return signedAxis(vector);}function analyzedFacing(root, intent) {@@ -13000,8 +13028,8 @@ function clipEndpointMatches(clip) {const last = Array.from(track.values.slice(end, end + size));if (![...first, ...last].every(Number.isFinite))return false;- const a = new THREE6.Quaternion().fromArray(first);- const b = new THREE6.Quaternion().fromArray(last);+ const a = new THREE7.Quaternion().fromArray(first);+ const b = new THREE7.Quaternion().fromArray(last);if (a.lengthSq() === 0 || b.lengthSq() === 0)return false;return 1 - Math.abs(a.normalize().dot(b.normalize())) <= 0.000001;@@ -14022,7 +14050,7 @@ var init_gltf_io = __esm(() => {});// src/qa/breadth-final.ts-import * as THREE7 from "three";+import * as THREE8 from "three";function bytesContainAscii(bytes, value) {const needle = new TextEncoder().encode(value);outer:@@ -14081,7 +14109,7 @@ function finalEffectAxis(nodes, mode) {if (!(semantic?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {continue;}- const matrix = new THREE7.Matrix4().fromArray(node.getWorldMatrix());+ const matrix = new THREE8.Matrix4().fromArray(node.getWorldMatrix());const scale = node.getWorldScale();const scaleMagnitude = Math.hypot(scale[0], scale[1], scale[2]);for (const primitive of node.getMesh()?.listPrimitives() ?? []) {@@ -14091,9 +14119,9 @@ function finalEffectAxis(nodes, mode) {const min = position.getMin([]);const max = position.getMax([]);const axes = [- { score: (max[0] ?? 0) - (min[0] ?? 0), direction: new THREE7.Vector3(1, 0, 0) },- { score: (max[1] ?? 0) - (min[1] ?? 0), direction: new THREE7.Vector3(0, 1, 0) },- { score: (max[2] ?? 0) - (min[2] ?? 0), direction: new THREE7.Vector3(0, 0, 1) }+ { score: (max[0] ?? 0) - (min[0] ?? 0), direction: new THREE8.Vector3(1, 0, 0) },+ { score: (max[1] ?? 0) - (min[1] ?? 0), direction: new THREE8.Vector3(0, 1, 0) },+ { score: (max[2] ?? 0) - (min[2] ?? 0), direction: new THREE8.Vector3(0, 0, 1) }];const selected = axes.reduce((candidate, value) => mode === "length" ? value.score > candidate.score ? value : candidate : value.score < candidate.score ? value : candidate);const candidate = {@@ -14717,10 +14745,10 @@ var init_universal = __esm(() => {});// src/gltf-texture-binding.ts-import * as THREE8 from "three";+import * as THREE9 from "three";function restoreGltfTextureBinding(texture, info) {texture.minFilter = MIN[info.getMinFilter() ?? 9729];- texture.magFilter = info.getMagFilter() === 9728 ? THREE8.NearestFilter : THREE8.LinearFilter;+ texture.magFilter = info.getMagFilter() === 9728 ? THREE9.NearestFilter : THREE9.LinearFilter;texture.wrapS = WRAP[info.getWrapS()];texture.wrapT = WRAP[info.getWrapT()];texture.generateMipmaps = [9984, 9985, 9986, 9987].includes(info.getMinFilter() ?? 9729);@@ -14757,22 +14785,22 @@ function gltfTextureBindingKey(info) {var MIN, WRAP;var init_gltf_texture_binding = __esm(() => {MIN = {- 9728: THREE8.NearestFilter,- 9729: THREE8.LinearFilter,- 9984: THREE8.NearestMipmapNearestFilter,- 9985: THREE8.LinearMipmapNearestFilter,- 9986: THREE8.NearestMipmapLinearFilter,- 9987: THREE8.LinearMipmapLinearFilter+ 9728: THREE9.NearestFilter,+ 9729: THREE9.LinearFilter,+ 9984: THREE9.NearestMipmapNearestFilter,+ 9985: THREE9.LinearMipmapNearestFilter,+ 9986: THREE9.NearestMipmapLinearFilter,+ 9987: THREE9.LinearMipmapLinearFilter};WRAP = {- 33071: THREE8.ClampToEdgeWrapping,- 33648: THREE8.MirroredRepeatWrapping,- 10497: THREE8.RepeatWrapping+ 33071: THREE9.ClampToEdgeWrapping,+ 33648: THREE9.MirroredRepeatWrapping,+ 10497: THREE9.RepeatWrapping};});// src/atlas-provenance.ts-import * as THREE9 from "three";+import * as THREE10 from "three";function fail3(message) {throw new TypeError(`atlas provenance: ${message}`);}@@ -14934,7 +14962,7 @@ function collectAtlasProvenance(root) {"aoMap"]) {const texture = mat[slot];- if (!(texture instanceof THREE9.Texture))+ if (!(texture instanceof THREE10.Texture))continue;let ref = textures.get(texture);if (!ref) {@@ -15170,7 +15198,7 @@ var init_atlas_provenance = __esm(() => {});// src/qa/atlas.ts-import * as THREE10 from "three";+import * as THREE11 from "three";function own(value, key) {if (!value || typeof value !== "object")return;@@ -15209,7 +15237,7 @@ function inspectAtlasScene(root) {nodesChecked: 0,truncated: false};- if (!(root instanceof THREE10.Object3D))+ if (!(root instanceof THREE11.Object3D))return result;let encountered = false, metadataBytes = 0, metadataFull = false;const cache = new Map;@@ -15314,7 +15342,7 @@ function inspectAtlasScene(root) {continue;for (const [slot, allowed] of slots) {const texture = material[slot];- if (!(texture instanceof THREE10.Texture))+ if (!(texture instanceof THREE11.Texture))continue;let p = cache.get(texture);if (!cache.has(texture)) {@@ -15415,7 +15443,7 @@ function inspectAtlasScene(root) {throw Error("invalid override version");sampler = canonicalizePortableSamplerV1(own(override, "sampler"));}- const expected = applyPortableSamplerV1(new THREE10.Texture, sampler);+ const expected = applyPortableSamplerV1(new THREE11.Texture, sampler);if (texture.minFilter !== expected.minFilter || texture.magFilter !== expected.magFilter || texture.wrapS !== expected.wrapS || texture.wrapT !== expected.wrapT || texture.generateMipmaps !== expected.generateMipmaps)finding("ATLAS_SAMPLER_MISMATCH", "Actual atlas filtering, wrapping or mip policy differs from its declared sampler.", path, entry);} catch {@@ -15484,7 +15512,7 @@ function inspectAtlasScene(root) {continue;}const texture = entry.texture;- const matrix = texture.matrixAutoUpdate ? new THREE10.Matrix3().setUvTransform(texture.offset.x, texture.offset.y, texture.repeat.x, texture.repeat.y, texture.rotation, texture.center.x, texture.center.y) : texture.matrix.clone();+ const matrix = texture.matrixAutoUpdate ? new THREE11.Matrix3().setUvTransform(texture.offset.x, texture.offset.y, texture.repeat.x, texture.repeat.y, texture.rotation, texture.center.x, texture.center.y) : texture.matrix.clone();if (!matrix.elements.every(Number.isFinite)) {finding("ATLAS_BINDING_TRANSFORM", "Atlas texture transform is nonfinite.", path, entry);continue;@@ -15494,7 +15522,7 @@ function inspectAtlasScene(root) {const minY = (region.content.y + center) / entry.p.manifest.height, maxY = (region.content.y + region.content.height - center) / entry.p.manifest.height;const tolerance = 4 * 2 ** -23;let invalid = false;- const point = new THREE10.Vector2;+ const point = new THREE11.Vector2;for (const range of ranges) {if ((range.materialIndex ?? 0) !== entry.materialIndex)continue;@@ -15590,7 +15618,7 @@ var init_atlas = __esm(() => {});// src/qa/material.ts-import * as THREE11 from "three";+import * as THREE12 from "three";function textureMeta(texture) {return texture.userData["kilnTexture"];}@@ -15638,7 +15666,7 @@ function validateTextureSlot(findings, mesh, material, texture, slot, expected)if (!texture)return;const meta = textureMeta(texture);- const actual = texture.colorSpace === THREE11.SRGBColorSpace ? "srgb" : texture.colorSpace === THREE11.NoColorSpace ? "linear" : meta?.colorSpace ?? "linear";+ const actual = texture.colorSpace === THREE12.SRGBColorSpace ? "srgb" : texture.colorSpace === THREE12.NoColorSpace ? "linear" : meta?.colorSpace ?? "linear";if (!meta || !encodedTextureIsExportable(texture)) {findings.push({code: "MAT_TEXTURE_DECODE_FAILED",@@ -15739,7 +15767,7 @@ function validateMaterial(mesh, material, requiresPrecomputedTangents) {}if (mesh.geometry.userData["kilnGeometryRole"] === "foliageCard") {const validMask = standard.alphaTest > 0 && !standard.transparent;- if (!standard.map || !textureHasAlpha2(standard.map) || !validMask || standard.side !== THREE11.DoubleSide || !mesh.geometry.getAttribute("uv")) {+ if (!standard.map || !textureHasAlpha2(standard.map) || !validMask || standard.side !== THREE12.DoubleSide || !mesh.geometry.getAttribute("uv")) {findings.push({code: "MAT_FOLIAGE_CARD_CONTRACT",disposition: "block",@@ -15792,7 +15820,7 @@ var init_material = __esm(() => {});// src/qa/prop.ts-import * as THREE12 from "three";+import * as THREE13 from "three";function finding2(context, value) {return {...value,@@ -15814,11 +15842,11 @@ function nodePath2(root, node) {return names.reverse().join("/");}function transformedBox(source, transform) {- const result = new THREE12.Box3;+ const result = new THREE13.Box3;for (const x of [source.min.x, source.max.x]) {for (const y of [source.min.y, source.max.y]) {for (const z of [source.min.z, source.max.z]) {- result.expandByPoint(new THREE12.Vector3(x, y, z).applyMatrix4(transform));+ result.expandByPoint(new THREE13.Vector3(x, y, z).applyMatrix4(transform));}}}@@ -15830,9 +15858,9 @@ function collectParts(root, measureVertices = false) {const result = [];root.traverseVisible((node) => {const roles = rolesOf(node);- const renderable = node instanceof THREE12.Mesh;+ const renderable = node instanceof THREE13.Mesh;let box;- if (renderable && node.geometry instanceof THREE12.BufferGeometry) {+ if (renderable && node.geometry instanceof THREE13.BufferGeometry) {const position = node.geometry.getAttribute("position");node.geometry.computeBoundingBox();if (node.geometry.boundingBox) {@@ -15840,17 +15868,17 @@ function collectParts(root, measureVertices = false) {const measure = (matrix) => {if (!measureVertices || !position)return transformedBox(node.geometry.boundingBox, matrix);- const result = new THREE12.Box3;- const point = new THREE12.Vector3;+ const result = new THREE13.Box3;+ const point = new THREE13.Vector3;for (let i = 0;i < position.count; i++) {point.fromBufferAttribute(position, i).applyMatrix4(matrix);result.expandByPoint(point);}return result;};- if (node instanceof THREE12.InstancedMesh) {- box = new THREE12.Box3;- const instance = new THREE12.Matrix4;+ if (node instanceof THREE13.InstancedMesh) {+ box = new THREE13.Box3;+ const instance = new THREE13.Matrix4;for (let i = 0;i < node.count; i++) {node.getMatrixAt(i, instance);box.union(measure(transform.clone().multiply(instance)));@@ -15860,7 +15888,7 @@ function collectParts(root, measureVertices = false) {}}} else if (roles.length > 0) {- box = transformedBox(new THREE12.Box3(new THREE12.Vector3(-0.5, -0.5, -0.5), new THREE12.Vector3(0.5, 0.5, 0.5)), rootInverse.clone().multiply(node.matrixWorld));+ box = transformedBox(new THREE13.Box3(new THREE13.Vector3(-0.5, -0.5, -0.5), new THREE13.Vector3(0.5, 0.5, 0.5)), rootInverse.clone().multiply(node.matrixWorld));}if (box?.isEmpty())box = undefined;@@ -15944,14 +15972,14 @@ function legacyArticulationEvidence(context, root) {});if (joints.length === 0)return false;- const clips = (context.clips ?? []).filter((clip) => clip instanceof THREE12.AnimationClip);+ const clips = (context.clips ?? []).filter((clip) => clip instanceof THREE13.AnimationClip);if ((context.intent.animation?.clips.length ?? 0) === 0 && clips.length === 0)return true;const targets = new Set(clips.flatMap((clip) => clip.tracks.map((track) => track.name.split(".")[0] ?? "")));return joints.some((joint) => targets.has(joint));}function evaluatePropArticulationQa(context) {- if (context.intent.category !== "prop" || !context.intent.capabilities.includes("articulated") || !(context.scene instanceof THREE12.Object3D)) {+ if (context.intent.category !== "prop" || !context.intent.capabilities.includes("articulated") || !(context.scene instanceof THREE13.Object3D)) {return [];}if (usesExplicitLegacyProfile(context) && motionAssemblies(collectParts(context.scene)).length === 0 && legacyArticulationEvidence(context, context.scene))@@ -15963,7 +15991,7 @@ function evaluatePropArticulationQa(context) {});}function inspectArticulation(input) {- if (!(input.scene instanceof THREE12.Object3D))+ if (!(input.scene instanceof THREE13.Object3D))return [];const root = input.scene;const context = { profile: input.profile ?? "asset.requirements.v1" };@@ -16077,11 +16105,11 @@ function rolePart(parts, expression) {return parts.find((part) => part.roles.some((role) => expression.test(role)));}function interiorUsable(box, minimumExtent) {- const size = box.getSize(new THREE12.Vector3);+ const size = box.getSize(new THREE13.Vector3);return [size.x, size.y, size.z].every((value) => value > 0 && value >= minimumExtent);}function evaluatePropContainerQa(context) {- if (context.intent.category !== "prop" || !(context.scene instanceof THREE12.Object3D))+ if (context.intent.category !== "prop" || !(context.scene instanceof THREE13.Object3D))return [];const explicitlyOpen = context.intent.capabilities.includes("openable");const explicitContainment = /^(?:open-)?(?:container|chest|case|box)$/i.test(context.intent.subtype ?? "");@@ -16103,7 +16131,7 @@ function evaluatePropContainerQa(context) {});}function inspectContainerOpening(input) {- if (!(input.scene instanceof THREE12.Object3D))+ if (!(input.scene instanceof THREE13.Object3D))return [];const root = input.scene;const context = { profile: input.profile ?? "asset.requirements.v1" };@@ -16145,7 +16173,7 @@ function inspectContainerOpening(input) {repairText: "Add a non-rendered scaled prop.container.interior.main marker inside the shell."}));} else if (!interiorUsable(interior.box, minimumExtent)) {- const size = interior.box.getSize(new THREE12.Vector3);+ const size = interior.box.getSize(new THREE13.Vector3);findings.push(finding2(context, {code: "PROP_CONTAINER_INTERIOR_UNUSABLE",disposition: "block",@@ -16203,21 +16231,21 @@ function inspectContainerOpening(input) {return findings;}function horizontalDirection(part, root) {- if (!(part.node instanceof THREE12.Mesh) || !(part.node.geometry instanceof THREE12.BufferGeometry)) {+ if (!(part.node instanceof THREE13.Mesh) || !(part.node.geometry instanceof THREE13.BufferGeometry)) {return;}part.node.geometry.computeBoundingBox();const box = part.node.geometry.boundingBox;if (!box)return;- const size = box.getSize(new THREE12.Vector3);- const axis = size.x >= size.z ? new THREE12.Vector3(1, 0, 0) : new THREE12.Vector3(0, 0, 1);+ const size = box.getSize(new THREE13.Vector3);+ const axis = size.x >= size.z ? new THREE13.Vector3(1, 0, 0) : new THREE13.Vector3(0, 0, 1);root.updateWorldMatrix(true, true);- const rootQuaternion = root.getWorldQuaternion(new THREE12.Quaternion).invert();- return axis.applyQuaternion(part.node.getWorldQuaternion(new THREE12.Quaternion)).applyQuaternion(rootQuaternion).setY(0).normalize();+ const rootQuaternion = root.getWorldQuaternion(new THREE13.Quaternion).invert();+ return axis.applyQuaternion(part.node.getWorldQuaternion(new THREE13.Quaternion)).applyQuaternion(rootQuaternion).setY(0).normalize();}function evaluatePropCircularAssemblyQa(context) {- if (context.intent.category !== "prop" || !(context.scene instanceof THREE12.Object3D))+ if (context.intent.category !== "prop" || !(context.scene instanceof THREE13.Object3D))return [];const root = context.scene;const parts = collectParts(root);@@ -16228,8 +16256,8 @@ function evaluatePropCircularAssemblyQa(context) {const memberParts = parts.filter((part) => part.box && (part.roles.some((role) => role.startsWith("prop.circular.member.")) || namedProfile && /(?:stave|ring[_.-]?segment)/i.test(part.node.name)));if (memberParts.length < 3)return [];- const centers = memberParts.map((part) => part.box.getCenter(new THREE12.Vector3));- const ringCenter = centers.reduce((sum, center) => sum.add(center), new THREE12.Vector3).multiplyScalar(1 / centers.length);+ const centers = memberParts.map((part) => part.box.getCenter(new THREE13.Vector3));+ const ringCenter = centers.reduce((sum, center) => sum.add(center), new THREE13.Vector3).multiplyScalar(1 / centers.length);const members = memberParts.map((part, index) => {const center = centers[index];return {@@ -16268,7 +16296,7 @@ function evaluatePropCircularAssemblyQa(context) {if (!member.horizontalDirection)return false;const radial = member.center.clone().sub(ringCenter).setY(0).normalize();- const tangent = new THREE12.Vector3(-radial.z, 0, radial.x);+ const tangent = new THREE13.Vector3(-radial.z, 0, radial.x);const radialScore = Math.abs(member.horizontalDirection.dot(radial));const tangentScore = Math.abs(member.horizontalDirection.dot(tangent));return expectedOrientation === "tangent" ? tangentScore + 0.1 < radialScore : radialScore + 0.1 < tangentScore;@@ -16295,7 +16323,7 @@ function evaluatePropCircularAssemblyQa(context) {return findings;}function inspectPlacement(input) {- if (!(input.scene instanceof THREE12.Object3D))+ if (!(input.scene instanceof THREE13.Object3D))return [];const placementFinding = (value) => ({...value,@@ -16306,8 +16334,8 @@ function inspectPlacement(input) {const renderable = parts.filter((part) => part.renderable && part.box);if (renderable.length === 0)return [];- const bounds = renderable.reduce((box, part) => box.union(part.box), new THREE12.Box3);- const size = bounds.getSize(new THREE12.Vector3);+ const bounds = renderable.reduce((box, part) => box.union(part.box), new THREE13.Box3);+ const size = bounds.getSize(new THREE13.Vector3);const findings = [];for (const axis of ["x", "y", "z"]) {const expected = input.bounds?.[axis];@@ -16354,7 +16382,7 @@ function inspectPlacement(input) {}const placement = parts.find((part) => part.roles.includes("prop.pivot.placement"));if (placement) {- const point = placement.node.getWorldPosition(new THREE12.Vector3);+ const point = placement.node.getWorldPosition(new THREE13.Vector3);point.applyMatrix4(root.matrixWorld.clone().invert());const horizontalOutside = point.x < bounds.min.x - GROUND_TOLERANCE_METERS || point.x > bounds.max.x + GROUND_TOLERANCE_METERS || point.z < bounds.min.z - GROUND_TOLERANCE_METERS || point.z > bounds.max.z + GROUND_TOLERANCE_METERS;const verticalDelta = Math.abs(point.y - bounds.min.y);@@ -16427,7 +16455,7 @@ var init_prop = __esm(() => {});// src/delivery.ts-import * as THREE13 from "three";+import * as THREE14 from "three";import { ConvexGeometry } from "three/addons/geometries/ConvexGeometry.js";function fail4(helper, detail) {throw new AuthoringDiagnosticError("DELIVERY_CONTRACT", `${helper}: ${detail}`);@@ -16455,7 +16483,7 @@ function place(helper, node, options) {node.position.set(...triple2(helper, "position", options.position));if (options.rotation !== undefined) {const [x, y, z] = triple2(helper, "rotation", options.rotation);- node.rotation.set(THREE13.MathUtils.degToRad(x), THREE13.MathUtils.degToRad(y), THREE13.MathUtils.degToRad(z));+ node.rotation.set(THREE14.MathUtils.degToRad(x), THREE14.MathUtils.degToRad(y), THREE14.MathUtils.degToRad(z));}if (options.parent !== undefined) {if (!isObject3D(options.parent))@@ -16484,10 +16512,10 @@ function addSemanticRoles(node, roles) {});}function proxyMaterial() {- return new THREE13.MeshBasicMaterial({ name: COLLIDER_PROXY_MATERIAL_NAME, color: 16711935 });+ return new THREE14.MeshBasicMaterial({ name: COLLIDER_PROXY_MATERIAL_NAME, color: 16711935 });}function proxy(shape, id, geometry) {- const mesh = new THREE13.Mesh(geometry, proxyMaterial());+ const mesh = new THREE14.Mesh(geometry, proxyMaterial());mesh.name = `Collider_${shape}_${id}`;mesh.visible = false;addSemanticRoles(mesh, [@@ -16502,7 +16530,7 @@ function colliderBox(size, opts) {const dims = typeof size === "number" ? [size, size, size] : triple2(helper, "size", size).map((value) => value);for (const [index, value] of dims.entries())finitePositive2(helper, `size[${index}]`, value);- const mesh = proxy("box", id, new THREE13.BoxGeometry(1, 1, 1));+ const mesh = proxy("box", id, new THREE14.BoxGeometry(1, 1, 1));mesh.scale.set(dims[0], dims[1], dims[2]);place(helper, mesh, settings);return mesh;@@ -16515,7 +16543,7 @@ function colliderCapsule(radius, height, opts) {finitePositive2(helper, "height", height);if (height < 2 * radius)fail4(helper, `height is the total height including both caps and must be at least 2 * radius (${2 * radius}), got ${height}.`);- const geometry = new THREE13.CapsuleGeometry(radius, height - 2 * radius, 4, 12);+ const geometry = new THREE14.CapsuleGeometry(radius, height - 2 * radius, 4, 12);geometry.scale(1 / (2 * radius), 1 / height, 1 / (2 * radius));const mesh = proxy("capsule", id, geometry);mesh.scale.set(2 * radius, height, 2 * radius);@@ -16534,7 +16562,7 @@ function colliderHull(mesh, opts) {fail4(helper, `mesh has ${position.count} vertices; a hull proxy reads at most ${GEOMETRY_ALLOCATION_LIMITS.colliderHullVertices}.`);const points = [];for (let i = 0;i < position.count; i++)- points.push(new THREE13.Vector3().fromBufferAttribute(position, i));+ points.push(new THREE14.Vector3().fromBufferAttribute(position, i));let geometry;try {geometry = new ConvexGeometry(points);@@ -16560,7 +16588,7 @@ function anchor(kind, id, opts) {const settings = options(helper, opts);const kindSegment = segment(helper, "kind", kind);const idSegment = segment(helper, "id", id);- const node = new THREE13.Object3D;+ const node = new THREE14.Object3D;node.name = `Anchor_${kindSegment}_${idSegment}`;node.visible = false;addSemanticRoles(node, [semanticRole(KILN_SEMANTIC_ROLES.anchor, kindSegment, idSegment)]);@@ -16604,7 +16632,7 @@ function port(id, opts) {const helper = "port(id, opts?)";const settings = options(helper, opts);const idSegment = segment(helper, "id", id);- const node = new THREE13.Object3D;+ const node = new THREE14.Object3D;node.name = `Port_${idSegment}`;addSemanticRoles(node, [semanticRole(KILN_SEMANTIC_ROLES.kitPort, idSegment)]);place(helper, node, settings);@@ -16796,7 +16824,7 @@ var init_lod2 = __esm(() => {});// src/qa/part-connectivity.ts-import * as THREE14 from "three";+import * as THREE15 from "three";function collectParts2(root, exempt, supports) {const parts = [];let lodExcluded = 0;@@ -16814,7 +16842,7 @@ function collectParts2(root, exempt, supports) {exempt.push(name);return;}- const box = new THREE14.Box3().setFromObject(mesh);+ const box = new THREE15.Box3().setFromObject(mesh);if (box.isEmpty())return;const support = restingSupport(mesh, box.min.y, supports);@@ -16909,7 +16937,7 @@ function analyzePartConnectivity(root, supports) {return report;}function inspectPartConnectivity(scene, supports) {- if (!(scene instanceof THREE14.Object3D))+ if (!(scene instanceof THREE15.Object3D))return [];const report = analyzePartConnectivity(scene, supports);const lodNote = report.lodExcluded === 1 ? " 1 part on an LOD level above 0 was not analyzed." : report.lodExcluded > 1 ? ` ${report.lodExcluded} parts on LOD levels above 0 were not analyzed.` : "";@@ -16969,9 +16997,9 @@ var init_part_connectivity = __esm(() => {});// src/sweep-analysis.ts-import * as THREE15 from "three";+import * as THREE16 from "three";function segmentHitsTriangle(a, b, tri, epsilon) {- const plane = new THREE15.Plane().setFromCoplanarPoints(tri.a, tri.b, tri.c);+ const plane = new THREE16.Plane().setFromCoplanarPoints(tri.a, tri.b, tri.c);if (plane.normal.lengthSq() === 0)return false;const da = plane.distanceToPoint(a), db = plane.distanceToPoint(b);@@ -17009,7 +17037,7 @@ function recordSweepAnalysis(geometry, rings, profiles, closed) {return result;}const unique = closed ? rings.length - 1 : rings.length;- const centers = rings.map((ring) => ring.reduce((sum, p) => sum.add(p), new THREE15.Vector3).divideScalar(ring.length));+ const centers = rings.map((ring) => ring.reduce((sum, p) => sum.add(p), new THREE16.Vector3).divideScalar(ring.length));for (let i = closed ? 0 : 1;i < (closed ? unique : unique - 1); i++) {const a = centers[(i - 1 + unique) % unique], b = centers[i], c = centers[(i + 1) % unique];const u = b.clone().sub(a), v = c.clone().sub(b);@@ -17023,17 +17051,17 @@ function recordSweepAnalysis(geometry, rings, profiles, closed) {const triangles = new Map;const faces = (index) => {if (!triangles.has(index))- triangles.set(index, THREE15.ShapeUtils.triangulateShape(profiles[index], []).map(([a, b, c]) => new THREE15.Triangle(rings[index][a], rings[index][b], rings[index][c])));+ triangles.set(index, THREE16.ShapeUtils.triangulateShape(profiles[index], []).map(([a, b, c]) => new THREE16.Triangle(rings[index][a], rings[index][b], rings[index][c])));return triangles.get(index);};for (let i = 1;i < rings.length; i++) {- const boundsA = new THREE15.Box3().setFromPoints(rings[i - 1]);- const boundsB = new THREE15.Box3().setFromPoints(rings[i]);+ const boundsA = new THREE16.Box3().setFromPoints(rings[i - 1]);+ const boundsB = new THREE16.Box3().setFromPoints(rings[i]);if (!boundsA.intersectsBox(boundsB)) {result.ringPairsChecked++;continue;}- const epsilon = Math.max(boundsA.getSize(new THREE15.Vector3).length(), boundsB.getSize(new THREE15.Vector3).length()) * 0.0000000001;+ const epsilon = Math.max(boundsA.getSize(new THREE16.Vector3).length(), boundsB.getSize(new THREE16.Vector3).length()) * 0.0000000001;let hit = false;pair:for (const [a, b] of [@@ -17188,7 +17216,7 @@ var init_open_shell = __esm(() => {});// src/qa/self-intersection.ts-import * as THREE16 from "three";+import * as THREE17 from "three";function boxOverlapRatio(a, b) {const shared = Math.max(0, Math.min(a.max.x, b.max.x) - Math.max(a.min.x, b.min.x)) * Math.max(0, Math.min(a.max.y, b.max.y) - Math.max(a.min.y, b.min.y)) * Math.max(0, Math.min(a.max.z, b.max.z) - Math.max(a.min.z, b.min.z));const ratio = shared / Math.min(boxVolume(a), boxVolume(b));@@ -17239,8 +17267,8 @@ function collectParts3(root, skipped) {const box = mesh.geometry.boundingBox.clone().applyMatrix4(mesh.matrixWorld);if (box.isEmpty())return;- const center = box.getCenter(new THREE16.Vector3);- const size = box.getSize(new THREE16.Vector3);+ const center = box.getCenter(new THREE17.Vector3);+ const size = box.getSize(new THREE17.Vector3);const scale = Math.max(size.x, size.y, size.z);if (![...box.min, ...box.max, scale].every(Number.isFinite) || !(scale > 0) || !Number.isFinite(mesh.matrixWorld.determinant()) || mesh.matrixWorld.determinant() === 0) {skipped.push({@@ -17272,7 +17300,7 @@ function meshToArrays(part) {matrix.elements[12] -= center.x;matrix.elements[13] -= center.y;matrix.elements[14] -= center.z;- const v = new THREE16.Vector3;+ const v = new THREE17.Vector3;const verts = new Float32Array(position.count * 3);for (let i = 0;i < position.count; i++) {v.set(position.getX(i), position.getY(i), position.getZ(i)).applyMatrix4(matrix).divideScalar(scale);@@ -17620,7 +17648,7 @@ var init_self_intersection = __esm(() => {});// src/vehicle.ts-import * as THREE17 from "three";+import * as THREE18 from "three";function assertId(value, name) {if (!ID_PATTERN.test(value))throw new TypeError(`${name} must be a stable identifier`);@@ -17655,7 +17683,7 @@ function createTypedSocket(kind, input, parent) {if (!input.position.every(Number.isFinite))throw new TypeError(`${kind}.${id} position must be finite`);const rotation = normalizedQuaternion(input.rotation);- const node = new THREE17.Object3D;+ const node = new THREE18.Object3D;node.name = `Socket_${kind}_${id}`;node.position.set(...input.position);node.quaternion.set(...rotation);@@ -17676,7 +17704,7 @@ function createTypedSocket(kind, input, parent) {return node;}function createVehicleFrame(name, options = {}) {- const root = new THREE17.Object3D;+ const root = new THREE18.Object3D;root.name = name;stampSemanticMetadataV1(root, semantic2([KILN_SEMANTIC_ROLES.vehicleFrame, KILN_SEMANTIC_ROLES.vehicleForward], {frames: [@@ -17701,7 +17729,7 @@ function createVehicleFrame(name, options = {}) {};}function cylinderZ(radius, width, segments = 16) {- const geometry = new THREE17.CylinderGeometry(radius, radius, width, segments);+ const geometry = new THREE18.CylinderGeometry(radius, radius, width, segments);geometry.rotateX(Math.PI / 2);return geometry;}@@ -17718,14 +17746,14 @@ function defaultTireGeometry(radius, width) {if (width >= radius * 2)throw new RangeError("default wheel tire width must be less than its diameter");const tube = width / 2;- return new THREE17.TorusGeometry(radius - tube, tube, 8, 20);+ return new THREE18.TorusGeometry(radius - tube, tube, 8, 20);}function checkWheelGeometry(part, geometry, radius, width) {const positions = geometry.getAttribute("position");if (positions?.itemSize !== 3 || positions.count < 1 || positions.count > 2000000)throw new RangeError(`wheel ${part} position must have 1..2000000 three-component samples.`);- const bounds = new THREE17.Box3;- const point = new THREE17.Vector3;+ const bounds = new THREE18.Box3;+ const point = new THREE18.Vector3;let actualRadius = 0;for (let i = 0;i < positions.count; i++) {point.fromBufferAttribute(positions, i);@@ -17735,7 +17763,7 @@ function checkWheelGeometry(part, geometry, radius, width) {actualRadius = Math.max(actualRadius, Math.hypot(point.x, point.y));}const actualWidth = bounds.max.z - bounds.min.z;- const center = bounds.getCenter(new THREE17.Vector3);+ const center = bounds.getCenter(new THREE18.Vector3);const tolerance = 0.00001 * Math.max(radius, width, actualRadius, actualWidth);const differences = [];if (Math.abs(actualRadius - radius) > tolerance)@@ -17780,11 +17808,11 @@ function createWheelAssembly(name, materials, options) {const index = assertId(String(options.index), "wheel index");const key = `${options.side}.${index}`;const parent = options.parent;- const root = new THREE17.Object3D;+ const root = new THREE18.Object3D;root.name = `${name}_Assembly_${options.side}_${index}`;let steeringPivot;if (options.steering) {- steeringPivot = new THREE17.Object3D;+ steeringPivot = new THREE18.Object3D;steeringPivot.name = `SteeringPivot_${options.side}_${index}`;steeringPivot.position.set(...options.position ?? [0, 0, 0]);stampSemanticMetadataV1(steeringPivot, semantic2([semanticRole(ROLE.steeringPivot, key)], {@@ -17795,7 +17823,7 @@ function createWheelAssembly(name, materials, options) {}));root.add(steeringPivot);}- const spinPivot = new THREE17.Object3D;+ const spinPivot = new THREE18.Object3D;spinPivot.name = `WheelPivot_${options.side}_${index}`;if (!steeringPivot)spinPivot.position.set(...options.position ?? [0, 0, 0]);@@ -17816,9 +17844,9 @@ function createWheelAssembly(name, materials, options) {]}));(steeringPivot ?? root).add(spinPivot);- const tire = new THREE17.Mesh(options.geometries?.tire ?? defaultTireGeometry(radius, width), materials.tire);- const rim = new THREE17.Mesh(options.geometries?.rim ?? cylinderZ(rimRadius, rimWidth), materials.rim);- const hub = new THREE17.Mesh(options.geometries?.hub ?? cylinderZ(hubRadius, hubWidth), materials.hub ?? materials.rim);+ const tire = new THREE18.Mesh(options.geometries?.tire ?? defaultTireGeometry(radius, width), materials.tire);+ const rim = new THREE18.Mesh(options.geometries?.rim ?? cylinderZ(rimRadius, rimWidth), materials.rim);+ const hub = new THREE18.Mesh(options.geometries?.hub ?? cylinderZ(hubRadius, hubWidth), materials.hub ?? materials.rim);tire.name = `Tire_${options.side}_${index}`;rim.name = `Rim_${options.side}_${index}`;hub.name = `Hub_${options.side}_${index}`;@@ -17838,7 +17866,7 @@ function createWheelAssembly(name, materials, options) {]}));spinPivot.add(tire, rim, hub);- const contact = new THREE17.Object3D;+ const contact = new THREE18.Object3D;contact.name = `Contact_${options.side}_${index}`;contact.position.y = -radius;stampSemanticMetadataV1(contact, semantic2([semanticRole(ROLE.wheelContact, key), semanticRole(ROLE.contact, key)], {@@ -17896,10 +17924,10 @@ function objectBoundsInFrame(object, frame) {object.updateWorldMatrix(true, true);frame.updateWorldMatrix(true, false);const worldToFrame = frame.matrixWorld.clone().invert();- const bounds = new THREE17.Box3;+ const bounds = new THREE18.Box3;let found = false;object.traverse((node) => {- if (!(node instanceof THREE17.Mesh) || !(node.geometry instanceof THREE17.BufferGeometry))+ if (!(node instanceof THREE18.Mesh) || !(node.geometry instanceof THREE18.BufferGeometry))return;node.geometry.computeBoundingBox();const local = node.geometry.boundingBox;@@ -17909,7 +17937,7 @@ function objectBoundsInFrame(object, frame) {for (const x of [local.min.x, local.max.x])for (const y of [local.min.y, local.max.y])for (const z of [local.min.z, local.max.z]) {- bounds.expandByPoint(new THREE17.Vector3(x, y, z).applyMatrix4(matrix));+ bounds.expandByPoint(new THREE18.Vector3(x, y, z).applyMatrix4(matrix));found = true;}});@@ -17921,9 +17949,9 @@ function dimensions(object, frame) {const bounds = objectBoundsInFrame(object, frame);if (!bounds)return;- const size = bounds.getSize(new THREE17.Vector3);+ const size = bounds.getSize(new THREE18.Vector3);return {- center: bounds.getCenter(new THREE17.Vector3),+ center: bounds.getCenter(new THREE18.Vector3),radius: Math.max(size.x, size.y) / 2,width: size.z};@@ -17933,7 +17961,7 @@ function resolved(source, id, root, pivot, parts) {const tire = dimensions(parts.tire, pivot);const rim = dimensions(parts.rim, pivot);const hub = dimensions(parts.hub, pivot);- const centerLocal = tire?.center ?? rim?.center ?? hub?.center ?? new THREE17.Vector3;+ const centerLocal = tire?.center ?? rim?.center ?? hub?.center ?? new THREE18.Vector3;const toWorld = (value) => value.clone().applyMatrix4(pivot.matrixWorld);return {id,@@ -17948,11 +17976,11 @@ function resolved(source, id, root, pivot, parts) {...parts.hub ? { hub: parts.hub } : {},...parts.contact ? { contact: parts.contact } : {},centerWorld: toWorld(centerLocal),- pivotCenterWorld: new THREE17.Vector3().setFromMatrixPosition(pivot.matrixWorld),+ pivotCenterWorld: new THREE18.Vector3().setFromMatrixPosition(pivot.matrixWorld),...tire ? { tireCenterWorld: toWorld(tire.center) } : {},...rim ? { rimCenterWorld: toWorld(rim.center) } : {},...hub ? { hubCenterWorld: toWorld(hub.center) } : {},- spinAxisWorld: new THREE17.Vector3(0, 0, 1).transformDirection(pivot.matrixWorld),+ spinAxisWorld: new THREE18.Vector3(0, 0, 1).transformDirection(pivot.matrixWorld),...tire ? { radius: tire.radius, width: tire.width } : {},...rim ? { rimRadius: rim.radius, rimWidth: rim.width } : {},...hub ? { hubRadius: hub.radius, hubWidth: hub.width } : {},@@ -18289,7 +18317,7 @@ var EPSILON = 0.0000000001, DEFAULT_TOLERANCE = 0.000001, finiteVector = (value)];// src/qa/vehicle-advisory.ts-import * as THREE18 from "three";+import * as THREE19 from "three";function advisory(context, value) {return {...value,@@ -18363,7 +18391,7 @@ function isFender(node) {return semanticRoles(node).some((role) => /(?:^|\.)(?:fender|wheel-arch)(?:\.|$)/i.test(role)) || /fender|wheel[ _.-]?arch/i.test(node.name);}function isChassisMesh(node) {- if (!(node instanceof THREE18.Mesh) || isFender(node))+ if (!(node instanceof THREE19.Mesh) || isFender(node))return false;return semanticRoles(node).some((role) => /^(?:vehicle\.)?(?:chassis|body|hull)(?:\.|$)/i.test(role)) || /chassis|vehicle[ _.-]?body|fuselage|hull/i.test(node.name);}@@ -18371,10 +18399,10 @@ function objectBoundsInFrame2(object, frame) {object.updateWorldMatrix(true, true);frame.updateWorldMatrix(true, false);const worldToFrame = frame.matrixWorld.clone().invert();- const bounds = new THREE18.Box3;+ const bounds = new THREE19.Box3;let found = false;object.traverseVisible((part) => {- if (!(part instanceof THREE18.Mesh) || !(part.geometry instanceof THREE18.BufferGeometry))+ if (!(part instanceof THREE19.Mesh) || !(part.geometry instanceof THREE19.BufferGeometry))return;part.geometry.computeBoundingBox();const box = part.geometry.boundingBox;@@ -18384,7 +18412,7 @@ function objectBoundsInFrame2(object, frame) {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 THREE18.Vector3(x, y, z).applyMatrix4(matrix));+ bounds.expandByPoint(new THREE19.Vector3(x, y, z).applyMatrix4(matrix));found = true;}});@@ -18395,15 +18423,15 @@ function tuple5(value) {}function probeBox(id, root, bounds) {root.updateWorldMatrix(true, false);- const center = bounds.getCenter(new THREE18.Vector3).applyMatrix4(root.matrixWorld);- const size = bounds.getSize(new THREE18.Vector3);- const position = new THREE18.Vector3;- const quaternion = new THREE18.Quaternion;- const scale = new THREE18.Vector3;+ const center = bounds.getCenter(new THREE19.Vector3).applyMatrix4(root.matrixWorld);+ const size = bounds.getSize(new THREE19.Vector3);+ const position = new THREE19.Vector3;+ const quaternion = new THREE19.Quaternion;+ const scale = new THREE19.Vector3;root.matrixWorld.decompose(position, quaternion, scale);- const xAxis = new THREE18.Vector3(1, 0, 0).applyQuaternion(quaternion).normalize();- const yAxis = new THREE18.Vector3(0, 1, 0).applyQuaternion(quaternion).normalize();- const zAxis = new THREE18.Vector3(0, 0, 1).applyQuaternion(quaternion).normalize();+ const xAxis = new THREE19.Vector3(1, 0, 0).applyQuaternion(quaternion).normalize();+ const yAxis = new THREE19.Vector3(0, 1, 0).applyQuaternion(quaternion).normalize();+ const zAxis = new THREE19.Vector3(0, 0, 1).applyQuaternion(quaternion).normalize();return createOrientedProbeBox3({id,frame: createProbeLocalFrame3({@@ -18472,7 +18500,7 @@ function orientationFindings(context, root, intent) {const bounds = wholeAssetBounds(root);if (!bounds)return [];- const size = bounds.getSize(new THREE18.Vector3);+ const size = bounds.getSize(new THREE19.Vector3);const ratio = size.z / Math.max(size.x, 0.000000001);if (ratio <= ORIENTATION_RATIO)return [];@@ -18516,13 +18544,13 @@ function weldedBoundaryEdges(root, loop) {let triangleCount = 0;const vertexKey = (point) => [point.x, point.y, point.z].map((value) => Math.round(value * 1e6)).join(",");loop.traverseVisible((node) => {- if (!(node instanceof THREE18.Mesh) || !(node.geometry instanceof THREE18.BufferGeometry))+ if (!(node instanceof THREE19.Mesh) || !(node.geometry instanceof THREE19.BufferGeometry))return;const positions = node.geometry.getAttribute("position");if (!positions)return;const matrix = inverse.clone().multiply(node.matrixWorld);- const keys = Array.from({ length: positions.count }, (_, index) => vertexKey(new THREE18.Vector3().fromBufferAttribute(positions, index).applyMatrix4(matrix)));+ const keys = Array.from({ length: positions.count }, (_, index) => vertexKey(new THREE19.Vector3().fromBufferAttribute(positions, index).applyMatrix4(matrix)));const index = node.geometry.getIndex();const indices = index ? Array.from(index.array, Number) : Array.from({ length: positions.count }, (_, value) => value);for (let offset = 0;offset + 2 < indices.length; offset += 3) {@@ -18592,7 +18620,7 @@ function trackProfileFindings(context, root, intent) {const wheelBounds = objectBoundsInFrame2(roadWheel, root);if (!wheelBounds)continue;- const center = wheelBounds.getCenter(new THREE18.Vector3);+ const center = wheelBounds.getCenter(new THREE19.Vector3);if (expanded.containsPoint(center))continue;const clamped = center.clone().clamp(expanded.min, expanded.max);@@ -18618,7 +18646,7 @@ function trackProfileFindings(context, root, intent) {return findings;}function inspectMobilityAdvisory(context) {- if (!(context.scene instanceof THREE18.Object3D)) {+ if (!(context.scene instanceof THREE19.Object3D)) {return [];}const intent = context.mobility;@@ -18665,7 +18693,7 @@ var init_vehicle_advisory = __esm(() => {});// src/qa/vehicle.ts-import * as THREE19 from "three";+import * as THREE20 from "three";function finding3(context, value) {return {...value,@@ -18682,7 +18710,7 @@ function rootAxis(root, axis) {return axis.clone().transformDirection(root.matrixWorld);}function angleDegrees(a, b) {- return THREE19.MathUtils.radToDeg(Math.acos(THREE19.MathUtils.clamp(a.clone().normalize().dot(b.clone().normalize()), -1, 1)));+ return THREE20.MathUtils.radToDeg(Math.acos(THREE20.MathUtils.clamp(a.clone().normalize().dot(b.clone().normalize()), -1, 1)));}function isDescendant(node, ancestor) {let current = node;@@ -18730,7 +18758,7 @@ function wheelCountFindings(context, intent, wheels) {}function wheelGeometryFindings(context, root, wheels) {const findings = [];- const expectedAxle = rootAxis(root, new THREE19.Vector3(0, 0, 1));+ const expectedAxle = rootAxis(root, new THREE20.Vector3(0, 0, 1));for (const wheel of wheels) {const disposition = componentDisposition(wheel);const centerTolerance = Math.max(CENTER_MINIMUM, (wheel.radius ?? 0) * CENTER_RATIO);@@ -18919,7 +18947,7 @@ function contactFindings(context, root, intent, wheels) {function renderableMinYInRoot(rootInverse, node) {let minimum = Infinity;node.traverseVisible((part) => {- if (!(part instanceof THREE19.Mesh) || !(part.geometry instanceof THREE19.BufferGeometry))+ if (!(part instanceof THREE20.Mesh) || !(part.geometry instanceof THREE20.BufferGeometry))return;part.geometry.computeBoundingBox();const bounds = part.geometry.boundingBox;@@ -18929,7 +18957,7 @@ function renderableMinYInRoot(rootInverse, node) {for (const x of [bounds.min.x, bounds.max.x]) {for (const y of [bounds.min.y, bounds.max.y]) {for (const z of [bounds.min.z, bounds.max.z]) {- minimum = Math.min(minimum, new THREE19.Vector3(x, y, z).applyMatrix4(matrix).y);+ minimum = Math.min(minimum, new THREE20.Vector3(x, y, z).applyMatrix4(matrix).y);}}}@@ -18947,7 +18975,7 @@ function supportContactFindings(context, root, intent) {if (!isWheelContact && roles.some((role) => role.startsWith("contact."))) {explicitContacts.push({node,- contactY: localPoint2(inverse, new THREE19.Vector3().setFromMatrixPosition(node.matrixWorld)).y,+ contactY: localPoint2(inverse, new THREE20.Vector3().setFromMatrixPosition(node.matrixWorld)).y,source: "contact"});}@@ -19027,7 +19055,7 @@ function steeringFindings(context, root, intent, wheels) {return [];root.updateWorldMatrix(true, false);const inverse = root.matrixWorld.clone().invert();- const expectedAxis = rootAxis(root, new THREE19.Vector3(0, 1, 0));+ const expectedAxis = rootAxis(root, new THREE20.Vector3(0, 1, 0));const localCenters = wheels.map((wheel) => ({wheel,center: localPoint2(inverse, wheel.centerWorld)@@ -19037,8 +19065,8 @@ function steeringFindings(context, root, intent, wheels) {const findings = [];for (const { wheel } of targets) {const steering = wheel.steeringPivot;- const centerDelta = steering ? localPoint2(inverse, new THREE19.Vector3().setFromMatrixPosition(steering.matrixWorld)).distanceTo(localPoint2(inverse, wheel.centerWorld)) : Infinity;- const axisAngle = steering ? angleDegrees(new THREE19.Vector3(0, 1, 0).transformDirection(steering.matrixWorld), expectedAxis) : Infinity;+ const centerDelta = steering ? localPoint2(inverse, new THREE20.Vector3().setFromMatrixPosition(steering.matrixWorld)).distanceTo(localPoint2(inverse, wheel.centerWorld)) : Infinity;+ const axisAngle = steering ? angleDegrees(new THREE20.Vector3(0, 1, 0).transformDirection(steering.matrixWorld), expectedAxis) : Infinity;if (!steering || !isDescendant(wheel.pivot, steering) || centerDelta > CENTER_MINIMUM || axisAngle > AXIS_TOLERANCE_DEGREES) {const axisInvalid = axisAngle > AXIS_TOLERANCE_DEGREES;findings.push(finding3(context, {@@ -19093,14 +19121,14 @@ function propulsionFindings(context, root, intent) {}for (const component of candidates) {const pivot = pivots.get(component.id);- const box = new THREE19.Box3().setFromObject(component.node);- const center = box.isEmpty() ? undefined : box.getCenter(new THREE19.Vector3);- const pivotCenter = pivot ? new THREE19.Vector3().setFromMatrixPosition(pivot.matrixWorld) : undefined;+ const box = new THREE20.Box3().setFromObject(component.node);+ const center = box.isEmpty() ? undefined : box.getCenter(new THREE20.Vector3);+ const pivotCenter = pivot ? new THREE20.Vector3().setFromMatrixPosition(pivot.matrixWorld) : undefined;const delta = center && pivotCenter ? localPoint2(rootInverse, center).distanceTo(localPoint2(rootInverse, pivotCenter)) : Infinity;const frameId = kind === "rotor" ? "propulsion-axis.+y" : "propulsion-axis.+x";const axisFrame = readSemanticMetadataV1(pivot ?? component.node)?.frames.find((frame) => frame.id === frameId);- const canonicalAxis = kind === "rotor" ? new THREE19.Vector3(0, 1, 0) : new THREE19.Vector3(1, 0, 0);- const axisAngle = pivot && axisFrame ? angleDegrees(canonicalAxis.clone().applyQuaternion(new THREE19.Quaternion(...axisFrame.rotation)).transformDirection(pivot.matrixWorld), rootAxis(root, canonicalAxis)) : Infinity;+ const canonicalAxis = kind === "rotor" ? new THREE20.Vector3(0, 1, 0) : new THREE20.Vector3(1, 0, 0);+ const axisAngle = pivot && axisFrame ? angleDegrees(canonicalAxis.clone().applyQuaternion(new THREE20.Quaternion(...axisFrame.rotation)).transformDirection(pivot.matrixWorld), rootAxis(root, canonicalAxis)) : Infinity;if (!pivot || !isDescendant(component.node, pivot) || delta > CENTER_MINIMUM || !axisFrame || axisAngle > AXIS_TOLERANCE_DEGREES) {findings.push(finding3(context, {code: "VEH_ROTOR_PIVOT",@@ -19122,7 +19150,7 @@ function propulsionFindings(context, root, intent) {return findings;}function inspectMobility(context) {- if (!(context.scene instanceof THREE19.Object3D))+ if (!(context.scene instanceof THREE20.Object3D))return [];const intent = context.mobility;if (!intent)@@ -19195,7 +19223,7 @@ var init_vehicle2 = __esm(() => {});// src/qa/vegetation.ts-import * as THREE20 from "three";+import * as THREE21 from "three";function rolesOf2(node) {return readSemanticMetadataV1(node)?.roles ?? [];}@@ -19211,22 +19239,22 @@ function pathOf(node, root) {return names.reverse().join("/");}function localPoint3(rootInverse, node) {- return node.getWorldPosition(new THREE20.Vector3).applyMatrix4(rootInverse);+ return node.getWorldPosition(new THREE21.Vector3).applyMatrix4(rootInverse);}function meshLocalBox(mesh, rootInverse) {- if (!(mesh.geometry instanceof THREE20.BufferGeometry))+ if (!(mesh.geometry instanceof THREE21.BufferGeometry))return;mesh.geometry.computeBoundingBox();const source = mesh.geometry.boundingBox;if (!source || source.isEmpty())return;const base = rootInverse.clone().multiply(mesh.matrixWorld);- const result = new THREE20.Box3;- const count = mesh instanceof THREE20.InstancedMesh ? mesh.count : 1;+ const result = new THREE21.Box3;+ const count = mesh instanceof THREE21.InstancedMesh ? mesh.count : 1;for (let index = 0;index < count; index++) {const transform = base.clone();- if (mesh instanceof THREE20.InstancedMesh) {- const instance = new THREE20.Matrix4;+ if (mesh instanceof THREE21.InstancedMesh) {+ const instance = new THREE21.Matrix4;mesh.getMatrixAt(index, instance);transform.multiply(instance);}@@ -19239,7 +19267,7 @@ function collectRenderableBounds(root) {const inverse = root.matrixWorld.clone().invert();const values = [];root.traverseVisible((node) => {- if (!(node instanceof THREE20.Mesh))+ if (!(node instanceof THREE21.Mesh))return;const box = meshLocalBox(node, inverse);if (!box)@@ -19257,7 +19285,7 @@ function vegetationIntent(intent) {}function inspectFoliageContact(context) {const trusted = context.foliage;- if (!trusted?.grounded || !(context.scene instanceof THREE20.Object3D))+ if (!trusted?.grounded || !(context.scene instanceof THREE21.Object3D))return [];const planeY = context.groundPlaneY ?? 0;const root = context.scene;@@ -19295,7 +19323,7 @@ function inspectFoliageContact(context) {}const findings = [];for (const contact of contacts) {- const contactPoint = contact.frameTranslation ? new THREE20.Vector3(...contact.frameTranslation).applyMatrix4(contact.node.matrixWorld).applyMatrix4(inverse) : localPoint3(inverse, contact.node);+ const contactPoint = contact.frameTranslation ? new THREE21.Vector3(...contact.frameTranslation).applyMatrix4(contact.node.matrixWorld).applyMatrix4(inverse) : localPoint3(inverse, contact.node);const y = contactPoint.y;const offset = y - planeY;if (Math.abs(offset) <= VEGETATION_CONTACT_TOLERANCE_METERS)@@ -19324,7 +19352,7 @@ function inspectFoliageContact(context) {for (const support of semanticSupports) {let minimumY = Infinity;support.traverseVisible((node) => {- if (!(node instanceof THREE20.Mesh))+ if (!(node instanceof THREE21.Mesh))return;const box = meshLocalBox(node, inverse);if (box)@@ -19352,25 +19380,25 @@ function inspectFoliageContact(context) {return findings;}function materialNames(node) {- if (!(node instanceof THREE20.Mesh))+ if (!(node instanceof THREE21.Mesh))return [];const materials = Array.isArray(node.material) ? node.material : [node.material];return materials.filter(Boolean).map((material) => material.name ?? "");}function inspectFoliageScope(context) {const trusted = context.foliage;- if (!trusted?.standalone || !(context.scene instanceof THREE20.Object3D))+ if (!trusted?.standalone || !(context.scene instanceof THREE21.Object3D))return [];const root = context.scene;const renderables = collectRenderableBounds(root);if (renderables.length === 0)return [];- const overall = renderables.reduce((box, value) => box.union(value.box), new THREE20.Box3);- const overallSize = overall.getSize(new THREE20.Vector3);+ const overall = renderables.reduce((box, value) => box.union(value.box), new THREE21.Box3);+ const overallSize = overall.getSize(new THREE21.Vector3);const findings = [];for (const value of renderables) {- const size = value.box.getSize(new THREE20.Vector3);- const center = value.box.getCenter(new THREE20.Vector3);+ const size = value.box.getSize(new THREE21.Vector3);+ const center = value.box.getCenter(new THREE21.Vector3);const names = [value.node.name, ...value.roles];const nameEvidence = names.some((name) => CLUTTER_NAME.test(name));const roleEvidence = value.roles.some((role) => /(?:terrain|soil|rock|pot|planter|base)/i.test(role));@@ -19407,8 +19435,8 @@ function inspectFoliageScope(context) {function unionVolume(boxes) {if (boxes.length === 0)return 0;- const union = boxes.reduce((result, box) => result.union(box), new THREE20.Box3);- const size = union.getSize(new THREE20.Vector3);+ const union = boxes.reduce((result, box) => result.union(box), new THREE21.Box3);+ const size = union.getSize(new THREE21.Vector3);return size.x * size.y * size.z;}function projectedOccupancy(boxes, axes) {@@ -19478,7 +19506,7 @@ function boxDistanceToPoint(box, point) {function endpointRadius(position, axis, axisValue, tolerance, scale) {const radialAxes = [0, 1, 2].filter((value) => value !== axis);const points = [];- const point = new THREE20.Vector3;+ const point = new THREE21.Vector3;for (let index = 0;index < position.count; index++) {point.fromBufferAttribute(position, index);if (Math.abs(point.getComponent(axis) - axisValue) <= tolerance)@@ -19486,7 +19514,7 @@ function endpointRadius(position, axis, axisValue, tolerance, scale) {}if (points.length === 0)return;- const center = new THREE20.Vector3;+ const center = new THREE21.Vector3;center.setComponent(axis, axisValue);for (const radialAxis of radialAxes) {center.setComponent(radialAxis, points.reduce((sum, value) => sum + value.getComponent(radialAxis), 0) / points.length);@@ -19500,7 +19528,7 @@ function endpointRadius(position, axis, axisValue, tolerance, scale) {return { center, radius };}function growthNodeMeasurement(root, candidate, allCandidates, band) {- if (!(candidate.node instanceof THREE20.Mesh))+ if (!(candidate.node instanceof THREE21.Mesh))return;const geometry = candidate.node.geometry;const position = geometry.getAttribute("position");@@ -19512,9 +19540,9 @@ function growthNodeMeasurement(root, candidate, allCandidates, band) {return;root.updateWorldMatrix(true, true);const relative = root.matrixWorld.clone().invert().multiply(candidate.node.matrixWorld);- const relativeScale = new THREE20.Vector3;- relative.decompose(new THREE20.Vector3, new THREE20.Quaternion, relativeScale);- const size = geometryBox.getSize(new THREE20.Vector3);+ const relativeScale = new THREE21.Vector3;+ relative.decompose(new THREE21.Vector3, new THREE21.Quaternion, relativeScale);+ const size = geometryBox.getSize(new THREE21.Vector3);const scaledSizes = [Math.abs(size.x * relativeScale.x),Math.abs(size.y * relativeScale.y),@@ -19581,7 +19609,7 @@ function measureFoliageGrowth(foliage, root) {};}function inspectFoliageGrowth(context) {- if (!context.foliage || !(context.scene instanceof THREE20.Object3D))+ if (!context.foliage || !(context.scene instanceof THREE21.Object3D))return [];const measured = measureFoliageGrowth(context.foliage, context.scene);const findings = [];@@ -19632,7 +19660,7 @@ function measureVegetationFoliageAttachment(root) {const support = renderables.filter((value) => roleOrNameSource(value, TRUNK_PATTERNS) || roleOrNameSource(value, BRANCH_PATTERNS));const foliage = renderables.filter((value) => roleOrNameSource(value, CANOPY_PATTERNS));const clusters = foliage.map((value) => {- const size = value.box.getSize(new THREE20.Vector3);+ const size = value.box.getSize(new THREE21.Vector3);const threshold = stable7(Math.max(0.03, Math.min(0.18, size.length() * 0.12)));const nearest = support.map((candidate) => ({ candidate, gap: distanceBetweenBoxes(value.box, candidate.box) })).sort((a, b) => a.gap - b.gap || (a.candidate.node.name || "").localeCompare(b.candidate.node.name || ""))[0];const source = roleOrNameSource(value, CANOPY_PATTERNS) ?? "fallback";@@ -19655,7 +19683,7 @@ function measureVegetationFoliageAttachment(root) {};}function inspectFoliageAttachment(context) {- if (!context.foliage || !(context.scene instanceof THREE20.Object3D))+ if (!context.foliage || !(context.scene instanceof THREE21.Object3D))return [];return measureVegetationFoliageAttachment(context.scene).clusters.filter((cluster) => cluster.detached).map((cluster) => finding4(context, {code: "VEG_FOLIAGE_DETACHED",@@ -19675,9 +19703,9 @@ function inspectFoliageAttachment(context) {}function relativeTransformSignature(root, node) {const matrix = root.matrixWorld.clone().invert().multiply(node.matrixWorld);- const scale = new THREE20.Vector3;- const quaternion = new THREE20.Quaternion;- matrix.decompose(new THREE20.Vector3, quaternion, scale);+ const scale = new THREE21.Vector3;+ const quaternion = new THREE21.Quaternion;+ matrix.decompose(new THREE21.Vector3, quaternion, scale);if (quaternion.w < 0)quaternion.set(-quaternion.x, -quaternion.y, -quaternion.z, -quaternion.w);const values = [...scale.toArray(), ...quaternion.toArray()].map((value) => stable7(value));@@ -19698,9 +19726,9 @@ function measureFoliageRepetition(requirements, root) {nodes: values.map((value) => value.node.name || "foliage-cluster").sort()})).sort((a, b) => a.signature.localeCompare(b.signature));const supports = collectRenderableBounds(root).filter((value) => roleOrNameSource(value, TRUNK_PATTERNS));- const centerBox = supports.reduce((box, value) => box.union(value.box), new THREE20.Box3);- const centers = foliage.map((value) => value.box.getCenter(new THREE20.Vector3));- const center = centerBox.isEmpty() ? centers.reduce((result, value) => result.add(value), new THREE20.Vector3).multiplyScalar(centers.length > 0 ? 1 / centers.length : 0) : centerBox.getCenter(new THREE20.Vector3);+ const centerBox = supports.reduce((box, value) => box.union(value.box), new THREE21.Box3);+ const centers = foliage.map((value) => value.box.getCenter(new THREE21.Vector3));+ const center = centerBox.isEmpty() ? centers.reduce((result, value) => result.add(value), new THREE21.Vector3).multiplyScalar(centers.length > 0 ? 1 / centers.length : 0) : centerBox.getCenter(new THREE21.Vector3);const radial = centers.map((value) => ({angle: Math.atan2(value.z - center.z, value.x - center.x),radius: Math.hypot(value.x - center.x, value.z - center.z)@@ -19735,7 +19763,7 @@ function measureFoliageRepetition(requirements, root) {};}function inspectFoliageRepetition(context) {- if (!context.foliage || !(context.scene instanceof THREE20.Object3D))+ if (!context.foliage || !(context.scene instanceof THREE21.Object3D))return [];const measured = measureFoliageRepetition(context.foliage, context.scene);if (measured.suppressedForTopiary)@@ -19793,7 +19821,7 @@ function measureFoliageCanopy(profile, root) {}function inspectFoliageCanopy(context) {const trusted = context.foliage;- if (!trusted?.canopyProfile || !(context.scene instanceof THREE20.Object3D))+ if (!trusted?.canopyProfile || !(context.scene instanceof THREE21.Object3D))return [];const measurements = measureFoliageCanopy(trusted.canopyProfile, context.scene);const bands = PROFILE_BANDS[measurements.profile];@@ -19854,7 +19882,7 @@ function inspectFoliageCanopy(context) {return findings;}function materialValue(material) {- if (!(material instanceof THREE20.MeshStandardMaterial) && !(material instanceof THREE20.MeshBasicMaterial)) {+ if (!(material instanceof THREE21.MeshStandardMaterial) && !(material instanceof THREE21.MeshBasicMaterial)) {return;}const color = material.color;@@ -19864,11 +19892,11 @@ function measureFoliageMaterials(mode, root) {const values = [];let foliageNodeCount = 0;root.traverseVisible((node) => {- if (!(node instanceof THREE20.Mesh))+ if (!(node instanceof THREE21.Mesh))return;const bounds = {node,- box: new THREE20.Box3,+ box: new THREE21.Box3,roles: rolesOf2(node),source: rolesOf2(node).length > 0 ? "semantic" : "fallback"};@@ -19895,7 +19923,7 @@ function measureFoliageMaterials(mode, root) {};}function inspectFoliageMaterial(context) {- if (!context.foliage || !(context.scene instanceof THREE20.Object3D))+ if (!context.foliage || !(context.scene instanceof THREE21.Object3D))return [];if (!context.materialMode)return [];@@ -20097,7 +20125,7 @@ var init_character_repairs = __esm(() => {});// src/qa/character.ts-import * as THREE21 from "three";+import * as THREE22 from "three";function isClipLike(value) {if (typeof value !== "object" || value === null)return false;@@ -20335,7 +20363,7 @@ function contactFindings2(input, root) {const planeY = input.groundPlaneY ?? 0;const findings = [];for (const contact of contacts) {- const point = contact.node.getWorldPosition(new THREE21.Vector3).applyMatrix4(rootInverse);+ const point = contact.node.getWorldPosition(new THREE22.Vector3).applyMatrix4(rootInverse);const offset = point.y - planeY;if (offset > tolerance) {findings.push(block(input, "CHAR_CONTACT_FLOATING", `Ground contact ${contact.descriptor.role} is ${offset.toFixed(6)} m above asset-local ground.`, {@@ -20600,13 +20628,13 @@ function declaredHeldItem(nodes) {function characterJointScale(root) {root.updateMatrixWorld(true);const inverse = root.matrixWorld.clone().invert();- const bounds = new THREE21.Box3;+ const bounds = new THREE22.Box3;for (const joint of collectCharacterJointNodes(root)) {- bounds.expandByPoint(joint.node.getWorldPosition(new THREE21.Vector3).applyMatrix4(inverse));+ bounds.expandByPoint(joint.node.getWorldPosition(new THREE22.Vector3).applyMatrix4(inverse));}if (bounds.isEmpty())return 1;- const size = bounds.getSize(new THREE21.Vector3);+ const size = bounds.getSize(new THREE22.Vector3);return Math.max(size.x, size.y, size.z, 1);}function heldItemMotionFindings(input, root, clips) {@@ -20642,8 +20670,8 @@ function heldItemMotionFindings(input, root, clips) {if (!cloneItem || !cloneAttachment)continue;const inverse = clone.matrixWorld.clone().invert();- const itemPoint = cloneItem.getWorldPosition(new THREE21.Vector3).applyMatrix4(inverse);- const gripPoint = cloneAttachment.getWorldPosition(new THREE21.Vector3).applyMatrix4(inverse);+ const itemPoint = cloneItem.getWorldPosition(new THREE22.Vector3).applyMatrix4(inverse);+ const gripPoint = cloneAttachment.getWorldPosition(new THREE22.Vector3).applyMatrix4(inverse);const distance = itemPoint.distanceTo(gripPoint);baseline ??= distance;const drift = Math.abs(distance - baseline);@@ -20676,7 +20704,7 @@ function heldItemMotionFindings(input, root, clips) {function inspectRig(context) {if (!context.rig)return [];- const root = context.scene instanceof THREE21.Object3D ? context.scene : undefined;+ const root = context.scene instanceof THREE22.Object3D ? context.scene : undefined;const clips = (context.clips ?? []).filter(isClipLike);const findings = [];if (root) {@@ -20726,7 +20754,7 @@ var init_character2 = __esm(() => {});// src/qa/character-advisory.ts-import * as THREE22 from "three";+import * as THREE23 from "three";function isClipLike2(value) {if (typeof value !== "object" || value === null)return false;@@ -20749,16 +20777,16 @@ function jointPoints(root) {const inverse = rootInverse(root);return collectCharacterJointNodes(root).map((evidence) => ({evidence,- local: evidence.node.getWorldPosition(new THREE22.Vector3).applyMatrix4(inverse)+ local: evidence.node.getWorldPosition(new THREE23.Vector3).applyMatrix4(inverse)}));}function characterScale(points) {if (points.length === 0)return 1;- const bounds = new THREE22.Box3;+ const bounds = new THREE23.Box3;for (const point of points)bounds.expandByPoint(point.local);- const size = bounds.getSize(new THREE22.Vector3);+ const size = bounds.getSize(new THREE23.Vector3);return Math.max(size.x, size.y, size.z, 1);}function pairKey(descriptor) {@@ -20857,12 +20885,12 @@ function restChainFindings(context, root) {}function forwardMarkerFindings(context, root) {root.updateMatrixWorld(true);- const expected = new THREE22.Vector3(1, 0, 0).transformDirection(root.matrixWorld);+ const expected = new THREE23.Vector3(1, 0, 0).transformDirection(root.matrixWorld);const markers = collectCharacterJointNodes(root).filter((joint) => /(?:^|[._-])(?:toe|muzzle|head)(?:$|[._-])/i.test(joint.descriptor.role));return markers.flatMap((marker) => {- const quaternion = marker.node.getWorldQuaternion(new THREE22.Quaternion);- const actual = new THREE22.Vector3(...marker.descriptor.localForwardAxis).applyQuaternion(quaternion).normalize();- const angle = THREE22.MathUtils.radToDeg(Math.acos(THREE22.MathUtils.clamp(actual.dot(expected), -1, 1)));+ const quaternion = marker.node.getWorldQuaternion(new THREE23.Quaternion);+ const actual = new THREE23.Vector3(...marker.descriptor.localForwardAxis).applyQuaternion(quaternion).normalize();+ const angle = THREE23.MathUtils.radToDeg(Math.acos(THREE23.MathUtils.clamp(actual.dot(expected), -1, 1)));if (angle <= FORWARD_ANGLE_DEGREES)return [];return [@@ -20916,7 +20944,7 @@ function sampleClip(root, clip) {byRole: new Map(collectCharacterJointNodes(clone).map((evidence) => [evidence.descriptor.role,{- point: evidence.node.getWorldPosition(new THREE22.Vector3).applyMatrix4(inverse),+ point: evidence.node.getWorldPosition(new THREE23.Vector3).applyMatrix4(inverse),evidence}]))@@ -21028,12 +21056,12 @@ function phaseOppositionFindings(context, root, clips) {return findings;}function signedBendDegrees(descriptor, quaternion) {- const rest = new THREE22.Quaternion(...descriptor.rest.rotation);+ const rest = new THREE23.Quaternion(...descriptor.rest.rotation);const delta = rest.invert().multiply(quaternion).normalize();- const axis = new THREE22.Vector3(delta.x, delta.y, delta.z);- const signedMagnitude = axis.dot(new THREE22.Vector3(...descriptor.localBendAxis));+ const axis = new THREE23.Vector3(delta.x, delta.y, delta.z);+ const signedMagnitude = axis.dot(new THREE23.Vector3(...descriptor.localBendAxis));const angle = 2 * Math.atan2(signedMagnitude, delta.w);- return THREE22.MathUtils.radToDeg(THREE22.MathUtils.euclideanModulo(angle + Math.PI, Math.PI * 2) - Math.PI);+ return THREE23.MathUtils.radToDeg(THREE23.MathUtils.euclideanModulo(angle + Math.PI, Math.PI * 2) - Math.PI);}function bendDirectionFindings(context, root, clips) {const joints = collectCharacterJointNodes(root).filter((joint) => /(?:^|[._-])(?:knee|elbow)(?:$|[._-])/i.test(joint.descriptor.role));@@ -21047,7 +21075,7 @@ function bendDirectionFindings(context, root, clips) {let maximumFraction = 0;for (const fraction of SAMPLE_FRACTIONS) {const value = track.createInterpolant().evaluate(fraction * clip.duration);- const bend = signedBendDegrees(joint.descriptor, new THREE22.Quaternion().fromArray(value).normalize());+ const bend = signedBendDegrees(joint.descriptor, new THREE23.Quaternion().fromArray(value).normalize());if (Math.abs(bend) > Math.abs(maximum)) {maximum = bend;maximumFraction = fraction;@@ -21130,7 +21158,7 @@ function footSlideFindings(context, root, clips) {return findings;}function inspectRigAdvisory(context) {- if (!context.rig || !(context.scene instanceof THREE22.Object3D)) {+ if (!context.rig || !(context.scene instanceof THREE23.Object3D)) {return [];}const root = context.scene;@@ -21249,7 +21277,7 @@ var init_architecture_repairs = __esm(() => {});// src/qa/architecture.ts-import * as THREE23 from "three";+import * as THREE24 from "three";function hasRoofDimensions(value) {return value.footprint !== undefined && value.roof?.ridgeAxis !== undefined && value.roof.rise !== undefined && value.roof.overhang !== undefined;}@@ -21259,7 +21287,7 @@ function semanticMetadata(node) {function markerBounds(matrix) {const bounds = emptyBounds();for (let corner = 0;corner < 8; corner++) {- expandBounds(bounds, new THREE23.Vector3(corner & 1 ? 0.5 : -0.5, corner & 2 ? 0.5 : -0.5, corner & 4 ? 0.5 : -0.5).applyMatrix4(matrix));+ expandBounds(bounds, new THREE24.Vector3(corner & 1 ? 0.5 : -0.5, corner & 2 ? 0.5 : -0.5, corner & 4 ? 0.5 : -0.5).applyMatrix4(matrix));}return bounds;}@@ -21268,7 +21296,7 @@ function geometryPlaneNormal(geometry, relativeMatrix) {const local = geometry.boundingBox;if (!local)return;- const size = local.getSize(new THREE23.Vector3);+ const size = local.getSize(new THREE24.Vector3);const dimensions = [["x", size.x],["y", size.y],@@ -21278,7 +21306,7 @@ function geometryPlaneNormal(geometry, relativeMatrix) {const axis = dimensions[0]?.[0];if (!axis)return;- const normal = new THREE23.Vector3(axis === "x" ? 1 : 0, axis === "y" ? 1 : 0, axis === "z" ? 1 : 0).transformDirection(relativeMatrix);+ const normal = new THREE24.Vector3(axis === "x" ? 1 : 0, axis === "y" ? 1 : 0, axis === "z" ? 1 : 0).transformDirection(relativeMatrix);if (normal.y < 0)normal.multiplyScalar(-1);return normal.normalize();@@ -21290,7 +21318,7 @@ function geometryEvidence(geometry, relativeMatrix) {if (position?.itemSize !== 3)return { bounds, vertices, triangles: [] };for (let index = 0;index < position.count; index++) {- const point = new THREE23.Vector3(position.getX(index), position.getY(index), position.getZ(index));+ const point = new THREE24.Vector3(position.getX(index), position.getY(index), position.getZ(index));point.applyMatrix4(relativeMatrix);vertices.push(point);expandBounds(bounds, point);@@ -21317,7 +21345,7 @@ function geometryEvidence(geometry, relativeMatrix) {return { bounds, vertices, triangles, ...planeNormal ? { planeNormal } : {} };}function collectArchitectureEvidence(scene) {- if (!(scene instanceof THREE23.Object3D))+ if (!(scene instanceof THREE24.Object3D))return;scene.updateMatrixWorld(true);const rootInverse = scene.matrixWorld.clone().invert();@@ -21337,7 +21365,7 @@ function collectArchitectureEvidence(scene) {const nodePath = parentPath ? `${parentPath}/${segment}` : segment;const relativeMatrix = rootInverse.clone().multiply(node.matrixWorld);const mesh = node;- const isMesh = mesh.isMesh === true && mesh.geometry instanceof THREE23.BufferGeometry;+ const isMesh = mesh.isMesh === true && mesh.geometry instanceof THREE24.BufferGeometry;const evidence = isMesh ? geometryEvidence(mesh.geometry, relativeMatrix) : {bounds: markerBounds(relativeMatrix),vertices: [],@@ -21396,7 +21424,7 @@ function architectureFinding(context, value) {function averageNormal(normals) {if (normals.length === 0)return;- const result = normals.reduce((sum, normal) => sum.add(normal), new THREE23.Vector3);+ const result = normals.reduce((sum, normal) => sum.add(normal), new THREE24.Vector3);return result.lengthSq() > EPSILON2 ? result.normalize() : undefined;}function intervalCoverage(min, max, expectedMin, expectedMax) {@@ -22107,8 +22135,8 @@ function evaluateArchitectureQa(context) {});}var PROFILE_RULE_ID2 = "ARCHITECTURE_PROFILE", EPSILON2 = 0.000001, ARCHITECTURE_REALISTIC_SCALE_BANDS, emptyBounds = () => ({- min: new THREE23.Vector3(Infinity, Infinity, Infinity),- max: new THREE23.Vector3(-Infinity, -Infinity, -Infinity)+ min: new THREE24.Vector3(Infinity, Infinity, Infinity),+ max: new THREE24.Vector3(-Infinity, -Infinity, -Infinity)}), expandBounds = (bounds, point) => {bounds.min.min(point);bounds.max.max(point);@@ -22152,7 +22180,7 @@ var init_architecture = __esm(() => {});// src/qa/environment.ts-import * as THREE24 from "three";+import * as THREE25 from "three";function finding5(context, value) {return { ...value, profile: context.profile ?? "asset.requirements.v1" };}@@ -22171,11 +22199,11 @@ function nodePath4(root, node) {return names.reverse().join("/");}function transformedBox2(source, transform) {- const result = new THREE24.Box3;+ const result = new THREE25.Box3;for (const x of [source.min.x, source.max.x]) {for (const y of [source.min.y, source.max.y]) {for (const z of [source.min.z, source.max.z]) {- result.expandByPoint(new THREE24.Vector3(x, y, z).applyMatrix4(transform));+ result.expandByPoint(new THREE25.Vector3(x, y, z).applyMatrix4(transform));}}}@@ -22184,16 +22212,16 @@ function transformedBox2(source, transform) {function orientedBoxFromLocalBounds(root, node, source, relative = root.matrixWorld.clone().invert().multiply(node.matrixWorld)) {if (!relative.elements.every(Number.isFinite))return;- const position = new THREE24.Vector3;- const rotation = new THREE24.Quaternion;- const scale = new THREE24.Vector3;+ const position = new THREE25.Vector3;+ const rotation = new THREE25.Quaternion;+ const scale = new THREE25.Vector3;relative.decompose(position, rotation, scale);- const recomposed = new THREE24.Matrix4().compose(position, rotation, scale);+ const recomposed = new THREE25.Matrix4().compose(position, rotation, scale);const residual = Math.max(...relative.elements.map((component, index) => Math.abs(component - (recomposed.elements[index] ?? component))));if (residual > 0.00001)return;- const center = source.getCenter(new THREE24.Vector3).applyMatrix4(relative);- const sourceHalf = source.getSize(new THREE24.Vector3).multiplyScalar(0.5);+ const center = source.getCenter(new THREE25.Vector3).applyMatrix4(relative);+ const sourceHalf = source.getSize(new THREE25.Vector3).multiplyScalar(0.5);const halfExtents = [Math.abs(sourceHalf.x * scale.x),Math.abs(sourceHalf.y * scale.y),@@ -22214,24 +22242,24 @@ function collectParts4(root) {const result = [];root.traverseVisible((node) => {const roles = rolesOf3(node);- const renderable = node instanceof THREE24.Mesh;+ const renderable = node instanceof THREE25.Mesh;let box;let orientedBox;let source;- if (renderable && node.geometry instanceof THREE24.BufferGeometry) {+ if (renderable && node.geometry instanceof THREE25.BufferGeometry) {node.geometry.computeBoundingBox();if (node.geometry.boundingBox) {source = node.geometry.boundingBox;}} else if (roles.length > 0) {- source = new THREE24.Box3(new THREE24.Vector3(-0.5, -0.5, -0.5), new THREE24.Vector3(0.5, 0.5, 0.5));+ source = new THREE25.Box3(new THREE25.Vector3(-0.5, -0.5, -0.5), new THREE25.Vector3(0.5, 0.5, 0.5));}const relative = rootInverse.clone().multiply(node.matrixWorld);- const count = node instanceof THREE24.InstancedMesh ? node.count : 1;+ const count = node instanceof THREE25.InstancedMesh ? node.count : 1;for (let index = 0;index < count; index++) {const transform = relative.clone();- if (node instanceof THREE24.InstancedMesh) {- const instance = new THREE24.Matrix4;+ if (node instanceof THREE25.InstancedMesh) {+ const instance = new THREE25.Matrix4;node.getMatrixAt(index, instance);transform.multiply(instance);}@@ -22262,9 +22290,9 @@ function resolveSocket(root, node, socket) {return;root.updateWorldMatrix(true, true);const rootInverse = root.matrixWorld.clone().invert();- const point = new THREE24.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);- const rootInverseQuaternion = root.getWorldQuaternion(new THREE24.Quaternion).invert();- const rotation = node.getWorldQuaternion(new THREE24.Quaternion).multiply(new THREE24.Quaternion(...frame.rotation)).premultiply(rootInverseQuaternion).normalize();+ const point = new THREE25.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);+ const rootInverseQuaternion = root.getWorldQuaternion(new THREE25.Quaternion).invert();+ const rotation = node.getWorldQuaternion(new THREE25.Quaternion).multiply(new THREE25.Quaternion(...frame.rotation)).premultiply(rootInverseQuaternion).normalize();return {id: socket.id,type: socket.type,@@ -22293,7 +22321,7 @@ function socketByType(sockets, type) {return sockets.find((socket) => socket.type === type);}function inspectPlacementSockets(context) {- if (!(context.scene instanceof THREE24.Object3D)) {+ if (!(context.scene instanceof THREE25.Object3D)) {return [];}const root = context.scene;@@ -22357,7 +22385,7 @@ function materialSignature(material) {function boundarySamples(root, axis, side, bins = 12) {root.updateWorldMatrix(true, true);const inverse = root.matrixWorld.clone().invert();- const localBounds = new THREE24.Box3;+ const localBounds = new THREE25.Box3;for (const part of collectParts4(root))if (part.renderable && part.box)localBounds.union(part.box);@@ -22371,30 +22399,30 @@ function boundarySamples(root, axis, side, bins = 12) {const crossExtent = Math.max(0.000000001, localBounds.max[crossAxis] - crossMin);const byBin = new Map;root.traverseVisible((node) => {- if (!(node instanceof THREE24.Mesh) || !(node.geometry instanceof THREE24.BufferGeometry))+ if (!(node instanceof THREE25.Mesh) || !(node.geometry instanceof THREE25.BufferGeometry))return;const positions = node.geometry.getAttribute("position");if (positions?.itemSize !== 3)return;const normals = node.geometry.getAttribute("normal");const relative = inverse.clone().multiply(node.matrixWorld);- const count = node instanceof THREE24.InstancedMesh ? node.count : 1;+ const count = node instanceof THREE25.InstancedMesh ? node.count : 1;for (let instanceIndex = 0;instanceIndex < count; instanceIndex++) {const transform = relative.clone();- if (node instanceof THREE24.InstancedMesh) {- const instance = new THREE24.Matrix4;+ if (node instanceof THREE25.InstancedMesh) {+ const instance = new THREE25.Matrix4;node.getMatrixAt(instanceIndex, instance);transform.multiply(instance);}- const normalMatrix = new THREE24.Matrix3().getNormalMatrix(transform);+ const normalMatrix = new THREE25.Matrix3().getNormalMatrix(transform);const material = materialSignature(node.material);for (let index = 0;index < positions.count; index++) {- const point = new THREE24.Vector3(positions.getX(index), positions.getY(index), positions.getZ(index)).applyMatrix4(transform);+ const point = new THREE25.Vector3(positions.getX(index), positions.getY(index), positions.getZ(index)).applyMatrix4(transform);if (Math.abs(point[axis] - edge) > band)continue;- const t = THREE24.MathUtils.clamp((point[crossAxis] - crossMin) / crossExtent, 0, 1);+ const t = THREE25.MathUtils.clamp((point[crossAxis] - crossMin) / crossExtent, 0, 1);const bin = Math.min(bins - 1, Math.floor(t * bins));- const normal = normals ? new THREE24.Vector3(normals.getX(index), normals.getY(index), normals.getZ(index)).applyMatrix3(normalMatrix).normalize() : new THREE24.Vector3(0, 1, 0);+ const normal = normals ? new THREE25.Vector3(normals.getX(index), normals.getY(index), normals.getZ(index)).applyMatrix3(normalMatrix).normalize() : new THREE25.Vector3(0, 1, 0);const current = byBin.get(bin);if (!current || point.y > current.height || point.y === current.height && normal.y > current.normal.y) {byBin.set(bin, { bin, height: point.y, normal, material });@@ -22417,7 +22445,7 @@ function edgePairMeasurements(root, axis, sockets) {...positive.map((sample) => sample.bin)]);const maximumHeightDelta = pairs.length ? Math.max(...pairs.map(([a, b]) => Math.abs(a.height - b.height))) : Number.POSITIVE_INFINITY;- const maximumNormalDeltaDegrees = pairs.length ? Math.max(...pairs.map(([a, b]) => THREE24.MathUtils.radToDeg(Math.acos(THREE24.MathUtils.clamp(a.normal.dot(b.normal), -1, 1))))) : 180;+ const maximumNormalDeltaDegrees = pairs.length ? Math.max(...pairs.map(([a, b]) => THREE25.MathUtils.radToDeg(Math.acos(THREE25.MathUtils.clamp(a.normal.dot(b.normal), -1, 1))))) : 180;const materialMismatch = pairs.some(([a, b]) => a.material !== b.material);const negativeSocket = socketByType(sockets, `environment.tile.${axis}-negative`);const positiveSocket = socketByType(sockets, `environment.tile.${axis}-positive`);@@ -22434,7 +22462,7 @@ function edgePairMeasurements(root, axis, sockets) {};}function inspectTileEdges(context) {- if (context.tileable !== true || !(context.scene instanceof THREE24.Object3D)) {+ if (context.tileable !== true || !(context.scene instanceof THREE25.Object3D)) {return [];}const root = context.scene;@@ -22517,7 +22545,7 @@ function isCorridor(part) {return part.roles.some((role) => /^environment\.(?:navigation\.)?corridor(?:\.|$)/.test(role));}function inspectNavigationClearance(context) {- if (context.navigable !== true || !(context.scene instanceof THREE24.Object3D)) {+ if (context.navigable !== true || !(context.scene instanceof THREE25.Object3D)) {return [];}const root = context.scene;@@ -22647,7 +22675,7 @@ function functionalLayer(part) {return part.roles.some((role) => role.startsWith("environment.functional") || role.startsWith("environment.layer") || role.startsWith("environment.path") || role.startsWith("environment.road") || role.startsWith("environment.bridge") || role.startsWith("environment.gate"));}function inspectSpatialSupport(context) {- if (context.groundPlaneY === undefined || !(context.scene instanceof THREE24.Object3D)) {+ if (context.groundPlaneY === undefined || !(context.scene instanceof THREE25.Object3D)) {return [];}const root = context.scene;@@ -22694,7 +22722,7 @@ function inspectSpatialSupport(context) {}));}}- const size = box.getSize(new THREE24.Vector3);+ const size = box.getSize(new THREE25.Vector3);if (box.min.y < context.groundPlaneY - 0.05 && size.y <= Math.max(0.05, Math.min(size.x, size.z) * 0.03) && Math.max(size.x, size.z) >= 1) {findings.push(finding5(context, {code: "ENV_GROUND_UNDECLARED_SKIRT",@@ -23155,7 +23183,7 @@ function writtenNodeResolver(root, doc, purpose) {// src/node-visibility.tsimport { KHRNodeVisibility } from "@gltf-transform/extensions";-import * as THREE25 from "three";+import * as THREE26 from "three";function applyNodeVisibility(root, doc) {const hidden = [];root.traverse((node) => {@@ -23198,7 +23226,7 @@ function drawnSceneBounds(scene) {return;const mesh = node.getMesh();if (mesh) {- const base = new THREE25.Matrix4().fromArray(node.getWorldMatrix());+ const base = new THREE26.Matrix4().fromArray(node.getWorldMatrix());const instances = node.getExtension("EXT_mesh_gpu_instancing");const translation = instances?.getAttribute("TRANSLATION");const rotation = instances?.getAttribute("ROTATION");@@ -23209,7 +23237,7 @@ function drawnSceneBounds(scene) {const t = translation?.getElement(i, []) ?? [0, 0, 0];const r = rotation?.getElement(i, []) ?? [0, 0, 0, 1];const s = scale?.getElement(i, []) ?? [1, 1, 1];- const localMatrix = new THREE25.Matrix4().compose(new THREE25.Vector3().fromArray(t), new THREE25.Quaternion().fromArray(r), new THREE25.Vector3().fromArray(s));+ const localMatrix = new THREE26.Matrix4().compose(new THREE26.Vector3().fromArray(t), new THREE26.Quaternion().fromArray(r), new THREE26.Vector3().fromArray(s));matrices.push(base.clone().multiply(localMatrix).toArray());}const local = [0, 0, 0];@@ -23250,12 +23278,12 @@ var init_node_visibility = __esm(() => {});// src/delivery-inspect.ts-import * as THREE26 from "three";+import * as THREE27 from "three";import { PropertyType as PropertyType2 } from "@gltf-transform/core";function decompose(matrix) {- const translation = new THREE26.Vector3;- const rotation = new THREE26.Quaternion;- const scale = new THREE26.Vector3;+ const translation = new THREE27.Vector3;+ const rotation = new THREE27.Quaternion;+ const scale = new THREE27.Vector3;matrix.decompose(translation, rotation, scale);const clean = (value) => Object.is(value, -0) ? 0 : value;return {@@ -23267,7 +23295,7 @@ function decompose(matrix) {function drawnTriangles(visited) {const values = [];const local = [0, 0, 0];- const point = new THREE26.Vector3;+ const point = new THREE27.Vector3;for (const { node, roles, hidden } of visited) {const mesh = node.getMesh();if (!mesh || hidden || roles.some((role) => role.startsWith("collider.")))@@ -23280,7 +23308,7 @@ function drawnTriangles(visited) {const copies = translation?.getCount() ?? rotation?.getCount() ?? scale?.getCount() ?? 1;const matrices = [];for (let i = 0;i < copies; i++) {- const instance = new THREE26.Matrix4().compose(new THREE26.Vector3().fromArray(translation?.getElement(i, []) ?? [0, 0, 0]), new THREE26.Quaternion().fromArray(rotation?.getElement(i, []) ?? [0, 0, 0, 1]), new THREE26.Vector3().fromArray(scale?.getElement(i, []) ?? [1, 1, 1]));+ const instance = new THREE27.Matrix4().compose(new THREE27.Vector3().fromArray(translation?.getElement(i, []) ?? [0, 0, 0]), new THREE27.Quaternion().fromArray(rotation?.getElement(i, []) ?? [0, 0, 0, 1]), new THREE27.Vector3().fromArray(scale?.getElement(i, []) ?? [1, 1, 1]));matrices.push(base.clone().multiply(instance));}for (const primitive of mesh.listPrimitives()) {@@ -23311,20 +23339,20 @@ function triangleOverlapsBox(a, b, c, h, tolerance) {return false;}const e = [- new THREE26.Vector3().subVectors(b, a),- new THREE26.Vector3().subVectors(c, b),- new THREE26.Vector3().subVectors(a, c)+ new THREE27.Vector3().subVectors(b, a),+ new THREE27.Vector3().subVectors(c, b),+ new THREE27.Vector3().subVectors(a, c)];- const normal = new THREE26.Vector3().crossVectors(e[0], e[1]);+ const normal = new THREE27.Vector3().crossVectors(e[0], e[1]);const axes = [normal];const units = [- new THREE26.Vector3(1, 0, 0),- new THREE26.Vector3(0, 1, 0),- new THREE26.Vector3(0, 0, 1)+ new THREE27.Vector3(1, 0, 0),+ new THREE27.Vector3(0, 1, 0),+ new THREE27.Vector3(0, 0, 1)];for (const unit of units)for (const edge of e)- axes.push(new THREE26.Vector3().crossVectors(unit, edge));+ axes.push(new THREE27.Vector3().crossVectors(unit, edge));for (const axis of axes) {if (axis.lengthSq() < 0.000000000000000000000001)continue;@@ -23336,14 +23364,14 @@ function triangleOverlapsBox(a, b, c, h, tolerance) {return true;}function closestPointOnTriangle(p, a, b, c) {- const ab = new THREE26.Vector3().subVectors(b, a);- const ac = new THREE26.Vector3().subVectors(c, a);- const ap = new THREE26.Vector3().subVectors(p, a);+ const ab = new THREE27.Vector3().subVectors(b, a);+ const ac = new THREE27.Vector3().subVectors(c, a);+ const ap = new THREE27.Vector3().subVectors(p, a);const d1 = ab.dot(ap);const d2 = ac.dot(ap);if (d1 <= 0 && d2 <= 0)return a.clone();- const bp = new THREE26.Vector3().subVectors(p, b);+ const bp = new THREE27.Vector3().subVectors(p, b);const d3 = ab.dot(bp);const d4 = ac.dot(bp);if (d3 >= 0 && d4 <= d3)@@ -23351,7 +23379,7 @@ function closestPointOnTriangle(p, a, b, c) {const vc = d1 * d4 - d3 * d2;if (vc <= 0 && d1 >= 0 && d3 <= 0)return a.clone().addScaledVector(ab, d1 / (d1 - d3));- const cp = new THREE26.Vector3().subVectors(p, c);+ const cp = new THREE27.Vector3().subVectors(p, c);const d5 = ab.dot(cp);const d6 = ac.dot(cp);if (d6 >= 0 && d5 <= d6)@@ -23361,14 +23389,14 @@ function closestPointOnTriangle(p, a, b, c) {return a.clone().addScaledVector(ac, d2 / (d2 - d6));const va = d3 * d6 - d5 * d4;if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0)- return b.clone().addScaledVector(new THREE26.Vector3().subVectors(c, b), (d4 - d3) / (d4 - d3 + (d5 - d6)));+ return b.clone().addScaledVector(new THREE27.Vector3().subVectors(c, b), (d4 - d3) / (d4 - d3 + (d5 - d6)));const denominator = 1 / (va + vb + vc);return a.clone().addScaledVector(ab, vb * denominator).addScaledVector(ac, vc * denominator);}function segmentSegmentDistanceSq(p1, q1, p2, q2) {- const d1 = new THREE26.Vector3().subVectors(q1, p1);- const d2 = new THREE26.Vector3().subVectors(q2, p2);- const r = new THREE26.Vector3().subVectors(p1, p2);+ const d1 = new THREE27.Vector3().subVectors(q1, p1);+ const d2 = new THREE27.Vector3().subVectors(q2, p2);+ const r = new THREE27.Vector3().subVectors(p1, p2);const a = d1.dot(d1);const e = d2.dot(d2);const f = d2.dot(r);@@ -23377,22 +23405,22 @@ function segmentSegmentDistanceSq(p1, q1, p2, q2) {if (a <= 0.000000000000000000000001 && e <= 0.000000000000000000000001)return r.lengthSq();if (a <= 0.000000000000000000000001)- t = THREE26.MathUtils.clamp(f / e, 0, 1);+ t = THREE27.MathUtils.clamp(f / e, 0, 1);else {const c = d1.dot(r);if (e <= 0.000000000000000000000001)- s = THREE26.MathUtils.clamp(-c / a, 0, 1);+ s = THREE27.MathUtils.clamp(-c / a, 0, 1);else {const b = d1.dot(d2);const denominator = a * e - b * b;- s = denominator !== 0 ? THREE26.MathUtils.clamp((b * f - c * e) / denominator, 0, 1) : 0;+ s = denominator !== 0 ? THREE27.MathUtils.clamp((b * f - c * e) / denominator, 0, 1) : 0;t = (b * s + f) / e;if (t < 0) {t = 0;- s = THREE26.MathUtils.clamp(-c / a, 0, 1);+ s = THREE27.MathUtils.clamp(-c / a, 0, 1);} else if (t > 1) {t = 1;- s = THREE26.MathUtils.clamp((b - c) / a, 0, 1);+ s = THREE27.MathUtils.clamp((b - c) / a, 0, 1);}}}@@ -23401,8 +23429,8 @@ function segmentSegmentDistanceSq(p1, q1, p2, q2) {return c1.distanceToSquared(c2);}function segmentCrossesTriangle(p, q, a, b, c) {- const hit = new THREE26.Vector3;- const ray = new THREE26.Ray(p, new THREE26.Vector3().subVectors(q, p));+ const hit = new THREE27.Vector3;+ const ray = new THREE27.Ray(p, new THREE27.Vector3().subVectors(q, p));const length = ray.direction.length();if (length === 0)return false;@@ -23519,9 +23547,9 @@ function inspectDelivery(doc) {visit(scene.listChildren(), segment3(scene.getName() || "Scene", 0), false, undefined);const finding = (code, path, message) => summary.diagnostics.push({ code, path, message });const { min, max } = drawnSceneBounds(scene);- const bounds = new THREE26.Box3(new THREE26.Vector3(...min), new THREE26.Vector3(...max));+ const bounds = new THREE27.Box3(new THREE27.Vector3(...min), new THREE27.Vector3(...max));const finiteBounds = [...min, ...max].every(Number.isFinite);- const diagonal = finiteBounds ? bounds.getSize(new THREE26.Vector3).length() : 0;+ const diagonal = finiteBounds ? bounds.getSize(new THREE27.Vector3).length() : 0;const tolerance = Math.max(0.0001, diagonal * 0.0001);const colliderNodes = [];for (const entry of visited) {@@ -23600,23 +23628,23 @@ function inspectDelivery(doc) {const triangles = colliderNodes.some(({ record }) => record.shape.kind !== "hull") ? drawnTriangles(visited) : new Float64Array;const triangleCount = triangles.length / 9;let overlapTests = 0;- const a = new THREE26.Vector3;- const b = new THREE26.Vector3;- const c = new THREE26.Vector3;+ const a = new THREE27.Vector3;+ const b = new THREE27.Vector3;+ const c = new THREE27.Vector3;for (const { visit: entry, record } of colliderNodes) {if (!entry.hidden)finding("DELIVERY_COLLIDER_NOT_HIDDEN", record.path, "collider proxy draws; hide it (the delivery helpers do) so importers that ignore roles draw only the asset.");const matrix = worldMatrix(entry.node);- const proxyBounds = new THREE26.Box3;+ const proxyBounds = new THREE27.Box3;const mesh = entry.node.getMesh();const local = [0, 0, 0];for (const primitive of mesh?.listPrimitives() ?? []) {const position = primitive.getAttribute("POSITION");for (let i = 0;i < (position?.getCount() ?? 0); i++)- proxyBounds.expandByPoint(new THREE26.Vector3().fromArray(position.getElement(i, local)).applyMatrix4(matrix));+ proxyBounds.expandByPoint(new THREE27.Vector3().fromArray(position.getElement(i, local)).applyMatrix4(matrix));}if (proxyBounds.isEmpty())- proxyBounds.expandByPoint(new THREE26.Vector3().setFromMatrixPosition(matrix));+ proxyBounds.expandByPoint(new THREE27.Vector3().setFromMatrixPosition(matrix));const expanded = bounds.clone().expandByScalar(tolerance);if (!finiteBounds || !expanded.containsBox(proxyBounds))finding("DELIVERY_COLLIDER_OUTSIDE_BOUNDS", record.path, "collider proxy reaches outside the bounds of the drawn asset.");@@ -23627,11 +23655,11 @@ function inspectDelivery(doc) {continue;}overlapTests += triangleCount;- const toLocal = new THREE26.Matrix4;+ const toLocal = new THREE27.Matrix4;let touches = false;if (record.shape.kind === "box") {toLocal.copy(matrix).invert();- const half = new THREE26.Vector3(0.5, 0.5, 0.5);+ const half = new THREE27.Vector3(0.5, 0.5, 0.5);const scale = Math.max(...record.transform.scale.map(Math.abs), 0.000000001);for (let t = 0;t < triangleCount && !touches; t++) {a.fromArray(triangles, t * 9).applyMatrix4(toLocal);@@ -23641,10 +23669,10 @@ function inspectDelivery(doc) {}} else {const { translation, rotation } = record.transform;- toLocal.compose(new THREE26.Vector3(...translation), new THREE26.Quaternion(...rotation), new THREE26.Vector3(1, 1, 1)).invert();+ toLocal.compose(new THREE27.Vector3(...translation), new THREE27.Quaternion(...rotation), new THREE27.Vector3(1, 1, 1)).invert();const { radius, height } = record.shape;- const p = new THREE26.Vector3(0, -height / 2 + radius, 0);- const q = new THREE26.Vector3(0, height / 2 - radius, 0);+ const p = new THREE27.Vector3(0, -height / 2 + radius, 0);+ const q = new THREE27.Vector3(0, height / 2 - radius, 0);for (let t = 0;t < triangleCount && !touches; t++) {a.fromArray(triangles, t * 9).applyMatrix4(toLocal);b.fromArray(triangles, t * 9 + 3).applyMatrix4(toLocal);@@ -23663,7 +23691,7 @@ function inspectDelivery(doc) {finding("DELIVERY_PORT_WITHOUT_MODULE", record.path, "port is not under a valid kit module; place ports under the root defineModule marked.");continue;}- const point = new THREE26.Vector3(...record.transform.translation).applyMatrix4(worldMatrix(moduleEntry.node).invert());+ const point = new THREE27.Vector3(...record.transform.translation).applyMatrix4(worldMatrix(moduleEntry.node).invert());const [width, depth] = spec.footprint;const [x0, x1, z0, z1] = spec.origin === "corner" ? [0, width, 0, depth] : [-width / 2, width / 2, -depth / 2, depth / 2];const slack = Math.max(0.0001, Math.max(width, depth, spec.height) * 0.00001);@@ -23677,7 +23705,7 @@ function inspectDelivery(doc) {}return summary;}-var DELIVERY_OVERLAP_TEST_LIMIT = 50000000, segment3 = (name, occurrence) => `/${encodeURIComponent(name)}[${occurrence}]`, roleTail = (role, base) => role.startsWith(`${base}.`) ? role.slice(base.length + 1) : undefined, worldMatrix = (node) => new THREE26.Matrix4().fromArray(node.getWorldMatrix());+var DELIVERY_OVERLAP_TEST_LIMIT = 50000000, segment3 = (name, occurrence) => `/${encodeURIComponent(name)}[${occurrence}]`, roleTail = (role, base) => role.startsWith(`${base}.`) ? role.slice(base.length + 1) : undefined, worldMatrix = (node) => new THREE27.Matrix4().fromArray(node.getWorldMatrix());var init_delivery_inspect = __esm(() => {init_gltf_io();init_semantic();@@ -24491,7 +24519,7 @@ var init_requirements_run = __esm(() => {});// src/qa/skin-integrity.ts-import * as THREE27 from "three";+import * as THREE28 from "three";function validAttribute(a, count, size) {if (!a || a.itemSize !== size || a.count !== count || !Number.isSafeInteger(count) || count < 1)return false;@@ -24538,9 +24566,9 @@ function inspectSkinIntegrity(root) {}while (chain.length) {const n = chain.pop();- const local = n.matrixAutoUpdate ? new THREE27.Matrix4().compose(n.position, n.quaternion, n.scale) : n.matrix.clone();+ const local = n.matrixAutoUpdate ? new THREE28.Matrix4().compose(n.position, n.quaternion, n.scale) : n.matrix.clone();const parent = n.parent ? worlds.get(n.parent) : undefined;- const value = n.matrixWorldAutoUpdate === false ? n.matrixWorld.clone() : parent ? new THREE27.Matrix4().multiplyMatrices(parent, local) : local;+ const value = n.matrixWorldAutoUpdate === false ? n.matrixWorld.clone() : parent ? new THREE28.Matrix4().multiplyMatrices(parent, local) : local;worlds.set(n, value);}return worlds.get(node);@@ -24590,7 +24618,7 @@ function inspectSkinIntegrity(root) {if (result.truncated)break;}- if (!finiteAffine(mesh.bindMatrix) || !Number.isFinite(mesh.bindMatrix.determinant()) || mesh.bindMatrix.determinant() === 0 || ![THREE27.AttachedBindMode, THREE27.DetachedBindMode].includes(mesh.bindMode)) {+ if (!finiteAffine(mesh.bindMatrix) || !Number.isFinite(mesh.bindMatrix.determinant()) || mesh.bindMatrix.determinant() === 0 || ![THREE28.AttachedBindMode, THREE28.DetachedBindMode].includes(mesh.bindMode)) {add("SKIN_BIND_MATRIX", "Mesh requires a finite invertible affine bind matrix and an attached or detached bind mode.", "bindMatrix");}const position = mesh.geometry?.getAttribute("position"), count = position?.count ?? 0;@@ -24639,7 +24667,7 @@ function inspectSkinIntegrity(root) {add("SKIN_POSE_TRANSFORM", "Current mesh world transform must be finite and affine.");continue;}- const inverse = mesh.bindMode === THREE27.AttachedBindMode ? meshWorld.clone().invert() : mesh.bindMatrix.clone().invert();+ const inverse = mesh.bindMode === THREE28.AttachedBindMode ? meshWorld.clone().invert() : mesh.bindMatrix.clone().invert();const matrices = [];for (let joint = 0;joint < bones.length; joint++) {const boneWorld = world(bones[joint]);@@ -24647,13 +24675,13 @@ function inspectSkinIntegrity(root) {add("SKIN_POSE_TRANSFORM", `Current transform for joint ${joint} must be finite and affine.`, `joints[${joint}]`);break;}- matrices.push(new THREE27.Matrix4().multiplyMatrices(boneWorld, skeleton.boneInverses[joint]).multiply(mesh.bindMatrix));+ matrices.push(new THREE28.Matrix4().multiplyMatrices(boneWorld, skeleton.boneInverses[joint]).multiply(mesh.bindMatrix));}if (result.findings.length !== start)continue;- const base = new THREE27.Vector3, posed = new THREE27.Vector3, temp = new THREE27.Vector3, box = new THREE27.Box3;+ const base = new THREE28.Vector3, posed = new THREE28.Vector3, temp = new THREE28.Vector3, box = new THREE28.Box3;for (let vertex = 0;vertex < count; vertex++) {- THREE27.Mesh.prototype.getVertexPosition.call(mesh, vertex, base);+ THREE28.Mesh.prototype.getVertexPosition.call(mesh, vertex, base);posed.set(0, 0, 0);for (let lane = 0;lane < 4; lane++) {const weight = weights.getComponent(vertex, lane);@@ -24850,7 +24878,7 @@ var init_material_export = __esm(() => {});// src/community-exporter.ts-import * as THREE28 from "three";+import * as THREE29 from "three";import { GLTFExporter } from "three/addons/exporters/GLTFExporter.js";import { GLB_BUFFER } from "@gltf-transform/core";function resolveGltfExporter(value = typeof process !== "undefined" ? process.env["KILN_GLTF_EXPORTER"] : undefined) {@@ -24880,7 +24908,7 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, areturn found;const copy = cleanClone(source);normalizeTextureTransform(copy);- copy.source = new THREE28.TextureSource(source.image);+ copy.source = new THREE29.TextureSource(source.image);textures.set(source, copy);const bytes = source.userData["encoded"];if (bytes?.bytes) {@@ -24889,8 +24917,8 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, aencoded.push((async () => {copy.image = await platform.decode(bytes.bytes);Object.defineProperty(copy, "isDataTexture", { value: true });- copy.format = THREE28.RGBAFormat;- copy.type = THREE28.UnsignedByteType;+ copy.format = THREE29.RGBAFormat;+ copy.type = THREE29.UnsignedByteType;})());}return copy;@@ -24907,7 +24935,7 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, aphysical.sheen = 1;}for (const [key, value] of Object.entries(copy)) {- if (value instanceof THREE28.Texture)+ if (value instanceof THREE29.Texture)copy[key] = texture(value);}materials.set(source, copy);@@ -24923,15 +24951,15 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, aif (!copy.matrixAutoUpdate)copy.matrix.decompose(copy.position, copy.quaternion, copy.scale);if (source.isScene) {- copy = new THREE28.Group;+ copy = new THREE29.Group;copy.copy(shadow, false);}if (source.isSprite) {const sprite = source;- const geometry = new THREE28.PlaneGeometry(1, 1);+ const geometry = new THREE29.PlaneGeometry(1, 1);geometry.translate(0.5 - sprite.center.x, 0.5 - sprite.center.y, 0);geometry.rotateZ(sprite.material.rotation);- const spriteMaterial = new THREE28.MeshBasicMaterial({+ const spriteMaterial = new THREE29.MeshBasicMaterial({name: sprite.material.name,color: sprite.material.color,opacity: sprite.material.opacity,@@ -24942,8 +24970,8 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, a});Object.assign(spriteMaterial.userData, authorExtras?.material(sprite.material));originalMaterials.set(spriteMaterial, sprite.material);- copy = new THREE28.Mesh(geometry, spriteMaterial);- THREE28.Object3D.prototype.copy.call(copy, shadow, false);+ copy = new THREE29.Mesh(geometry, spriteMaterial);+ THREE29.Object3D.prototype.copy.call(copy, shadow, false);}Object.assign(copy.userData, authorExtras?.node(source), rigExtrasForExport(source), openShellExtras(source), kitExtras(source), repeatInstancesExtras(source));const semantic = source.userData[KILN_SEMANTIC_EXTRAS_KEY];@@ -25007,8 +25035,8 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, aif (!context)throw new Error("A 2D canvas is required to prepare export texture channels.");context.putImageData(new ImageData(new Uint8ClampedArray(data), width, height), 0, 0);- const adapted = new THREE28.Texture().copy(map);- adapted.source = new THREE28.TextureSource(canvas);+ const adapted = new THREE29.Texture().copy(map);+ adapted.source = new THREE29.TextureSource(canvas);canvasInputs.set(map, adapted);const direct = directImages.get(map);if (direct)@@ -25017,7 +25045,7 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, a};for (const material of materials.values()) {for (const [key, value] of Object.entries(material)) {- if (value instanceof THREE28.Texture && value.flipY && value.image?.data)+ if (value instanceof THREE29.Texture && value.flipY && value.image?.data)material[key] = canvasInput(value);}const standard = material;@@ -25039,8 +25067,8 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, a}cloned.tracks = cloned.tracks.filter((track) => {try {- const binding = THREE28.PropertyBinding.parseTrackName(track.name);- return ["position", "quaternion", "scale", "morphTargetInfluences"].includes(binding.propertyName) && THREE28.PropertyBinding.findNode(copy, binding.nodeName) !== null;+ const binding = THREE29.PropertyBinding.parseTrackName(track.name);+ return ["position", "quaternion", "scale", "morphTargetInfluences"].includes(binding.propertyName) && THREE29.PropertyBinding.findNode(copy, binding.nodeName) !== null;} catch {return false;}@@ -25235,7 +25263,7 @@ function applyIndexPolicy(doc, policy) {var init_index_policy = () => {};// src/surface-bake.ts-import * as THREE29 from "three";+import * as THREE30 from "three";function settings(value, label) {if (value === false)return;@@ -25277,13 +25305,13 @@ function drawnMeshes(root) {function weld(mesh) {const position = mesh.geometry.getAttribute("position");const world = [];- const box = new THREE29.Box3;+ const box = new THREE30.Box3;for (let i = 0;i < position.count; i++) {- const point = new THREE29.Vector3().fromBufferAttribute(position, i).applyMatrix4(mesh.matrixWorld);+ const point = new THREE30.Vector3().fromBufferAttribute(position, i).applyMatrix4(mesh.matrixWorld);world.push(point);box.expandByPoint(point);}- const size = box.isEmpty() ? 0 : box.getSize(new THREE29.Vector3).length();+ const size = box.isEmpty() ? 0 : box.getSize(new THREE30.Vector3).length();const tolerance = size > 0 ? size * 0.000001 : 0.000000001;const keys = new Map;const ids = new Int32Array(position.count);@@ -25317,7 +25345,7 @@ function bakeEdge(topology, thresholdDegrees, smoothing) {const a = points[triangles[t]];const b = points[triangles[t + 1]];const c = points[triangles[t + 2]];- normals.push(new THREE29.Vector3().subVectors(b, a).cross(new THREE29.Vector3().subVectors(c, a)).normalize());+ normals.push(new THREE30.Vector3().subVectors(b, a).cross(new THREE30.Vector3().subVectors(c, a)).normalize());}const edges = new Map;const neighbours = points.map(() => new Set);@@ -25336,7 +25364,7 @@ function bakeEdge(topology, thresholdDegrees, smoothing) {edges.set(key, list);}}- const threshold = THREE29.MathUtils.degToRad(thresholdDegrees);+ const threshold = THREE30.MathUtils.degToRad(thresholdDegrees);const weights = new Float64Array(points.length);for (const [key, incidences] of edges) {let weight;@@ -25346,10 +25374,10 @@ function bakeEdge(topology, thresholdDegrees, smoothing) {const [[f1], [f2, opposite2]] = incidences;const n1 = normals[f1];const n2 = normals[f2];- const angle = Math.acos(THREE29.MathUtils.clamp(n1.dot(n2), -1, 1));+ const angle = Math.acos(THREE30.MathUtils.clamp(n1.dot(n2), -1, 1));const [u] = key.split(":").map(Number);const scale = Math.max(points[u].distanceTo(points[opposite2]), 0.000000000001);- const side = new THREE29.Vector3().subVectors(points[opposite2], points[u]).dot(n1) / scale;+ const side = new THREE30.Vector3().subVectors(points[opposite2], points[u]).dot(n1) / scale;weight = side < -0.000000001 ? smoothstep2(threshold / 2, threshold, angle) : 0;}for (const id of key.split(":").map(Number))@@ -25511,12 +25539,12 @@ function hemisphereDirections(count) {const phi = i * golden;const x = r * Math.cos(phi);const y = r * Math.sin(phi);- return new THREE29.Vector3(x, y, Math.sqrt(Math.max(0, 1 - x * x - y * y)));+ return new THREE30.Vector3(x, y, Math.sqrt(Math.max(0, 1 - x * x - y * y)));});}function occluderTriangles(occluders, bakedTier) {const values = [];- const point = new THREE29.Vector3;+ const point = new THREE30.Vector3;for (const mesh of drawnMeshes(occluders)) {if (!drawn(mesh, null))continue;@@ -25580,12 +25608,12 @@ function bakeSurfaceAttributes(target, options = {}) {let entry = bvhs.get(key);if (!entry) {const triangles = occluderTriangles(occluders, tier);- const box = new THREE29.Box3;+ const box = new THREE30.Box3;for (let i = 0;i < triangles.length; i += 3)- box.expandByPoint(new THREE29.Vector3(triangles[i], triangles[i + 1], triangles[i + 2]));+ box.expandByPoint(new THREE30.Vector3(triangles[i], triangles[i + 1], triangles[i + 2]));entry = {bvh: new TriangleBvh(triangles),- diagonal: box.isEmpty() ? 0 : box.getSize(new THREE29.Vector3).length()+ diagonal: box.isEmpty() ? 0 : box.getSize(new THREE30.Vector3).length()};bvhs.set(key, entry);}@@ -25602,27 +25630,27 @@ function bakeSurfaceAttributes(target, options = {}) {const welded = bakeEdge(topology, thresholdDegrees, smoothing);const values = new Float32Array(sourceCount);for (let i = 0;i < sourceCount; i++)- values[i] = THREE29.MathUtils.clamp(welded[topology.ids[i]], 0, 1);- geometry.setAttribute("_edge", new THREE29.BufferAttribute(values, 1));+ values[i] = THREE30.MathUtils.clamp(welded[topology.ids[i]], 0, 1);+ geometry.setAttribute("_edge", new THREE30.BufferAttribute(values, 1));record._EDGE = { thresholdDegrees, smoothing };}if (cavityOptions) {const { bvh, diagonal } = occlusion(tierOf(mesh));const radius = cavityOptions.radius ?? SURFACE_BAKE_DEFAULTS.cavity.radiusFactor * diagonal;const epsilon = Math.max(diagonal * 0.00001, 0.0000001);- const normals = topology.points.map(() => new THREE29.Vector3);+ const normals = topology.points.map(() => new THREE30.Vector3);const { points, triangles } = topology;for (let t = 0;t < triangles.length; t += 3) {const a = points[triangles[t]];- const face = new THREE29.Vector3().subVectors(points[triangles[t + 1]], a).cross(new THREE29.Vector3().subVectors(points[triangles[t + 2]], a));+ const face = new THREE30.Vector3().subVectors(points[triangles[t + 1]], a).cross(new THREE30.Vector3().subVectors(points[triangles[t + 2]], a));for (let k = 0;k < 3; k++)normals[triangles[t + k]].add(face);}const exposure = new Float64Array(points.length);- const tangent = new THREE29.Vector3;- const bitangent = new THREE29.Vector3;- const origin = new THREE29.Vector3;- const direction = new THREE29.Vector3;+ const tangent = new THREE30.Vector3;+ const bitangent = new THREE30.Vector3;+ const origin = new THREE30.Vector3;+ const direction = new THREE30.Vector3;points.forEach((point, id) => {const normal = normals[id];if (normal.lengthSq() === 0) {@@ -25644,8 +25672,8 @@ function bakeSurfaceAttributes(target, options = {}) {});const values = new Float32Array(sourceCount);for (let i = 0;i < sourceCount; i++)- values[i] = THREE29.MathUtils.clamp(exposure[topology.ids[i]], 0, 1);- geometry.setAttribute("_cavity", new THREE29.BufferAttribute(values, 1));+ values[i] = THREE30.MathUtils.clamp(exposure[topology.ids[i]], 0, 1);+ geometry.setAttribute("_cavity", new THREE30.BufferAttribute(values, 1));record._CAVITY = { rays, radius };}geometry.userData = { ...geometry.userData, [SURFACE_BAKE_KEY]: record };@@ -25665,7 +25693,7 @@ function surfaceBakeRecord(geometry) {return record;}var SURFACE_ATTRIBUTES, SURFACE_BAKE_KEY = "kilnSurfaceBakeV1", SURFACE_BAKE_DEFAULTS, isObject3D2 = (value) => value?.isObject3D === true, smoothstep2 = (edge0, edge1, x) => {- const t = THREE29.MathUtils.clamp((x - edge0) / (edge1 - edge0), 0, 1);+ const t = THREE30.MathUtils.clamp((x - edge0) / (edge1 - edge0), 0, 1);return t * t * (3 - 2 * t);};var init_surface_bake = __esm(() => {@@ -25679,7 +25707,7 @@ var init_surface_bake = __esm(() => {});// src/geometry.ts-import * as THREE30 from "three";+import * as THREE31 from "three";function finiteArray(values, label, length) {const result = Array.from(values);if (length !== undefined && result.length !== length)@@ -25693,8 +25721,8 @@ function meshGeo(data) {if (positions.length < 9 || positions.length % 3)throw new Error("meshGeo positions: need at least three xyz vertices");const count = positions.length / 3;- const geometry = new THREE30.BufferGeometry;- geometry.setAttribute("position", new THREE30.Float32BufferAttribute(positions, 3));+ const geometry = new THREE31.BufferGeometry;+ geometry.setAttribute("position", new THREE31.Float32BufferAttribute(positions, 3));if (data.indices) {const indices = Array.from(data.indices);if (!indices.length || indices.length % 3)@@ -25706,7 +25734,7 @@ function meshGeo(data) {throw new Error("meshGeo: non-indexed positions must form complete triangles");if (data.normals) {const normals = finiteArray(data.normals, "meshGeo normals", count * 3);- geometry.setAttribute("normal", new THREE30.Float32BufferAttribute(normals, 3));+ geometry.setAttribute("normal", new THREE31.Float32BufferAttribute(normals, 3));for (let i = 0;i < count; i++)if (Math.hypot(normals[i * 3], normals[i * 3 + 1], normals[i * 3 + 2]) === 0)throw new Error("meshGeo normals: zero-length normal");@@ -25714,36 +25742,36 @@ function meshGeo(data) {} elsegeometry.computeVertexNormals();if (data.uvs)- geometry.setAttribute("uv", new THREE30.Float32BufferAttribute(finiteArray(data.uvs, "meshGeo uvs", count * 2), 2));+ geometry.setAttribute("uv", new THREE31.Float32BufferAttribute(finiteArray(data.uvs, "meshGeo uvs", count * 2), 2));if (data.tangents) {const tangents = finiteArray(data.tangents, "meshGeo tangents", count * 4);for (let i = 0;i < count; i++) {if (Math.abs(Math.hypot(tangents[i * 4], tangents[i * 4 + 1], tangents[i * 4 + 2]) - 1) > 0.0001 || Math.abs(tangents[i * 4 + 3]) !== 1)throw new Error("meshGeo tangents: expected unit xyz and handedness +1 or -1");}- geometry.setAttribute("tangent", new THREE30.Float32BufferAttribute(tangents, 4));+ geometry.setAttribute("tangent", new THREE31.Float32BufferAttribute(tangents, 4));}geometry.computeBoundingBox();geometry.computeBoundingSphere();return geometry;}function boundsScale(bounds) {- const size = bounds.getSize(new THREE30.Vector3);+ const size = bounds.getSize(new THREE31.Vector3);const scale = Math.hypot(size.x, size.y, size.z);if (!Number.isFinite(scale))throw new Error("Geometry position extent must be finite");return scale;}function positionFrame(position) {- const bounds = new THREE30.Box3;- const point = new THREE30.Vector3;+ const bounds = new THREE31.Box3;+ const point = new THREE31.Vector3;for (let i = 0;i < position.count; i++) {point.fromBufferAttribute(position, i);if ([point.x, point.y, point.z].every(Number.isFinite))bounds.expandByPoint(point);}return {- origin: bounds.isEmpty() ? new THREE30.Vector3 : bounds.min,+ origin: bounds.isEmpty() ? new THREE31.Vector3 : bounds.min,scale: boundsScale(bounds)};}@@ -25783,11 +25811,11 @@ function geometryDiagnostics(geometry, tolerance) {solid: { closed: false, manifold: true, orientation: "mixed", signedVolume: 0 }};let signedVolume = 0;- const pa = new THREE30.Vector3, pb = new THREE30.Vector3, pc = new THREE30.Vector3;+ const pa = new THREE31.Vector3, pb = new THREE31.Vector3, pc = new THREE31.Vector3;const ids = [];const points = new Map;const finite = [];- const point = new THREE30.Vector3;+ const point = new THREE31.Vector3;for (let i = 0;i < p.count; i++) {point.fromBufferAttribute(p, i);finite[i] = [point.x, point.y, point.z].every(Number.isFinite);@@ -25800,7 +25828,7 @@ function geometryDiagnostics(geometry, tolerance) {}const indices = geometry.index ? Array.from(geometry.index.array) : Array.from({ length: p.count }, (_, i) => i);const edges = new Map;- const a = new THREE30.Vector3, b = new THREE30.Vector3, c = new THREE30.Vector3;+ const a = new THREE31.Vector3, b = new THREE31.Vector3, c = new THREE31.Vector3;for (let i = 0;i < indices.length; i += 3) {result.triangles++;const triangle = indices.slice(i, i + 3);@@ -25885,8 +25913,8 @@ function parametricSurface(sample, options = {}) {if (orientation !== "uv" && orientation !== "vu")throw new Error("parametricSurface orientation must be uv or vu");const positions = [], uvs = [], indices = [];- const sampledBounds = new THREE30.Box3;- const sampledPoint = new THREE30.Vector3;+ const sampledBounds = new THREE31.Box3;+ const sampledPoint = new THREE31.Vector3;for (let j = 0;j <= nv; j++)for (let i = 0;i <= nu; i++) {const point = sample(u[0] + (u[1] - u[0]) * i / nu, v[0] + (v[1] - v[0]) * j / nv);@@ -25928,8 +25956,8 @@ function parametricSurface(sample, options = {}) {const sums = new Map;for (let i = 0;i < normal.count; i++) {const id = find(i);- const sum = sums.get(id) ?? new THREE30.Vector3;- sum.add(new THREE30.Vector3().fromBufferAttribute(normal, i));+ const sum = sums.get(id) ?? new THREE31.Vector3;+ sum.add(new THREE31.Vector3().fromBufferAttribute(normal, i));sums.set(id, sum);}for (let i = 0;i < normal.count; i++) {@@ -25954,13 +25982,13 @@ function creaseNormals(geometry, options = {}) {const keys = [];const faces = [];for (let i = 0;i < position.count; i += 3) {- const a = new THREE30.Vector3().fromBufferAttribute(position, i);- const b = new THREE30.Vector3().fromBufferAttribute(position, i + 1);- const c = new THREE30.Vector3().fromBufferAttribute(position, i + 2);+ const a = new THREE31.Vector3().fromBufferAttribute(position, i);+ const b = new THREE31.Vector3().fromBufferAttribute(position, i + 1);+ const c = new THREE31.Vector3().fromBufferAttribute(position, i + 2);const face = b.sub(a).divideScalar(scale).cross(c.sub(a).divideScalar(scale)).normalize();faces.push(face);for (let j = i;j < i + 3; j++) {- const point = new THREE30.Vector3().fromBufferAttribute(position, j);+ const point = new THREE31.Vector3().fromBufferAttribute(position, j);if (![point.x, point.y, point.z].every(Number.isFinite))throw new Error("creaseNormals positions must be finite");const key = positionKey(point, frame.origin, tolerance);@@ -25971,15 +25999,15 @@ function creaseNormals(geometry, options = {}) {}}const normals = new Float32Array(position.count * 3);- const threshold = Math.cos(THREE30.MathUtils.degToRad(angle));+ const threshold = Math.cos(THREE31.MathUtils.degToRad(angle));for (let i = 0;i < position.count; i++) {- const face = faces[Math.floor(i / 3)], sum = new THREE30.Vector3;+ const face = faces[Math.floor(i / 3)], sum = new THREE31.Vector3;for (const other of adjacent.get(keys[i]))if (face.dot(faces[other]) >= threshold - 0.000000000001)sum.add(faces[other]);sum.normalize().toArray(normals, i * 3);}- out.setAttribute("normal", new THREE30.BufferAttribute(normals, 3));+ out.setAttribute("normal", new THREE31.BufferAttribute(normals, 3));out.deleteAttribute("tangent");out.computeBoundingBox();out.computeBoundingSphere();@@ -26577,16 +26605,16 @@ function buildWallPanels(length, height, thickness, apertures) {}// src/assembly-transform.ts-import * as THREE31 from "three";+import * as THREE32 from "three";function checkedTrs(matrix, label) {const e = matrix.elements;if (!e.every(Number.isFinite) || e[3] !== 0 || e[7] !== 0 || e[11] !== 0 || Math.abs(e[15] - 1) > 16 * Number.EPSILON)throw new Error(`${label}: finite affine TRS is required.`);if (!Number.isFinite(matrix.determinant()) || matrix.determinant() === 0)throw new Error(`${label}: singular/zero-scale transforms are unsupported.`);- const position = new THREE31.Vector3, quaternion = new THREE31.Quaternion, scale = new THREE31.Vector3;+ const position = new THREE32.Vector3, quaternion = new THREE32.Quaternion, scale = new THREE32.Vector3;matrix.decompose(position, quaternion, scale);- const rebuilt = new THREE31.Matrix4().compose(position, quaternion, scale);+ const rebuilt = new THREE32.Matrix4().compose(position, quaternion, scale);if (rebuilt.elements.some((value, i) => !Number.isFinite(value) || Math.abs(value - e[i]) > 0.00000001 * Math.max(1, Math.abs(e[i]))))throw new Error(`${label}: local shear cannot be represented losslessly as TRS.`);return { position, quaternion, scale };@@ -26594,7 +26622,7 @@ function checkedTrs(matrix, label) {var init_assembly_transform = () => {};// src/assembly.ts-import * as THREE32 from "three";+import * as THREE33 from "three";function jsonData(value, label, ancestors = new Set) {if (value === null || typeof value === "string" || typeof value === "boolean")return;@@ -26641,7 +26669,7 @@ function knownMetadata(source, parsed, label) {throw new Error(`${label}: unsupported fields in known metadata would be lost during remapping.`);}function localMatrix(node) {- return node.matrixAutoUpdate ? new THREE32.Matrix4().compose(node.position, node.quaternion, node.scale) : node.matrix.clone();+ return node.matrixAutoUpdate ? new THREE33.Matrix4().compose(node.position, node.quaternion, node.scale) : node.matrix.clone();}function worldMatrix2(node) {const chain = [], seen = new Set;@@ -26651,7 +26679,7 @@ function worldMatrix2(node) {seen.add(cursor);chain.push(cursor);}- const result = new THREE32.Matrix4;+ const result = new THREE33.Matrix4;for (const entry of chain.reverse())result.multiply(localMatrix(entry));return result;@@ -26667,7 +26695,7 @@ function census(root) {const stack = [root];while (stack.length) {const node = stack.pop();- if (!(node instanceof THREE32.Object3D) || ![THREE32.Object3D, THREE32.Group, THREE32.Mesh].includes(node.constructor))+ if (!(node instanceof THREE33.Object3D) || ![THREE33.Object3D, THREE33.Group, THREE33.Mesh].includes(node.constructor))throw new Error("Unsupported assembly node: only ordinary Object3D, Group and Mesh hierarchies are qualified; no skins, instances or custom node classes.");if (matrices.has(node))throw new Error("Assembly must be a tree; duplicate/cyclic children are unsupported.");@@ -26683,21 +26711,21 @@ function census(root) {checkedTrs(matrix, node.name || "unnamed node");nodes.push(node);matrices.set(node, matrix);- if (node.onBeforeRender !== THREE32.Object3D.prototype.onBeforeRender || node.onAfterRender !== THREE32.Object3D.prototype.onAfterRender || node.onBeforeShadow !== THREE32.Object3D.prototype.onBeforeShadow || node.onAfterShadow !== THREE32.Object3D.prototype.onAfterShadow)+ if (node.onBeforeRender !== THREE33.Object3D.prototype.onBeforeRender || node.onAfterRender !== THREE33.Object3D.prototype.onAfterRender || node.onBeforeShadow !== THREE33.Object3D.prototype.onBeforeShadow || node.onAfterShadow !== THREE33.Object3D.prototype.onAfterShadow)throw new Error("Custom node render callbacks are unsupported in assembly replication.");- if (node instanceof THREE32.Mesh) {- if (!(node.geometry instanceof THREE32.BufferGeometry) || node.geometry instanceof THREE32.InstancedBufferGeometry)+ if (node instanceof THREE33.Mesh) {+ if (!(node.geometry instanceof THREE33.BufferGeometry) || node.geometry instanceof THREE33.InstancedBufferGeometry)throw new Error("Unsupported assembly geometry type.");if (Object.values(node.geometry.morphAttributes).some((attributes) => attributes?.length) || node.morphTargetInfluences?.length)throw new Error("Assembly morph target replication is unsupported.");const materials = Array.isArray(node.material) ? node.material : [node.material];- if (materials.length === 0 || materials.some((material) => !(material instanceof THREE32.Material)))+ if (materials.length === 0 || materials.some((material) => !(material instanceof THREE33.Material)))throw new Error("Assembly mesh materials must be Material instances.");}if (!object(node.userData))throw new Error("Assembly node metadata must be an object.");jsonData(node.userData, node.name);- if (!Array.isArray(node.animations) || node.animations.some((clip) => !(clip instanceof THREE32.AnimationClip)))+ if (!Array.isArray(node.animations) || node.animations.some((clip) => !(clip instanceof THREE33.AnimationClip)))throw new Error("Assembly node animations must contain AnimationClip instances.");if (node.userData[KILN_SEMANTIC_EXTRAS_KEY] !== undefined) {const metadata = readSemanticMetadataV1(node);@@ -26738,11 +26766,11 @@ function describeAssembly(root, options = {}) {const state = census(root), roles = new Map;const frames = [], sockets = [], joints = [], materials = [];const relative = new Map;- const bounds = new THREE32.Box3, point = new THREE32.Vector3;+ const bounds = new THREE33.Box3, point = new THREE33.Vector3;let positionSamples = 0;for (const [index, node] of state.nodes.entries()) {const nodeId = `n${index}`;- const matrix = node === root ? new THREE32.Matrix4 : relative.get(node.parent).clone().multiply(state.matrices.get(node));+ const matrix = node === root ? new THREE33.Matrix4 : relative.get(node.parent).clone().multiply(state.matrices.get(node));relative.set(node, matrix);const metadata = state.semantics.get(node);const descriptor = state.joints.get(node);@@ -26764,7 +26792,7 @@ function describeAssembly(root, options = {}) {for (const role of metadata?.roles ?? [])addIndex(roles, role, node);for (const frame of metadata?.frames ?? []) {- const local = new THREE32.Matrix4().compose(new THREE32.Vector3(...frame.translation), new THREE32.Quaternion(...frame.rotation), new THREE32.Vector3(1, 1, 1));+ const local = new THREE33.Matrix4().compose(new THREE33.Vector3(...frame.translation), new THREE33.Quaternion(...frame.rotation), new THREE33.Vector3(1, 1, 1));frames.push({node,nodeId,@@ -26774,7 +26802,7 @@ function describeAssembly(root, options = {}) {}for (const socket of metadata?.sockets ?? [])sockets.push({ node, nodeId, socket: structuredClone(socket) });- if (!(node instanceof THREE32.Mesh))+ if (!(node instanceof THREE33.Mesh))continue;for (const [materialIndex, material] of (Array.isArray(node.material) ? node.material : [node.material]).entries())materials.push({ node, nodeId, index: materialIndex, material });@@ -26809,7 +26837,7 @@ function describeAssembly(root, options = {}) {space: "root-local",min: bounds.min.toArray(),max: bounds.max.toArray(),- size: bounds.getSize(new THREE32.Vector3).toArray()+ size: bounds.getSize(new THREE33.Vector3).toArray()},clips,ownership: {@@ -26848,7 +26876,7 @@ function replicateAssembly(source, options) {if (value !== undefined && !choices.includes(value))throw new Error(`Unsupported assembly ${key} policy.`);}- if (options.parent !== undefined && !(options.parent instanceof THREE32.Object3D))+ if (options.parent !== undefined && !(options.parent instanceof THREE33.Object3D))throw new Error("Assembly parent must be an Object3D.");const fresh = describeAssembly(source.root, { clips: source.clips }), state = census(source.root);if (options.parent && state.nodes.includes(options.parent))@@ -26881,16 +26909,16 @@ function replicateAssembly(source, options) {throw new Error(`Unsupported custom metadata ${key} on ${node.name}; use copy-json only for inert data whose references you own.`);}jsonData(node.userData, node.name);- if (node instanceof THREE32.Mesh) {+ if (node instanceof THREE33.Mesh) {if (options.geometry === "copy") {jsonData(node.geometry.userData, `${node.name} geometry`);- if (node.geometry.clone !== THREE32.BufferGeometry.prototype.clone || !threeConstructors.has(node.geometry.constructor))+ if (node.geometry.clone !== THREE33.BufferGeometry.prototype.clone || !threeConstructors.has(node.geometry.constructor))throw new Error("Copying custom geometry classes/clone implementations is unsupported; explicitly share the resource.");}if (options.materials === "copy")for (const material of Array.isArray(node.material) ? node.material : [node.material]) {jsonData(material.userData, `${node.name} material`);- if (material.onBeforeCompile !== THREE32.Material.prototype.onBeforeCompile || material.onBeforeRender !== THREE32.Material.prototype.onBeforeRender || material.clone !== THREE32.Material.prototype.clone || !threeConstructors.has(material.constructor) || material.customProgramCacheKey !== THREE32.Material.prototype.customProgramCacheKey || material instanceof THREE32.ShaderMaterial)+ if (material.onBeforeCompile !== THREE33.Material.prototype.onBeforeCompile || material.onBeforeRender !== THREE33.Material.prototype.onBeforeRender || material.clone !== THREE33.Material.prototype.clone || !threeConstructors.has(material.constructor) || material.customProgramCacheKey !== THREE33.Material.prototype.customProgramCacheKey || material instanceof THREE33.ShaderMaterial)throw new Error("Copying custom/shader materials is unsupported; explicit sharing preserves their existing implementation.");}}@@ -26978,9 +27006,9 @@ function replicateAssembly(source, options) {const trackTargets = new Map;const animatedNodes = new Set;for (const clip of fresh.clips) {- if (!(clip instanceof THREE32.AnimationClip))+ if (!(clip instanceof THREE33.AnimationClip))throw new Error("Assembly clips must be AnimationClip instances.");- if (clip.blendMode !== THREE32.NormalAnimationBlendMode)+ if (clip.blendMode !== THREE33.NormalAnimationBlendMode)throw new Error("Additive/other animation blend modes are unsupported in assembly replication.");jsonData(clip.userData, `Clip ${clip.name}`);if (Object.keys(clip.userData).length && options.unknownMetadata !== "copy-json")@@ -27007,7 +27035,7 @@ function replicateAssembly(source, options) {if (options.space === "world") {if (state.joints.has(source.root))throw new Error("World placement of a declared joint root requires rest-transform rebasing; wrap it in an assembly root or use local placement.");- const parentWorld = options.parent ? worldMatrix2(options.parent) : new THREE32.Matrix4;+ const parentWorld = options.parent ? worldMatrix2(options.parent) : new THREE33.Matrix4;if (!Number.isFinite(parentWorld.determinant()) || parentWorld.determinant() === 0)throw new Error("World placement requires an invertible, nonsingular parent transform.");rootMatrix = parentWorld.invert().multiply(worldMatrix2(source.root));@@ -27048,7 +27076,7 @@ function replicateAssembly(source, options) {return materials.get(material);};for (const node of state.nodes) {- const copy = node instanceof THREE32.Mesh ? new THREE32.Mesh(node.geometry, node.material) : node instanceof THREE32.Group ? new THREE32.Group : new THREE32.Object3D;+ const copy = node instanceof THREE33.Mesh ? new THREE33.Mesh(node.geometry, node.material) : node instanceof THREE33.Group ? new THREE33.Group : new THREE33.Object3D;copy.copy(node, false);copy.name = names.get(node);copy.animations = [];@@ -27061,7 +27089,7 @@ function replicateAssembly(source, options) {}copy.matrix.copy(matrix);copy.matrixWorldNeedsUpdate = true;- if (node instanceof THREE32.Mesh && copy instanceof THREE32.Mesh) {+ if (node instanceof THREE33.Mesh && copy instanceof THREE33.Mesh) {if (options.geometry === "copy") {if (!geometries.has(node.geometry))geometries.set(node.geometry, node.geometry.clone());@@ -27126,7 +27154,7 @@ var init_assembly = __esm(() => {KILN_CHARACTER_JOINT_EXTRAS_KEY,KILN_CHARACTER_RIG_EXTRAS_KEY]);- threeConstructors = new Set(Object.values(THREE32));+ threeConstructors = new Set(Object.values(THREE33));});// src/palette-check.ts@@ -27339,7 +27367,7 @@ var init_budget = __esm(() => {});// src/animation-cubic.ts-import * as THREE33 from "three";+import * as THREE34 from "three";function useCubicSpline(track) {track.createInterpolant = cubicSplineFactory;return track;@@ -27347,7 +27375,7 @@ function useCubicSpline(track) {var CubicSplineInterpolant, CubicSplineQuaternionInterpolant, cubicSplineFactory;var init_animation_cubic = __esm(() => {init_animation_spline();- CubicSplineInterpolant = class CubicSplineInterpolant extends THREE33.Interpolant {+ CubicSplineInterpolant = class CubicSplineInterpolant extends THREE34.Interpolant {copySampleValue_(index) {const result = this.resultBuffer;const size = this.valueSize;@@ -27375,7 +27403,7 @@ var init_animation_cubic = __esm(() => {});// src/architecture.ts-import * as THREE34 from "three";+import * as THREE35 from "three";function positive4(value, name) {if (!Number.isFinite(value) || value <= 0)throw new RangeError(`${name} must be finite and > 0`);@@ -27440,17 +27468,17 @@ function buildFace(roofRoot, profile, sideSign) {const verticalRun = profile.ridgeY - profile.eaveY;const downhillLength = Math.hypot(horizontalRun, verticalRun);const alongRidge = (profile.ridgeAxis === "x" ? profile.spanX : profile.spanZ) + profile.overhang * 2;- const downhill = profile.ridgeAxis === "x" ? new THREE34.Vector3(0, -verticalRun, sideSign * horizontalRun).normalize() : new THREE34.Vector3(sideSign * horizontalRun, -verticalRun, 0).normalize();- const tangent = profile.ridgeAxis === "x" ? new THREE34.Vector3(sideSign, 0, 0) : new THREE34.Vector3(0, 0, -sideSign);+ const downhill = profile.ridgeAxis === "x" ? new THREE35.Vector3(0, -verticalRun, sideSign * horizontalRun).normalize() : new THREE35.Vector3(sideSign * horizontalRun, -verticalRun, 0).normalize();+ const tangent = profile.ridgeAxis === "x" ? new THREE35.Vector3(sideSign, 0, 0) : new THREE35.Vector3(0, 0, -sideSign);const normal = downhill.clone().cross(tangent).normalize();- const localToRoof = new THREE34.Matrix4().makeBasis(tangent, normal, downhill);+ const localToRoof = new THREE35.Matrix4().makeBasis(tangent, normal, downhill);localToRoof.setPosition(0, profile.ridgeY, 0);const world = () => {roofRoot.updateWorldMatrix(true, false);return roofRoot.matrixWorld.clone().multiply(localToRoof);};const direction = (axis) => axis.clone().transformDirection(world());- const point = (x, z) => new THREE34.Vector3(x, 0, z).applyMatrix4(world());+ const point = (x, z) => new THREE35.Vector3(x, 0, z).applyMatrix4(world());return {side,ridgeAxis: profile.ridgeAxis,@@ -27460,13 +27488,13 @@ function buildFace(roofRoot, profile, sideSign) {return world();},get ridgeTangent() {- return direction(new THREE34.Vector3(1, 0, 0));+ return direction(new THREE35.Vector3(1, 0, 0));},get downhillDirection() {- return direction(new THREE34.Vector3(0, 0, 1));+ return direction(new THREE35.Vector3(0, 0, 1));},get outwardNormal() {- return direction(new THREE34.Vector3(0, 1, 0));+ return direction(new THREE35.Vector3(0, 1, 0));},get ridgeStart() {return point(-alongRidge / 2, 0);@@ -27484,17 +27512,17 @@ function buildFace(roofRoot, profile, sideSign) {};}function buildRoof(name, material, profile, parent) {- const root = new THREE34.Object3D;+ const root = new THREE35.Object3D;root.name = name;if (parent)parent.add(root);stampSemanticMetadataV1(root, roleMetadata([semanticRole(KILN_SEMANTIC_ROLES.roof, "assembly")], [relationship("separable-from", "architecture.shell.gable")]));const faces = [buildFace(root, profile, 1), buildFace(root, profile, -1)];const buildSlope = (face) => {- const geometry = new THREE34.BoxGeometry(face.dimensions.alongRidge, profile.thickness, face.dimensions.downhill);- const mesh = new THREE34.Mesh(geometry, material);+ const geometry = new THREE35.BoxGeometry(face.dimensions.alongRidge, profile.thickness, face.dimensions.downhill);+ const mesh = new THREE35.Mesh(geometry, material);mesh.name = `Mesh_${name}_${face.side}`;- const center = new THREE34.Matrix4().makeTranslation(0, -profile.thickness / 2, face.dimensions.downhill / 2);+ const center = new THREE35.Matrix4().makeTranslation(0, -profile.thickness / 2, face.dimensions.downhill / 2);setTransform(mesh, face.localToRoof.clone().multiply(center));const coveredWall = profile.ridgeAxis === "x" ? face.side === "positive" ? "wall.right" : "wall.left" : face.side === "positive" ? "wall.front" : "wall.back";stampSemanticMetadataV1(mesh, roleMetadata([semanticRole(KILN_SEMANTIC_ROLES.roof, "slope", face.side)], [@@ -27564,7 +27592,7 @@ function createGableEndPanel(name, material, options) {const ridgeAxis = options.ridgeAxis ?? "x";const side = options.side ?? "positive";const half = span / 2;- const shape = new THREE34.Shape;+ const shape = new THREE35.Shape;shape.moveTo(-half, 0);shape.lineTo(half, 0);shape.lineTo(0, rise);@@ -27583,7 +27611,7 @@ function createGableEndPanel(name, material, options) {const right = opening.offset + opening.width / 2;const bottom = opening.bottom;const top = bottom + opening.height;- const hole = new THREE34.Path;+ const hole = new THREE35.Path;hole.moveTo(left, bottom);hole.lineTo(left, top);hole.lineTo(right, top);@@ -27591,7 +27619,7 @@ function createGableEndPanel(name, material, options) {hole.closePath();shape.holes.push(hole);}- const geometry = new THREE34.ExtrudeGeometry(shape, {+ const geometry = new THREE35.ExtrudeGeometry(shape, {depth: thickness,bevelEnabled: false,steps: 1@@ -27600,7 +27628,7 @@ function createGableEndPanel(name, material, options) {if (ridgeAxis === "x")geometry.rotateY(-Math.PI / 2);geometry.computeVertexNormals();- const root = new THREE34.Mesh(geometry, material);+ const root = new THREE35.Mesh(geometry, material);root.name = `Mesh_${name}`;stampSemanticMetadataV1(root, roleMetadata([`roof.gable.${side}`], [relationship("adjacent-to", "roof.slope.positive"),@@ -27616,7 +27644,7 @@ function createGableEndPanel(name, material, options) {}]));const markers = normalized.map((opening, index) => {- const marker = new THREE34.Object3D;+ const marker = new THREE35.Object3D;marker.name = `Opening_${name}_${opening.id ?? index + 1}`;marker.position.set(ridgeAxis === "z" ? opening.offset : 0, opening.bottom + opening.height / 2, ridgeAxis === "x" ? opening.offset : 0);marker.scale.set(ridgeAxis === "x" ? thickness : opening.width, opening.height, ridgeAxis === "x" ? opening.width : thickness);@@ -27636,7 +27664,7 @@ function wallNeighbors(wall) {}function createShellWall(name, wall, material, length, height, thickness, openings) {const axis = wallRunAxis(wall);- const root = new THREE34.Object3D;+ const root = new THREE35.Object3D;root.name = `${name}_Wall_${wall}`;const neighbors = wallNeighbors(wall);stampSemanticMetadataV1(root, roleMetadata([`wall.${wall}`], [@@ -27648,8 +27676,8 @@ function createShellWall(name, wall, material, length, height, thickness, openinconst panel = (suffix, lo, hi, y0, y1) => {if (hi <= lo || y1 <= y0)return;- const geometry = axis === "x" ? new THREE34.BoxGeometry(hi - lo, y1 - y0, thickness) : new THREE34.BoxGeometry(thickness, y1 - y0, hi - lo);- const mesh = new THREE34.Mesh(geometry, material);+ const geometry = axis === "x" ? new THREE35.BoxGeometry(hi - lo, y1 - y0, thickness) : new THREE35.BoxGeometry(thickness, y1 - y0, hi - lo);+ const mesh = new THREE35.Mesh(geometry, material);mesh.name = `Mesh_${name}_${wall}_${suffix}`;mesh.position.set(axis === "x" ? (lo + hi) / 2 : 0, (y0 + y1) / 2, axis === "z" ? (lo + hi) / 2 : 0);root.add(mesh);@@ -27666,7 +27694,7 @@ function createShellWall(name, wall, material, length, height, thickness, openinpanel(singleNames[segment.suffix] ?? segment.suffix.slice(1), segment.left, segment.right, segment.bottom, segment.top);}for (const opening of built.openings) {- const marker = new THREE34.Object3D;+ const marker = new THREE35.Object3D;marker.name = `Opening_${wall}_${opening.id}`;marker.position.set(axis === "x" ? opening.offset : 0, opening.sill + opening.height / 2, axis === "z" ? opening.offset : 0);marker.scale.set(axis === "x" ? opening.width : opening.depth, opening.height, axis === "z" ? opening.width : opening.depth);@@ -27689,7 +27717,7 @@ function createGableShell(name, materials, options) {const closedEnds = options.closedEnds ?? true;const enterable = options.enterable ?? true;const shellOpenings = options.openings ?? (enterable ? [{ wall: "front", kind: "door" }] : []);- const root = new THREE34.Object3D;+ const root = new THREE35.Object3D;root.name = name;stampSemanticMetadataV1(root, roleMetadata(["architecture.shell.gable"], [relationship("contains", "floor"), relationship("contains", "roof.assembly")]));const wallSpecs = {@@ -27707,7 +27735,7 @@ function createGableShell(name, materials, options) {walls[wall] = built.root;openingMarkers.push(...built.openings);}- const floor = new THREE34.Mesh(new THREE34.BoxGeometry(spanX, floorThickness, spanZ), materials.floor ?? materials.wall);+ const floor = new THREE35.Mesh(new THREE35.BoxGeometry(spanX, floorThickness, spanZ), materials.floor ?? materials.wall);floor.name = `Mesh_${name}_Floor`;floor.position.y = -floorThickness / 2;stampSemanticMetadataV1(floor, roleMetadata(["floor"], ["front", "back", "left", "right"].map((wall) => relationship("adjacent-to", `wall.${wall}`))));@@ -27822,13 +27850,13 @@ function createRoofSurfaceLayout(name, material, options) {assertDimension("createRoofSurfaceLayout generated width", spec.width);assertDimension("createRoofSurfaceLayout generated length", spec.length);}- const root = new THREE34.Object3D;+ const root = new THREE35.Object3D;root.name = name;stampSemanticMetadataV1(root, roleMetadata([`roof.surface.${options.kind}`], [relationship("coverage-of", `roof.slope.${options.face.side}`)]));const items = specs.map((spec, index) => {- const mesh = new THREE34.Mesh(new THREE34.BoxGeometry(spec.width, thickness, spec.length), material);+ const mesh = new THREE35.Mesh(new THREE35.BoxGeometry(spec.width, thickness, spec.length), material);mesh.name = `Mesh_${name}_${index + 1}`;- const local = new THREE34.Matrix4().makeTranslation(spec.x, thickness / 2 + 0.002, spec.z);+ const local = new THREE35.Matrix4().makeTranslation(spec.x, thickness / 2 + 0.002, spec.z);setTransform(mesh, faceToRoot.clone().multiply(local));root.add(mesh);return mesh;@@ -27845,7 +27873,7 @@ var init_architecture2 = __esm(() => {});// src/gears.ts-import * as THREE35 from "three";+import * as THREE36 from "three";function gearGeo(opts = {}) {const {teeth = 12,@@ -27944,8 +27972,8 @@ function gearGeo(opts = {}) {indices.push(tA, bA, bB);indices.push(tA, bB, tB);}- const geo = new THREE35.BufferGeometry;- geo.setAttribute("position", new THREE35.Float32BufferAttribute(positions, 3));+ const geo = new THREE36.BufferGeometry;+ geo.setAttribute("position", new THREE36.Float32BufferAttribute(positions, 3));geo.setIndex(indices);const nonIndexed = geo.toNonIndexed();nonIndexed.computeVertexNormals();@@ -28030,8 +28058,8 @@ function bladeGeo(opts = {}) {indices.push(count + i, tip, count + j);}}- const geo = new THREE35.BufferGeometry;- geo.setAttribute("position", new THREE35.Float32BufferAttribute(positions, 3));+ const geo = new THREE36.BufferGeometry;+ geo.setAttribute("position", new THREE36.Float32BufferAttribute(positions, 3));geo.setIndex(indices);const nonIndexed = geo.toNonIndexed();nonIndexed.computeVertexNormals();@@ -28043,7 +28071,7 @@ var init_gears = __esm(() => {});// src/ops.ts-import * as THREE36 from "three";+import * as THREE37 from "three";import { LoopSubdivision } from "three-subdivide/build/index.module.js";import { mergeVertices as threeMergeVertices } from "three/examples/jsm/utils/BufferGeometryUtils.js";function assertFiniteSourceFrame(name, source) {@@ -28077,9 +28105,9 @@ function arrayLinear(namePrefix, source, count, offset, parent) {}function degreesOf(euler) {return [- THREE36.MathUtils.radToDeg(euler.x),- THREE36.MathUtils.radToDeg(euler.y),- THREE36.MathUtils.radToDeg(euler.z)+ THREE37.MathUtils.radToDeg(euler.x),+ THREE37.MathUtils.radToDeg(euler.y),+ THREE37.MathUtils.radToDeg(euler.z)];}function arrayRadial(namePrefix, source, count, axis = "y", parent, center, options = {}) {@@ -28092,12 +28120,12 @@ function arrayRadial(namePrefix, source, count, axis = "y", parent, center, optiif (center)assertFiniteTriple("arrayRadial center", center);const out = [];- const pivot = center ? new THREE36.Vector3(...center) : new THREE36.Vector3;+ const pivot = center ? new THREE37.Vector3(...center) : new THREE37.Vector3;const basePos = source.position.clone().sub(pivot);- const axisVec = axis === "x" ? new THREE36.Vector3(1, 0, 0) : axis === "z" ? new THREE36.Vector3(0, 0, 1) : new THREE36.Vector3(0, 1, 0);+ const axisVec = axis === "x" ? new THREE37.Vector3(1, 0, 0) : axis === "z" ? new THREE37.Vector3(0, 0, 1) : new THREE37.Vector3(0, 1, 0);const positions = [];for (let i = 1;i < count; i++) {- const position = basePos.clone().applyMatrix4(new THREE36.Matrix4().makeRotationAxis(axisVec, i / count * Math.PI * 2)).add(pivot);+ const position = basePos.clone().applyMatrix4(new THREE37.Matrix4().makeRotationAxis(axisVec, i / count * Math.PI * 2)).add(pivot);assertFiniteTriple("arrayRadial resulting position", position.toArray());positions.push(position);}@@ -28136,7 +28164,7 @@ function repeatAlongCurve(source, points, options) {assertFiniteTriple(`${name} points[${i}]`, point);const up = options.up ?? [0, 1, 0];assertFiniteTriple(`${name} up`, up);- const upVector = new THREE36.Vector3(...up);+ const upVector = new THREE37.Vector3(...up);if (upVector.lengthSq() === 0)throw new RangeError(`${name} up must not be zero.`);upVector.normalize();@@ -28175,13 +28203,13 @@ function repeatAlongCurve(source, points, options) {segment++;while (segment < points.length - 2 && cumulative[segment + 1] === cumulative[segment])segment++;- const a = new THREE36.Vector3(...points[segment]);- const b = new THREE36.Vector3(...points[segment + 1]);+ const a = new THREE37.Vector3(...points[segment]);+ const b = new THREE37.Vector3(...points[segment + 1]);const segmentLength = cumulative[segment + 1] - cumulative[segment];const local = segmentLength > 0 ? (s - cumulative[segment]) / segmentLength : 0;const position = a.clone().lerp(b, Math.min(Math.max(local, 0), 1));- const k = THREE36.MathUtils.lerp(scale[0], scale[1], t);- const rotation = new THREE36.Matrix4;+ const k = THREE37.MathUtils.lerp(scale[0], scale[1], t);+ const rotation = new THREE37.Matrix4;let angle = 0;if (align === "tangent") {const tangent = b.clone().sub(a).normalize();@@ -28189,17 +28217,17 @@ function repeatAlongCurve(source, points, options) {if (side.lengthSq() < 0.000000000001)side = previousUp.clone().sub(tangent.clone().multiplyScalar(previousUp.dot(tangent)));if (side.lengthSq() < 0.000000000001)- side = new THREE36.Vector3(Math.abs(tangent.x) < 0.9 ? 1 : 0, Math.abs(tangent.x) < 0.9 ? 0 : 1, 0).sub(tangent.clone().multiplyScalar(Math.abs(tangent.x) < 0.9 ? tangent.x : tangent.y));+ side = new THREE37.Vector3(Math.abs(tangent.x) < 0.9 ? 1 : 0, Math.abs(tangent.x) < 0.9 ? 0 : 1, 0).sub(tangent.clone().multiplyScalar(Math.abs(tangent.x) < 0.9 ? tangent.x : tangent.y));side.normalize();previousUp = side;- rotation.makeBasis(tangent, side, new THREE36.Vector3().crossVectors(tangent, side));- angle = THREE36.MathUtils.degToRad(THREE36.MathUtils.lerp(twist[0], twist[1], t));+ rotation.makeBasis(tangent, side, new THREE37.Vector3().crossVectors(tangent, side));+ angle = THREE37.MathUtils.degToRad(THREE37.MathUtils.lerp(twist[0], twist[1], t));}for (const extra of opposite ? [0, Math.PI] : [0]) {const turned = rotation.clone();if (angle + extra)- turned.multiply(new THREE36.Matrix4().makeRotationX(angle + extra));- const matrix = new THREE36.Matrix4().makeTranslation(position.x, position.y, position.z).multiply(turned).multiply(new THREE36.Matrix4().makeScale(k, k, k));+ turned.multiply(new THREE37.Matrix4().makeRotationX(angle + extra));+ const matrix = new THREE37.Matrix4().makeTranslation(position.x, position.y, position.z).multiply(turned).multiply(new THREE37.Matrix4().makeScale(k, k, k));if (!matrix.elements.every(Number.isFinite))throw new RangeError(`${name} produced a non-finite copy transform.`);frames.push({ matrix, t });@@ -28231,9 +28259,9 @@ function repeatAlongCurve(source, points, options) {const total = perCopy * copies;if (total > GEOMETRY_ALLOCATION_LIMITS.curveRepeatVertices)throw new RangeError(`${name} would produce ${total} vertices; the limit is ${GEOMETRY_ALLOCATION_LIMITS.curveRepeatVertices}. Reduce count, simplify the source, or use merge: false.`);- const merged = new THREE36.BufferGeometry;- const vector = new THREE36.Vector3;- const normalMatrix = new THREE36.Matrix3;+ const merged = new THREE37.BufferGeometry;+ const vector = new THREE37.Vector3;+ const normalMatrix = new THREE37.Matrix3;for (const [key, attribute] of Object.entries(geometry.attributes)) {const size = attribute.itemSize;const transformed = key === "position" || key === "normal" || key === "tangent";@@ -28257,13 +28285,13 @@ function repeatAlongCurve(source, points, options) {}}}- merged.setAttribute(key, new THREE36.BufferAttribute(out, size, transformed ? false : attribute.normalized));+ merged.setAttribute(key, new THREE37.BufferAttribute(out, size, transformed ? false : attribute.normalized));}if (options.along) {const along = new Float32Array(total);for (let copy = 0;copy < copies; copy++)along.fill(frames[copy].t, copy * perCopy, (copy + 1) * perCopy);- merged.setAttribute("_along", new THREE36.BufferAttribute(along, 1));+ merged.setAttribute("_along", new THREE37.BufferAttribute(along, 1));}const index = geometry.getIndex();if (index) {@@ -28271,7 +28299,7 @@ function repeatAlongCurve(source, points, options) {for (let copy = 0;copy < copies; copy++)for (let i = 0;i < index.count; i++)indices[copy * index.count + i] = index.getX(i) + copy * perCopy;- merged.setIndex(new THREE36.BufferAttribute(indices, 1));+ merged.setIndex(new THREE37.BufferAttribute(indices, 1));}merged.computeBoundingBox();merged.computeBoundingSphere();@@ -28280,15 +28308,15 @@ function repeatAlongCurve(source, points, options) {function mirror(name, source, axis, parent) {if (source.matrixAutoUpdate)source.updateMatrix();- const reflected = new THREE36.Matrix4().makeScale(axis === "x" ? -1 : 1, axis === "y" ? -1 : 1, axis === "z" ? -1 : 1).multiply(source.matrix);+ const reflected = new THREE37.Matrix4().makeScale(axis === "x" ? -1 : 1, axis === "y" ? -1 : 1, axis === "z" ? -1 : 1).multiply(source.matrix);if (!reflected.elements.every(Number.isFinite) || reflected.determinant() === 0) {throw new RangeError(`mirror("${name}"): source requires a finite, nonsingular local transform.`);}- const position = new THREE36.Vector3;- const quaternion = new THREE36.Quaternion;- const scale = new THREE36.Vector3;+ const position = new THREE37.Vector3;+ const quaternion = new THREE37.Quaternion;+ const scale = new THREE37.Vector3;reflected.decompose(position, quaternion, scale);- const recomposed = new THREE36.Matrix4().compose(position, quaternion, scale);+ const recomposed = new THREE37.Matrix4().compose(position, quaternion, scale);if (reflected.elements.some((value, i) => Math.abs(value - recomposed.elements[i]) > 0.00000001 * Math.max(1, Math.abs(value)))) {throw new RangeError(`mirror("${name}"): local shear cannot be represented by a reflected TRS.`);}@@ -28304,13 +28332,13 @@ function mergeVertices(geometry, opts = {}) {const { tolerance = 0.0001, positionOnly = false } = typeof opts === "number" ? { tolerance: opts } : opts;if (!positionOnly)return threeMergeVertices(geometry, tolerance);- const stripped = new THREE36.BufferGeometry;+ const stripped = new THREE37.BufferGeometry;const pos = geometry.getAttribute("position");if (!pos)return geometry;- stripped.setAttribute("position", new THREE36.BufferAttribute(new Float32Array(pos.array), pos.itemSize, pos.normalized));+ stripped.setAttribute("position", new THREE37.BufferAttribute(new Float32Array(pos.array), pos.itemSize, pos.normalized));if (geometry.index) {- stripped.setIndex(new THREE36.BufferAttribute(new Uint32Array(geometry.index.array), 1));+ stripped.setIndex(new THREE37.BufferAttribute(new Uint32Array(geometry.index.array), 1));}return threeMergeVertices(stripped, tolerance);}@@ -28345,8 +28373,8 @@ function subdivide(geometry, iterations = 1, opts = {}) {const { weld = true, preserveUV = false, ...subOpts } = opts;const prepared = geometry.clone();prepared.computeBoundingBox();- const center = prepared.boundingBox.getCenter(new THREE36.Vector3);- const extent = prepared.boundingBox.getSize(new THREE36.Vector3);+ const center = prepared.boundingBox.getCenter(new THREE37.Vector3);+ const extent = prepared.boundingBox.getSize(new THREE37.Vector3);const size = Math.max(extent.x, extent.y, extent.z);const normalizationScale = size > 0 ? 1e4 / size : 1;if (!Number.isFinite(normalizationScale) || !center.toArray().every(Number.isFinite))@@ -28376,13 +28404,13 @@ function subdivide(geometry, iterations = 1, opts = {}) {const values = new Float32Array(attribute.count);for (let i = 0;i < attribute.count; i++)values[i] = decoded[i * 4 + component];- input.setAttribute(lane, new THREE36.BufferAttribute(values, 1));+ input.setAttribute(lane, new THREE37.BufferAttribute(values, 1));lanes.push(lane);}input.deleteAttribute(name);fourthComponents.push({ name, lanes });} else- input.setAttribute(name, new THREE36.BufferAttribute(decoded, components));+ input.setAttribute(name, new THREE37.BufferAttribute(decoded, components));}for (const targets of Object.values(input.morphAttributes))for (let target = 0;target < targets.length; target++) {@@ -28391,7 +28419,7 @@ function subdivide(geometry, iterations = 1, opts = {}) {for (let i = 0;i < attribute.count; i++)for (let component = 0;component < 3; component++)decoded[i * 3 + component] = attribute.getComponent(i, component);- targets[target] = new THREE36.BufferAttribute(decoded, 3);+ targets[target] = new THREE37.BufferAttribute(decoded, 3);}if (preserveUV)subOpts.uvSmooth = false;@@ -28405,7 +28433,7 @@ function subdivide(geometry, iterations = 1, opts = {}) {values[i * 4 + component] = lane.getX(i);output.deleteAttribute(lanes[component]);}- output.setAttribute(name, new THREE36.BufferAttribute(values, 4));+ output.setAttribute(name, new THREE37.BufferAttribute(values, 4));}output.scale(1 / normalizationScale, 1 / normalizationScale, 1 / normalizationScale).translate(center.x, center.y, center.z);output.userData = structuredClone(geometry.userData);@@ -28470,9 +28498,9 @@ function assertTubeRadius(radius) {}function curveToMesh(points, radius, tubularSegments = 32, radialSegments = 8, closed = false) {assertTubeRadius(radius);- const vectors = points.map((p) => new THREE36.Vector3(p[0], p[1], p[2]));- const curve = new THREE36.CatmullRomCurve3(vectors, closed);- return new THREE36.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);+ const vectors = points.map((p) => new THREE37.Vector3(p[0], p[1], p[2]));+ const curve = new THREE37.CatmullRomCurve3(vectors, closed);+ return new THREE37.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);}function normalizeSurfaceNormals(geo) {const normal = geo.getAttribute("normal");@@ -28503,15 +28531,15 @@ function lathe(profile, segments = 12) {}function revolveGeo(profile, options = {}) {const { angle = Math.PI * 2, axis = [0, 1, 0], segments = 12 } = options;- const points2d = profile.map((p) => new THREE36.Vector2(p[0], p[1]));- const geo = normalizeSurfaceNormals(new THREE36.LatheGeometry(points2d, segments, 0, angle));- const n = new THREE36.Vector3(axis[0], axis[1], axis[2]);+ const points2d = profile.map((p) => new THREE37.Vector2(p[0], p[1]));+ const geo = normalizeSurfaceNormals(new THREE37.LatheGeometry(points2d, segments, 0, angle));+ const n = new THREE37.Vector3(axis[0], axis[1], axis[2]);if (n.lengthSq() < 0.000000000001) {throw new Error(`revolveGeo: axis must be a non-zero vector (got [${axis.join(",")}]).`);}n.normalize();if (n.x !== 0 || n.y !== 1 || n.z !== 0) {- const q = new THREE36.Quaternion().setFromUnitVectors(new THREE36.Vector3(0, 1, 0), n);+ const q = new THREE37.Quaternion().setFromUnitVectors(new THREE37.Vector3(0, 1, 0), n);geo.applyQuaternion(q);}return geo;@@ -28527,9 +28555,9 @@ function pipeAlongPath(points, radius, options = {}) {const smoothed = [];smoothed.push(points[0]);for (let i = 1;i < points.length - 1; i++) {- const prev = new THREE36.Vector3(...points[i - 1]);- const cur = new THREE36.Vector3(...points[i]);- const next = new THREE36.Vector3(...points[i + 1]);+ const prev = new THREE37.Vector3(...points[i - 1]);+ const cur = new THREE37.Vector3(...points[i]);+ const next = new THREE37.Vector3(...points[i + 1]);const inDir = cur.clone().sub(prev);const outDir = next.clone().sub(cur);const inLen = inDir.length();@@ -28547,12 +28575,12 @@ function pipeAlongPath(points, radius, options = {}) {return curveToMesh(pathPoints, radius, tubularSegments, radialSegments, closed);}function bezierCurve(controlPoints, samples = 32) {- const vecs = controlPoints.map((p) => new THREE36.Vector3(p[0], p[1], p[2]));+ const vecs = controlPoints.map((p) => new THREE37.Vector3(p[0], p[1], p[2]));let curve;if (vecs.length === 3) {- curve = new THREE36.QuadraticBezierCurve3(vecs[0], vecs[1], vecs[2]);+ curve = new THREE37.QuadraticBezierCurve3(vecs[0], vecs[1], vecs[2]);} else if (vecs.length === 4) {- curve = new THREE36.CubicBezierCurve3(vecs[0], vecs[1], vecs[2], vecs[3]);+ curve = new THREE37.CubicBezierCurve3(vecs[0], vecs[1], vecs[2], vecs[3]);} else {throw new Error(`bezierCurve: need 3 or 4 control points, got ${vecs.length}`);}@@ -28565,20 +28593,20 @@ var init_ops = __esm(() => {});// src/deformation-normals.ts-import * as THREE37 from "three";+import * as THREE38 from "three";function recomputeDeformedNormals(source, output) {const original = source.getAttribute("position");const authored = source.getAttribute("normal");const position = output.getAttribute("position");const bounds = (attribute) => {- const box = new THREE37.Box3().setFromBufferAttribute(attribute);+ const box = new THREE38.Box3().setFromBufferAttribute(attribute);return {- center: box.getCenter(new THREE37.Vector3),- size: box.getSize(new THREE37.Vector3).length() || 1+ center: box.getCenter(new THREE38.Vector3),+ size: box.getSize(new THREE38.Vector3).length() || 1};};const before = bounds(original), after = bounds(position);- const point = new THREE37.Vector3, normal = new THREE37.Vector3;+ const point = new THREE38.Vector3, normal = new THREE38.Vector3;const quantized = (attribute, index, frame) => {point.fromBufferAttribute(attribute, index).sub(frame.center).divideScalar(frame.size);return point.toArray().map((value) => Math.round(value * 1e7)).join(",");@@ -28601,7 +28629,7 @@ function recomputeDeformedNormals(source, output) {const sums = new Float64Array(classes.size * 3);const index = output.index;const corners = index?.count ?? position.count;- const a = new THREE37.Vector3, b = new THREE37.Vector3, c = new THREE37.Vector3;+ const a = new THREE38.Vector3, b = new THREE38.Vector3, c = new THREE38.Vector3;for (let t = 0;t < corners; t += 3) {const ia = index ? index.getX(t) : t;const ib = index ? index.getX(t + 1) : t + 1;@@ -28622,17 +28650,17 @@ function recomputeDeformedNormals(source, output) {const offset = ids[i] * 3;normal.set(sums[offset], sums[offset + 1], sums[offset + 2]).normalize().toArray(normals, i * 3);}- output.setAttribute("normal", new THREE37.BufferAttribute(normals, 3));+ output.setAttribute("normal", new THREE38.BufferAttribute(normals, 3));}var init_deformation_normals = () => {};// src/deform.ts-import * as THREE38 from "three";+import * as THREE39 from "three";function geometryFrameMatrix(frame = {}) {const origin = frame.origin ?? [0, 0, 0], rotation = frame.rotation ?? [0, 0, 0];if (origin.length !== 3 || rotation.length !== 3 || ![...origin, ...rotation].every(Number.isFinite))throw new Error("geometry frame requires finite xyz origin and rotation");- return new THREE38.Matrix4().compose(new THREE38.Vector3(...origin), new THREE38.Quaternion().setFromEuler(new THREE38.Euler(...rotation.map(THREE38.MathUtils.degToRad), "XYZ")), new THREE38.Vector3(1, 1, 1));+ return new THREE39.Matrix4().compose(new THREE39.Vector3(...origin), new THREE39.Quaternion().setFromEuler(new THREE39.Euler(...rotation.map(THREE39.MathUtils.degToRad), "XYZ")), new THREE39.Vector3(1, 1, 1));}function deform(geometry, options, map) {const source = geometry.getAttribute("position");@@ -28659,7 +28687,7 @@ function deform(geometry, options, map) {throw new Error("deformation normals must be finite");}const matrix = geometryFrameMatrix(options.frame), inverse = matrix.clone().invert();- const points = Array.from({ length: source.count }, (_, i) => new THREE38.Vector3().fromBufferAttribute(source, i).applyMatrix4(inverse));+ const points = Array.from({ length: source.count }, (_, i) => new THREE39.Vector3().fromBufferAttribute(source, i).applyMatrix4(inverse));if (points.some((p) => ![p.x, p.y, p.z].every(Number.isFinite)))throw new Error("deformation positions must be finite");let low = Infinity, high = -Infinity;@@ -28682,7 +28710,7 @@ function deform(geometry, options, map) {const point = points[i];if (point.y < low - epsilon || point.y > high + epsilon)continue;- const t = length > 0 ? THREE38.MathUtils.clamp((point.y - low) / length, 0, 1) : 0;+ const t = length > 0 ? THREE39.MathUtils.clamp((point.y - low) / length, 0, 1) : 0;const weight = options.falloff?.(t) ?? 1;if (!Number.isFinite(weight) || weight < 0 || weight > 1)throw new Error("deformation falloff must return a finite weight between 0 and 1");@@ -28716,31 +28744,31 @@ function deform(geometry, options, map) {function twist(geometry, options) {if (!Number.isFinite(options.angle))throw new Error("twist angle must be finite degrees");- return deform(geometry, options, (p, t) => p.applyAxisAngle(new THREE38.Vector3(0, 1, 0), THREE38.MathUtils.degToRad(options.angle) * t));+ return deform(geometry, options, (p, t) => p.applyAxisAngle(new THREE39.Vector3(0, 1, 0), THREE39.MathUtils.degToRad(options.angle) * t));}function bend(geometry, options) {if (!Number.isFinite(options.angle))throw new Error("bend angle must be finite degrees");- const angle = THREE38.MathUtils.degToRad(options.angle);+ const angle = THREE39.MathUtils.degToRad(options.angle);return deform(geometry, options, (p, t, low, length) => {if (Math.abs(angle) < 0.0000000001 || length === 0)return p;const radius = length / angle, theta = angle * t;- return new THREE38.Vector3(radius - (radius - p.x) * Math.cos(theta), low + (radius - p.x) * Math.sin(theta), p.z);+ return new THREE39.Vector3(radius - (radius - p.x) * Math.cos(theta), low + (radius - p.x) * Math.sin(theta), p.z);});}function taper(geometry, options) {const start = options.startScale ?? [1, 1], end = options.endScale;if (start.length !== 2 || end.length !== 2 || ![...start, ...end].every((n) => Number.isFinite(n) && n > 0))throw new Error("taper scales must be two finite positive values");- return deform(geometry, options, (p, t) => p.set(p.x * THREE38.MathUtils.lerp(start[0], end[0], t), p.y, p.z * THREE38.MathUtils.lerp(start[1], end[1], t)));+ return deform(geometry, options, (p, t) => p.set(p.x * THREE39.MathUtils.lerp(start[0], end[0], t), p.y, p.z * THREE39.MathUtils.lerp(start[1], end[1], t)));}function displace(geometry, offset, options = {}) {return deform(geometry, options, (p, t) => {const delta = offset([p.x, p.y, p.z], t);if (delta.length !== 3 || !delta.every(Number.isFinite))throw new Error("displace callback must return three finite offsets");- return p.add(new THREE38.Vector3(...delta));+ return p.add(new THREE39.Vector3(...delta));});}var init_deform = __esm(() => {@@ -28748,7 +28776,7 @@ var init_deform = __esm(() => {});// src/sweep.ts-import * as THREE39 from "three";+import * as THREE40 from "three";function rejectHoles(value, label) {if ("holes" in value && value.holes !== undefined)throw new AuthoringDiagnosticError("PROFILE_HOLES_UNSUPPORTED", `${label}: holes are unsupported. Use extrudeProfile for a holed cross-section with optional twist/taper; independently varying contours need explicit geometry or solid subtraction.`);@@ -28756,9 +28784,9 @@ function rejectHoles(value, label) {function profilePoints(profile) {if (profile.length < 3 || profile.some((p) => p.length !== 2 || !p.every(Number.isFinite)))throw new Error("profile requires at least three finite xy points");- const points = profile.map((p) => new THREE39.Vector2(...p));- const bounds = new THREE39.Box2().setFromPoints(points);- const extent = bounds.getSize(new THREE39.Vector2).length();+ const points = profile.map((p) => new THREE40.Vector2(...p));+ const bounds = new THREE40.Box2().setFromPoints(points);+ const extent = bounds.getSize(new THREE40.Vector2).length();if (!(extent > 0) || !Number.isFinite(extent))throw new Error("profile requires a finite nonzero extent");const normalized = points.map((p) => p.clone().sub(bounds.min).divideScalar(extent));@@ -28781,7 +28809,7 @@ function profilePoints(profile) {throw new Error("profile self-intersects or touches itself");}}- const area = THREE39.ShapeUtils.area(normalized);+ const area = THREE40.ShapeUtils.area(normalized);if (Math.abs(area) < 0.000000000001)throw new Error("profile area must be nonzero");if (area < 0)@@ -28795,11 +28823,11 @@ function isCrease(first, second, creaseAngle) {if (!(first.lengthSq() > 0 && second.lengthSq() > 0))return false;const angle = Math.atan2(first.clone().cross(second).length(), first.dot(second));- return THREE39.MathUtils.radToDeg(angle) > creaseAngle + CREASE_TOLERANCE_DEGREES;+ return THREE40.MathUtils.radToDeg(angle) > creaseAngle + CREASE_TOLERANCE_DEGREES;}function buildLoft(rings, profiles, closed, cap, firstFrameForward, creaseAngle) {const n = rings[0].length, positions = [], uvs = [], indices = [];- const centers = rings.map((r) => r.reduce((sum, p) => sum.add(p), new THREE39.Vector3).multiplyScalar(1 / n));+ const centers = rings.map((r) => r.reduce((sum, p) => sum.add(p), new THREE40.Vector3).multiplyScalar(1 / n));const lengths = [0];for (let i = 1;i < centers.length; i++)lengths.push(lengths[i - 1] + centers[i].distanceTo(centers[i - 1]));@@ -28859,13 +28887,13 @@ function buildLoft(rings, profiles, closed, cap, firstFrameForward, creaseAngle)continue;const ring = rings[station], profile = profiles[station];const start = positions.length / 3;- const bounds = new THREE39.Box2().setFromPoints(profile);- const size = bounds.getSize(new THREE39.Vector2);+ const bounds = new THREE40.Box2().setFromPoints(profile);+ const size = bounds.getSize(new THREE40.Vector2);for (let j = 0;j < n; j++) {positions.push(...ring[j].toArray());uvs.push((profile[j].x - bounds.min.x) / (size.x || 1), (profile[j].y - bounds.min.y) / (size.y || 1));}- for (const tri of THREE39.ShapeUtils.triangulateShape(profile, [])) {+ for (const tri of THREE40.ShapeUtils.triangulateShape(profile, [])) {if (station === 0)indices.push(...tri.map((j) => start + j));else@@ -28878,7 +28906,7 @@ function buildLoft(rings, profiles, closed, cap, firstFrameForward, creaseAngle)const out = meshGeo({ positions, indices, uvs });const normal = out.getAttribute("normal");const share = (a, b) => {- const sum = new THREE39.Vector3().fromBufferAttribute(normal, a).add(new THREE39.Vector3().fromBufferAttribute(normal, b)).normalize();+ const sum = new THREE40.Vector3().fromBufferAttribute(normal, a).add(new THREE40.Vector3().fromBufferAttribute(normal, b)).normalize();normal.setXYZ(a, sum.x, sum.y, sum.z);normal.setXYZ(b, sum.x, sum.y, sum.z);};@@ -28916,8 +28944,8 @@ function loftProfiles(sections, options = {}) {if (profiles.some((p) => p.length !== profiles[0].length))throw new Error("loftProfiles sections must have the same point count and correspondence");const frames = sections.map((section) => geometryFrameMatrix(section.frame));- const rings = profiles.map((profile, i) => profile.map((p) => new THREE39.Vector3(p.x, 0, p.y).applyMatrix4(frames[i])));- const out = buildLoft(rings, profiles, false, loftCapEnds(options.cap), new THREE39.Vector3(0, 1, 0).transformDirection(frames[0]));+ const rings = profiles.map((profile, i) => profile.map((p) => new THREE40.Vector3(p.x, 0, p.y).applyMatrix4(frames[i])));+ const out = buildLoft(rings, profiles, false, loftCapEnds(options.cap), new THREE40.Vector3(0, 1, 0).transformDirection(frames[0]));const analysis = recordSweepAnalysis(out, rings, profiles, false);out.userData.kilnGeometryWarnings = analysis.complete ? [] : [{@@ -28940,8 +28968,8 @@ function sweepProfile(profile, path, options = {}) {const cap = sweepCapEnds(options.cap, closed);if (path.length < (closed ? 3 : 2) || path.some((p) => p.length !== 3 || !p.every(Number.isFinite)))throw new Error("sweepProfile requires finite path points (two open or three closed)");- const stations = path.map((p) => new THREE39.Vector3(...p));- const pathExtent = new THREE39.Box3().setFromPoints(stations).getSize(new THREE39.Vector3).length();+ const stations = path.map((p) => new THREE40.Vector3(...p));+ const pathExtent = new THREE40.Box3().setFromPoints(stations).getSize(new THREE40.Vector3).length();if (!(pathExtent > 0) || !Number.isFinite(pathExtent))throw new Error("sweepProfile path stations must be distinct with finite extent");const pathTolerance = pathExtent * 0.0000000001;@@ -28982,7 +29010,7 @@ function sweepProfile(profile, path, options = {}) {});return incoming.clone().add(outgoing).normalize();});- const up = options.up ? new THREE39.Vector3(...options.up) : Math.abs(tangents[0].z) < 0.9 ? new THREE39.Vector3(0, 0, 1) : new THREE39.Vector3(1, 0, 0);+ const up = options.up ? new THREE40.Vector3(...options.up) : Math.abs(tangents[0].z) < 0.9 ? new THREE40.Vector3(0, 0, 1) : new THREE40.Vector3(1, 0, 0);const upLength = Math.hypot(up.x, up.y, up.z);if (!(upLength > 0) || !Number.isFinite(upLength))throw new Error("sweepProfile up must be a finite nonzero vector");@@ -28999,7 +29027,7 @@ function sweepProfile(profile, path, options = {}) {}const distances = [0];for (let i = 1;i < stations.length; i++) {- z = z.clone().applyQuaternion(new THREE39.Quaternion().setFromUnitVectors(tangents[i - 1], tangents[i]));+ z = z.clone().applyQuaternion(new THREE40.Quaternion().setFromUnitVectors(tangents[i - 1], tangents[i]));normals.push(z);distances.push(distances[i - 1] + stations[i].distanceTo(stations[i - 1]));}@@ -29009,7 +29037,7 @@ function sweepProfile(profile, path, options = {}) {correction = Math.atan2(tangents[0].dot(normals[normals.length - 1].clone().cross(normals[0])), normals[normals.length - 1].dot(normals[0]));const rings = stations.map((station, i) => {const tangent = tangents[i], t = distances[i] / total;- const axisZ = normals[i].clone().applyAxisAngle(tangent, (correction + THREE39.MathUtils.degToRad(twist)) * t);+ const axisZ = normals[i].clone().applyAxisAngle(tangent, (correction + THREE40.MathUtils.degToRad(twist)) * t);const axisX = tangent.clone().cross(axisZ).normalize(), scale = scales[i];return points.map((p) => station.clone().addScaledVector(axisX, p.x * scale[0]).addScaledVector(axisZ, p.y * scale[1]));});@@ -29034,7 +29062,7 @@ var init_sweep2 = __esm(() => {});// src/simplify.ts-import * as THREE40 from "three";+import * as THREE41 from "three";function loadSimplifier() {simplifierReady ??= import("meshoptimizer/simplifier").then(async ({ MeshoptSimplifier }) => {await MeshoptSimplifier.ready;@@ -29056,7 +29084,7 @@ function gather(attribute, vertices) {for (let i = 0;i < vertices.length; i++)for (let c = 0;c < attribute.itemSize; c++)values[i * attribute.itemSize + c] = raw(attribute, vertices[i], c);- const out = new THREE40.BufferAttribute(values, attribute.itemSize, attribute.normalized);+ const out = new THREE41.BufferAttribute(values, attribute.itemSize, attribute.normalized);out.name = attribute.name;return out;}@@ -29341,14 +29369,14 @@ async function simplifyGeometry(geometry, options) {indexValues[i] = remap[w];}const sources = Uint32Array.from(used, (w) => representative[w]);- const out = new THREE40.BufferGeometry;+ const out = new THREE41.BufferGeometry;out.name = geometry.name;const outPosition = new Float32Array(sources.length * 3);for (let i = 0;i < used.length; i++)outPosition.set(positions.subarray(used[i] * 3, used[i] * 3 + 3), i * 3);for (const [name, attribute] of Object.entries(geometry.attributes)) {if (name === "position") {- const attr = new THREE40.BufferAttribute(outPosition, 3);+ const attr = new THREE41.BufferAttribute(outPosition, 3);attr.name = attribute.name;out.setAttribute(name, attr);} else@@ -29357,7 +29385,7 @@ async function simplifyGeometry(geometry, options) {for (const [name, targets] of Object.entries(geometry.morphAttributes))out.morphAttributes[name] = targets.map((target) => gather(target, sources));out.morphTargetsRelative = geometry.morphTargetsRelative;- out.setIndex(new THREE40.BufferAttribute(indexValues, 1));+ out.setIndex(new THREE41.BufferAttribute(indexValues, 1));for (const group of outGroups)out.addGroup(group.start, group.count, group.materialIndex);out.computeBoundingBox();@@ -29412,7 +29440,7 @@ var init_simplify = __esm(() => {});// src/solids.ts-import * as THREE41 from "three";+import * as THREE42 from "three";async function getManifoldModule() {if (_module)return _module;@@ -29442,10 +29470,10 @@ function computationFrame(parts) {meshes.push(mesh);});}- const origin = meshes.length ? new THREE41.Vector3().setFromMatrixPosition(meshes[0].matrixWorld) : new THREE41.Vector3;+ const origin = meshes.length ? new THREE42.Vector3().setFromMatrixPosition(meshes[0].matrixWorld) : new THREE42.Vector3;const matrices = new Map;- const bounds = new THREE41.Box3;- const point = new THREE41.Vector3;+ const bounds = new THREE42.Box3;+ const point = new THREE42.Vector3;for (const mesh of meshes) {const matrix = mesh.matrixWorld.clone();matrix.elements[12] -= origin.x;@@ -29462,11 +29490,11 @@ function computationFrame(parts) {bounds.expandByPoint(point);}}- const size = bounds.getSize(new THREE41.Vector3);+ const size = bounds.getSize(new THREE42.Vector3);const scale = Math.hypot(size.x, size.y, size.z);if (!Number.isFinite(scale))throw new Error("CSG: combined operand extent must be finite");- return { origin, center: bounds.getCenter(new THREE41.Vector3), scale: scale || 1, matrices };+ return { origin, center: bounds.getCenter(new THREE42.Vector3), scale: scale || 1, matrices };}function retainNotes(target, notes) {if (!Array.isArray(notes))@@ -29546,7 +29574,7 @@ function threeToManifold(src, mod, label, context) {elsecontext.missingUV.add(mesh.name || label);}- const point = new THREE41.Vector3;+ const point = new THREE42.Vector3;for (let i = 0;i < position.count; i++) {point.fromBufferAttribute(position, i).applyMatrix4(context.frame.matrices.get(mesh)).sub(context.frame.center).divideScalar(context.frame.scale);if (![point.x, point.y, point.z].every((n) => Number.isFinite(Math.fround(n))))@@ -29689,11 +29717,11 @@ function solidMeshToGeometry({ mesh, collapsed }, opts = {}) {if (uvs)uvs.set(mesh.vertProperties.subarray(i + 3, i + 5), v * 2);}- const geometry = new THREE41.BufferGeometry;- geometry.setAttribute("position", new THREE41.BufferAttribute(positions, 3));- geometry.setIndex(new THREE41.BufferAttribute(new Uint32Array(mesh.triVerts), 1));+ const geometry = new THREE42.BufferGeometry;+ geometry.setAttribute("position", new THREE42.BufferAttribute(positions, 3));+ geometry.setIndex(new THREE42.BufferAttribute(new Uint32Array(mesh.triVerts), 1));if (uvs)- geometry.setAttribute("uv", new THREE41.BufferAttribute(uvs, 2));+ geometry.setAttribute("uv", new THREE42.BufferAttribute(uvs, 2));const out = opts.smooth ? geometry : geometry.toNonIndexed();out.computeVertexNormals();if (opts.smooth && uvs) {@@ -29724,7 +29752,7 @@ function firstMaterial(src) {if (!material && mesh.isMesh)material = Array.isArray(mesh.material) ? mesh.material[0] : mesh.material;});- return material ?? new THREE41.MeshStandardMaterial;+ return material ?? new THREE42.MeshStandardMaterial;}function outputMesh(result, name, parts, opts, context, isHull) {const materialized = materializeSolid(result);@@ -29783,7 +29811,7 @@ function outputMesh(result, name, parts, opts, context, isHull) {retainNotes(context.geometryWarnings, geometry.userData.kilnGeometryWarnings);if (context.geometryWarnings.size)geometry.userData.kilnGeometryWarnings = [...context.geometryWarnings.values()];- const output = new THREE41.Mesh(geometry, context.preserve && !isHull && materials.length ? materials : firstMaterial(parts[0]));+ const output = new THREE42.Mesh(geometry, context.preserve && !isHull && materials.length ? materials : firstMaterial(parts[0]));output.name = `Mesh_${name}`;output.position.copy(context.frame.origin);return output;@@ -30192,7 +30220,7 @@ function smoothUnionSpheres(point, spheres, blend) {}// src/organic.ts-import * as THREE42 from "three";+import * as THREE43 from "three";function assertSafePathCount(name, count) {if (!Number.isSafeInteger(count))throw new Error(`${name} derived sample count must be a safe integer; reduce sample counts.`);@@ -30224,8 +30252,8 @@ function catmullRomPath(controlPoints, samplesPerSpan = 8, closed = false) {assertSafePathCount("catmullRomPath", spans * samplesPerSpan + 1);if (controlPoints.some((p) => p.length !== 3 || !p.every(Number.isFinite)))throw new Error("catmullRomPath control points must be finite [x,y,z] triples");- const vectors = controlPoints.map((p) => new THREE42.Vector3(p[0], p[1], p[2]));- const curve = new THREE42.CatmullRomCurve3(vectors, closed);+ const vectors = controlPoints.map((p) => new THREE43.Vector3(p[0], p[1], p[2]));+ const curve = new THREE43.CatmullRomCurve3(vectors, closed);const points = curve.getPoints(spans * samplesPerSpan);if (closed)points.pop();@@ -30279,8 +30307,8 @@ function spiralPath(options) {throw new Error("spiralPath center must be a finite [x,y,z] triple");if (axis.length !== 3 || forward.length !== 3 || ![...axis, ...forward].every(Number.isFinite))throw new Error("spiralPath axis and forward must be finite [x,y,z] triples");- const up = new THREE42.Vector3(...axis);- const fwd = new THREE42.Vector3(...forward);+ const up = new THREE43.Vector3(...axis);+ const fwd = new THREE43.Vector3(...forward);if (up.lengthSq() < 0.000000000001 || fwd.lengthSq() < 0.000000000001)throw new Error("spiralPath axis and forward must be nonzero");up.normalize();@@ -30288,7 +30316,7 @@ function spiralPath(options) {if (horiz.lengthSq() < 0.000000000001)throw new Error("spiralPath forward must not be parallel to axis");horiz.normalize();- const right = new THREE42.Vector3().crossVectors(up, horiz).normalize();+ const right = new THREE43.Vector3().crossVectors(up, horiz).normalize();const out = [];for (let i = 0;i <= samples; i++) {const u = i / samples;@@ -30402,7 +30430,7 @@ var init_seeded_random = __esm(() => {});// src/uv-shapes.ts-import * as THREE43 from "three";+import * as THREE44 from "three";function remapUV(geo, options = {}) {if (!options || typeof options !== "object" || Array.isArray(options) || Object.keys(options).some((key) => !["scale", "offset"].includes(key))) {throw new Error("remapUV: options may contain only scale and offset.");@@ -30431,7 +30459,7 @@ function remapUV(geo, options = {}) {}const cloned = geo.clone();cloned.userData = structuredClone(geo.userData);- cloned.setAttribute("uv", new THREE43.Float32BufferAttribute(values, 2));+ cloned.setAttribute("uv", new THREE44.Float32BufferAttribute(values, 2));if ((scale[0] !== 1 || scale[1] !== 1) && cloned.hasAttribute("tangent")) {cloned.deleteAttribute("tangent");const previous = cloned.userData.kilnAttributeWarnings;@@ -30448,13 +30476,13 @@ function remapUV(geo, options = {}) {var init_uv_shapes = () => {};// src/texture-atlas.ts-import * as THREE44 from "three";+import * as THREE45 from "three";async function textureAtlas(input, options = {}) {const compiled = await compileTextureAtlasSpecV1(input, options);- const texture = new THREE44.DataTexture(compiled.pixels, compiled.spec.width, compiled.spec.height, THREE44.RGBAFormat, THREE44.UnsignedByteType);+ const texture = new THREE45.DataTexture(compiled.pixels, compiled.spec.width, compiled.spec.height, THREE45.RGBAFormat, THREE45.UnsignedByteType);texture.name = "Atlas";texture.flipY = false;- texture.colorSpace = compiled.spec.usage === "albedo" || compiled.spec.usage === "emissive" ? THREE44.SRGBColorSpace : THREE44.NoColorSpace;+ texture.colorSpace = compiled.spec.usage === "albedo" || compiled.spec.usage === "emissive" ? THREE45.SRGBColorSpace : THREE45.NoColorSpace;applyPortableSamplerV1(texture, compiled.spec.sampler);texture.userData.kilnAtlas = { spec: compiled.spec, manifest: compiled.manifest };texture.userData.kilnTexture = {@@ -30505,7 +30533,7 @@ function remapUVToAtlas(geometry, atlas, name, options) {bytes += buffer.byteLength;}} else {- bytes += attribute.array.byteLength * (attribute.constructor === THREE44.BufferAttribute || attribute.constructor === THREE44.InstancedBufferAttribute ? 1 : 2);+ bytes += attribute.array.byteLength * (attribute.constructor === THREE45.BufferAttribute || attribute.constructor === THREE45.InstancedBufferAttribute ? 1 : 2);}};for (const attr of Object.values(geometry.attributes))@@ -30729,7 +30757,7 @@ var init_portable_material_runtime = __esm(() => {});// src/uv-data.ts-import * as THREE45 from "three";+import * as THREE46 from "three";function validateAtlasRemap(mesh, inputIndex, sourceCount) {const count = mesh.vertexCount;if (!Number.isSafeInteger(count) || count < 1 || count > GEOMETRY_ALLOCATION_LIMITS.unwrapVertices)@@ -30764,7 +30792,7 @@ function remapUnwrapAttribute(attribute, oldIndexes) {for (let c = 0;c < attribute.itemSize; c++)array[i * attribute.itemSize + c] = attribute.array[oldIndexes[i] * stride + offset + c];}- const output = attribute.isFloat16BufferAttribute ? new THREE45.Float16BufferAttribute(array, attribute.itemSize, attribute.normalized) : new THREE45.BufferAttribute(array, attribute.itemSize, attribute.normalized);+ const output = attribute.isFloat16BufferAttribute ? new THREE46.Float16BufferAttribute(array, attribute.itemSize, attribute.normalized) : new THREE46.BufferAttribute(array, attribute.itemSize, attribute.normalized);output.name = attribute.name;output.setUsage(interleaved(attribute) ? attribute.data.usage : attribute.usage);if (!interleaved(attribute))@@ -30876,7 +30904,7 @@ var init_uv_data = __esm(() => {});// src/uv.ts-import * as THREE46 from "three";+import * as THREE47 from "three";async function getXatlas() {if (!_xatlasReady) {_xatlasReady = (async () => {@@ -30908,7 +30936,7 @@ async function autoUnwrap(geometry, opts = {}) {if (result.atlasCount !== 1 || !Number.isSafeInteger(result.width) || result.width <= 0 || !Number.isSafeInteger(result.height) || result.height <= 0)throw new Error("autoUnwrap: xatlas must return one valid atlas; multiple atlas pages are unsupported.");const remap = validateAtlasRemap(mesh, prepared.index, geometry.getAttribute("position").count);- const out = new THREE46.BufferGeometry;+ const out = new THREE47.BufferGeometry;for (const [name, attribute] of Object.entries(geometry.attributes)) {if (name === "uv" || name === "tangent" || name === "normal" && !prepared.useNormals)continue;@@ -30918,8 +30946,8 @@ async function autoUnwrap(geometry, opts = {}) {out.morphAttributes[name] = targets.map((attribute) => remapUnwrapAttribute(attribute, remap.oldIndexes));}out.morphTargetsRelative = geometry.morphTargetsRelative;- out.setIndex(new THREE46.BufferAttribute(new Uint32Array(remap.index), 1));- out.setAttribute("uv", new THREE46.BufferAttribute(new Float32Array(remap.uv), 2));+ out.setIndex(new THREE47.BufferAttribute(new Uint32Array(remap.index), 1));+ out.setAttribute("uv", new THREE47.BufferAttribute(new Float32Array(remap.uv), 2));out.name = geometry.name;out.groups = geometry.groups.map((group) => ({ ...group }));out.setDrawRange(geometry.drawRange.start, geometry.drawRange.count);@@ -30954,11 +30982,11 @@ function repairZeroNormals(geo) {if (broken.size === 0)return;const acc = new Float32Array(normal.count * 3);- const a = new THREE46.Vector3;- const b = new THREE46.Vector3;- const c = new THREE46.Vector3;- const face = new THREE46.Vector3;- const edge = new THREE46.Vector3;+ const a = new THREE47.Vector3;+ const b = new THREE47.Vector3;+ const c = new THREE47.Vector3;+ const face = new THREE47.Vector3;+ const edge = new THREE47.Vector3;for (let t = 0;t + 2 < index.count; t += 3) {const tri = [index.getX(t), index.getX(t + 1), index.getX(t + 2)];if (!tri.some((i) => broken.has(i)))@@ -30994,7 +31022,7 @@ var init_uv = __esm(() => {});// src/uv-project.ts-import * as THREE47 from "three";+import * as THREE48 from "three";function projectUV(geometry, options) {if (!options || typeof options !== "object" || Array.isArray(options) || !["planar", "box", "cylindrical"].includes(options.projection) || Object.keys(options).some((key) => !["projection", "frame", "seamDegrees", "angularRange", "caps", "metersPerUnit"].includes(key)))throw new Error("projectUV: select an explicit planar, box or cylindrical projection with documented options.");@@ -31035,15 +31063,15 @@ function projectUV(geometry, options) {throw new Error("projectUV: index contains an invalid vertex reference.");}const points = [];- const bounds = new THREE47.Box3;+ const bounds = new THREE48.Box3;for (let i = 0;i < positions.count; i++) {- const point = new THREE47.Vector3().fromBufferAttribute(positions, i).applyMatrix4(inverse);+ const point = new THREE48.Vector3().fromBufferAttribute(positions, i).applyMatrix4(inverse);if (![point.x, point.y, point.z].every(Number.isFinite))throw new Error("projectUV: frame-local positions must be finite.");points.push(point);bounds.expandByPoint(point);}- const extent = bounds.getSize(new THREE47.Vector3);+ const extent = bounds.getSize(new THREE48.Vector3);const fit = (point, axis) => metric !== undefined ? point[axis] / metric : extent[axis] > 0 ? (point[axis] - bounds.min[axis]) / extent[axis] : 0.5;const flip = (point, axis) => metric !== undefined ? -point[axis] / metric : 1 - fit(point, axis);const outputUVs = new Float32Array(corners * 2);@@ -31058,8 +31086,8 @@ function projectUV(geometry, options) {if (metric !== undefined) {uScale = fullWrap ? Math.max(1, Math.round(2 * Math.PI * radius / metric)) : sweep * radius / metric;}- const normal = new THREE47.Vector3;- const edge = new THREE47.Vector3;+ const normal = new THREE48.Vector3;+ const edge = new THREE48.Vector3;for (let i = 0;i < corners; i += 3) {const triangle = [0, 1, 2].map((offset) => points[index ? index.getX(i + offset) : i + offset]);normal.subVectors(triangle[1], triangle[0]).cross(edge.subVectors(triangle[2], triangle[0])).normalize();@@ -31115,7 +31143,7 @@ function projectUV(geometry, options) {const out = geometry.index ? geometry.toNonIndexed() : geometry.clone();out.userData = structuredClone(geometry.userData);out.setDrawRange(geometry.drawRange.start, geometry.drawRange.count);- out.setAttribute("uv", new THREE47.Float32BufferAttribute(outputUVs, 2));+ out.setAttribute("uv", new THREE48.Float32BufferAttribute(outputUVs, 2));if (out.hasAttribute("tangent")) {out.deleteAttribute("tangent");const previous = out.userData.kilnAttributeWarnings;@@ -31136,17 +31164,17 @@ var init_uv_project = __esm(() => {});// src/primitives.ts-import * as THREE48 from "three";+import * as THREE49 from "three";function vectorToTuple(v) {return [v.x, v.y, v.z];}function createRoot(name) {- const root = new THREE48.Object3D;+ const root = new THREE49.Object3D;root.name = name;return root;}function createPivot(name, position = [0, 0, 0], parent) {- const pivot = new THREE48.Object3D;+ const pivot = new THREE49.Object3D;pivot.name = `Joint_${name}`;pivot.position.set(...position);if (parent)@@ -31178,16 +31206,16 @@ function assertPartArgs(name, geometry2, material) {}function createPart(name, geometry2, material, options = {}) {assertPartArgs(name, geometry2, material);- const mesh = new THREE48.Mesh(geometry2, material);+ const mesh = new THREE49.Mesh(geometry2, material);mesh.name = `Mesh_${name}`;if (options.position)mesh.position.set(...options.position);if (options.rotation)- mesh.rotation.set(THREE48.MathUtils.degToRad(options.rotation[0]), THREE48.MathUtils.degToRad(options.rotation[1]), THREE48.MathUtils.degToRad(options.rotation[2]));+ mesh.rotation.set(THREE49.MathUtils.degToRad(options.rotation[0]), THREE49.MathUtils.degToRad(options.rotation[1]), THREE49.MathUtils.degToRad(options.rotation[2]));if (options.scale)mesh.scale.set(...options.scale);if (options.pivot) {- const pivot = new THREE48.Object3D;+ const pivot = new THREE49.Object3D;pivot.name = `Joint_${name}`;pivot.add(mesh);mesh.position.set(0, 0, 0);@@ -31210,7 +31238,7 @@ function capsuleGeo(radius, height, segments = 6) {assertDimension("capsuleGeo height (straight middle length)", height, true);assertDimension("capsuleGeo outer half-length", height / 2 + radius);assertPrimitiveSegments("capsuleGeo segments", segments, 3);- return new THREE48.CapsuleGeometry(radius, height, 2, segments);+ return new THREE49.CapsuleGeometry(radius, height, 2, segments);}function capsuleXGeo(radius, length, segments = 6) {const geo = capsuleGeo(radius, length, segments);@@ -31229,7 +31257,7 @@ function cylinderGeo(radiusTop, radiusBottom, height, segments = 8) {throw new RangeError("cylinderGeo requires at least one positive radius.");assertDimension("cylinderGeo height", height);assertPrimitiveSegments("cylinderGeo segments", segments, 3);- return new THREE48.CylinderGeometry(radiusTop, radiusBottom, height, segments);+ return new THREE49.CylinderGeometry(radiusTop, radiusBottom, height, segments);}function cylinderXGeo(radiusTop, radiusBottom, length, segments = 8) {const geo = cylinderGeo(radiusTop, radiusBottom, length, segments);@@ -31244,20 +31272,20 @@ function cylinderZGeo(radiusTop, radiusBottom, length, segments = 8) {function boxGeo(width, height, depth) {for (const [name, value] of Object.entries({ width, height, depth }))assertDimension(`boxGeo ${name} (use planeGeo for a sheet)`, value);- return new THREE48.BoxGeometry(width, height, depth);+ return new THREE49.BoxGeometry(width, height, depth);}function sphereGeo(radius, widthSegments = 8, heightSegments = 6) {assertDimension("sphereGeo radius", radius);assertPrimitiveSegments("sphereGeo widthSegments", widthSegments, 3);assertPrimitiveSegments("sphereGeo heightSegments", heightSegments, 2);assertPrimitiveGrid("sphereGeo", widthSegments, heightSegments);- return new THREE48.SphereGeometry(radius, widthSegments, heightSegments);+ return new THREE49.SphereGeometry(radius, widthSegments, heightSegments);}function coneGeo(radius, height, segments = 8) {assertDimension("coneGeo radius", radius);assertDimension("coneGeo height", height);assertPrimitiveSegments("coneGeo segments", segments, 3);- return new THREE48.ConeGeometry(radius, height, segments);+ return new THREE49.ConeGeometry(radius, height, segments);}function coneXGeo(radius, length, segments = 8) {const geo = coneGeo(radius, length, segments);@@ -31274,7 +31302,7 @@ function cylinderOnAxis(center, normal, radiusBottom, height, options = {}) {const segments = options.segments ?? 8;assertFiniteTriple("cylinderOnAxis center", center);assertFiniteTriple("cylinderOnAxis normal", normal);- const n = new THREE48.Vector3(normal[0], normal[1], normal[2]);+ const n = new THREE49.Vector3(normal[0], normal[1], normal[2]);const len = Math.hypot(...normal);if (len < 0.000001) {throw new Error(`cylinderOnAxis: normal must be a non-zero vector (got [${normal.join(",")}]).`);@@ -31282,7 +31310,7 @@ function cylinderOnAxis(center, normal, radiusBottom, height, options = {}) {const magnitude = Math.max(...normal.map(Math.abs));n.set(normal[0] / magnitude, normal[1] / magnitude, normal[2] / magnitude).normalize();const geo = cylinderGeo(radiusTop, radiusBottom, height, segments);- const q = new THREE48.Quaternion().setFromUnitVectors(new THREE48.Vector3(0, 1, 0), n);+ const q = new THREE49.Quaternion().setFromUnitVectors(new THREE49.Vector3(0, 1, 0), n);geo.applyQuaternion(q);geo.translate(center[0], center[1], center[2]);return geo;@@ -31304,7 +31332,7 @@ function torusGeo(radius, tube, radialSegments = 8, tubularSegments = 12) {assertPrimitiveSegments("torusGeo radialSegments", radialSegments, 3);assertPrimitiveSegments("torusGeo tubularSegments", tubularSegments, 3);assertPrimitiveGrid("torusGeo", radialSegments, tubularSegments);- return new THREE48.TorusGeometry(radius, tube, radialSegments, tubularSegments);+ return new THREE49.TorusGeometry(radius, tube, radialSegments, tubularSegments);}function planeGeo(width, height, widthSegments = 1, heightSegments = 1) {assertDimension("planeGeo width", width);@@ -31312,14 +31340,14 @@ function planeGeo(width, height, widthSegments = 1, heightSegments = 1) {assertPrimitiveSegments("planeGeo widthSegments", widthSegments, 1);assertPrimitiveSegments("planeGeo heightSegments", heightSegments, 1);assertPrimitiveGrid("planeGeo", widthSegments, heightSegments);- return new THREE48.PlaneGeometry(width, height, widthSegments, heightSegments);+ return new THREE49.PlaneGeometry(width, height, widthSegments, heightSegments);}function decalBox(width, height, depth = 0.01) {assertDimension("decalBox width", width);assertDimension("decalBox height", height);assertDimension("decalBox depth", depth, true);const d = Math.max(depth, 0.002);- return new THREE48.BoxGeometry(width, height, d);+ return new THREE49.BoxGeometry(width, height, d);}function validateCardFrame(name, width, height, yPivot) {assertDimension(`${name} width`, width);@@ -31333,7 +31361,7 @@ function foliageCardGeo(opts = {}) {const h = opts.height ?? 1;const yPivot = opts.yPivot ?? 0;validateCardFrame("foliageCardGeo", w, h, yPivot);- const geom = new THREE48.PlaneGeometry(w, h);+ const geom = new THREE49.PlaneGeometry(w, h);geom.translate(0, h * (0.5 - yPivot), 0);geom.userData["kilnGeometryRole"] = "foliageCard";return geom;@@ -31349,12 +31377,12 @@ function crossedQuadsGeo(opts = {}) {const geometries = [];for (let i = 0;i < planes; i++) {const angle = i / planes * Math.PI;- const quad = new THREE48.PlaneGeometry(w, h);+ const quad = new THREE49.PlaneGeometry(w, h);quad.translate(0, h * (0.5 - yPivot), 0);quad.rotateY(angle);geometries.push(quad);}- const out = new THREE48.BufferGeometry;+ const out = new THREE49.BufferGeometry;const posCount = geometries.reduce((sum, g) => sum + (g.attributes.position?.count ?? 0), 0);const positions = new Float32Array(posCount * 3);const normals = new Float32Array(posCount * 3);@@ -31381,9 +31409,9 @@ function crossedQuadsGeo(opts = {}) {}vOffset += p.count;}- out.setAttribute("position", new THREE48.BufferAttribute(positions, 3));- out.setAttribute("normal", new THREE48.BufferAttribute(normals, 3));- out.setAttribute("uv", new THREE48.BufferAttribute(uvs, 2));+ out.setAttribute("position", new THREE49.BufferAttribute(positions, 3));+ out.setAttribute("normal", new THREE49.BufferAttribute(normals, 3));+ out.setAttribute("uv", new THREE49.BufferAttribute(uvs, 2));out.setIndex(indices);out.userData["kilnGeometryRole"] = "foliageCard";return out;@@ -31398,7 +31426,7 @@ function octaGridPlane(opts) {const h = opts.height ?? 1;const yPivot = opts.yPivot ?? 0;validateCardFrame("octaGridPlane", w, h, yPivot);- const geom = new THREE48.PlaneGeometry(w, h);+ const geom = new THREE49.PlaneGeometry(w, h);geom.translate(0, h * (0.5 - yPivot), 0);const uv = geom.attributes.uv;const du = 1 / opts.tilesX;@@ -31494,8 +31522,8 @@ function wingGeo(options = {}) {7,6];- const geo = new THREE48.BufferGeometry;- geo.setAttribute("position", new THREE48.BufferAttribute(vertices, 3));+ const geo = new THREE49.BufferGeometry;+ geo.setAttribute("position", new THREE49.BufferAttribute(vertices, 3));geo.setIndex(tipChord === 0 ? [0, 1, 3, 4, 7, 5, 0, 2, 6, 0, 6, 4, 1, 5, 7, 1, 7, 3, 0, 4, 5, 0, 5, 1] : indices);geo.computeVertexNormals();return geo;@@ -31526,17 +31554,17 @@ function createWingPair(name, material, options) {};}function beamBetween(name, start, end, radius, material, options = {}) {- const a = new THREE48.Vector3(...start);- const b = new THREE48.Vector3(...end);+ const a = new THREE49.Vector3(...start);+ const b = new THREE49.Vector3(...end);const direction = b.clone().sub(a);const length = direction.length();if (length <= 0.0001) {throw new Error(`beamBetween("${name}"): start and end must be different points (got start=[${start.join(",")}], end=[${end.join(",")}], delta=${length.toExponential(2)}). Pick two distinct endpoints or switch to cylinderGeo with an explicit length + position.`);}- const mesh = new THREE48.Mesh(cylinderGeo(radius, radius, length, options.segments ?? 8), material);+ const mesh = new THREE49.Mesh(cylinderGeo(radius, radius, length, options.segments ?? 8), material);mesh.name = `Mesh_${name}`;mesh.position.copy(a.add(b).multiplyScalar(0.5));- mesh.quaternion.setFromUnitVectors(new THREE48.Vector3(0, 1, 0), direction.normalize());+ mesh.quaternion.setFromUnitVectors(new THREE49.Vector3(0, 1, 0), direction.normalize());if (options.parent)options.parent.add(mesh);return mesh;@@ -31545,11 +31573,11 @@ function snapTo(part, host, options = {}) {const overlap = options.overlap ?? 0.02;part.updateWorldMatrix(true, true);host.updateWorldMatrix(true, true);- const a = new THREE48.Box3().setFromObject(part);- const b = new THREE48.Box3().setFromObject(host);+ const a = new THREE49.Box3().setFromObject(part);+ const b = new THREE49.Box3().setFromObject(host);if (a.isEmpty() || b.isEmpty())return part;- const delta = new THREE48.Vector3;+ const delta = new THREE49.Vector3;for (const axis of ["x", "y", "z"]) {if (a.min[axis] > b.max[axis])delta[axis] = b.max[axis] - a.min[axis];@@ -31565,7 +31593,7 @@ function snapTo(part, host, options = {}) {delta[dominant] = -overlap;const parent = part.parent;if (parent) {- const p0 = new THREE48.Vector3;+ const p0 = new THREE49.Vector3;part.getWorldPosition(p0);const p1 = p0.clone().add(delta);const l0 = parent.worldToLocal(p0.clone());@@ -31600,8 +31628,8 @@ function createLadder(name, options) {throw new RangeError("createLadder rungCount must be an integer from 0 to 10000.");if (widthAxis !== "x" && widthAxis !== "z")throw new RangeError("createLadder widthAxis must be x or z.");- const bottomVec = new THREE48.Vector3;- const topVec = new THREE48.Vector3(...top).sub(new THREE48.Vector3(...bottom));+ const bottomVec = new THREE49.Vector3;+ const topVec = new THREE49.Vector3(...top).sub(new THREE49.Vector3(...bottom));const length = Math.hypot(topVec.x, topVec.y, topVec.z);assertDimension("createLadder endpoint distance", length);if (length <= 0.0001)@@ -31609,7 +31637,7 @@ function createLadder(name, options) {const along = topVec.clone().divideScalar(length);if (widthDirection !== undefined)assertFiniteTriple("createLadder widthDirection", widthDirection);- let across = widthDirection ? new THREE48.Vector3(...widthDirection) : widthAxis === "x" ? new THREE48.Vector3(1, 0, 0) : new THREE48.Vector3(0, 0, 1);+ let across = widthDirection ? new THREE49.Vector3(...widthDirection) : widthAxis === "x" ? new THREE49.Vector3(1, 0, 0) : new THREE49.Vector3(0, 0, 1);const largest = Math.max(Math.abs(across.x), Math.abs(across.y), Math.abs(across.z));if (!largest)throw new RangeError("createLadder widthDirection must be nonzero.");@@ -31619,19 +31647,19 @@ function createLadder(name, options) {if (widthDirection)throw new RangeError("createLadder widthDirection must not be parallel to the endpoints.");const axes = [- new THREE48.Vector3(1, 0, 0),- new THREE48.Vector3(0, 1, 0),- new THREE48.Vector3(0, 0, 1)+ new THREE49.Vector3(1, 0, 0),+ new THREE49.Vector3(0, 1, 0),+ new THREE49.Vector3(0, 0, 1)];across = axes.reduce((best, axis) => Math.abs(axis.dot(along)) < Math.abs(best.dot(along)) ? axis : best);across.addScaledVector(along, -across.dot(along));}across.normalize();const offset = across.clone().multiplyScalar(width / 2);- const root = new THREE48.Object3D;+ const root = new THREE49.Object3D;root.name = name;root.position.set(...bottom);- const rotation = new THREE48.Quaternion().setFromRotationMatrix(new THREE48.Matrix4().makeBasis(across, along, across.clone().cross(along))).toArray();+ const rotation = new THREE49.Quaternion().setFromRotationMatrix(new THREE49.Matrix4().makeBasis(across, along, across.clone().cross(along))).toArray();stampSemanticMetadataV1(root, {roles: ["ladder"],frames: [@@ -31671,7 +31699,7 @@ function wallWithOpening(name, material, options) {if (opening && openings)throw new TypeError("wallWithOpening: use opening or openings, not both.");const built = buildWallPanels(length, height, thickness, openings ?? (opening ? [opening] : []));- const group = new THREE48.Object3D;+ const group = new THREE49.Object3D;group.name = name;const panel = (suffix, lenStart, lenEnd, yLo, yHi) => {const segLen = lenEnd - lenStart;@@ -31702,7 +31730,7 @@ function room(name, material, options = {}) {parent} = options;const openings = options.openings ?? [{ wall: "front", kind: "door" }];- const root = new THREE48.Object3D;+ const root = new THREE49.Object3D;root.name = name;const wall = (suffix, len, axis, pos, which) => {const w = wallWithOpening(`${name}_Wall${suffix}`, material, {@@ -31756,7 +31784,7 @@ function createStairs(name, material, options) {if (Math.abs(totalRise) < 0.0001 || Math.abs(totalRun) < 0.0001) {throw new Error(`createStairs("${name}"): totalRise and totalRun must be non-zero (got rise=${totalRise}, run=${totalRun}).`);}- const root = new THREE48.Object3D;+ const root = new THREE49.Object3D;root.name = name;const stepRise = totalRise / steps;const stepRun = totalRun / steps;@@ -31786,7 +31814,7 @@ function requireColor(color, fn) {}function gameMaterial(color, options = {}) {requireColor(color, "gameMaterial");- return new THREE48.MeshStandardMaterial({+ return new THREE49.MeshStandardMaterial({color,metalness: options.metalness ?? 0,roughness: options.roughness ?? 0.8,@@ -31797,7 +31825,7 @@ function gameMaterial(color, options = {}) {}function basicMaterial(color, options = {}) {requireColor(color, "basicMaterial");- return new THREE48.MeshBasicMaterial({+ return new THREE49.MeshBasicMaterial({color,transparent: options.transparent ?? false,opacity: options.opacity ?? 1@@ -31805,18 +31833,18 @@ function basicMaterial(color, options = {}) {}function glassMaterial(color, options = {}) {requireColor(color, "glassMaterial");- return new THREE48.MeshStandardMaterial({+ return new THREE49.MeshStandardMaterial({color,transparent: true,opacity: options.opacity ?? 0.35,roughness: options.roughness ?? 0.1,metalness: options.metalness ?? 0,- side: THREE48.DoubleSide+ side: THREE49.DoubleSide});}function lambertMaterial(color, options = {}) {requireColor(color, "lambertMaterial");- return new THREE48.MeshLambertMaterial({+ return new THREE49.MeshLambertMaterial({color,flatShading: options.flatShading ?? true,emissive: options.emissive ?? 0@@ -31826,12 +31854,12 @@ function threeInterpolation(mode) {if (mode !== undefined && !TRACK_INTERPOLATIONS.includes(mode)) {throw new Error(`Animation interpolation must be one of ${TRACK_INTERPOLATIONS.join(", ")}.`);}- return mode === "STEP" ? THREE48.InterpolateDiscrete : THREE48.InterpolateLinear;+ return mode === "STEP" ? THREE49.InterpolateDiscrete : THREE49.InterpolateLinear;}function interpolatedTrack(Type, name, times, values, interpolation) {if (!isCubicInterpolation(interpolation))return new Type(name, times, values, threeInterpolation(interpolation));- const quaternion = Type === THREE48.QuaternionKeyframeTrack;+ const quaternion = Type === THREE49.QuaternionKeyframeTrack;return useCubicSpline(new Type(name, times, cubicSplineValues(times, values, quaternion ? 4 : 3, interpolation, quaternion)));}function animationNumber(value, label) {@@ -31885,15 +31913,15 @@ function rotationTrack(jointName, keyframes, interpolation) {animationKeys(jointName, keyframes, "rotation", interpolation);const times = [];const values = [];- const euler = new THREE48.Euler;- const quat = new THREE48.Quaternion;+ const euler = new THREE49.Euler;+ const quat = new THREE49.Quaternion;for (const kf of keyframes) {times.push(kf.time);- euler.set(THREE48.MathUtils.degToRad(kf.rotation[0]), THREE48.MathUtils.degToRad(kf.rotation[1]), THREE48.MathUtils.degToRad(kf.rotation[2]));+ euler.set(THREE49.MathUtils.degToRad(kf.rotation[0]), THREE49.MathUtils.degToRad(kf.rotation[1]), THREE49.MathUtils.degToRad(kf.rotation[2]));quat.setFromEuler(euler);values.push(quat.x, quat.y, quat.z, quat.w);}- return interpolatedTrack(THREE48.QuaternionKeyframeTrack, `${jointName}.quaternion`, times, values, interpolation);+ return interpolatedTrack(THREE49.QuaternionKeyframeTrack, `${jointName}.quaternion`, times, values, interpolation);}function positionTrack(jointName, keyframes, interpolation) {animationKeys(jointName, keyframes, "position", interpolation);@@ -31903,7 +31931,7 @@ function positionTrack(jointName, keyframes, interpolation) {times.push(kf.time);values.push(...kf.position);}- return interpolatedTrack(THREE48.VectorKeyframeTrack, `${jointName}.position`, times, values, interpolation);+ return interpolatedTrack(THREE49.VectorKeyframeTrack, `${jointName}.position`, times, values, interpolation);}function scaleTrack(jointName, keyframes, interpolation) {animationKeys(jointName, keyframes, "scale", interpolation);@@ -31913,7 +31941,7 @@ function scaleTrack(jointName, keyframes, interpolation) {times.push(kf.time);values.push(...kf.scale);}- return interpolatedTrack(THREE48.VectorKeyframeTrack, `${jointName}.scale`, times, values, interpolation);+ return interpolatedTrack(THREE49.VectorKeyframeTrack, `${jointName}.scale`, times, values, interpolation);}function createClip(name, duration, tracks, options) {if (typeof name !== "string" || !name.trim())@@ -31926,7 +31954,7 @@ function createClip(name, duration, tracks, options) {const loop = clipLoopOption(options);const names = new Set;for (const track of tracks) {- if (!(track instanceof THREE48.KeyframeTrack))+ if (!(track instanceof THREE49.KeyframeTrack))throw new Error("Animation clip tracks must be KeyframeTrack instances.");if (typeof track.name !== "string")throw new Error("Animation track target/channel must use a string name.");@@ -31940,12 +31968,12 @@ function createClip(name, duration, tracks, options) {throw new Error(`Duplicate animation target/channel: ${track.name}.`);names.add(track.name);const quaternion = channel === "quaternion";- const Type = quaternion ? THREE48.QuaternionKeyframeTrack : THREE48.VectorKeyframeTrack;+ const Type = quaternion ? THREE49.QuaternionKeyframeTrack : THREE49.VectorKeyframeTrack;if (!(track instanceof Type))throw new Error(`Animation channel ${channel} requires ${quaternion ? "QuaternionKeyframeTrack" : "VectorKeyframeTrack"}.`);const cubic = isCubicSplineTrack(track);const mode = track.getInterpolation();- if (!cubic && mode !== THREE48.InterpolateLinear && mode !== THREE48.InterpolateDiscrete) {+ if (!cubic && mode !== THREE49.InterpolateLinear && mode !== THREE49.InterpolateDiscrete) {throw new Error("Animation interpolation must be LINEAR, STEP or CUBICSPLINE (the glTF sampler modes); three.js smooth and Bezier interpolants have no glTF form.");}animationTimes(track.times, track.name);@@ -31968,7 +31996,7 @@ function createClip(name, duration, tracks, options) {throw new Error(`Animation clip duration ${duration} does not include every key of ${track.name}.`);}}- const clip = new THREE48.AnimationClip(name, duration, tracks);+ const clip = new THREE49.AnimationClip(name, duration, tracks);if (loop !== undefined)clip.userData.kilnLoopIntent = loop ? "loop" : "once";return clip;@@ -32045,12 +32073,12 @@ function createInstance(name, source, options = {}) {if (!sourceMesh) {throw new Error(`createInstance("${name}"): source "${source.name}" has no Mesh to clone from`);}- const mesh = new THREE48.Mesh(sourceMesh.geometry, sourceMesh.material);+ const mesh = new THREE49.Mesh(sourceMesh.geometry, sourceMesh.material);mesh.name = `Mesh_${name}`;if (options.position)mesh.position.set(...options.position);if (options.rotation)- mesh.rotation.set(THREE48.MathUtils.degToRad(options.rotation[0]), THREE48.MathUtils.degToRad(options.rotation[1]), THREE48.MathUtils.degToRad(options.rotation[2]));+ mesh.rotation.set(THREE49.MathUtils.degToRad(options.rotation[0]), THREE49.MathUtils.degToRad(options.rotation[1]), THREE49.MathUtils.degToRad(options.rotation[2]));if (options.scale)mesh.scale.set(...options.scale);if (options.parent)@@ -32343,7 +32371,7 @@ function buildSandboxGlobals(usage, options = {}) {getJointNames: wrap("getJointNames", getJointNames),materialBudgetAdvisory: wrap("materialBudgetAdvisory", materialBudgetAdvisory),seededRandom: wrap("seededRandom", seededRandom),- THREE: THREE48,+ THREE: THREE49,Math,console: options.console ?? console};@@ -32718,7 +32746,7 @@ import {PropertyType as PropertyType4} from "@gltf-transform/core";import { createTransform, dequantizePrimitive, joinPrimitives } from "@gltf-transform/functions";-import * as THREE49 from "three";+import * as THREE50 from "three";function isSingular(matrix) {const e = matrix.elements;const scale = Math.hypot(e[0], e[1], e[2]) * Math.hypot(e[4], e[5], e[6]) * Math.hypot(e[8], e[9], e[10]);@@ -32836,10 +32864,10 @@ function reverseWinding(prim) {}}function bake(prim, matrix) {- const linear = new THREE49.Matrix3().setFromMatrix4(matrix);- const normalMatrix = new THREE49.Matrix3().getNormalMatrix(matrix);+ const linear = new THREE50.Matrix3().setFromMatrix4(matrix);+ const normalMatrix = new THREE50.Matrix3().getNormalMatrix(matrix);const mirrored = matrix.determinant() < 0;- const v = new THREE49.Vector3;+ const v = new THREE50.Vector3;const each = (semantic, apply) => {const attribute = prim.getAttribute(semantic);const element = [];@@ -32863,7 +32891,7 @@ function destinationOf(entries) {let best = Infinity;let bestScale = Infinity;for (const { node } of entries) {- const linear = new THREE49.Matrix3().setFromMatrix4(worldOf(node));+ const linear = new THREE50.Matrix3().setFromMatrix4(worldOf(node));const norm = Math.hypot(...linear.elements);const inverseNorm = Math.hypot(...linear.clone().invert().elements);const condition = norm * inverseNorm;@@ -32877,9 +32905,9 @@ function destinationOf(entries) {return chosen;}function checkPositionPrecision(input, output, sourceWorld, destinationWorld, reversed) {- const expected = new THREE49.Vector3;- const actual = new THREE49.Vector3;- const bounds = new THREE49.Box3;+ const expected = new THREE50.Vector3;+ const actual = new THREE50.Vector3;+ const bounds = new THREE50.Box3;const element = [];let error = 0;let magnitude = 0;@@ -33200,7 +33228,7 @@ function rigidMerge(options = {}, onSummary) {onSummary?.(summary);});}-var JOINT_PIVOT, RESTART_MODES, BAKED, MAX_VERTICES = 65534, MAX_BYTES_PER_SAVED_DRAW = 4096, hasKeys = (value) => Object.keys(value).length > 0, worldOf = (node) => new THREE49.Matrix4().fromArray(node.getWorldMatrix()), nodeUsers = (mesh) => mesh.listParents().filter((parent) => parent.propertyType === PropertyType4.NODE).length, accessorsOf = (prim) => {+var JOINT_PIVOT, RESTART_MODES, BAKED, MAX_VERTICES = 65534, MAX_BYTES_PER_SAVED_DRAW = 4096, hasKeys = (value) => Object.keys(value).length > 0, worldOf = (node) => new THREE50.Matrix4().fromArray(node.getWorldMatrix()), nodeUsers = (mesh) => mesh.listParents().filter((parent) => parent.propertyType === PropertyType4.NODE).length, accessorsOf = (prim) => {const indices = prim.getIndices();return indices ? [...prim.listAttributes(), indices] : prim.listAttributes();}, primitiveBytes = (primitives) => [...new Set(primitives.flatMap(accessorsOf))].reduce((sum, a) => sum + (a.getArray()?.byteLength ?? 0), 0), countPrimitives = (nodes) => [...nodes].reduce((sum, node) => sum + (node.getMesh()?.listPrimitives().length ?? 0), 0);@@ -34550,7 +34578,7 @@ var init_kit = __esm(() => {// src/texture-bake.tsimport { createHash as createHash8 } from "node:crypto";-import * as THREE50 from "three";+import * as THREE51 from "three";function readPixels(texture) {const image = texture.image;if (!image)@@ -34677,7 +34705,7 @@ async function bakeSceneTextures(root, warnings) {mime: "image/png",bytes};- const colorSpace = entry.texture.colorSpace === THREE50.SRGBColorSpace ? "srgb" : "linear";+ const colorSpace = entry.texture.colorSpace === THREE51.SRGBColorSpace ? "srgb" : "linear";const recipe = entry.texture.userData["kilnProcedural"];const primaryUsage = atlasRecord?.spec.usage ?? recipe?.usage ?? (entry.bindings.some(({ slot }) => slot === "roughnessMap") && entry.bindings.some(({ slot }) => slot === "metalnessMap") ? "metallicRoughness" : entry.bindings[0]?.usage ?? "albedo");if (!encoded)@@ -34760,10 +34788,10 @@ function computeTangentBasis(geometry) {}}const out = new Float32Array(vertexCount * 4);- const n = new THREE50.Vector3;- const t = new THREE50.Vector3;- const tmp = new THREE50.Vector3;- const tmp2 = new THREE50.Vector3;+ const n = new THREE51.Vector3;+ const t = new THREE51.Vector3;+ const tmp = new THREE51.Vector3;+ const tmp2 = new THREE51.Vector3;for (let v = 0;v < vertexCount; v++) {n.set(normal.getX(v), normal.getY(v), normal.getZ(v));t.set(tan1[v * 3], tan1[v * 3 + 1], tan1[v * 3 + 2]);@@ -34783,7 +34811,7 @@ function computeTangentBasis(geometry) {out[v * 4 + 2] = tmp.z;out[v * 4 + 3] = w;}- geometry.setAttribute("tangent", new THREE50.BufferAttribute(out, 4));+ geometry.setAttribute("tangent", new THREE51.BufferAttribute(out, 4));}function ensureNormalMapTangents(root, warnings) {let count = 0;@@ -35021,7 +35049,7 @@ import {KHRTextureBasisu as KHRTextureBasisu2} from "@gltf-transform/extensions";import { cloneDocument, dedup, prune, quantize, reorder } from "@gltf-transform/functions";-import * as THREE51 from "three";+import * as THREE52 from "three";function meshSignature(mesh, ids) {const id = (property) => {if (!property)@@ -35169,8 +35197,8 @@ function isCoreMaterialUse(parent) {return parent.propertyType === PropertyType5.MATERIAL;}function decomposeDelta(before, after) {- const delta = new THREE51.Matrix4().fromArray(before).invert().multiply(new THREE51.Matrix4().fromArray(after));- const position = new THREE51.Vector3, quaternion = new THREE51.Quaternion, scale = new THREE51.Vector3;+ const delta = new THREE52.Matrix4().fromArray(before).invert().multiply(new THREE52.Matrix4().fromArray(after));+ const position = new THREE52.Vector3, quaternion = new THREE52.Quaternion, scale = new THREE52.Vector3;delta.decompose(position, quaternion, scale);return {scale: scale.x,@@ -35198,12 +35226,12 @@ function positionGridSteps(doc, bits) {if (level.propertyType === PropertyType5.NODE)lodBase.set(level, node);const world = (node) => {- const matrix = new THREE51.Matrix4().fromArray(node.getWorldMatrix());+ const matrix = new THREE52.Matrix4().fromArray(node.getWorldMatrix());let top = node;while (top.getParentNode())top = top.getParentNode();const placed = lodBase.get(top)?.getParentNode();- return placed ? new THREE51.Matrix4().fromArray(placed.getWorldMatrix()).multiply(matrix) : matrix;+ return placed ? new THREE52.Matrix4().fromArray(placed.getWorldMatrix()).multiply(matrix) : matrix;};const halfExtent = (mesh) => {const min = [Infinity, Infinity, Infinity];@@ -35351,7 +35379,7 @@ async function deliverRuntimeThreeGlb(bytes, meshoptEncoder, options = {}, layouconst original = matrices.get(node);const moved = original === undefined;const split = moved || proxyNodes.has(node);- const reference = moved ? new THREE51.Matrix4().identity().toArray() : original;+ const reference = moved ? new THREE52.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))@@ -35547,7 +35575,7 @@ var init_exporter_node = __esm(() => {});// src/views/character.ts-import * as THREE52 from "three";+import * as THREE53 from "three";function rounded(value) {const result = Math.round(value * 1e9) / 1e9;return Object.is(result, -0) ? 0 : result;@@ -35589,9 +35617,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 THREE52.Vector3().setFromMatrixPosition(relative);- const forward = new THREE52.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);- const bend = new THREE52.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);+ const position = new THREE53.Vector3().setFromMatrixPosition(relative);+ const forward = new THREE53.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);+ const bend = new THREE53.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);const chainId = chainIdFor(joint.descriptor, descriptorByRole);return {role: joint.descriptor.role,@@ -36557,9 +36585,9 @@ import {import {BufferAttribute as BufferAttribute13,BufferGeometry as BufferGeometry16,- Group as Group5,+ Group as Group6,Matrix4 as Matrix418,- Mesh as Mesh14,+ Mesh as Mesh15,Bone as Bone2,SkinnedMesh as SkinnedMesh2,Skeleton as Skeleton3,@@ -36882,7 +36910,7 @@ function reviewSceneFromDocument(document) {if (!sourceScene)throw new GlbGeometryFlatError("GLB_FLAT_NO_SCENE", "Final GLB has no scene.");const reasons = new Set;- const root = new Group5;+ const root = new Group6;root.name = sourceScene.getName() || "Scene";const nodeMap = new Map;const atlas = atlasDocumentTable(document);@@ -36902,7 +36930,7 @@ function reviewSceneFromDocument(document) {const existing = nodeMap.get(source);if (existing)return existing;- const target = joints.has(source) ? new Bone2 : new Group5;+ const target = joints.has(source) ? new Bone2 : new Group6;target.name = source.getName();target.position.fromArray(source.getTranslation());target.quaternion.fromArray(source.getRotation());@@ -37023,7 +37051,7 @@ function reviewSceneFromDocument(document) {threeMaterial.aoMapIntensity = material.getOcclusionStrength();}for (const [index, matrix] of matrices.entries()) {- const mesh = source.getSkin() ? new SkinnedMesh2(geometry, threeMaterial) : new Mesh14(geometry, threeMaterial);+ const mesh = source.getSkin() ? new SkinnedMesh2(geometry, threeMaterial) : new Mesh15(geometry, threeMaterial);if (mesh instanceof SkinnedMesh2)pendingSkins.push({ source, mesh });const baseName = source.getName() || sourceMesh.getName() || "Mesh";@@ -37238,7 +37266,7 @@ var init_renderer_id = __esm(() => {});// src/views/scene-raster.ts-import * as THREE53 from "three";+import * as THREE54 from "three";var DEG2;var init_scene_raster = __esm(() => {init_evaluator();@@ -37250,18 +37278,18 @@ var init_scene_raster = __esm(() => {});// src/views/vehicle.ts-import * as THREE54 from "three";+import * as THREE55 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 THREE54.Box3;+ const bounds = new THREE55.Box3;let found = false;root.traverse((node) => {if (!hasRole2(node, "chassis"))return;node.traverse((part) => {- if (!(part instanceof THREE54.Mesh) || !(part.geometry instanceof THREE54.BufferGeometry))+ if (!(part instanceof THREE55.Mesh) || !(part.geometry instanceof THREE55.BufferGeometry))return;part.geometry.computeBoundingBox();const box = part.geometry.boundingBox;@@ -37271,7 +37299,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 THREE54.Vector3(x, y, z).applyMatrix4(matrix));+ bounds.expandByPoint(new THREE55.Vector3(x, y, z).applyMatrix4(matrix));found = true;}});@@ -37339,33 +37367,33 @@ function tagDiagnostic(node, role) {stampSemanticMetadataV1(node, { roles: [role] });}function rod(name, start, end, radius, color, role) {- const from = new THREE54.Vector3(...start);- const to = new THREE54.Vector3(...end);+ const from = new THREE55.Vector3(...start);+ const to = new THREE55.Vector3(...end);const direction = to.clone().sub(from);const length = direction.length();- const geometry = length > 0.000000001 ? new THREE54.CylinderGeometry(radius, radius, length, 8) : new THREE54.SphereGeometry(radius, 8, 6);- const result = new THREE54.Mesh(geometry, new THREE54.MeshBasicMaterial({ color }));+ const geometry = length > 0.000000001 ? new THREE55.CylinderGeometry(radius, radius, length, 8) : new THREE55.SphereGeometry(radius, 8, 6);+ const result = new THREE55.Mesh(geometry, new THREE55.MeshBasicMaterial({ color }));result.name = name;result.position.copy(from).add(to).multiplyScalar(0.5);if (length > 0.000000001) {- result.quaternion.setFromUnitVectors(new THREE54.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));+ result.quaternion.setFromUnitVectors(new THREE55.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));}tagDiagnostic(result, role);return result;}function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnostics(root)) {- const overlay = new THREE54.Group;+ const overlay = new THREE55.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 THREE54.Group;+ const arrow = new THREE55.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 THREE54.Mesh(new THREE54.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE54.MeshBasicMaterial({ color: 16724804 }));+ const arrowHead = new THREE55.Mesh(new THREE55.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE55.MeshBasicMaterial({ color: 16724804 }));arrowHead.name = "Diagnostic_Forward_Head";arrowHead.position.set(descriptor.forwardArrow.end[0] - 0.12, 0, 0);- arrowHead.quaternion.setFromUnitVectors(new THREE54.Vector3(0, 1, 0), new THREE54.Vector3(1, 0, 0));+ arrowHead.quaternion.setFromUnitVectors(new THREE55.Vector3(0, 1, 0), new THREE55.Vector3(1, 0, 0));tagDiagnostic(arrowHead, "diagnostic.vehicle.forward");arrow.add(arrowHead);overlay.add(arrow);@@ -37373,18 +37401,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 THREE54.Mesh(new THREE54.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE54.MeshBasicMaterial({ color: 16763955 }));+ const ring = new THREE55.Mesh(new THREE55.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE55.MeshBasicMaterial({ color: 16763955 }));ring.name = `Diagnostic_Wheel_${wheel.id}`;ring.position.set(...wheel.center);- const axle = new THREE54.Vector3(...wheel.axle);+ const axle = new THREE55.Vector3(...wheel.axle);if (axle.lengthSq() > 0.000000000001) {- ring.quaternion.setFromUnitVectors(new THREE54.Vector3(0, 0, 1), axle.normalize());+ ring.quaternion.setFromUnitVectors(new THREE55.Vector3(0, 0, 1), axle.normalize());}tagDiagnostic(ring, `diagnostic.vehicle.wheel.${wheel.id}`);overlay.add(ring);}if (descriptor.chassisBox) {- const chassis = new THREE54.Group;+ const chassis = new THREE55.Group;chassis.name = "Diagnostic_ChassisBox";tagDiagnostic(chassis, "diagnostic.vehicle.chassis");const { min, max } = descriptor.chassisBox;@@ -37418,7 +37446,7 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnooverlay.add(chassis);}if (descriptor.supportPlaneY !== undefined) {- const plane = new THREE54.Group;+ const plane = new THREE55.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;@@ -38016,7 +38044,7 @@ var init_views = __esm(() => {});// src/views/character-capture.ts-import * as THREE55 from "three";+import * as THREE56 from "three";function drawLine2(rgb, width, height, from, to, color) {let x0 = Math.round(from[0]);let y0 = Math.round(from[1]);@@ -38053,22 +38081,22 @@ function drawCross(rgb, width, height, point, color, radius = 3) {}function projector(root, cameraId, size) {root.updateMatrixWorld(true);- const bounds = new THREE55.Box3().setFromObject(root);+ const bounds = new THREE56.Box3().setFromObject(root);if (bounds.isEmpty())- bounds.set(new THREE55.Vector3(-0.5, 0, -0.5), new THREE55.Vector3(0.5, 1, 0.5));- const center = bounds.getCenter(new THREE55.Vector3);- const camera = cameraId === "front" ? new THREE55.Vector3(1, 0, 0) : new THREE55.Vector3(0, 0, 1);- const upHint = new THREE55.Vector3(0, 1, 0);- const xAxis = new THREE55.Vector3().crossVectors(upHint, camera).normalize();- const yAxis = new THREE55.Vector3().crossVectors(camera, xAxis).normalize();+ bounds.set(new THREE56.Vector3(-0.5, 0, -0.5), new THREE56.Vector3(0.5, 1, 0.5));+ const center = bounds.getCenter(new THREE56.Vector3);+ const camera = cameraId === "front" ? new THREE56.Vector3(1, 0, 0) : new THREE56.Vector3(0, 0, 1);+ const upHint = new THREE56.Vector3(0, 1, 0);+ const xAxis = new THREE56.Vector3().crossVectors(upHint, camera).normalize();+ const yAxis = new THREE56.Vector3().crossVectors(camera, xAxis).normalize();let extent = 0.000001;for (let corner = 0;corner < 8; corner++) {- const point = new THREE55.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 THREE56.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 THREE55.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);+ const world = new THREE56.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);return [size / 2 + world.dot(xAxis) * scale, size / 2 - world.dot(yAxis) * scale];};}@@ -38194,7 +38222,7 @@ var init_character_capture = __esm(() => {});// src/render.ts-import * as THREE56 from "three";+import * as THREE57 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";@@ -38421,7 +38449,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache, authorExtras, atlas)} else if (stdMat.transparent) {mat.setAlphaMode("BLEND");}- if (stdMat.side === THREE56.DoubleSide) {+ if (stdMat.side === THREE57.DoubleSide) {mat.setDoubleSided(true);}if (stdMat.map) {@@ -38498,7 +38526,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache, authorExtras, atlas)} else if (common.transparent || (common.opacity ?? 1) < 1) {mat.setAlphaMode("BLEND");}- if (threeMat.side === THREE56.DoubleSide)+ if (threeMat.side === THREE57.DoubleSide)mat.setDoubleSided(true);if (common.map && !mat.getBaseColorTexture()) {const texture = bridgeTexture(doc, common.map, textureCache);@@ -38661,7 +38689,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 THREE56.PlaneGeometry(1, 1);+ const geometry = new THREE57.PlaneGeometry(1, 1);if (centerX !== 0.5 || centerY !== 0.5) {geometry.translate(0.5 - centerX, 0.5 - centerY, 0);}@@ -38685,9 +38713,9 @@ function animationInterpolation(track) {if (isCubicSplineTrack(track))return "CUBICSPLINE";const mode = track.getInterpolation();- if (mode === THREE56.InterpolateDiscrete)+ if (mode === THREE57.InterpolateDiscrete)return "STEP";- if (mode === THREE56.InterpolateLinear)+ if (mode === THREE57.InterpolateLinear)return "LINEAR";throw new Error(`Unsupported animation interpolation on ${track.name}; use LINEAR, STEP or CUBICSPLINE.`);}@@ -39252,8 +39280,8 @@ function collectMeshStats(root) {if (!Number.isFinite(box.min.x) || !Number.isFinite(box.max.x)) {return;}- const center = new THREE56.Vector3;- const size = new THREE56.Vector3;+ const center = new THREE57.Vector3;+ const size = new THREE57.Vector3;box.getCenter(center);box.getSize(size);out.push({@@ -39269,7 +39297,7 @@ function collectMeshStats(root) {return out;}function minimalGapVector(a, b) {- const v = new THREE56.Vector3;+ const v = new THREE57.Vector3;for (const axis of ["x", "y", "z"]) {if (a.min[axis] > b.max[axis])v[axis] = b.max[axis] - a.min[axis];@@ -39287,10 +39315,10 @@ function inspectSceneStructure(root, opts = {}) {return warnings;const cat = opts.category?.toLowerCase();if (cat === "vehicle" || cat === "weapon" || cat === "boat" || cat === "aircraft") {- const all = new THREE56.Box3;+ const all = new THREE57.Box3;for (const m of meshes)all.union(m.box);- const size = new THREE56.Vector3;+ const size = new THREE57.Vector3;all.getSize(size);if (cat === "aircraft") {if (size.y > size.x * 1.2) {@@ -39415,18 +39443,18 @@ var init_render = __esm(() => {engineIO = createGltfIO;ACCESSOR_TYPES = [TYPE_SCALAR, TYPE_VEC2, TYPE_VEC3, TYPE_VEC4];GLTF_MIN_FILTER = {- [THREE56.NearestFilter]: 9728,- [THREE56.LinearFilter]: 9729,- [THREE56.NearestMipmapNearestFilter]: 9984,- [THREE56.LinearMipmapNearestFilter]: 9985,- [THREE56.NearestMipmapLinearFilter]: 9986,- [THREE56.LinearMipmapLinearFilter]: 9987- };- GLTF_MAG_FILTER = { [THREE56.NearestFilter]: 9728, [THREE56.LinearFilter]: 9729 };+ [THREE57.NearestFilter]: 9728,+ [THREE57.LinearFilter]: 9729,+ [THREE57.NearestMipmapNearestFilter]: 9984,+ [THREE57.LinearMipmapNearestFilter]: 9985,+ [THREE57.NearestMipmapLinearFilter]: 9986,+ [THREE57.LinearMipmapLinearFilter]: 9987+ };+ GLTF_MAG_FILTER = { [THREE57.NearestFilter]: 9728, [THREE57.LinearFilter]: 9729 };GLTF_WRAP = {- [THREE56.ClampToEdgeWrapping]: 33071,- [THREE56.MirroredRepeatWrapping]: 33648,- [THREE56.RepeatWrapping]: 10497+ [THREE57.ClampToEdgeWrapping]: 33071,+ [THREE57.MirroredRepeatWrapping]: 33648,+ [THREE57.RepeatWrapping]: 10497};REVIEW_CLIP_LIMITS2 = {clips: 32,@@ -40002,12 +40030,12 @@ var exports_part_placement = {};__export(exports_part_placement, {createPartPlacementReader: () => createPartPlacementReader});-import * as THREE57 from "three";+import * as THREE58 from "three";function createPartPlacementReader(root) {const bounds = createPartBoundsReader(root);- const position = new THREE57.Vector3;- const quaternion = new THREE57.Quaternion;- const scale = new THREE57.Vector3;+ const position = new THREE58.Vector3;+ const quaternion = new THREE58.Quaternion;+ const scale = new THREE58.Vector3;return (node) => {node.matrixWorld.decompose(position, quaternion, scale);const box = bounds(node);@@ -40812,7 +40840,7 @@ __export(exports_draw_diagnostics, {});import { Primitive as Primitive3 } from "@gltf-transform/core";import { cloneDocument as cloneDocument2 } from "@gltf-transform/functions";-import * as THREE58 from "three";+import * as THREE59 from "three";function withinLimits(doc) {const root = doc.getRoot();if (root.listNodes().length > MAX_NODES2 || root.listAccessors().length > 4096 || root.listMaterials().length > 2048 || root.listTextures().length > 256 || root.listScenes().length > 32 || doc.getGraph().listEdges().length > 32768)@@ -40865,7 +40893,7 @@ function collect2(doc, keep) {function overlaps(a, b) {if (Math.abs(a.normal.dot(b.normal)) < 1 - 0.00000001 || !a.bounds.intersectsBox(b.bounds))return false;- const tolerance = Math.max(a.bounds.getSize(new THREE58.Vector3).length(), b.bounds.getSize(new THREE58.Vector3).length(), 0.000000000001) * 0.000001;+ const tolerance = Math.max(a.bounds.getSize(new THREE59.Vector3).length(), b.bounds.getSize(new THREE59.Vector3).length(), 0.000000000001) * 0.000001;if (b.points.some((p) => Math.abs(a.normal.dot(p.clone().sub(a.points[0]))) > tolerance))return false;const normal = a.normal.toArray().map(Math.abs);@@ -40907,7 +40935,7 @@ function observe(uses) {unexaminedPrimitiveUses++;continue;}- const matrix = new THREE58.Matrix4().fromArray(node.getWorldMatrix());+ const matrix = new THREE59.Matrix4().fromArray(node.getWorldMatrix());if (primitive.getAttribute("TANGENT") && matrix.determinant() < 0)mirrored.set(part.id, part);const position = primitive.getAttribute("POSITION");@@ -40921,14 +40949,14 @@ function observe(uses) {const amount = Math.min(count, 8, MAX_SAMPLES - samples.length);for (let i = 0;i < amount; i++) {const start = Math.floor(i * count / amount) * 3;- const points = [0, 1, 2].map((j) => new THREE58.Vector3().fromArray(position.getElement(indices ? indices.getScalar(start + j) : start + j, [])).applyMatrix4(matrix));+ const points = [0, 1, 2].map((j) => new THREE59.Vector3().fromArray(position.getElement(indices ? indices.getScalar(start + j) : start + j, [])).applyMatrix4(matrix));const normal = points[1].clone().sub(points[0]).cross(points[2].clone().sub(points[0]));if (!Number.isFinite(normal.lengthSq()) || normal.lengthSq() === 0)continue;samples.push({points,normal: normal.normalize(),- bounds: new THREE58.Box3().setFromPoints(points),+ bounds: new THREE59.Box3().setFromPoints(points),part});}@@ -47918,7 +47946,7 @@ function createCachedEvaluatorPort(evaluator, options) {// src/tools/registry.tsinit_validation();-import * as THREE59 from "three";+import * as THREE60 from "three";// src/evaluator/source-check.tsinit_validation();@@ -48547,8 +48575,8 @@ function collectSceneMetrics(root) {let meshes = 0;const materialSet = new Set;let lowestPart;- const box = new THREE59.Box3;- const point = new THREE59.Vector3;+ const box = new THREE60.Box3;+ const point = new THREE60.Vector3;root.updateWorldMatrix(true, true);root.traverseVisible((node) => {const n = node;@@ -48564,7 +48592,7 @@ function collectSceneMetrics(root) {const mesh = node;const position = mesh.geometry.getAttribute("position");const index = mesh.geometry.index;- const mb = new THREE59.Box3;+ const mb = new THREE60.Box3;if (position) {for (let i = 0;i < (index?.count ?? position.count); i++) {point.fromBufferAttribute(position, index ? index.getX(i) : i);@@ -48579,7 +48607,7 @@ function collectSceneMetrics(root) {});let bbox;if (!box.isEmpty()) {- const size = new THREE59.Vector3;+ const size = new THREE60.Vector3;box.getSize(size);bbox = {min: [box.min.x, box.min.y, box.min.z],diff --git a/dist/build.json b/dist/build.jsonindex 649f694e..e51b75b0 100644--- a/dist/build.json+++ b/dist/build.json@@ -2,10 +2,10 @@"schemaVersion": 1,"entries": {"worker": {- "identity": "sha256:ae5bde6fdebeb76e16ce628332942d31b598da16b7e07c46490f65ac58a9e163",+ "identity": "sha256:083e33f84bf843db5a6c42cf19fb6cc3bc8a038824d196dac15284d2e3291d06","engineVersion": "1.4.0","toolchain": "[email protected]",- "sourceHash": "6b6e7c6fd6f48063ba153972d2260442101005312035c709e3e7f7c07bba7d88",+ "sourceHash": "a8663cce75940046f86086c317e54fc53915a38dcbf4ffa472d723fbb3a8d139","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -37,13 +37,13 @@},"target": "node","file": "evaluator-worker.mjs",- "bundleHash": "sha256:c7a5406b63e034ba5f68ae9db872fef48864bcbfc7e34ead37f6b66c063de0f4"+ "bundleHash": "sha256:3f48aee9b0f51826d299364438a10317c5df2d32c8901e32bd2ad32883984ef4"},"agent-run": {- "identity": "sha256:ae5bde6fdebeb76e16ce628332942d31b598da16b7e07c46490f65ac58a9e163",+ "identity": "sha256:083e33f84bf843db5a6c42cf19fb6cc3bc8a038824d196dac15284d2e3291d06","engineVersion": "1.4.0","toolchain": "[email protected]",- "sourceHash": "6b6e7c6fd6f48063ba153972d2260442101005312035c709e3e7f7c07bba7d88",+ "sourceHash": "a8663cce75940046f86086c317e54fc53915a38dcbf4ffa472d723fbb3a8d139","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -75,13 +75,13 @@},"target": "node","file": "agent-run.mjs",- "bundleHash": "sha256:0ca973fde02381f727156c34e519e8b9b8847c9513fb0574a0117ae7d825fbbc"+ "bundleHash": "sha256:a9b8ea268099f3fee7f67b9bc0e19627359723acab0371df640b0a00a99c0a55"},"agent-providers": {- "identity": "sha256:ae5bde6fdebeb76e16ce628332942d31b598da16b7e07c46490f65ac58a9e163",+ "identity": "sha256:083e33f84bf843db5a6c42cf19fb6cc3bc8a038824d196dac15284d2e3291d06","engineVersion": "1.4.0","toolchain": "[email protected]",- "sourceHash": "6b6e7c6fd6f48063ba153972d2260442101005312035c709e3e7f7c07bba7d88",+ "sourceHash": "a8663cce75940046f86086c317e54fc53915a38dcbf4ffa472d723fbb3a8d139","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -116,10 +116,10 @@"bundleHash": "sha256:9d6faf03d307321bc2e3bd5ce5bdee0bbbf61e0ebed8bfebfa1fb072287b83fa"},"mcp": {- "identity": "sha256:ae5bde6fdebeb76e16ce628332942d31b598da16b7e07c46490f65ac58a9e163",+ "identity": "sha256:083e33f84bf843db5a6c42cf19fb6cc3bc8a038824d196dac15284d2e3291d06","engineVersion": "1.4.0","toolchain": "[email protected]",- "sourceHash": "6b6e7c6fd6f48063ba153972d2260442101005312035c709e3e7f7c07bba7d88",+ "sourceHash": "a8663cce75940046f86086c317e54fc53915a38dcbf4ffa472d723fbb3a8d139","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -154,10 +154,10 @@"bundleHash": "sha256:8c2fcbae79116bb20b75e98313f9c5044835b4f8d28def79c8333944748202a9"},"cli": {- "identity": "sha256:ae5bde6fdebeb76e16ce628332942d31b598da16b7e07c46490f65ac58a9e163",+ "identity": "sha256:083e33f84bf843db5a6c42cf19fb6cc3bc8a038824d196dac15284d2e3291d06","engineVersion": "1.4.0","toolchain": "[email protected]",- "sourceHash": "6b6e7c6fd6f48063ba153972d2260442101005312035c709e3e7f7c07bba7d88",+ "sourceHash": "a8663cce75940046f86086c317e54fc53915a38dcbf4ffa472d723fbb3a8d139","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -189,13 +189,13 @@},"target": "node","file": "cli.mjs",- "bundleHash": "sha256:4aad316658aa30149228513cb081b5ce0ecd5e4ad0cacab80b3fc2b789859b8a"+ "bundleHash": "sha256:9c862e5bc37dea4ac08421a2b77406af541400d0f97264453d0b12e8873ab1fd"},"engine": {- "identity": "sha256:ae5bde6fdebeb76e16ce628332942d31b598da16b7e07c46490f65ac58a9e163",+ "identity": "sha256:083e33f84bf843db5a6c42cf19fb6cc3bc8a038824d196dac15284d2e3291d06","engineVersion": "1.4.0","toolchain": "[email protected]",- "sourceHash": "6b6e7c6fd6f48063ba153972d2260442101005312035c709e3e7f7c07bba7d88",+ "sourceHash": "a8663cce75940046f86086c317e54fc53915a38dcbf4ffa472d723fbb3a8d139","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -227,7 +227,7 @@},"target": "node","file": "mcp-engine.mjs",- "bundleHash": "sha256:f6f1735b83a3f23f80e0781ff18321544e2294969d9acbff6e970b6ad9ab7838"+ "bundleHash": "sha256:2055e1f6f86436cfc2501ac36b20d00ab6d43b67effe205a9a614ac8ea09ead3"}}}diff --git a/dist/cli.mjs b/dist/cli.mjsindex b4e2f78e..48238eb4 100644--- a/dist/cli.mjs+++ b/dist/cli.mjs@@ -20274,1075 +20274,421 @@ var init_procedural_material_v3 = __esm(() => {};});-// src/material-library-node.ts-import { createHash as createHash6, randomUUID as randomUUID2 } from "node:crypto";-import { lstat as lstat3, mkdir as mkdir2, readFile as readFile2, readdir, realpath as realpath2, rm, writeFile as writeFile2 } from "node:fs/promises";-import { dirname as dirname2, join as join2, relative, resolve as resolve4, sep } from "node:path";-import sharp from "sharp";-import { DataTexture as DataTexture3 } from "three";-function revisionHash(manifest) {- const { revisionId: _, ...content } = manifest;- return digest(canonicalMaterialJson(content));-}-function snapshot(record) {- validateMaterialRecordShape(record);- return {- manifest: structuredClone(record.manifest),- files: Object.fromEntries(Object.entries(record.files).map(([name, bytes]) => [name, Uint8Array.from(bytes)]))- };-}-function exactKeys(value, keys) {- if (Object.keys(value).some((key) => !keys.includes(key)))- throw new Error("Unknown material draft field");+// src/qa/breadth-final.ts+import * as THREE26 from "three";+function bytesContainAscii(bytes, value) {+ const needle = new TextEncoder().encode(value);+ outer:+ for (let index = 0;index <= bytes.length - needle.length; index++) {+ for (let offset = 0;offset < needle.length; offset++) {+ if (bytes[index + offset] !== needle[offset])+ continue outer;+ }+ return true;+ }+ return false;}-function derivedNormalPixels(compiled, size, derive) {- if (!derive)- return compiled;- materialNormalDerivationSchema.parse(derive);- if (size.usage !== "normal")- throw new Error("Height derivation requires a normal map slot");- const height = new DataTexture3(compiled.pixels, size.width, size.height);- const normal = normalMapFromHeight(height, { strength: derive.strength });- if (!(normal.image.data instanceof Uint8Array))- throw new Error("Normal derivation must produce RGBA8 pixels");- const pixels = Uint8Array.from(normal.image.data);- height.dispose();- normal.dispose();- return { ...compiled, pixels };+function encodedTextureHasAlpha(mimeType, bytes) {+ if (mimeType === "image/png") {+ const colorType = bytes[25];+ return colorType === 4 || colorType === 6 || bytesContainAscii(bytes, "tRNS");+ }+ if (mimeType === "image/webp") {+ if (bytesContainAscii(bytes, "ALPH"))+ return true;+ const vp8xIndex = (() => {+ const marker = new TextEncoder().encode("VP8X");+ for (let index = 0;index <= bytes.length - marker.length; index++) {+ if (marker.every((value, offset) => bytes[index + offset] === value))+ return index;+ }+ return -1;+ })();+ return vp8xIndex >= 0 && ((bytes[vp8xIndex + 8] ?? 0) & 16) !== 0;+ }+ return false;}-function materialPixels(spec, derive) {- const compiled = compileProceduralTextureSpecV2(spec);- const { size, usage } = compiled.spec;- return derivedNormalPixels(compiled, { width: size, height: size, usage }, derive);+function animationDuration(animation) {+ let duration = 0;+ for (const sampler of animation.listSamplers()) {+ const max = sampler.getInput()?.getMax([]);+ if (max && typeof max[0] === "number" && Number.isFinite(max[0])) {+ duration = Math.max(duration, max[0]);+ }+ }+ return stable8(duration);}-function materialPixelsV3(spec, derive) {- const compiled = compileProceduralTextureSpecV3(spec);- return derivedNormalPixels(compiled, compiled.spec, derive);+function signedAxis2(vector) {+ const values = [+ { axis: "X", value: vector.x },+ { axis: "Y", value: vector.y },+ { axis: "Z", value: vector.z }+ ];+ const dominant = [...values].sort((a, b) => Math.abs(b.value) - Math.abs(a.value))[0];+ return `${dominant.value < 0 ? "-" : "+"}${dominant.axis}`;}-async function createMaterialRecordV1(draft) {- assertMaterialJson(draft, true);- exactKeys(draft, [- "materialId",- "name",- "tags",- "tileable",- "physicalSizeMeters",- "parameters",- "sources",- "maps"- ]);- if (!Array.isArray(draft.maps) || !draft.maps.length || draft.maps.length > 5)- throw new Error("Material requires 1..5 maps");- const files = {};- const maps = [];- let totalPixels = 0;- for (const input of draft.maps) {- exactKeys(input, [- "slot",- "sourceId",- "transforms",- "normalConvention",- "channelPacking",- "bytes",- "originalFile",- "procedural",- "derive"- ]);- if (!MATERIAL_LIBRARY_SLOTS.includes(input.slot))- throw new Error("Unsupported material map slot");- if (input.bytes !== undefined === (input.procedural !== undefined))- throw new Error("Supply exactly one map byte source or procedural recipe");- let bytes;- let procedural;- if (input.procedural) {- const compiled = materialPixels(input.procedural, input.derive);- if (compiled.spec.usage !== MATERIAL_LIBRARY_USAGE[input.slot])- throw new Error("Procedural map usage mismatch");- bytes = new Uint8Array(await sharp(compiled.pixels, {- raw: { width: compiled.spec.size, height: compiled.spec.size, channels: 4 }- }).png({ compressionLevel: 9, adaptiveFiltering: false }).toBuffer());- procedural = {- compiler: "kiln.procedural-texture.v2",- spec: compiled.spec,- ...input.derive ? { derive: structuredClone(input.derive) } : {},- recipeHash: compiled.recipeHash,- pixelHash: digest(compiled.pixels),- encoder+function finalEffectAxis(nodes, mode) {+ let best;+ for (const node of nodes) {+ const semantic = readSemanticMetadataV1FromExtras(node.getExtras());+ if (!(semantic?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {+ continue;+ }+ const matrix = new THREE26.Matrix4().fromArray(node.getWorldMatrix());+ const scale = node.getWorldScale();+ const scaleMagnitude = Math.hypot(scale[0], scale[1], scale[2]);+ for (const primitive of node.getMesh()?.listPrimitives() ?? []) {+ const position = primitive.getAttribute("POSITION");+ if (!position)+ continue;+ const min = position.getMin([]);+ const max = position.getMax([]);+ const axes = [+ { score: (max[0] ?? 0) - (min[0] ?? 0), direction: new THREE26.Vector3(1, 0, 0) },+ { score: (max[1] ?? 0) - (min[1] ?? 0), direction: new THREE26.Vector3(0, 1, 0) },+ { score: (max[2] ?? 0) - (min[2] ?? 0), direction: new THREE26.Vector3(0, 0, 1) }+ ];+ const selected = axes.reduce((candidate, value) => mode === "length" ? value.score > candidate.score ? value : candidate : value.score < candidate.score ? value : candidate);+ const candidate = {+ score: selected.score * scaleMagnitude,+ direction: selected.direction.transformDirection(matrix)};- } else {- if ("derive" in input)- throw new Error("External maps cannot declare a procedural derivation");- if (!(input.bytes instanceof Uint8Array))- throw new Error("Material map bytes must be Uint8Array");- bytes = Uint8Array.from(input.bytes);+ if (!best || (mode === "length" ? candidate.score > best.score : candidate.score < best.score)) {+ best = candidate;+ }}- if (bytes.length > MATERIAL_LIBRARY_LIMITS.maxMapBytes)- throw new Error("Material map exceeds encoded byte limit");- const dimensions = materialPngDimensions(bytes);- totalPixels += dimensions.width * dimensions.height;- if (dimensions.width < 1 || dimensions.height < 1 || dimensions.width > MATERIAL_LIBRARY_LIMITS.maxMapEdge || dimensions.height > MATERIAL_LIBRARY_LIMITS.maxMapEdge || totalPixels > MATERIAL_LIBRARY_LIMITS.maxRecordPixels)- throw new Error("Material maps exceed pixel budget");- const file = `${input.slot}.png`;- if (files[file])- throw new Error("Duplicate material map slot");- files[file] = bytes;- maps.push({- slot: input.slot,- file,- ...dimensions,- sha256: digest(bytes),- bytes: bytes.length,- usage: MATERIAL_LIBRARY_USAGE[input.slot],- colorSpace: input.slot === "baseColor" || input.slot === "emissive" ? "srgb" : "linear",- ...input.slot === "normal" ? { normalConvention: input.normalConvention ?? (procedural ? "opengl" : undefined) } : {},- ...input.slot === "metallicRoughness" ? {- channelPacking: input.channelPacking ?? (procedural ? "r-occlusion-g-roughness-b-metallic" : undefined)- } : {},- sourceId: input.sourceId,- ...input.originalFile ? { originalFile: input.originalFile } : {},- transforms: structuredClone(input.transforms),- ...procedural ? { procedural } : {}- });}- const manifest = materialManifestSchema.parse({- schemaVersion: 1,- materialId: draft.materialId,- revisionId: `sha256:${"0".repeat(64)}`,- name: draft.name,- tags: draft.tags ?? [],- tileable: draft.tileable,- ...draft.physicalSizeMeters ? { physicalSizeMeters: draft.physicalSizeMeters } : {},- parameters: draft.parameters ?? {},- sources: draft.sources,- maps- });- manifest.revisionId = revisionHash(manifest);- const record = { manifest, files };- await verifyMaterialRecordV1(record);- return record;+ return best ? signedAxis2(best.direction) : undefined;}-async function verifyMaterialRecordV1(record) {- const manifest = validateMaterialRecordShape(record);- if (revisionHash(manifest) !== manifest.revisionId)- throw new Error("Material identity hash mismatch");- for (const map of manifest.maps) {- const bytes = record.files[map.file];- if (digest(bytes) !== map.sha256)- throw new Error(`Material integrity hash mismatch: ${map.file}`);- const { data, info } = await sharp(bytes, {- limitInputPixels: MATERIAL_LIBRARY_LIMITS.maxRecordPixels,- failOn: "warning"- }).ensureAlpha().raw().toBuffer({ resolveWithObject: true });- if (info.width !== map.width || info.height !== map.height || info.channels !== 4)- throw new Error("Material decoded image mismatch");- if (map.procedural) {- const compiled = materialPixels(map.procedural.spec, map.procedural.derive);- if (compiled.recipeHash !== map.procedural.recipeHash || digest(compiled.pixels) !== map.procedural.pixelHash || digest(data) !== map.procedural.pixelHash)- throw new Error("Procedural material recipe or pixel hash mismatch");+async function analyzeFinalVfxGlbBytesV1(bytes) {+ const io = createGltfIO();+ const document = await io.readBinary(bytes);+ const root = document.getRoot();+ const renderableNodes = root.listNodes().filter((node) => node.getMesh() !== null);+ const meshes = [...new Set(renderableNodes.map((node) => node.getMesh()).filter(Boolean))];+ const primitives = meshes.flatMap((mesh) => mesh?.listPrimitives() ?? []);+ let triangleCount = 0;+ for (const primitive of primitives) {+ const indices = primitive.getIndices();+ const position = primitive.getAttribute("POSITION");+ triangleCount += indices ? indices.getCount() / 3 : (position?.getCount() ?? 0) / 3;+ }+ const effectSurfaceMaterials = new Set;+ for (const node of renderableNodes) {+ const semantic = readSemanticMetadataV1FromExtras(node.getExtras());+ if (!(semantic?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {+ continue;+ }+ for (const primitive of node.getMesh()?.listPrimitives() ?? []) {+ const material = primitive.getMaterial();+ if (material)+ effectSurfaceMaterials.add(material);}}-}-function validateMaterialLibraryPayload(value) {- assertMaterialJson(value);- if (!value || typeof value !== "object" || Array.isArray(value))- throw new Error("Invalid material resource payload");- const payload = value;- if (Object.keys(payload).some((key) => !["schemaVersion", "records"].includes(key)) || payload.schemaVersion !== 1 || !Array.isArray(payload.records) || payload.records.length > MATERIAL_LIBRARY_LIMITS.maxPayloadRecords)- throw new Error("Invalid material resource payload");- let total = 0;- let pixels = 0;- const identities = new Set;- for (const wire of payload.records) {- if (!wire || typeof wire !== "object" || Object.keys(wire).some((key) => !["manifest", "files"].includes(key)))- throw new Error("Invalid material resource record");- const manifest = materialManifestSchema.parse(wire.manifest);- if (identities.has(manifest.revisionId))- throw new Error("Duplicate material resource revision");- identities.add(manifest.revisionId);- if (!wire.files || typeof wire.files !== "object" || Array.isArray(wire.files) || Object.keys(wire.files).length !== manifest.maps.length)- throw new Error("Material payload inventory mismatch");- for (const map of manifest.maps) {- const encoded = wire.files[map.file];- if (typeof encoded !== "string" || encoded.length !== Math.ceil(map.bytes / 3) * 4 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encoded))- throw new Error("Invalid material map base64");- total += map.bytes;- pixels += map.width * map.height;+ const materials = [+ ...new Set(primitives.map((primitive) => primitive.getMaterial()).filter(Boolean))+ ].map((material, index) => {+ const baseColor = material.getBaseColorFactor();+ const texture = material.getBaseColorTexture();+ const image = texture?.getImage();+ const mimeType = texture?.getMimeType() ?? "";+ const mode = material.getAlphaMode().toLowerCase();+ return {+ id: material.getName() || `material.${index}`,+ effectSurface: effectSurfaceMaterials.has(material),+ alphaMode: mode,+ alphaData: (baseColor[3] ?? 1) < 1 || image !== null && image !== undefined && encodedTextureHasAlpha(mimeType, image),+ doubleSided: material.getDoubleSided(),+ ...mode === "mask" ? { alphaCutoff: material.getAlphaCutoff() } : {}+ };+ });+ const facingSemantics = new Set;+ for (const node of renderableNodes) {+ const semantic = readSemanticMetadataV1FromExtras(node.getExtras());+ for (const role of semantic?.roles ?? []) {+ const match = /^vfx\.facing\.(fixed|camera-spherical|camera-y-axis)$/.exec(role);+ if (match)+ facingSemantics.add(match[1]);}}- if (total > MATERIAL_LIBRARY_LIMITS.maxPayloadBytes || pixels > MATERIAL_LIBRARY_LIMITS.maxPayloadPixels)- throw new Error("Material resource payload exceeds byte or pixel budget");- return payload;-}-async function createMaterialLibraryPayloadV1(records) {- const snapshots = records.map(snapshot);- for (const record of snapshots)- await verifyMaterialRecordV1(record);- return validateMaterialLibraryPayload({+ const normalAxis = finalEffectAxis(renderableNodes, "normal");+ const directionAxis = finalEffectAxis(renderableNodes, "length");+ return {schemaVersion: 1,- records: snapshots.map((record) => ({- manifest: record.manifest,- files: Object.fromEntries(Object.entries(record.files).map(([name, bytes]) => [- name,- Buffer.from(bytes).toString("base64")- ]))+ meshCount: meshes.length,+ primitiveCount: primitives.length,+ triangleCount: Math.floor(triangleCount),+ materials,+ facingSemantics: [...facingSemantics].sort(),+ ...normalAxis ? { normalAxis } : {},+ ...directionAxis ? { directionAxis } : {},+ clips: root.listAnimations().map((animation) => ({+ name: animation.getName(),+ durationSeconds: animationDuration(animation)}))- });-}-async function decodeMaterialLibraryPayloadV1(value) {- const payload = validateMaterialLibraryPayload(value);- const records = payload.records.map((wire) => ({- manifest: structuredClone(wire.manifest),- files: Object.fromEntries(Object.entries(wire.files).map(([name, encoded]) => [- name,- new Uint8Array(Buffer.from(encoded, "base64"))- ]))- }));- for (const record of records)- await verifyMaterialRecordV1(record);- return records;+ };}-async function createMaterialLibraryTextureResolver(records, fallback = DEFAULT_TEXTURE_RESOLVER) {- const snapshots = await decodeMaterialLibraryPayload(await createMaterialLibraryPayload(records));- const maps = new Map;- for (const record of snapshots)- for (const map of record.manifest.maps)- maps.set(materialLibraryResourceId(record.manifest, map.slot), { record, map });- return Object.freeze({- pinnedMaterialMaps: createPinnedMaterialMapPort(snapshots),- describeApprovedTexture(id) {- const entry = typeof id === "string" ? maps.get(id) : undefined;- return entry ? { usage: entry.map.usage, allowedSlots: [entry.map.slot] } : fallback.describeApprovedTexture?.(id);- },- async loadApprovedTexture(id) {- const entry = typeof id === "string" ? maps.get(id) : undefined;- if (!entry)- return fallback.loadApprovedTexture(id);- const texture = await loadTexture(entry.record.files[entry.map.file].slice(), {- usage: entry.map.usage,- name: id- });- texture.userData["kilnMaterialResource"] = {- schemaVersion: entry.record.manifest.schemaVersion,- materialId: entry.record.manifest.materialId,- revisionId: entry.record.manifest.revisionId,- resourceId: id,- map: structuredClone(entry.map),- sources: structuredClone(entry.record.manifest.sources),- ...entry.record.manifest.physicalSizeMeters ? { physicalSizeMeters: { ...entry.record.manifest.physicalSizeMeters } } : {}- };- if ("sampler" in entry.map)- applyPortableSamplerV1(texture, entry.map.sampler);- if ("recipe" in entry.map && entry.map.recipe?.kind === "atlas")- texture.userData["kilnAtlas"] = {- spec: structuredClone(entry.map.recipe.spec),- manifest: structuredClone(entry.map.recipe.manifest)- };- return texture;- },- async preparePortableTexture(id, context) {- context?.signal?.throwIfAborted();- const entry = typeof id === "string" ? maps.get(id) : undefined;- if (!entry) {- if (!fallback.preparePortableTexture)- throw new Error("Portable texture preparation unavailable");- return fallback.preparePortableTexture(id, context);- }- const { record, map } = entry;- return {- descriptor: {- resourceId: id,- usage: map.usage,- allowedSlots: [map.slot],- colorSpace: map.colorSpace,- width: map.width,- height: map.height,- encodedByteLength: map.bytes,- imageSha256: map.sha256- },- bytes: record.files[map.file].slice(),- userData: {- ..."recipe" in map && map.recipe?.kind === "atlas" ? {- kilnAtlas: {- spec: structuredClone(map.recipe.spec),- manifest: structuredClone(map.recipe.manifest)- }- } : {},- kilnMaterialResource: {- schemaVersion: record.manifest.schemaVersion,- materialId: record.manifest.materialId,- revisionId: record.manifest.revisionId,- resourceId: id,- map: structuredClone(map),- sources: structuredClone(record.manifest.sources),- ...record.manifest.physicalSizeMeters ? { physicalSizeMeters: structuredClone(record.manifest.physicalSizeMeters) } : {}- }- }- };- },- materialRecipe: (id, overrides) => fallback.materialRecipe(id, overrides)- });+function finalFinding(profile, value) {+ return { ...value, profile };}--class FileMaterialLibrary {- root;- constructor(root) {- this.root = resolve4(root);- }- async path(...parts) {- await mkdir2(this.root, { recursive: true });- const canonical = await realpath2(this.root);- let current = canonical;- for (const part of parts) {- if (!/^[a-z0-9][a-z0-9_-]{0,79}$/.test(part))- throw new Error("Invalid material path identity");- current = join2(current, part);- try {- const stat = await lstat3(current);- if (stat.isSymbolicLink() || !stat.isDirectory())- throw new Error("Material library requires real directories");- const rel = relative(canonical, await realpath2(current));- if (rel === ".." || rel.startsWith(`..${sep}`))- throw new Error("Material path escapes library");- } catch (error) {- if (error.code !== "ENOENT")- throw error;- }- }- return current;- }- async file(dir, name, limit) {- const path = join2(dir, name);- const stat = await lstat3(path);- if (!stat.isFile() || stat.isSymbolicLink() || stat.size > limit)- throw new Error("Invalid material library file");- return new Uint8Array(await readFile2(path));- }- async readManifest(materialId, revisionId) {- materialLibraryIdSchema.parse(materialId);- materialLibraryHashSchema.parse(revisionId);- const dir = await this.path(materialId, revisionId.slice(7));- const manifest = validateMaterialManifestIdentityAny(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(await this.file(dir, "manifest.json", MATERIAL_LIBRARY_LIMITS.maxManifestBytes))));- if (manifest.materialId !== materialId || manifest.revisionId !== revisionId)- throw new Error("Material identity mismatch");- return manifest;- }- async readRecordFiles(materialId, revisionId) {- const manifest = await this.readManifest(materialId, revisionId);- const dir = await this.path(materialId, revisionId.slice(7));- const files = {};- for (const map of manifest.maps)- files[map.file] = await this.file(dir, map.file, MATERIAL_LIBRARY_LIMITS.maxMapBytes);- const record = { manifest, files };- validateMaterialRecordShapeAny(record);- for (const map of manifest.maps)- if (digest(files[map.file]) !== map.sha256)- throw new Error("Material integrity hash mismatch");- return record;+function inspectFinalEffects(contract, evidence, profile = "asset.requirements.v1") {+ const findings = [];+ if (evidence.meshCount === 0 || evidence.primitiveCount === 0 || evidence.triangleCount === 0) {+ findings.push(finalFinding(profile, {+ code: "VFX_GLTF_RENDERABLE_MISSING",+ disposition: "block",+ dimension: "exportIntegrity",+ message: "Final GLB contains no renderable VFX geometry.",+ measurement: {+ name: "finalVfxTriangles",+ actual: evidence.triangleCount,+ expected: ">=1"+ },+ repairText: "Export the effect surface as portable geometry before final-byte approval."+ }));}- async read(materialId, revisionId) {- const root = await this.readManifest(materialId, revisionId);- if (root.schemaVersion === 1) {- const record = await this.readRecordFiles(materialId, revisionId);- await verifyMaterialRecordV1(record);- return record;- }- const closure = await resolveMaterialRecordClosure([root], {- readManifest: this.readManifest.bind(this),- read: this.readRecordFiles.bind(this)- });- return closure.find((record) => record.manifest.materialId === materialId && record.manifest.revisionId === revisionId);+ const effectMaterials = evidence.materials.filter((material) => material.effectSurface);+ if (effectMaterials.length === 0) {+ findings.push(finalFinding(profile, {+ code: "VFX_GLTF_EFFECT_SURFACE_MISSING",+ disposition: "block",+ dimension: "exportIntegrity",+ message: "Final GLB contains no material attached to a vfx.effect.surface.* node.",+ repairText: "Preserve an explicit vfx.effect.surface.* semantic on each renderable effect node; use vfx.support.* for opaque support geometry."+ }));}- async list() {- const manifests = [];- for (const material of await readdir(await this.path(), { withFileTypes: true })) {- if (!material.isDirectory() || !materialLibraryIdSchema.safeParse(material.name).success)- continue;- for (const revision of await readdir(await this.path(material.name), {- withFileTypes: true- })) {- if (!revision.isDirectory() || !/^[a-f0-9]{64}$/.test(revision.name))- continue;- manifests.push((await this.read(material.name, `sha256:${revision.name}`)).manifest);- }- }- return manifests.sort((a, b) => a.materialId.localeCompare(b.materialId) || a.revisionId.localeCompare(b.revisionId));- }- async import(records, options) {- if (!Array.isArray(records) || !records.length || records.length > 100)- throw new Error("Material import requires 1..100 records");- let snapshots;- if (records.every((record) => record.manifest.schemaVersion === 1) && !options?.materials) {- snapshots = records.map(snapshot);- for (const record of snapshots)- await verifyMaterialRecordV1(record);- } else {- const candidates = [...records, ...options?.materials ?? []];- if (new Set(candidates.map((record) => identity(record.manifest))).size > 1024)- throw new Error("Material import context count limit exceeded");- const context = await resolveMaterialRecordClosure(records.map((r) => r.manifest), recordClosureReader(candidates, this), {- maxRecords: 1024,- maxBytes: 256 * 1024 * 1024,- maxPixels: 1024 * MATERIAL_LIBRARY_LIMITS.maxRecordPixels- });- const admitted = new Map(context.map((record) => [identity(record.manifest), record]));- snapshots = records.map((record) => admitted.get(identity(record.manifest)));- }- for (const record of snapshots) {- const { manifest, files } = record;- const dest = await this.path(manifest.materialId, manifest.revisionId.slice(7));- const parent = dirname2(dest);- await mkdir2(parent, { recursive: true });- const stage = join2(parent, `.stage-${randomUUID2()}`);- await mkdir2(stage);- try {- for (const [name, bytes] of Object.entries(files))- await writeFile2(join2(stage, name), bytes, { flag: "wx" });- await writeFile2(join2(stage, "manifest.json"), canonicalMaterialJson(manifest), {- flag: "wx"- });- try {- await renameDirectoryAtomically(stage, dest);- } catch (error) {- const existing = await this.read(manifest.materialId, manifest.revisionId).catch(() => {- return;- });- if (!existing || canonicalMaterialJson(existing.manifest) !== canonicalMaterialJson(manifest))- throw error;+ for (const material of effectMaterials) {+ if (material.alphaMode !== contract.transparency) {+ findings.push(finalFinding(profile, {+ code: "VFX_GLTF_TRANSPARENCY_MODE_MISMATCH",+ disposition: "block",+ dimension: "exportIntegrity",+ message: `${material.id} final GLB alpha mode is ${material.alphaMode}; expected ${contract.transparency}.`,+ affected: { material: material.id },+ measurement: {+ name: "finalAlphaMode",+ actual: material.alphaMode,+ expected: contract.transparency}- } finally {- const rel = relative(parent, resolve4(stage));- if (rel.startsWith(".stage-") && !rel.includes(sep))- await rm(stage, { recursive: true, force: true });- }+ }));}- return snapshots.map((record) => record.manifest);- }-}-function validateMaterialManifestIdentityAny(value) {- const manifest = validateMaterialManifestAny(value);- if (revisionHash(manifest) !== manifest.revisionId)- throw new Error("Material identity hash mismatch");- return manifest;-}-function snapshotAny(record) {- validateMaterialRecordShapeAny(record);- return {- manifest: structuredClone(record.manifest),- files: Object.fromEntries(Object.entries(record.files).map(([name, bytes]) => [name, bytes.slice()]))- };-}-async function resolveMaterialRecordClosure(roots, reader, limits = {- maxRecords: MATERIAL_LIBRARY_LIMITS.maxPayloadRecords,- maxBytes: MATERIAL_LIBRARY_LIMITS.maxPayloadBytes,- maxPixels: MATERIAL_LIBRARY_LIMITS.maxPayloadPixels-}) {- for (const n of Object.values(limits))- if (!Number.isSafeInteger(n) || n < 1)- throw new Error("Invalid material closure limits");- const manifests = new Map, active = new Set;- let bytes = 0, pixels = 0;- const visit = async (value) => {- const manifest = validateMaterialManifestIdentityAny(value), key = identity(manifest);- if (active.has(key))- throw new Error("Material dependency cycle");- const existing = manifests.get(key);- if (existing) {- if (canonicalMaterialJson(existing) !== canonicalMaterialJson(manifest))- throw new Error("Conflicting material dependency identity");- return;+ if (contract.transparency !== "opaque" && !material.alphaData) {+ findings.push(finalFinding(profile, {+ code: "VFX_GLTF_ALPHA_DATA_MISSING",+ disposition: "block",+ dimension: "exportIntegrity",+ message: `${material.id} final GLB has no alpha-bearing factor or embedded texture.`,+ affected: { material: material.id },+ measurement: { name: "finalAlphaData", actual: false, expected: true },+ repairText: "Pack a standalone alphaMap into the exported base-color texture alpha channel, or use an alpha-bearing base-color factor."+ }));}- manifests.set(key, structuredClone(manifest));- active.add(key);- for (const map of manifest.maps) {- bytes += map.bytes;- pixels += map.width * map.height;+ if (material.doubleSided !== contract.doubleSided) {+ findings.push(finalFinding(profile, {+ code: "VFX_GLTF_SIDEDNESS_MISMATCH",+ disposition: "block",+ dimension: "exportIntegrity",+ message: `${material.id} final GLB sidedness differs from trusted VFX intent.`,+ affected: { material: material.id },+ measurement: {+ name: "finalDoubleSided",+ actual: material.doubleSided,+ expected: contract.doubleSided+ }+ }));}- if (manifests.size > limits.maxRecords || bytes > limits.maxBytes || pixels > limits.maxPixels)- throw new Error("Material closure count/byte/pixel limit exceeded");- for (const pin of materialRecordDependencyPins(manifest)) {- const child = await reader.readManifest(pin.resourceId, pin.revisionId);- if (child.materialId !== pin.resourceId || child.revisionId !== pin.revisionId || pin.sha256 !== pin.revisionId)- throw new Error("Material dependency pin mismatch");- await visit(child);+ if (contract.transparency === "mask" && (material.alphaCutoff === undefined || material.alphaCutoff <= 0 || material.alphaCutoff > 1)) {+ findings.push(finalFinding(profile, {+ code: "VFX_GLTF_ALPHA_CUTOFF_INVALID",+ disposition: "block",+ dimension: "exportIntegrity",+ message: `${material.id} final GLB MASK cutoff is outside (0, 1].`,+ affected: { material: material.id }+ }));}- active.delete(key);- };- for (const root of roots)- await visit(root);- const records = [];- for (const [key, manifest] of manifests) {- const record = snapshotAny(await reader.read(manifest.materialId, manifest.revisionId));- if (identity(record.manifest) !== key || canonicalMaterialJson(record.manifest) !== canonicalMaterialJson(manifest))- throw new Error("Material closure manifest changed during read");- validateMaterialManifestIdentityAny(record.manifest);- for (const map of record.manifest.maps)- if (digest(record.files[map.file]) !== map.sha256)- throw new Error("Material integrity hash mismatch");- records.push(record);}- for (const record of records)- await verifyMaterialRecordContents(record, { materials: records });- return records;-}-function recordClosureReader(records, fallback) {- const byId = new Map;- const duplicates = new Map;- for (const record of records) {- const key = identity(record.manifest), existing = byId.get(key);- if (existing && canonicalMaterialJson(existing.manifest) !== canonicalMaterialJson(record.manifest))- throw new Error("Conflicting material record identity");- if (!existing)- byId.set(key, record);- else if (existing !== record)- duplicates.set(key, [...duplicates.get(key) ?? [], record]);+ if (contract.facing.mode !== "fixed" && !evidence.facingSemantics.includes(contract.facing.mode)) {+ findings.push(finalFinding(profile, {+ code: "VFX_GLTF_FACING_SEMANTIC_MISSING",+ disposition: "block",+ dimension: "exportIntegrity",+ message: `Final GLB does not carry the ${contract.facing.mode} runtime-facing semantic.`,+ measurement: {+ name: "finalFacingSemantics",+ actual: evidence.facingSemantics.join(",") || null,+ expected: contract.facing.mode+ },+ repairText: "Preserve the exporter-derived billboard semantic on the renderable quad node."+ }));}- return {- async readManifest(id, revision) {- const record = byId.get(`${id}/${revision}`);- if (record)- return record.manifest;- if (fallback)- return fallback.readManifest(id, revision);- throw new Error(`Missing pinned material revision: ${id} at ${revision}`);- },- async read(id, revision) {- const key = `${id}/${revision}`, record = byId.get(key);- if (record) {- for (const candidate of [record, ...duplicates.get(key) ?? []]) {- const manifest = validateMaterialRecordShapeAny(candidate);- if (canonicalMaterialJson(manifest) !== canonicalMaterialJson(record.manifest))- throw new Error("Conflicting material record identity");- for (const map of manifest.maps)- if (digest(candidate.files[map.file]) !== map.sha256)- throw new Error("Conflicting material record encoded integrity hash");- }- return record;+ if (contract.facing.source === "explicit" && contract.facing.mode === "fixed" && contract.facing.normalAxis !== evidence.normalAxis) {+ findings.push(finalFinding(profile, {+ code: "VFX_GLTF_NORMAL_AXIS_MISMATCH",+ disposition: "block",+ dimension: "exportIntegrity",+ message: "Final GLB effect-surface normal axis differs from explicit VFX intent.",+ measurement: {+ name: "finalNormalAxis",+ actual: evidence.normalAxis ?? null,+ expected: contract.facing.normalAxis ?? null}- if (fallback)- return fallback.readRecordFiles(id, revision);- throw new Error(`Missing pinned material revision: ${id} at ${revision}`);- }- };-}-function createPinnedMaterialMapPort(records) {- const entries = new Map;- for (const record of records) {- validateMaterialRecordShapeAny(record);- validateMaterialManifestIdentityAny(record.manifest);- for (const map of record.manifest.maps) {- if (digest(record.files[map.file]) !== map.sha256)- throw new Error("Material integrity hash mismatch");- entries.set(`${identity(record.manifest)}/${materialLibraryResourceId(record.manifest, map.slot)}`, { record, map });+ }));+ }+ if (contract.facing.source === "explicit" && contract.facing.directionAxis !== undefined && contract.facing.directionAxis !== evidence.directionAxis) {+ findings.push(finalFinding(profile, {+ code: "VFX_GLTF_DIRECTION_AXIS_MISMATCH",+ disposition: "block",+ dimension: "exportIntegrity",+ message: "Final GLB effect-surface direction axis differs from explicit VFX intent.",+ measurement: {+ name: "finalDirectionAxis",+ actual: evidence.directionAxis ?? null,+ expected: contract.facing.directionAxis+ }+ }));+ }+ if (contract.animation.driver === "clip") {+ const clip = evidence.clips.find((candidate) => candidate.name === contract.animation.clipName);+ if (!clip || Math.abs(clip.durationSeconds - contract.animation.durationSeconds) > 0.000001) {+ findings.push(finalFinding(profile, {+ code: "VFX_GLTF_REQUIRED_CLIP_MISSING",+ disposition: "block",+ dimension: "exportIntegrity",+ message: "Final GLB dropped or changed the declared VFX animation clip.",+ affected: { clip: contract.animation.clipName ?? "<missing>" },+ measurement: {+ name: "finalClipDurationSeconds",+ actual: clip?.durationSeconds ?? null,+ expected: contract.animation.durationSeconds,+ threshold: 0.000001,+ unit: "s"+ }+ }));}}- const find = (resourceId, pin) => {- if (typeof resourceId !== "string" || pin.sha256 !== pin.revisionId)- return;- return entries.get(`${pin.resourceId}/${pin.revisionId}/${resourceId}`);- };- const describe = (resourceId, pin) => {- const entry = find(resourceId, pin);- if (!entry)- return;- const { record, map } = entry;- return {- materialId: record.manifest.materialId,- revisionId: record.manifest.revisionId,- resourceId,- slot: map.slot,- usage: map.usage,- colorSpace: map.colorSpace,- width: map.width,- height: map.height,- encodedByteLength: map.bytes,- imageSha256: map.sha256,- ..."pixelHash" in map ? { decodedPixelHash: map.pixelHash } : {}- };- };+ return findings;+}+function finalEffectsMetrics(evidence) {return {- describePinnedMaterialMap: describe,- async resolvePinnedMaterialMapPixels(resourceId, pin, context) {- context?.signal?.throwIfAborted();- const descriptor = describe(resourceId, pin), entry = find(resourceId, pin);- if (!descriptor || !entry)- throw new Error("Missing verified pinned-library map; approved resources cannot be atlas sources");- const { data, info } = await sharp(entry.record.files[entry.map.file], {- limitInputPixels: MATERIAL_LIBRARY_LIMITS.maxRecordPixels,- failOn: "warning"- }).ensureAlpha().raw().toBuffer({ resolveWithObject: true });- context?.signal?.throwIfAborted();- if (info.width !== descriptor.width || info.height !== descriptor.height || info.channels !== 4)- throw new Error("Pinned material decoded dimensions mismatch");- const decodedPixelHash = digest(data);- if (descriptor.decodedPixelHash && descriptor.decodedPixelHash !== decodedPixelHash)- throw new Error("Pinned material pixel hash mismatch");- return { descriptor, pixels: Uint8Array.from(data), decodedPixelHash };- }+ finalVfxMeshCount: evidence.meshCount,+ finalVfxPrimitiveCount: evidence.primitiveCount,+ finalVfxTriangles: evidence.triangleCount,+ finalVfxMaterialCount: evidence.materials.length,+ finalVfxEffectMaterialCount: evidence.materials.filter((material) => material.effectSurface).length,+ finalVfxFacingSemantics: evidence.facingSemantics.join(","),+ finalVfxNormalAxis: evidence.normalAxis ?? null,+ finalVfxDirectionAxis: evidence.directionAxis ?? null,+ finalVfxClipCount: evidence.clips.length};}-async function verifyMaterialRecordContents(record, options) {- if (record.manifest.schemaVersion === 1)- return verifyMaterialRecordV1(record);- const manifest = validateMaterialRecordShapeAny(record);- validateMaterialManifestIdentityAny(manifest);- const pins = new Set(materialRecordDependencyPins(manifest).map((pin) => `${pin.resourceId}/${pin.revisionId}`));- pins.add(identity(manifest));- const resources = createPinnedMaterialMapPort((options?.materials ?? [record]).filter((candidate) => pins.has(identity(candidate.manifest))));- admitMaterialManifestRecipes(manifest, resources);- for (const map of manifest.maps) {- const bytes = record.files[map.file];- if (digest(bytes) !== map.sha256)- throw new Error("Material integrity hash mismatch");- const { data, info } = await sharp(bytes, {- limitInputPixels: MATERIAL_LIBRARY_LIMITS.maxRecordPixels,- failOn: "warning"- }).ensureAlpha().raw().toBuffer({ resolveWithObject: true });- if (info.width !== map.width || info.height !== map.height || info.channels !== 4 || digest(data) !== map.pixelHash)- throw new Error("Material decoded pixel hash/dimensions mismatch");- const recipe = map.recipe;- if (!recipe)+var stable8 = (value) => Math.round(value * 1e6) / 1e6;+var init_breadth_final = __esm(() => {+ init_gltf_io();+ init_contracts();+ init_types();+});++// src/qa/requirements-applicability.ts+function sceneMeasurementGaps(requirements, findings) {+ const codes = new Set(findings.map((finding) => finding.code));+ const gaps = [];+ const needs = requirements.requirements;+ for (const [code, marker, field] of [+ ["ENV_NAV_CLEARANCE_UNASSESSED", "navigation", "navigable"],+ ["ENV_TILE_EDGE_EVIDENCE_SPARSE", "tiling", "tileable"]+ ]) {+ if (!codes.has(code))continue;- if (recipe.kind === "atlas") {- const compiled = await compileTextureAtlasSpecV1(recipe.spec, { resources });- if (canonicalMaterialJson(compiled.manifest) !== canonicalMaterialJson(recipe.manifest) || digest(compiled.pixels) !== map.pixelHash)- throw new Error("Atlas recipe/manifest/pixel hash mismatch");- } else {- const compiled = recipe.spec.schemaVersion === 3 ? materialPixelsV3(recipe.spec, recipe.derive) : materialPixels(recipe.spec, recipe.derive);- if (compiled.recipeHash !== recipe.recipeHash || digest(compiled.pixels) !== recipe.pixelHash)- throw new Error("Procedural recipe/pixel hash mismatch");- }+ const reason = `${code}: required scene measurements could not be established.`;+ if (needs[marker]?.state === "requested")+ gaps.push({ key: marker, fields: ["*"], reason });+ if (needs.spatialLayout?.state === "requested" && needs.spatialLayout.value[field] === true)+ gaps.push({ key: "spatialLayout", fields: [field], reason });}+ return gaps;}-async function verifyMaterialRecord(record, options) {- if (record.manifest.schemaVersion === 1)- return verifyMaterialRecordV1(record);- await resolveMaterialRecordClosure([record.manifest], recordClosureReader([record, ...options?.materials ?? []]));-}-function admitMaterialManifestRecipes(manifest, resources) {- let texels = 0, work = 0, allocation = 0, encoded = 0;- for (const map of manifest.maps) {- encoded += map.bytes;- const recipe = map.recipe;- if (recipe?.kind === "procedural") {- if (recipe.spec.schemaVersion === 3) {- const a = admitProceduralTextureSpecV3(recipe.spec);- const derived = normalDerivationBudget(recipe.derive ? a.spec.width * a.spec.height : 0);- texels += a.spec.width * a.spec.height;- work += a.estimatedWorkUnits + derived.work;- allocation += a.conservativePixelAllocationBytes + derived.allocation;- } else {- texels += recipe.spec.size ** 2;- work += recipe.spec.size ** 2 * recipe.spec.layers.length * 16;- allocation += recipe.spec.size ** 2 * 12;- }- } else if (recipe?.kind === "atlas") {- const a = admitTextureAtlasSpecV1(recipe.spec, { resources });- texels += a.spec.width * a.spec.height + a.budget.sourceTexels;- work += a.budget.workUnits;- allocation += a.budget.conservativePixelAllocationBytes;- encoded += a.budget.encodedBytes;- } else {- texels += map.width * map.height;- work += map.width * map.height * 12 + map.bytes * 8;- allocation += map.width * map.height * 12 + map.bytes * 2;+function resolveRequirementsApplicability(requirements) {+ const requested = (key) => (key === "scope" ? requirements.scope : requirements.requirements[key])?.state === "requested";+ const rules = REQUIREMENTS_RULE_MAP.map((rule) => ({+ id: rule.id,+ mode: rule.mode,+ keys: rule.keys,+ status: rule.kernel && (rule.kernel === "universal" || rule.kernel === "material" || rule.observation || rule.keys.some(requested)) ? "evaluate" : rule.observation || rule.keys.some(requested) ? "notEvaluated" : "notRequested",+ ...!rule.kernel && (rule.observation || rule.keys.some(requested)) ? {+ reason: "Neutral measurement adapter remains to be qualified; no category fallback is used."+ } : {}+ }));+ const unevaluatedRequirements = [];+ const supportedFields = {+ rig: ["bodyPlan", "grounded", "clips", "heldItem"],+ foliage: ["grounded", "standalone", "canopyProfile"],+ effects: [+ "schemaVersion",+ "subtype",+ "portability",+ "transparency",+ "doubleSided",+ "facing",+ "animation",+ "sidecar"+ ],+ spatialLayout: ["tileable", "navigable"],+ structure: ["storeyCount", "interiorMode", "roofMode", "enterable", "portal", "scaleMode"],+ mobility: [+ "wheelCount",+ "axleCount",+ "steering",+ "supportPolicy",+ "supportAssemblies",+ "frontFrame"+ ],+ grounding: ["planeY"],+ bounds: ["units", "x", "y", "z"],+ animation: ["clips"],+ representation: ["precomputedTangents"],+ externalSupport: ["supports"],+ validation: ["version", "profileId", "mode", "checks"]+ };+ for (const [key, statement] of Object.entries(requirements.requirements)) {+ if (statement?.state !== "requested")+ continue;+ if (key === "navigation" || key === "tiling")+ continue;+ if (key === "articulation" || key === "opening") {+ unevaluatedRequirements.push({+ key,+ fields: ["*"],+ reason: key === "articulation" ? "Declared rigid pivots, subtrees and clearance prisms are checked. They do not establish the requested motion range, animated collisions or other articulation types; acceptance remains incomplete." : "Declared container opening markers are checked without an inferred minimum size. They do not establish usable access, interior occupancy, moving closures or other opening types; acceptance remains incomplete."+ });+ continue;}- }- if (texels > PORTABLE_MATERIAL_V3_LIMITS.maxTexels || work > PORTABLE_MATERIAL_V3_LIMITS.maxWork || allocation > PORTABLE_MATERIAL_V3_LIMITS.maxTransientBytes || encoded > PORTABLE_MATERIAL_V3_LIMITS.maxEncodedBytes)- throw new Error("Material recipe aggregate texel/work/allocation/encoded budget exceeded");-}-function validateMaterialLibraryPayloadAny(value) {- assertMaterialJson(value);- if (!value || typeof value !== "object" || Array.isArray(value))- throw new Error("Invalid material resource payload");- if (value["schemaVersion"] === 1)- return validateMaterialLibraryPayload(value);- const payload = value;- if (Object.keys(payload).some((k) => !["schemaVersion", "records"].includes(k)) || payload.schemaVersion !== 2 || !Array.isArray(payload.records) || payload.records.length > MATERIAL_LIBRARY_LIMITS.maxPayloadRecords)- throw new Error("Invalid material resource payload");- let bytes = 0, pixels = 0;- const seen = new Set;- for (const wire of payload.records) {- if (!wire || typeof wire !== "object" || Object.keys(wire).some((k) => !["manifest", "files"].includes(k)))- throw new Error("Invalid material resource record");- const manifest = validateMaterialManifestIdentityAny(wire.manifest), key = identity(manifest);- if (seen.has(key))- throw new Error("Duplicate material resource revision");- seen.add(key);- if (!wire.files || typeof wire.files !== "object" || Array.isArray(wire.files) || Object.keys(wire.files).length !== manifest.maps.length)- throw new Error("Material payload inventory mismatch");- for (const map of manifest.maps) {- const encoded = wire.files[map.file];- if (typeof encoded !== "string" || encoded.length !== Math.ceil(map.bytes / 3) * 4 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encoded))- throw new Error("Invalid material map base64");- bytes += map.bytes;- pixels += map.width * map.height;+ const supported = [...supportedFields[key] ?? []];+ if (key === "foliage" && requirements.requirements.foliage?.state === "requested" && requirements.requirements.foliage.value.canopyProfile !== undefined)+ supported.push("growthState");+ if (key === "mobility") {+ const mobility = requirements.requirements.mobility;+ if (mobility?.state === "requested") {+ if (mobility.value.propulsionAssemblies?.every((kind) => kind === "rotor" || kind === "propeller"))+ supported.push("propulsionAssemblies");+ if (mobility.value.animationAssemblies?.length === 0)+ supported.push("animationAssemblies");+ }}+ const fields = Object.keys(statement.value).filter((field) => !supported.includes(field));+ if (supported.length === 0 || fields.length > 0)+ unevaluatedRequirements.push({+ key,+ fields: fields.length ? fields : ["*"],+ reason: "Requested measurement is not yet evaluated by the neutral checker; acceptance remains incomplete."+ });}- if (bytes > MATERIAL_LIBRARY_LIMITS.maxPayloadBytes || pixels > MATERIAL_LIBRARY_LIMITS.maxPayloadPixels)- throw new Error("Material resource payload exceeds byte/pixel budget");- return payload;-}-async function createMaterialLibraryPayload(records) {- if (records.every((r) => r.manifest.schemaVersion === 1))- return createMaterialLibraryPayloadV1(records);- let bytes = 0, pixels = 0;- if (records.length > MATERIAL_LIBRARY_LIMITS.maxPayloadRecords)- throw new Error("Material payload record limit exceeded");- for (const record of records)- for (const map of validateMaterialManifestIdentityAny(record.manifest).maps) {- bytes += map.bytes;- pixels += map.width * map.height;- }- if (bytes > MATERIAL_LIBRARY_LIMITS.maxPayloadBytes || pixels > MATERIAL_LIBRARY_LIMITS.maxPayloadPixels)- throw new Error("Material payload byte/pixel budget exceeded");- const admitted = await resolveMaterialRecordClosure(records.map((r) => r.manifest), recordClosureReader(records));- const byIdentity = new Map(admitted.map((r) => [identity(r.manifest), r]));- const snapshots = records.map((r) => byIdentity.get(identity(r.manifest)));- return validateMaterialLibraryPayloadAny({- schemaVersion: 2,- records: snapshots.map((r) => ({- manifest: r.manifest,- files: Object.fromEntries(Object.entries(r.files).map(([name, bytes]) => [- name,- Buffer.from(bytes).toString("base64")- ]))- }))- });-}-async function decodeMaterialLibraryPayload(value) {- const payload = validateMaterialLibraryPayloadAny(value);- if (payload.schemaVersion === 1)- return decodeMaterialLibraryPayloadV1(payload);- const wires = payload.records.map((w) => ({- manifest: validateMaterialManifestIdentityAny(w.manifest),- files: { ...w.files }- }));- const byIdentity = new Map(wires.map((w) => [identity(w.manifest), w]));- const reader = {- async readManifest(id, revision) {- const wire = byIdentity.get(`${id}/${revision}`);- if (!wire)- throw new Error("Missing pinned material revision");- return wire.manifest;- },- async read(id, revision) {- const wire = byIdentity.get(`${id}/${revision}`);- if (!wire)- throw new Error("Missing pinned material revision");- return {- manifest: wire.manifest,- files: Object.fromEntries(Object.entries(wire.files).map(([name, encoded]) => [- name,- new Uint8Array(Buffer.from(encoded, "base64"))- ]))- };- }- };- const admitted = await resolveMaterialRecordClosure(wires.map((w) => w.manifest), reader);- const result = new Map(admitted.map((r) => [identity(r.manifest), r]));- return wires.map((w) => result.get(identity(w.manifest)));-}-async function createMaterialRecordV2(draft, options) {- assertMaterialJson(draft, true);- if (!draft || typeof draft !== "object" || Array.isArray(draft))- throw new Error("Invalid material draft");- exactKeys(draft, [- "schemaVersion",- "materialId",- "name",- "tags",- "tileable",- "physicalSizeMeters",- "parameters",- "sources",- "maps"- ]);- const input = draft;- if (input["schemaVersion"] !== 2 || !Array.isArray(input["maps"]) || input["maps"].length < 1 || input["maps"].length > 5)- throw new Error("V2 material requires schemaVersion2 and1..5 maps");- const candidates = options?.materials ?? [];- if (candidates.length > MATERIAL_LIBRARY_LIMITS.maxPayloadRecords)- throw new Error("Material source closure count limit exceeded");- const records = candidates.length ? await resolveMaterialRecordClosure(candidates.map((r) => r.manifest), recordClosureReader(candidates)) : [];- const resources = createPinnedMaterialMapPort(records), prepared = [];- let texels = 0, work = 0, allocation = 0, encoded = 0;- for (const value of input["maps"]) {- if (!value || typeof value !== "object" || Array.isArray(value))- throw new Error("Invalid material map draft");- exactKeys(value, [- "slot",- "sourceId",- "transforms",- "normalConvention",- "channelPacking",- "sampler",- "bytes",- "originalFile",- "procedural",- "derive",- "atlas"- ]);- const raw = value, slot = raw["slot"];- if (!MATERIAL_LIBRARY_SLOTS.includes(slot))- throw new Error("Unsupported material map slot");- const sampler = canonicalizePortableSamplerV1(raw["sampler"]);- if (["bytes", "procedural", "atlas"].filter((k) => raw[k] !== undefined).length !== 1)- throw new Error("Supply exactly one map bytes/procedural/atlas source");- if (raw["procedural"] !== undefined) {- const spec = raw["procedural"];- if (spec.schemaVersion === 3) {- const a = admitProceduralTextureSpecV3(spec);- if (a.spec.usage !== MATERIAL_LIBRARY_USAGE[slot])- throw new Error("Procedural usage mismatch");- if (raw["derive"] !== undefined && slot !== "normal")- throw new Error("Height derivation requires a normal map slot");- const derived = normalDerivationBudget(raw["derive"] !== undefined ? a.spec.width * a.spec.height : 0);- texels += a.spec.width * a.spec.height;- work += a.estimatedWorkUnits + derived.work;- allocation += a.conservativePixelAllocationBytes + derived.allocation;- prepared.push({ raw, slot, sampler, procedural: a.spec });- } else {- const canonical = canonicalizeProceduralTextureSpecV2(spec);- if (canonical.usage !== MATERIAL_LIBRARY_USAGE[slot])- throw new Error("Procedural usage mismatch");- texels += canonical.size ** 2;- work += canonical.size ** 2 * canonical.layers.length * 16;- allocation += canonical.size ** 2 * 12;- prepared.push({ raw, slot, sampler, procedural: canonical });- }- } else if (raw["atlas"] !== undefined) {- if (raw["derive"] !== undefined)- throw new Error("Atlas derivation unsupported");- const a = admitTextureAtlasSpecV1(raw["atlas"], { resources });- if (a.spec.usage !== MATERIAL_LIBRARY_USAGE[slot] || canonicalMaterialJson(a.spec.sampler) !== canonicalMaterialJson(sampler))- throw new Error("Atlas usage/sampler mismatch");- texels += a.spec.width * a.spec.height + a.budget.sourceTexels;- work += a.budget.workUnits;- allocation += a.budget.conservativePixelAllocationBytes;- encoded += a.budget.encodedBytes;- prepared.push({ raw, slot, sampler, atlas: a.spec });- } else {- if (raw["derive"] !== undefined || !(raw["bytes"] instanceof Uint8Array))- throw new Error("Invalid external map bytes/derivation");- const bytes = raw["bytes"];- if (bytes.length > MATERIAL_LIBRARY_LIMITS.maxMapBytes)- throw new Error("Material map encoded byte limit");- const d = materialPngDimensions(bytes);- if (d.width < 1 || d.height < 1 || d.width > 4096 || d.height > 4096)- throw new Error("Material map dimensions limit");- texels += d.width * d.height;- encoded += bytes.length;- work += d.width * d.height * 12 + bytes.length * 8;- allocation += d.width * d.height * 12 + bytes.length * 2;- prepared.push({ raw, slot, sampler, bytes });- }- }- if (texels > 4 * 1024 * 1024 || work > PORTABLE_MATERIAL_V3_LIMITS.maxWork || allocation > 64 * 1024 * 1024 || encoded > 16 * 1024 * 1024)- throw new Error("Material aggregate texel/work/allocation limit exceeded");- const maps = [], files = {}, pins = new Map;- for (const item of prepared) {- const { raw, slot, sampler } = item;- let bytes, pixelHash, recipe;- if (item.procedural !== undefined) {- const spec = item.procedural;- const derive = raw["derive"];- const compiled = spec.schemaVersion === 3 ? materialPixelsV3(spec, derive) : materialPixels(spec, derive);- const d = compiled.spec.schemaVersion === 3 ? { width: compiled.spec.width, height: compiled.spec.height } : { width: compiled.spec.size, height: compiled.spec.size };- pixelHash = digest(compiled.pixels);- bytes = new Uint8Array(await sharp(compiled.pixels, { raw: { ...d, channels: 4 } }).png({ compressionLevel: 9, adaptiveFiltering: false }).toBuffer());- recipe = {- kind: "procedural",- compilerId: compiled.spec.schemaVersion === 3 ? PROCEDURAL_TEXTURE_V3_COMPILER_ID : "kiln.procedural-texture.v2",- spec: compiled.spec,- recipeHash: compiled.recipeHash,- pixelHash,- encoder,- ...raw["derive"] ? {- derive: structuredClone(raw["derive"])- } : {}- };- } else if (item.atlas !== undefined) {- const compiled = await compileTextureAtlasSpecV1(item.atlas, { resources });- pixelHash = compiled.manifest.decodedPixelHash;- bytes = new Uint8Array(await sharp(compiled.pixels, {- raw: { width: compiled.spec.width, height: compiled.spec.height, channels: 4 }- }).png({ compressionLevel: 9, adaptiveFiltering: false }).toBuffer());- recipe = {- kind: "atlas",- compilerId: compiled.manifest.compilerId,- spec: compiled.spec,- manifest: compiled.manifest,- encoder- };- for (const r of compiled.spec.regions)- if (r.source.kind === "resource")- pins.set(`${r.source.pin.resourceId}/${r.source.pin.revisionId}`, r.source.pin);- } else {- bytes = item.bytes.slice();- const decoded = await sharp(bytes, {- limitInputPixels: MATERIAL_LIBRARY_LIMITS.maxRecordPixels,- failOn: "warning"- }).ensureAlpha().raw().toBuffer();- pixelHash = digest(decoded);- }- const d = materialPngDimensions(bytes), file = `${slot}.png`;- if (files[file])- throw new Error("Duplicate material map slot");- files[file] = bytes;- maps.push({- slot,- file,- ...d,- sha256: digest(bytes),- bytes: bytes.length,- usage: MATERIAL_LIBRARY_USAGE[slot],- colorSpace: slot === "baseColor" || slot === "emissive" ? "srgb" : "linear",- sampler,- pixelHash,- sourceId: raw["sourceId"],- transforms: structuredClone(raw["transforms"]),- ...slot === "normal" ? {- normalConvention: raw["normalConvention"] ?? (recipe ? "opengl" : undefined)- } : {},- ...slot === "metallicRoughness" ? {- channelPacking: raw["channelPacking"] ?? (recipe ? "r-occlusion-g-roughness-b-metallic" : undefined)- } : {},- ...raw["originalFile"] ? { originalFile: raw["originalFile"] } : {},- ...recipe ? { recipe } : {}- });- }- const manifest = materialManifestV2Schema.parse({- ...input,- schemaVersion: 2,- revisionId: `sha256:${"0".repeat(64)}`,- tags: input["tags"] ?? [],- parameters: input["parameters"] ?? {},- maps,- dependencies: [...pins.values()]- });- manifest.revisionId = revisionHash(manifest);- const record = { manifest, files };- await verifyMaterialRecord(record, { materials: [...records, record] });- return record;-}-var digest = (bytes) => `sha256:${createHash6("sha256").update(bytes).digest("hex")}`, encoder, normalDerivationBudget = (texels) => ({ work: texels * 16, allocation: texels * 8 }), identity = (manifest) => `${manifest.materialId}/${manifest.revisionId}`;-var init_material_library_node = __esm(() => {- init_atomic_directory();- init_material_library();- init_portable_sampler();- init_portable_sampler_runtime();- init_procedural_texture_v3();- init_procedural_texture_v3_contract();- init_texture_atlas_pixels();- init_procedural_texture();- init_procedural_material_v2();- init_textures();- init_texture_resolver();- init_procedural_material_v3();- encoder = { name: "sharp", version: sharp.versions.sharp };-});--// src/qa/requirements-applicability.ts-function sceneMeasurementGaps(requirements, findings) {- const codes = new Set(findings.map((finding) => finding.code));- const gaps = [];- const needs = requirements.requirements;- for (const [code, marker, field] of [- ["ENV_NAV_CLEARANCE_UNASSESSED", "navigation", "navigable"],- ["ENV_TILE_EDGE_EVIDENCE_SPARSE", "tiling", "tileable"]- ]) {- if (!codes.has(code))- continue;- const reason = `${code}: required scene measurements could not be established.`;- if (needs[marker]?.state === "requested")- gaps.push({ key: marker, fields: ["*"], reason });- if (needs.spatialLayout?.state === "requested" && needs.spatialLayout.value[field] === true)- gaps.push({ key: "spatialLayout", fields: [field], reason });- }- return gaps;-}-function resolveRequirementsApplicability(requirements) {- const requested = (key) => (key === "scope" ? requirements.scope : requirements.requirements[key])?.state === "requested";- const rules = REQUIREMENTS_RULE_MAP.map((rule) => ({- id: rule.id,- mode: rule.mode,- keys: rule.keys,- status: rule.kernel && (rule.kernel === "universal" || rule.kernel === "material" || rule.observation || rule.keys.some(requested)) ? "evaluate" : rule.observation || rule.keys.some(requested) ? "notEvaluated" : "notRequested",- ...!rule.kernel && (rule.observation || rule.keys.some(requested)) ? {- reason: "Neutral measurement adapter remains to be qualified; no category fallback is used."- } : {}- }));- const unevaluatedRequirements = [];- const supportedFields = {- rig: ["bodyPlan", "grounded", "clips", "heldItem"],- foliage: ["grounded", "standalone", "canopyProfile"],- effects: [- "schemaVersion",- "subtype",- "portability",- "transparency",- "doubleSided",- "facing",- "animation",- "sidecar"- ],- spatialLayout: ["tileable", "navigable"],- structure: ["storeyCount", "interiorMode", "roofMode", "enterable", "portal", "scaleMode"],- mobility: [- "wheelCount",- "axleCount",- "steering",- "supportPolicy",- "supportAssemblies",- "frontFrame"- ],- grounding: ["planeY"],- bounds: ["units", "x", "y", "z"],- animation: ["clips"],- representation: ["precomputedTangents"],- externalSupport: ["supports"],- validation: ["version", "profileId", "mode", "checks"]- };- for (const [key, statement] of Object.entries(requirements.requirements)) {- if (statement?.state !== "requested")- continue;- if (key === "navigation" || key === "tiling")- continue;- if (key === "articulation" || key === "opening") {- unevaluatedRequirements.push({- key,- fields: ["*"],- reason: key === "articulation" ? "Declared rigid pivots, subtrees and clearance prisms are checked. They do not establish the requested motion range, animated collisions or other articulation types; acceptance remains incomplete." : "Declared container opening markers are checked without an inferred minimum size. They do not establish usable access, interior occupancy, moving closures or other opening types; acceptance remains incomplete."- });- continue;- }- const supported = [...supportedFields[key] ?? []];- if (key === "foliage" && requirements.requirements.foliage?.state === "requested" && requirements.requirements.foliage.value.canopyProfile !== undefined)- supported.push("growthState");- if (key === "mobility") {- const mobility = requirements.requirements.mobility;- if (mobility?.state === "requested") {- if (mobility.value.propulsionAssemblies?.every((kind) => kind === "rotor" || kind === "propeller"))- supported.push("propulsionAssemblies");- if (mobility.value.animationAssemblies?.length === 0)- supported.push("animationAssemblies");- }- }- const fields = Object.keys(statement.value).filter((field) => !supported.includes(field));- if (supported.length === 0 || fields.length > 0)- unevaluatedRequirements.push({- key,- fields: fields.length ? fields : ["*"],- reason: "Requested measurement is not yet evaluated by the neutral checker; acceptance remains incomplete."- });- }- if (requirements.scope?.state === "requested")- unevaluatedRequirements.push({- key: "scope",- fields: ["*"],- reason: "Scope has advisory member/dressing measurements only; they do not certify semantic scope, modular reusability, or pack membership. Acceptance remains incomplete."- });- return { rules, unevaluatedRequirements };+ if (requirements.scope?.state === "requested")+ unevaluatedRequirements.push({+ key: "scope",+ fields: ["*"],+ reason: "Scope has advisory member/dressing measurements only; they do not certify semantic scope, modular reusability, or pack membership. Acceptance remains incomplete."+ });+ return { rules, unevaluatedRequirements };}var REQUIREMENTS_RULE_MAP;var init_requirements_applicability = __esm(() => {@@ -21560,388 +20906,60 @@ var init_requirements_report = __esm(() => {];});-// src/rebuild-options.ts-import { z as z6 } from "zod";-var FULL_OPTIMIZATION_PIPELINE = "rigid-v1", rebuildOptionsSchema;-var init_rebuild_options = __esm(() => {- rebuildOptionsSchema = z6.object({- indexPolicy: z6.enum(["indexed", "asBuilt"]).optional(),- gltfExporter: z6.enum(["legacy", "three"]),- geometryPolicy: z6.enum(["warn", "strict"]),- optimize: z6.enum(["off", "auto", "palette", "full"]),- optimizationPipeline: z6.literal(FULL_OPTIMIZATION_PIPELINE).optional(),- instance: z6.enum(["off", "auto", "on"])- });-});--// src/qa/breadth-final.ts-import * as THREE26 from "three";-function bytesContainAscii(bytes, value) {- const needle = new TextEncoder().encode(value);- outer:- for (let index = 0;index <= bytes.length - needle.length; index++) {- for (let offset = 0;offset < needle.length; offset++) {- if (bytes[index + offset] !== needle[offset])- continue outer;- }- return true;- }- return false;-}-function encodedTextureHasAlpha(mimeType, bytes) {- if (mimeType === "image/png") {- const colorType = bytes[25];- return colorType === 4 || colorType === 6 || bytesContainAscii(bytes, "tRNS");- }- if (mimeType === "image/webp") {- if (bytesContainAscii(bytes, "ALPH"))- return true;- const vp8xIndex = (() => {- const marker = new TextEncoder().encode("VP8X");- for (let index = 0;index <= bytes.length - marker.length; index++) {- if (marker.every((value, offset) => bytes[index + offset] === value))- return index;- }- return -1;- })();- return vp8xIndex >= 0 && ((bytes[vp8xIndex + 8] ?? 0) & 16) !== 0;- }- return false;+// src/qa/requirements-run.ts+import { Object3D as Object3D15 } from "three";+function sceneDecisions(context, policy) {+ const applicable = new Set(resolveRequirementsApplicability(context.requirements).rules.filter((rule) => rule.status === "evaluate").map((rule) => rule.id));+ return new QaRegistry(registry.list().filter((rule) => applicable.has(rule.id))).describePolicy(policy);}-function animationDuration(animation) {- let duration = 0;- for (const sampler of animation.listSamplers()) {- const max = sampler.getInput()?.getMax([]);- if (max && typeof max[0] === "number" && Number.isFinite(max[0])) {- duration = Math.max(duration, max[0]);- }+async function collectRequirementsSceneEvidence(context, scene, policy = {}) {+ if (!(scene instanceof Object3D15) || !sceneDecisions(context, policy).some((d) => d.ruleId === SELF_INTERSECTION_QA_RULE.id && d.mode !== "off"))+ return {};+ try {+ return { partPenetration: await analyzePartPenetration(scene) };+ } catch {+ return { partPenetrationFailed: true };}- return stable8(duration);}-function signedAxis2(vector) {- const values = [- { axis: "X", value: vector.x },- { axis: "Y", value: vector.y },- { axis: "Z", value: vector.z }+function runRequirementsSceneQa(context, scene, clips, policy = {}, evidence = {}) {+ const needs = context.requirements.requirements;+ const parts = needs.parts?.state === "requested" ? needs.parts.value.required : [];+ const animation = needs.animation?.state === "requested" ? needs.animation.value : undefined;+ const rig = needs.rig?.state === "requested" ? needs.rig.value : undefined;+ const requiredClips = [+ ...new Set([...animation?.clips ?? [], ...rig?.clips?.map((clip) => clip.name) ?? []])];- const dominant = [...values].sort((a, b) => Math.abs(b.value) - Math.abs(a.value))[0];- return `${dominant.value < 0 ? "-" : "+"}${dominant.axis}`;-}-function finalEffectAxis(nodes, mode) {- let best;- for (const node of nodes) {- const semantic = readSemanticMetadataV1FromExtras(node.getExtras());- if (!(semantic?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {- continue;- }- const matrix = new THREE26.Matrix4().fromArray(node.getWorldMatrix());- const scale = node.getWorldScale();- const scaleMagnitude = Math.hypot(scale[0], scale[1], scale[2]);- for (const primitive of node.getMesh()?.listPrimitives() ?? []) {- const position = primitive.getAttribute("POSITION");- if (!position)- continue;- const min = position.getMin([]);- const max = position.getMax([]);- const axes = [- { score: (max[0] ?? 0) - (min[0] ?? 0), direction: new THREE26.Vector3(1, 0, 0) },- { score: (max[1] ?? 0) - (min[1] ?? 0), direction: new THREE26.Vector3(0, 1, 0) },- { score: (max[2] ?? 0) - (min[2] ?? 0), direction: new THREE26.Vector3(0, 0, 1) }- ];- const selected = axes.reduce((candidate, value) => mode === "length" ? value.score > candidate.score ? value : candidate : value.score < candidate.score ? value : candidate);- const candidate = {- score: selected.score * scaleMagnitude,- direction: selected.direction.transformDirection(matrix)- };- if (!best || (mode === "length" ? candidate.score > best.score : candidate.score < best.score)) {- best = candidate;- }- }- }- return best ? signedAxis2(best.direction) : undefined;-}-async function analyzeFinalVfxGlbBytesV1(bytes) {- const io = createGltfIO();- const document = await io.readBinary(bytes);- const root = document.getRoot();- const renderableNodes = root.listNodes().filter((node) => node.getMesh() !== null);- const meshes = [...new Set(renderableNodes.map((node) => node.getMesh()).filter(Boolean))];- const primitives = meshes.flatMap((mesh) => mesh?.listPrimitives() ?? []);- let triangleCount = 0;- for (const primitive of primitives) {- const indices = primitive.getIndices();- const position = primitive.getAttribute("POSITION");- triangleCount += indices ? indices.getCount() / 3 : (position?.getCount() ?? 0) / 3;- }- const effectSurfaceMaterials = new Set;- for (const node of renderableNodes) {- const semantic = readSemanticMetadataV1FromExtras(node.getExtras());- if (!(semantic?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {- continue;- }- for (const primitive of node.getMesh()?.listPrimitives() ?? []) {- const material = primitive.getMaterial();- if (material)- effectSurfaceMaterials.add(material);- }- }- const materials = [- ...new Set(primitives.map((primitive) => primitive.getMaterial()).filter(Boolean))- ].map((material, index) => {- const baseColor = material.getBaseColorFactor();- const texture = material.getBaseColorTexture();- const image = texture?.getImage();- const mimeType = texture?.getMimeType() ?? "";- const mode = material.getAlphaMode().toLowerCase();- return {- id: material.getName() || `material.${index}`,- effectSurface: effectSurfaceMaterials.has(material),- alphaMode: mode,- alphaData: (baseColor[3] ?? 1) < 1 || image !== null && image !== undefined && encodedTextureHasAlpha(mimeType, image),- doubleSided: material.getDoubleSided(),- ...mode === "mask" ? { alphaCutoff: material.getAlphaCutoff() } : {}- };- });- const facingSemantics = new Set;- for (const node of renderableNodes) {- const semantic = readSemanticMetadataV1FromExtras(node.getExtras());- for (const role of semantic?.roles ?? []) {- const match = /^vfx\.facing\.(fixed|camera-spherical|camera-y-axis)$/.exec(role);- if (match)- facingSemantics.add(match[1]);- }- }- const normalAxis = finalEffectAxis(renderableNodes, "normal");- const directionAxis = finalEffectAxis(renderableNodes, "length");- return {- schemaVersion: 1,- meshCount: meshes.length,- primitiveCount: primitives.length,- triangleCount: Math.floor(triangleCount),- materials,- facingSemantics: [...facingSemantics].sort(),- ...normalAxis ? { normalAxis } : {},- ...directionAxis ? { directionAxis } : {},- clips: root.listAnimations().map((animation) => ({- name: animation.getName(),- durationSeconds: animationDuration(animation)- }))- };-}-function finalFinding(profile, value) {- return { ...value, profile };-}-function inspectFinalEffects(contract, evidence, profile = "asset.requirements.v1") {- const findings = [];- if (evidence.meshCount === 0 || evidence.primitiveCount === 0 || evidence.triangleCount === 0) {- findings.push(finalFinding(profile, {- code: "VFX_GLTF_RENDERABLE_MISSING",- disposition: "block",- dimension: "exportIntegrity",- message: "Final GLB contains no renderable VFX geometry.",- measurement: {- name: "finalVfxTriangles",- actual: evidence.triangleCount,- expected: ">=1"- },- repairText: "Export the effect surface as portable geometry before final-byte approval."- }));- }- const effectMaterials = evidence.materials.filter((material) => material.effectSurface);- if (effectMaterials.length === 0) {- findings.push(finalFinding(profile, {- code: "VFX_GLTF_EFFECT_SURFACE_MISSING",- disposition: "block",- dimension: "exportIntegrity",- message: "Final GLB contains no material attached to a vfx.effect.surface.* node.",- repairText: "Preserve an explicit vfx.effect.surface.* semantic on each renderable effect node; use vfx.support.* for opaque support geometry."- }));- }- for (const material of effectMaterials) {- if (material.alphaMode !== contract.transparency) {- findings.push(finalFinding(profile, {- code: "VFX_GLTF_TRANSPARENCY_MODE_MISMATCH",- disposition: "block",- dimension: "exportIntegrity",- message: `${material.id} final GLB alpha mode is ${material.alphaMode}; expected ${contract.transparency}.`,- affected: { material: material.id },- measurement: {- name: "finalAlphaMode",- actual: material.alphaMode,- expected: contract.transparency- }- }));- }- if (contract.transparency !== "opaque" && !material.alphaData) {- findings.push(finalFinding(profile, {- code: "VFX_GLTF_ALPHA_DATA_MISSING",- disposition: "block",- dimension: "exportIntegrity",- message: `${material.id} final GLB has no alpha-bearing factor or embedded texture.`,- affected: { material: material.id },- measurement: { name: "finalAlphaData", actual: false, expected: true },- repairText: "Pack a standalone alphaMap into the exported base-color texture alpha channel, or use an alpha-bearing base-color factor."- }));- }- if (material.doubleSided !== contract.doubleSided) {- findings.push(finalFinding(profile, {- code: "VFX_GLTF_SIDEDNESS_MISMATCH",- disposition: "block",- dimension: "exportIntegrity",- message: `${material.id} final GLB sidedness differs from trusted VFX intent.`,- affected: { material: material.id },- measurement: {- name: "finalDoubleSided",- actual: material.doubleSided,- expected: contract.doubleSided- }- }));- }- if (contract.transparency === "mask" && (material.alphaCutoff === undefined || material.alphaCutoff <= 0 || material.alphaCutoff > 1)) {- findings.push(finalFinding(profile, {- code: "VFX_GLTF_ALPHA_CUTOFF_INVALID",- disposition: "block",- dimension: "exportIntegrity",- message: `${material.id} final GLB MASK cutoff is outside (0, 1].`,- affected: { material: material.id }- }));- }- }- if (contract.facing.mode !== "fixed" && !evidence.facingSemantics.includes(contract.facing.mode)) {- findings.push(finalFinding(profile, {- code: "VFX_GLTF_FACING_SEMANTIC_MISSING",- disposition: "block",- dimension: "exportIntegrity",- message: `Final GLB does not carry the ${contract.facing.mode} runtime-facing semantic.`,- measurement: {- name: "finalFacingSemantics",- actual: evidence.facingSemantics.join(",") || null,- expected: contract.facing.mode- },- repairText: "Preserve the exporter-derived billboard semantic on the renderable quad node."- }));- }- if (contract.facing.source === "explicit" && contract.facing.mode === "fixed" && contract.facing.normalAxis !== evidence.normalAxis) {- findings.push(finalFinding(profile, {- code: "VFX_GLTF_NORMAL_AXIS_MISMATCH",- disposition: "block",- dimension: "exportIntegrity",- message: "Final GLB effect-surface normal axis differs from explicit VFX intent.",- measurement: {- name: "finalNormalAxis",- actual: evidence.normalAxis ?? null,- expected: contract.facing.normalAxis ?? null- }- }));- }- if (contract.facing.source === "explicit" && contract.facing.directionAxis !== undefined && contract.facing.directionAxis !== evidence.directionAxis) {- findings.push(finalFinding(profile, {- code: "VFX_GLTF_DIRECTION_AXIS_MISMATCH",- disposition: "block",- dimension: "exportIntegrity",- message: "Final GLB effect-surface direction axis differs from explicit VFX intent.",- measurement: {- name: "finalDirectionAxis",- actual: evidence.directionAxis ?? null,- expected: contract.facing.directionAxis- }- }));- }- if (contract.animation.driver === "clip") {- const clip = evidence.clips.find((candidate) => candidate.name === contract.animation.clipName);- if (!clip || Math.abs(clip.durationSeconds - contract.animation.durationSeconds) > 0.000001) {- findings.push(finalFinding(profile, {- code: "VFX_GLTF_REQUIRED_CLIP_MISSING",- disposition: "block",- dimension: "exportIntegrity",- message: "Final GLB dropped or changed the declared VFX animation clip.",- affected: { clip: contract.animation.clipName ?? "<missing>" },- measurement: {- name: "finalClipDurationSeconds",- actual: clip?.durationSeconds ?? null,- expected: contract.animation.durationSeconds,- threshold: 0.000001,- unit: "s"- }- }));- }- }- return findings;-}-function finalEffectsMetrics(evidence) {- return {- finalVfxMeshCount: evidence.meshCount,- finalVfxPrimitiveCount: evidence.primitiveCount,- finalVfxTriangles: evidence.triangleCount,- finalVfxMaterialCount: evidence.materials.length,- finalVfxEffectMaterialCount: evidence.materials.filter((material) => material.effectSurface).length,- finalVfxFacingSemantics: evidence.facingSemantics.join(","),- finalVfxNormalAxis: evidence.normalAxis ?? null,- finalVfxDirectionAxis: evidence.directionAxis ?? null,- finalVfxClipCount: evidence.clips.length- };-}-var stable8 = (value) => Math.round(value * 1e6) / 1e6;-var init_breadth_final = __esm(() => {- init_gltf_io();- init_contracts();- init_types();-});--// src/qa/requirements-run.ts-import { Object3D as Object3D15 } from "three";-function sceneDecisions(context, policy) {- const applicable = new Set(resolveRequirementsApplicability(context.requirements).rules.filter((rule) => rule.status === "evaluate").map((rule) => rule.id));- return new QaRegistry(registry.list().filter((rule) => applicable.has(rule.id))).describePolicy(policy);-}-async function collectRequirementsSceneEvidence(context, scene, policy = {}) {- if (!(scene instanceof Object3D15) || !sceneDecisions(context, policy).some((d) => d.ruleId === SELF_INTERSECTION_QA_RULE.id && d.mode !== "off"))- return {};- try {- return { partPenetration: await analyzePartPenetration(scene) };- } catch {- return { partPenetrationFailed: true };- }-}-function runRequirementsSceneQa(context, scene, clips, policy = {}, evidence = {}) {- const needs = context.requirements.requirements;- const parts = needs.parts?.state === "requested" ? needs.parts.value.required : [];- const animation = needs.animation?.state === "requested" ? needs.animation.value : undefined;- const rig = needs.rig?.state === "requested" ? needs.rig.value : undefined;- const requiredClips = [- ...new Set([...animation?.clips ?? [], ...rig?.clips?.map((clip) => clip.name) ?? []])- ];- const tangents = needs.representation?.state === "requested" && needs.representation.value.precomputedTangents === true;- const findings = [];- const decisions = sceneDecisions(context, policy);- const geometryMetrics = {};- const mobilityInput = {- scene,- mobility: needs.mobility?.state === "requested" ? needs.mobility.value : undefined,- groundPlaneY: needs.grounding?.state === "requested" ? needs.grounding.value.planeY : undefined- };- const mobilityFindings = mobilityInput.mobility && decisions.some((d) => (d.ruleId === "VEHICLE_PROFILE" || d.ruleId === "VEHICLE_ADVISORY_PROFILE") && d.mode !== "off") ? inspectMobility(mobilityInput) : [];- const executedRules = [];- const rigInput = {- scene,- clips,- rig,- groundPlaneY: needs.grounding?.state === "requested" ? needs.grounding.value.planeY : undefined- };- const foliageInput = {- scene,- foliage: needs.foliage?.state === "requested" ? needs.foliage.value : undefined,- materialMode: needs.material?.state === "requested" ? needs.material.value.mode : undefined,- groundPlaneY: needs.grounding?.state === "requested" ? needs.grounding.value.planeY : undefined- };- const effects = needs.effects?.state === "requested" ? needs.effects.value : undefined;- const scope = context.requirements.scope;- const scopeObservation = scope?.state === "requested" && scene instanceof Object3D15 && decisions.some((d) => d.ruleId === ASSET_SCOPE_QA_RULE.id && d.mode !== "off") ? analyzeAssetScopeObservationV1(scene) : undefined;- const effectsInput = {- effects,- derivedEvidence: {- source: "engine-scene-analysis",- ...effects && scene instanceof Object3D15 && decisions.some((d) => d.ruleId.startsWith("VFX_") && d.mode !== "off") ? { vfxArtifact: analyzeVfxArtifactEvidenceV1(effects, scene, clips) } : {}+ const tangents = needs.representation?.state === "requested" && needs.representation.value.precomputedTangents === true;+ const findings = [];+ const decisions = sceneDecisions(context, policy);+ const geometryMetrics = {};+ const mobilityInput = {+ scene,+ mobility: needs.mobility?.state === "requested" ? needs.mobility.value : undefined,+ groundPlaneY: needs.grounding?.state === "requested" ? needs.grounding.value.planeY : undefined+ };+ const mobilityFindings = mobilityInput.mobility && decisions.some((d) => (d.ruleId === "VEHICLE_PROFILE" || d.ruleId === "VEHICLE_ADVISORY_PROFILE") && d.mode !== "off") ? inspectMobility(mobilityInput) : [];+ const executedRules = [];+ const rigInput = {+ scene,+ clips,+ rig,+ groundPlaneY: needs.grounding?.state === "requested" ? needs.grounding.value.planeY : undefined+ };+ const foliageInput = {+ scene,+ foliage: needs.foliage?.state === "requested" ? needs.foliage.value : undefined,+ materialMode: needs.material?.state === "requested" ? needs.material.value.mode : undefined,+ groundPlaneY: needs.grounding?.state === "requested" ? needs.grounding.value.planeY : undefined+ };+ const effects = needs.effects?.state === "requested" ? needs.effects.value : undefined;+ const scope = context.requirements.scope;+ const scopeObservation = scope?.state === "requested" && scene instanceof Object3D15 && decisions.some((d) => d.ruleId === ASSET_SCOPE_QA_RULE.id && d.mode !== "off") ? analyzeAssetScopeObservationV1(scene) : undefined;+ const effectsInput = {+ effects,+ derivedEvidence: {+ source: "engine-scene-analysis",+ ...effects && scene instanceof Object3D15 && decisions.some((d) => d.ruleId.startsWith("VFX_") && d.mode !== "off") ? { vfxArtifact: analyzeVfxArtifactEvidenceV1(effects, scene, clips) } : {}}};const spatialInput = {@@ -30416,6 +29434,20 @@ var init_material_metrics = __esm(() => {});});+// src/rebuild-options.ts+import { z as z6 } from "zod";+var FULL_OPTIMIZATION_PIPELINE = "rigid-v1", rebuildOptionsSchema;+var init_rebuild_options = __esm(() => {+ rebuildOptionsSchema = z6.object({+ indexPolicy: z6.enum(["indexed", "asBuilt"]).optional(),+ gltfExporter: z6.enum(["legacy", "three"]),+ geometryPolicy: z6.enum(["warn", "strict"]),+ optimize: z6.enum(["off", "auto", "palette", "full"]),+ optimizationPipeline: z6.literal(FULL_OPTIMIZATION_PIPELINE).optional(),+ instance: z6.enum(["off", "auto", "on"])+ });+});+// src/rigid-merge.tsimport {ComponentTypeToTypedArray,@@ -33441,7 +32473,7 @@ var init_kit = __esm(() => {});// src/texture-bake.ts-import { createHash as createHash7 } from "node:crypto";+import { createHash as createHash6 } from "node:crypto";import * as THREE50 from "three";function readPixels(texture) {const image = texture.image;@@ -33541,7 +32573,7 @@ async function bakeSceneTextures(root, warnings) {if (encoded) {const delivery = readValidatedAtlasDelivery(entry.texture);if (delivery) {- if (delivery.id !== atlasRef.id || delivery.finalMime !== encoded.mime || delivery.finalImageSha256 !== `sha256:${createHash7("sha256").update(encoded.bytes).digest("hex")}`)+ if (delivery.id !== atlasRef.id || delivery.finalMime !== encoded.mime || delivery.finalImageSha256 !== `sha256:${createHash6("sha256").update(encoded.bytes).digest("hex")}`)throw stale();} else {const sharp = (await import("sharp")).default;@@ -33552,10 +32584,10 @@ async function bakeSceneTextures(root, warnings) {if (metadata.width !== atlasRecord.spec.width || metadata.height !== atlasRecord.spec.height)throw stale();const decoded = await image.ensureAlpha().raw().toBuffer();- if (`sha256:${createHash7("sha256").update(decoded).digest("hex")}` !== atlasRecord.manifest.decodedPixelHash)+ if (`sha256:${createHash6("sha256").update(decoded).digest("hex")}` !== atlasRecord.manifest.decodedPixelHash)throw stale();}- } else if (raw.width !== atlasRecord.spec.width || raw.height !== atlasRecord.spec.height || raw.channels !== 4 || `sha256:${createHash7("sha256").update(raw.data).digest("hex")}` !== atlasRecord.manifest.decodedPixelHash)+ } else if (raw.width !== atlasRecord.spec.width || raw.height !== atlasRecord.spec.height || raw.channels !== 4 || `sha256:${createHash6("sha256").update(raw.data).digest("hex")}` !== atlasRecord.manifest.decodedPixelHash)throw stale();}let bytes;@@ -33580,8 +32612,8 @@ async function bakeSceneTextures(root, warnings) {height: raw.height,hasAlpha: hasTranslucentPixel(raw)};- const sha1 = createHash7("sha1").update(bytes).digest("hex");- const imageSha256 = `sha256:${createHash7("sha256").update(bytes).digest("hex")}`;+ const sha1 = createHash6("sha1").update(bytes).digest("hex");+ const imageSha256 = `sha256:${createHash6("sha256").update(bytes).digest("hex")}`;baked.push({schemaVersion: 1,texture: name,@@ -36929,7 +35961,7 @@ __export(exports_capture_cache, {captureCpuCell: () => captureCpuCell,createCachedRenderPort: () => createCachedRenderPort});-import { createHash as createHash8 } from "node:crypto";+import { createHash as createHash7 } from "node:crypto";function clone(entry) {const result = structuredClone(entry);if (result.kind === "cpu")@@ -37027,9 +36059,9 @@ function createCachedRenderPort(port, options) {return port(input, execution);const validated = validatePbrRenderRequest(input);const request = { ...validated, glb: Uint8Array.from(validated.glb) };- const hash = digest2(request.glb);+ const hash = digest(request.glb);const selectors = request.cameras ?? request.viewDirs;- const keys = selectors.map((selector) => digest2(text5({+ const keys = selectors.map((selector) => digest(text5({version: "kiln.capture-cache.v1",kind: "gpu",identity,@@ -37113,7 +36145,7 @@ function createCachedRenderPort(port, options) {}async function captureCpuCell(cache, identity, produce) {const snapshot = structuredClone(identity);- const key = digest2(text5({ version: "kiln.capture-cache.v1", kind: "cpu", ...snapshot }));+ const key = digest(text5({ version: "kiln.capture-cache.v1", kind: "cpu", ...snapshot }));const valid = (result) => {try {enforcePngCaptureBudget([result.png]);@@ -37134,7 +36166,7 @@ async function captureCpuCell(cache, identity, produce) {await cache.put(key, { kind: "cpu", result }).catch(() => {});return { ...result, png: Buffer.from(result.png), captureCache: { hit: false } };}-var text5 = (value) => JSON.stringify(canonical4(value)), digest2 = (value) => `sha256:${createHash8("sha256").update(value).digest("hex")}`;+var text5 = (value) => JSON.stringify(canonical4(value)), digest = (value) => `sha256:${createHash7("sha256").update(value).digest("hex")}`;var init_capture_cache = __esm(() => {init_render_port();init_png();@@ -38124,6 +37156,257 @@ var init_glb = __esm(() => {glbIO = createGltfIO;});+// src/evaluator/protocol.ts+import { createHash as createHash8 } from "node:crypto";+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;+}+function isRecord6(value) {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}+function hasExactKeys(value, allowed) {+ return Object.keys(value).every((key) => allowed.includes(key));+}+function fail10(kind) {+ throw new Error(`invalid evaluator ${kind}`);+}+function validRequestId(value) {+ return typeof value === "string" && /^[A-Za-z0-9._-]{1,64}$/.test(value);+}+function validInteger(value, min, max) {+ return Number.isInteger(value) && Number(value) >= min && Number(value) <= max;+}+function validRequirementsQaReport(value) {+ try {+ validateRequirementsQaReport(value);+ return true;+ } catch {+ return false;+ }+}+function validGltfValidation(value) {+ const issues = isRecord6(value) && isRecord6(value.issues) ? value.issues : undefined;+ if (!issues || !Array.isArray(issues.messages)) {+ return false;+ }+ return ["numErrors", "numWarnings", "numInfos", "numHints"].every((key) => validInteger(issues[key], 0, Number.MAX_SAFE_INTEGER)) && issues.messages.length <= 1000 && issues.messages.every((issue) => isRecord6(issue) && typeof issue.code === "string" && typeof issue.message === "string" && typeof issue.severity === "number" && Number.isFinite(issue.severity));+}+function encodeRenderResultV2(requestId, render) {+ const { glb, diagnosticViews, buildCache: _hostCacheReceipt, ...rest } = render;+ return {+ version: EVALUATOR_RESULT_VERSION,+ requestId,+ ok: true,+ render: {+ ...rest,+ glbBase64: glb.toString("base64"),+ ...diagnosticViews ? {+ diagnosticViews: diagnosticViews.map(({ png, ...view }) => ({+ ...view,+ pngBase64: Buffer.from(png).toString("base64")+ }))+ } : {}+ }+ };+}+function isSha256(value) {+ return typeof value === "string" && /^sha256:[a-f0-9]{64}$/.test(value);+}+function decodeEvaluatorResultV2(json, maxGlbBytes, expectedRequestId) {+ let value;+ try {+ value = JSON.parse(json);+ } catch {+ return fail10("result");+ }+ if (!isRecord6(value) || !hasExactKeys(value, ["version", "requestId", "ok", "render", "error"]) || value.version !== EVALUATOR_RESULT_VERSION || !validRequestId(value.requestId) || typeof value.ok !== "boolean") {+ return fail10("result");+ }+ if (expectedRequestId !== undefined && value.requestId !== expectedRequestId)+ fail10("result");+ if (!value.ok) {+ if (value.render !== undefined)+ return fail10("result");+ if (!isRecord6(value.error) || !hasExactKeys(value.error, ["code", "message", "qa", "diagnostic", "solid"])) {+ return fail10("result");+ }+ const codes = [+ "INPUT_INVALID",+ "EXECUTION_REJECTED",+ "QA_BLOCKED",+ "DEADLINE_EXCEEDED",+ "CANCELLED",+ "OUTPUT_LIMIT_EXCEEDED",+ "ISOLATION_UNAVAILABLE",+ "WORKER_FAILED",+ "PROTOCOL_ERROR"+ ];+ if (!codes.includes(value.error.code) || typeof value.error.message !== "string" || value.error.message !== evaluatorOutcomeMessage(value.error.code)) {+ return fail10("result");+ }+ if (value.error.diagnostic !== undefined && (value.error.code !== "EXECUTION_REJECTED" || value.error.diagnostic !== "UNBOUND_VARIABLE" && value.error.diagnostic !== "GEAR_RADII_ORDER" && value.error.diagnostic !== "ROUNDED_BOX_RADIUS" && value.error.diagnostic !== "PROCEDURAL_TEXTURE_UNKNOWN_KEY" && value.error.diagnostic !== "PROCEDURAL_TEXTURE_BLEND" && value.error.diagnostic !== "PROCEDURAL_TEXTURE_USAGE" && value.error.diagnostic !== "PROCEDURAL_TEXTURE_V3_CONTRACT" && value.error.diagnostic !== "PORTABLE_MATERIAL_V3_CONTRACT" && value.error.diagnostic !== "TEXTURE_ATLAS_CONTRACT" && value.error.diagnostic !== "MATERIAL_FRACTION_RANGE" && value.error.diagnostic !== "MATERIAL_RECIPE_TEXTURE_BINDING" && value.error.diagnostic !== "PORTABLE_TEXTURE_REFERENCE" && value.error.diagnostic !== "PORTABLE_COLOR_ARGUMENT" && value.error.diagnostic !== "PARAMETRIC_PERIODIC_ENDPOINT" && value.error.diagnostic !== "PROFILE_HOLES_UNSUPPORTED" && value.error.diagnostic !== "PROFILE_BEVEL_COLLAPSE" && value.error.diagnostic !== "PROFILE_SOLID_FAILED" && value.error.diagnostic !== "PROFILE_CORRESPONDENCE_COLLAPSE" && value.error.diagnostic !== "REMOVED_HELPER" && value.error.diagnostic !== "TUBE_RADIUS" && value.error.diagnostic !== "TAPER_CONE_AXIS" && value.error.diagnostic !== "SOLID_FLOAT32_COLLAPSE" && value.error.diagnostic !== "MESH_DATA_NONFINITE" && value.error.diagnostic !== "MATERIAL_ALPHA_MODE" && value.error.diagnostic !== "MATERIAL_COLOR_ARGUMENT" && value.error.diagnostic !== "PART_NAME_ARGUMENT" && value.error.diagnostic !== "PART_GEOMETRY_ARGUMENT" && value.error.diagnostic !== "PART_MATERIAL_ARGUMENT" && value.error.diagnostic !== "MATERIAL_PACKED_CHANNELS" && value.error.diagnostic !== "UNINITIALIZED_BINDING" && value.error.diagnostic !== "BUILD_RESULT" && value.error.diagnostic !== "MATERIAL_RECIPE_OVERRIDE" && value.error.diagnostic !== "PROGRAM_TYPE_ERROR" && value.error.diagnostic !== "PROGRAM_RANGE_ERROR" && value.error.diagnostic !== "LOD_SET" && value.error.diagnostic !== "OPEN_SHELL" && value.error.diagnostic !== "DELIVERY_CONTRACT" && value.error.diagnostic !== "REQUIRE_SOLID" && value.error.diagnostic !== "EXPORT_MATERIAL_SIDE_UNSUPPORTED" && value.error.diagnostic !== "BONE_CHAIN_ARGUMENT" && value.error.diagnostic !== "SKIN_BINDING_ARGUMENT"))+ return fail10("result");+ if (value.error.solid !== undefined && (value.error.diagnostic !== "REQUIRE_SOLID" || !validSolidFailureDetails(value.error.solid)))+ return fail10("result");+ if (value.error.qa !== undefined) {+ if (value.error.code !== "QA_BLOCKED" || !isRecord6(value.error.qa) || !hasExactKeys(value.error.qa, ["report", "stage", "gltfValidation"]) || !validRequirementsQaReport(value.error.qa.report) || !["scene", "final-glb"].includes(String(value.error.qa.stage)) || value.error.qa.gltfValidation !== undefined && !validGltfValidation(value.error.qa.gltfValidation)) {+ return fail10("result");+ }+ } else if (value.error.code === "QA_BLOCKED") {+ return fail10("result");+ }+ return value;+ }+ if (value.error !== undefined || !isRecord6(value.render))+ fail10("result");+ const renderKeys = [+ "glbBase64",+ "artifactGlbSha256",+ "tris",+ "meta",+ "warnings",+ "diagnosticViews",+ "materialMetrics",+ "materialRecipeApplications",+ "materialResourceProvenance",+ "materialLibraryDependencies",+ "bakedTextures",+ "integrationManifest",+ "requirements",+ "rebuildOptions"+ ];+ if (!hasExactKeys(value.render, renderKeys) || typeof value.render.glbBase64 !== "string" || !validInteger(value.render.tris, 0, Number.MAX_SAFE_INTEGER) || !isRecord6(value.render.meta) || !Array.isArray(value.render.warnings) || !value.render.warnings.every((warning) => typeof warning === "string") || !isRecord6(value.render.integrationManifest)) {+ fail10("result");+ }+ let requirements;+ if (value.render.rebuildOptions !== undefined && !rebuildOptionsSchema.strict().safeParse(value.render.rebuildOptions).success)+ fail10("result");+ if (value.render.materialLibraryDependencies !== undefined) {+ if (!Array.isArray(value.render.materialLibraryDependencies) || value.render.materialLibraryDependencies.length > 16)+ fail10("result");+ try {+ for (const manifest of value.render.materialLibraryDependencies)+ validateMaterialManifestIdentityAny(manifest);+ } catch {+ return fail10("result");+ }+ }+ try {+ requirements = validateRequirementsContext(value.render.requirements);+ validateRequirementsQaReport(value.render.meta.qaReport, requirements);+ } catch {+ return fail10("result");+ }+ const glb = Buffer.from(value.render.glbBase64, "base64");+ if (glb.byteLength > maxGlbBytes || glb.toString("base64") !== value.render.glbBase64)+ fail10("result");+ if (!isSha256(value.render.artifactGlbSha256))+ fail10("result");+ const actualHash = `sha256:${createHash8("sha256").update(glb).digest("hex")}`;+ if (actualHash !== value.render.artifactGlbSha256)+ fail10("result");+ const diagnosticViews = value.render.diagnosticViews;+ if (diagnosticViews !== undefined && !Array.isArray(diagnosticViews))+ fail10("result");+ const decodedViews = diagnosticViews?.map((candidate) => {+ if (!isRecord6(candidate) || typeof candidate.pngBase64 !== "string")+ return fail10("result");+ const png = Buffer.from(candidate.pngBase64, "base64");+ if (png.toString("base64") !== candidate.pngBase64)+ return fail10("result");+ const { pngBase64: _, ...view } = candidate;+ return { ...view, png };+ });+ const { glbBase64: _, diagnosticViews: __, ...rest } = value.render;+ return {+ version: EVALUATOR_RESULT_VERSION,+ requestId: value.requestId,+ ok: true,+ render: {+ ...rest,+ glb,+ ...decodedViews ? { diagnosticViews: decodedViews } : {}+ }+ };+}+function assertEvaluatorResultMaterialResources(result, expected) {+ if (!result.ok)+ return;+ const actual = result.render.materialLibraryDependencies ?? [];+ const wanted = expected?.records.map((record) => record.manifest) ?? [];+ const identity = (manifest) => `${manifest.materialId}/${manifest.revisionId}`;+ if (new Set(actual.map(identity)).size !== actual.length || JSON.stringify(actual.map(canonicalMaterialJson).sort()) !== JSON.stringify(wanted.map(canonicalMaterialJson).sort()))+ throw new EvaluatorPortError("PROTOCOL_ERROR");+}+function assertEvaluatorResultRequirements(result, expected) {+ try {+ if (result.ok) {+ if (!requirementsContextsEqual(result.render.requirements, expected))+ throw new Error("Requirements mismatch.");+ } else if (result.error.code === "QA_BLOCKED" && result.error.qa) {+ validateRequirementsQaReport(result.error.qa.report, expected);+ }+ } catch {+ throw new EvaluatorPortError("PROTOCOL_ERROR", "Evaluator requirements context differs from the host request.");+ }+}+var EVALUATOR_REQUEST_VERSION = "kiln.evaluator.request.v2", EVALUATOR_RESULT_VERSION = "kiln.evaluator.result.v2", 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/evaluator/handler.tsvar init_handler = __esm(() => {init_authoring_diagnostic();@@ -38622,2246 +37905,3555 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagno}overlay.add(plane);}- return overlay;+ 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 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;+ 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;+ }+ 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;+ }+ }+ 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 };+}+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);+ }+ 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 } } : {}+ };+}+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("")}`;+}+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;+ }+ 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;+ }+ 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 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 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;+ }+ }+ 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]);+ }+ lockedCamera = {+ ...lockedCamera,+ near: Math.max(0.001, Math.min(lockedCamera.near, boxDistance(lockedCamera.position, union) / 2))+ };+ }+ 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);+ }+ 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}`);+ }+ 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 } : {}+ });+ }+ stampLabel(cell, size, size, labelScale, labelScale, `${Math.round(frameTimes[i] * 100)}%`, labelScale);+ cells.push(cell);+ }+ 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) {+ return {+ ...baseMeta,+ width: size,+ height: size,+ pngs: cells.map((c) => encodePng(c, size, size))+ };+ }+ const { rgb, width, height } = compositeCellGrid(cells, size);+ return { ...baseMeta, width, height, png: encodePng(rgb, width, height) };+}+function normalizeVec(v) {+ const len = Math.hypot(v[0], v[1], v[2]) || 1;+ return [v[0] / len, v[1] / len, v[2] / len];+}+function dotVec(a, b) {+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];+}+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}`);+ }+ 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);+ 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 THREE55 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;+ }+ }+}+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 THREE55.Box3().setFromObject(root);+ if (bounds.isEmpty())+ bounds.set(new THREE55.Vector3(-0.5, 0, -0.5), new THREE55.Vector3(0.5, 1, 0.5));+ const center = bounds.getCenter(new THREE55.Vector3);+ const camera = cameraId === "front" ? new THREE55.Vector3(1, 0, 0) : new THREE55.Vector3(0, 0, 1);+ const upHint = new THREE55.Vector3(0, 1, 0);+ const xAxis = new THREE55.Vector3().crossVectors(upHint, camera).normalize();+ const yAxis = new THREE55.Vector3().crossVectors(camera, xAxis).normalize();+ let extent = 0.000001;+ for (let corner = 0;corner < 8; corner++) {+ const point = new THREE55.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 THREE55.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]);+ }+ 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+ });+ }+ 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+ });+ }+ } finally {+ 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 captures;+}+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 THREE56 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 }]);+ });+ 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 {+ 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+ },+ visualQa: "not_assessed"+ };+}+async function executeKilnCode(code, options = {}) {+ if (!code || typeof code !== "string") {+ throw new Error("executeKilnCode: code must be a non-empty string");+ }+ 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`");+ }+ const root = await build();+ if (!root?.isObject3D) {+ throw new AuthoringDiagnosticError("BUILD_RESULT", "executeKilnCode: build() did not return a THREE.Object3D");+ }+ 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 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;+ }+ 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]}`);+ }+ }+ 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 (stdMat.side === THREE56.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 === THREE56.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);+ }+ }+ cache.set(threeMat, mat);+ return mat;+}+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 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));+ }+ 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 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"]+ ]+ };+ }+ }+ }+ 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 (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 THREE56.PlaneGeometry(1, 1);+ if (centerX !== 0.5 || centerY !== 0.5) {+ geometry.translate(0.5 - centerX, 0.5 - centerY, 0);+ }+ 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 === THREE56.InterpolateDiscrete)+ return "STEP";+ if (mode === THREE56.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;+ }+ 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;+ }+ 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);+ }+ 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 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);+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 {- 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]+ 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 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 resolveOptimize(opt) {+ if (opt)+ return opt;+ const env = process.env["KILN_BAKE_OPTIMIZE"];+ return env === "auto" || env === "palette" || env === "full" ? env : "off";}-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 resolveInstance(opt) {+ if (opt)+ return opt;+ const env = process.env["KILN_BAKE_INSTANCE"];+ return env === "off" || env === "auto" || env === "on" ? env : "auto";}-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 hasJointPivots(doc) {+ return doc.getRoot().listNodes().some((n) => /^joint[_-]/i.test(n.getName()));}-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;- }- 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;- }- }- return true;+function hasNodeLevelsOfDetail(doc) {+ return doc.getRoot().listNodes().some((n) => n.getExtension(MSFT_LOD) !== null);}-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 };+function hasPreservedNodeState(doc) {+ return doc.getRoot().listNodes().some((node) => node.getExtension("KHR_node_visibility") !== null || Object.keys(node.getExtras()).length > 0);}-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);+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;}- 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 } } : {}- };-}-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("")}`;+ if (batches === 0)+ return;+ const after = collectGlbMetrics(doc);+ return { batches, instances, drawsBefore: before.drawCalls, drawsAfter: after.drawCalls };}-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 } : {}- });+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 {- png: encodePng(rgb, size, size),- width: size,- height: size,- inputGlbSha256: await hashGlbViewInput(exactBytes),- reasonCodes: loaded.reasonCodes,- meshCount: loaded.meshCount,- instanceCount: loaded.instanceCount+ mode,+ materialsBefore: before.uniqueMaterials,+ materialsAfter: after.uniqueMaterials,+ drawsBefore: before.drawCalls,+ drawsAfter: after.drawCalls,+ ...merge ? { rigidMerge: merge } : {}};}-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 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 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;+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");}- 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;+ 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}`);}- 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 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 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)- };+ if (atlas.table) {+ const scene = doc.getRoot().getDefaultScene();+ scene.setExtras({ ...scene.getExtras(), kilnAtlasProvenance: atlas.table });}- 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)- }))- } : {}+ 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 })});- 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;+ }+ 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)}`);}}- 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);+ 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 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]);- }- lockedCamera = {- ...lockedCamera,- near: Math.max(0.001, Math.min(lockedCamera.near, boxDistance(lockedCamera.position, union) / 2))- };+ const optimizeMode = resolveOptimize(opts.optimize);+ let effectiveOptimize = optimizeMode === "auto" ? "off" : optimizeMode;+ if (optimizeMode === "auto" && collectGlbMetrics(doc, tris).uniqueMaterials >= PALETTE_MIN) {+ effectiveOptimize = "palette";}- 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);- }- 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}`);- }- 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 } : {}- });+ 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)}`);}- stampLabel(cell, size, size, labelScale, labelScale, `${Math.round(frameTimes[i] * 100)}%`, labelScale);- cells.push(cell);}- 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) {- return {- ...baseMeta,- width: size,- height: size,- pngs: cells.map((c) => encodePng(c, size, size))- };+ 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 { rgb, width, height } = compositeCellGrid(cells, size);- return { ...baseMeta, width, height, png: encodePng(rgb, width, height) };-}-function normalizeVec(v) {- const len = Math.hypot(v[0], v[1], v[2]) || 1;- return [v[0] / len, v[1] / len, v[2] / len];-}-function dotVec(a, b) {- return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];-}-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 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)}`);}- 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}`);- }- 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 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}`);}- 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 THREE55 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];+ 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 (x0 === x1 && y0 === y1)- break;- const doubled = 2 * error;- if (doubled >= dy) {- error += dy;- x0 += sx;+ if (requirements.requirements.requirements.mobility?.state === "requested") {+ await Promise.resolve().then(() => init_views());+ diagnosticViews.push(...captureVehicleDiagnosticViews(root));}- if (doubled <= dx) {- error += dx;- y0 += sy;+ } finally {+ for (const [parent, children] of diagnosticParents) {+ parent.clear();+ parent.add(...children);}}-}-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 THREE55.Box3().setFromObject(root);- if (bounds.isEmpty())- bounds.set(new THREE55.Vector3(-0.5, 0, -0.5), new THREE55.Vector3(0.5, 1, 0.5));- const center = bounds.getCenter(new THREE55.Vector3);- const camera = cameraId === "front" ? new THREE55.Vector3(1, 0, 0) : new THREE55.Vector3(0, 0, 1);- const upHint = new THREE55.Vector3(0, 1, 0);- const xAxis = new THREE55.Vector3().crossVectors(upHint, camera).normalize();- const yAxis = new THREE55.Vector3().crossVectors(camera, xAxis).normalize();- let extent = 0.000001;- for (let corner = 0;corner < 8; corner++) {- const point = new THREE55.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 THREE55.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);- return [size / 2 + world.dot(xAxis) * scale, size / 2 - world.dot(yAxis) * scale];+ 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 } : {}};}-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+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)};- 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- });+ 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 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));+ 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 {- 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+ 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 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()- });+function resolveEvaluatorMode(env = process.env) {+ const value = env["KILN_EVALUATOR_MODE"];+ if (value === undefined || value === "" || value === "in-process")+ return "in-process";+ if (value === "subprocess")+ return "subprocess";+ if (value === "isolated")+ return "isolated";+ throw new Error("Invalid KILN_EVALUATOR_MODE.");+}+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 requests = planCharacterDiagnosticRequests(requirements);- const captures = [];- try {- for (const request of requests) {- if (request.variant === "character-skeleton") {- captures.push(skeletonCapture(root, request, findings, size));+ 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;}- 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 saved of transforms) {- saved.node.position.copy(saved.position);- saved.node.quaternion.copy(saved.quaternion);- saved.node.scale.copy(saved.scale);+ 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}"`);+ }}- root.updateMatrixWorld(true);- }- return captures;-}-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 THREE56 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 }]);- });- 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 });}+ return warnings;}-function hiddenTriangles(root, lowerLevels) {- let hidden = 0;- const visit = (node) => {- if (lowerLevels.has(node))+function collectMeshStats(root) {+ root.updateMatrixWorld(true);+ const out = [];+ root.traverseVisible((obj) => {+ if (!obj.isMesh)return;- if (node.visible === false) {- hidden += countTriangles(node);+ 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;}- 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 {- 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- },- visualQa: "not_assessed"- };-}-async function executeKilnCode(code, options = {}) {- if (!code || typeof code !== "string") {- throw new Error("executeKilnCode: code must be a non-empty string");- }- 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`");- }- const root = await build();- if (!root?.isObject3D) {- throw new AuthoringDiagnosticError("BUILD_RESULT", "executeKilnCode: build() did not return a THREE.Object3D");+ if (!localBounds)+ return;+ const box = localBounds.clone().applyMatrix4(meshObj.matrixWorld);+ if (!Number.isFinite(box.min.x) || !Number.isFinite(box.max.x)) {+ return;}- 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);- }+ const center = new THREE56.Vector3;+ const size = new THREE56.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 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;+function minimalGapVector(a, b) {+ const v = new THREE56.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;}- target.setEmissiveFactor([emitted[0] / peak, emitted[1] / peak, emitted[2] / peak]);- target.setExtension("KHR_materials_emissive_strength", doc.createExtension(KHRMaterialsEmissiveStrength).createEmissiveStrength().setEmissiveStrength(peak));+ return v;}-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]}`);+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 THREE56.Box3;+ for (const m of meshes)+ all.union(m.box);+ const size = new THREE56.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.`);}}- 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");+ 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.`);}- if (stdMat.side === THREE56.DoubleSide) {- mat.setDoubleSided(true);+ }+ 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 });}- if (stdMat.map) {- const t = bridgeTexture(doc, stdMat.map, textureCache);- if (t) {- mat.setBaseColorTexture(t);- bridgeTextureSampler(stdMat.map, mat.getBaseColorTextureInfo(), atlas);+ 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 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 = {+ [THREE56.NearestFilter]: 9728,+ [THREE56.LinearFilter]: 9729,+ [THREE56.NearestMipmapNearestFilter]: 9984,+ [THREE56.LinearMipmapNearestFilter]: 9985,+ [THREE56.NearestMipmapLinearFilter]: 9986,+ [THREE56.LinearMipmapLinearFilter]: 9987+ };+ GLTF_MAG_FILTER = { [THREE56.NearestFilter]: 9728, [THREE56.LinearFilter]: 9729 };+ GLTF_WRAP = {+ [THREE56.ClampToEdgeWrapping]: 33071,+ [THREE56.MirroredRepeatWrapping]: 33648,+ [THREE56.RepeatWrapping]: 10497+ };+ REVIEW_CLIP_LIMITS2 = {+ clips: 32,+ tracks: 256,+ samplesPerTrack: 4096,+ valuesPerTrack: 16384+ };+});++// src/views/port.ts+async function sha256Bytes(bytes) {+ const input = new Uint8Array(bytes.byteLength);+ input.set(bytes);+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", input));+ return `sha256:${[...digest].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;+}+async function captureViewPngsViaPort(port, glb, timeoutMs, viewDirs, size, cameras, limits, backdrop, execution) {+ let timer;+ const controller = new AbortController;+ let abort;+ try {+ execution?.signal?.throwIfAborted();+ const exactCameras = cameras?.map(validateResolvedAssetCamera);+ if (exactCameras && exactCameras.length !== viewDirs.length)+ throw new Error("camera and view count mismatch");+ const requestGlb = Uint8Array.from(glb);+ const inputGlbSha256 = await sha256Bytes(requestGlb);+ execution?.signal?.throwIfAborted();+ const deadline = new Promise((_, reject) => {+ abort = () => {+ const error = execution?.signal?.reason ?? new Error("View request cancelled.");+ reject(error);+ controller.abort(error);+ };+ execution?.signal?.addEventListener("abort", abort, { once: true });+ timer = setTimeout(() => {+ const error = new Error(`view render port timed out after ${timeoutMs}ms`);+ reject(error);+ controller.abort(error);+ }, timeoutMs);+ });+ const result = await Promise.race([+ port({+ glb: requestGlb,+ ...backdrop ? { backdrop } : {},+ ...exactCameras ? { cameras: exactCameras, width: size, height: size } : { viewDirs: viewDirs.map((dir) => [...dir]), size }+ }, { signal: controller.signal }),+ deadline+ ]);+ execution?.signal?.throwIfAborted();+ if (!result?.ok) {+ return { ok: false, reason: result?.error ?? "view render port returned ok: false" };}- if (stdMat.normalMap) {- const t = bridgeTexture(doc, stdMat.normalMap, textureCache);- if (t) {- mat.setNormalTexture(t);- bridgeTextureSampler(stdMat.normalMap, mat.getNormalTextureInfo(), atlas);- }+ if (typeof result.rendererId !== "string" || !result.rendererId.trim()) {+ return { ok: false, reason: "view render port returned no rendererId" };}- 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.`);+ if (!result.viewsPng || result.viewsPng.length !== viewDirs.length) {+ return {+ ok: false,+ reason: `view render port returned ${result.viewsPng?.length ?? 0} view PNGs, expected ${viewDirs.length}`+ };}- 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 (exactCameras) {+ if (result.width !== size || result.height !== size || !result.cameras || result.cameras.length !== exactCameras.length)+ return { ok: false, reason: "camera receipt missing or dimensions mismatch" };+ for (let i = 0;i < exactCameras.length; i++) {+ const echoed = validateResolvedAssetCamera(result.cameras[i]);+ const wanted = exactCameras[i];+ for (const key of Object.keys(wanted))+ if (JSON.stringify(echoed[key]) !== JSON.stringify(wanted[key]))+ return { ok: false, reason: "camera receipt does not match requested camera" };}}- if (stdMat.emissiveMap) {- const t = bridgeTexture(doc, stdMat.emissiveMap, textureCache);- if (t) {- mat.setEmissiveTexture(t);- bridgeTextureSampler(stdMat.emissiveMap, mat.getEmissiveTextureInfo(), atlas);- }+ if (result.derivativeFidelity && result.derivativeFidelity.inputGlbSha256 !== inputGlbSha256) {+ return {+ ok: false,+ reason: `view render port derivative receipt hash mismatch (${result.derivativeFidelity.inputGlbSha256} != ${inputGlbSha256})`+ };}- if (stdMat.aoMap) {- const t = bridgeTexture(doc, stdMat.aoMap, textureCache);- if (t) {- mat.setOcclusionTexture(t);- bridgeTextureSampler(stdMat.aoMap, mat.getOcclusionTextureInfo(), atlas);+ enforcePngCaptureBudget(result.viewsPng, limits);+ for (const png of result.viewsPng) {+ const decoded = decodePng(png);+ if (exactCameras && (decoded.width !== size || decoded.height !== size))+ return { ok: false, reason: "camera PNG dimensions mismatch" };+ if (decoded.width !== decoded.height) {+ return {+ ok: false,+ reason: `view render port returned non-square ${decoded.width}x${decoded.height} PNG`+ };}- 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 === THREE56.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 {+ ok: true,+ pngs: result.viewsPng.map((png) => Uint8Array.from(png)),+ rendererId: result.rendererId,+ ...result.captureCache ? { captureCache: result.captureCache } : {},+ derivativeFidelityAttested: result.derivativeFidelity?.materialFaithful === true,+ ...result.derivativeFidelity ? { inputGlbSha256 } : {}+ };+ } catch (err) {+ return { ok: false, reason: err instanceof Error ? err.message : String(err) };+ } finally {+ if (timer !== undefined)+ clearTimeout(timer);+ if (abort)+ execution?.signal?.removeEventListener("abort", abort);}- cache.set(threeMat, mat);- return mat;-}-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 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));- }- 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 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"]- ]+async function captureViewsViaPort(port, glb, timeoutMs = DEFAULT_VIEW_RENDER_TIMEOUT_MS, capture, limits, execution) {+ if (capture?.shots || capture?.version) {+ try {+ execution?.signal?.throwIfAborted();+ await Promise.resolve().then(() => init_views());+ await Promise.resolve().then(() => init_camera_capture());+ await Promise.resolve().then(() => init_camera());+ await Promise.resolve().then(() => init_render());+ const loaded = await loadGlbReviewScene(Uint8Array.from(glb));+ let rendererId = "";+ const grid = await renderCaptureGrid(loaded.root, capture, async (input) => {+ execution?.signal?.throwIfAborted();+ const derivative = await renderSceneToGLB(withoutHiddenMeshes(input.root), { derivative: true, gltfExporter: "three" });+ const result = await captureViewPngsViaPort(port, derivative.bytes, timeoutMs, [input.view.dir], input.size, [input.camera], limits, input.backdrop, execution);+ if (!result.ok)+ throw new Error(result.reason);+ if (!result.derivativeFidelityAttested || !result.inputGlbSha256)+ throw new Error("advanced capture requires derivative material receipt");+ if (rendererId && rendererId !== result.rendererId)+ throw new Error("capture renderer changed between cells");+ rendererId = result.rendererId;+ return {+ png: Buffer.from(result.pngs[0]),+ receipt: {+ version: "kiln.view-fidelity.v1",+ derivativeLabel: input.label,+ requested: "full-preferred",+ delivered: "full-material",+ exactArtifact: false,+ rendererId: result.rendererId,+ materialFaithful: true,+ degraded: false,+ inputGlbSha256: result.inputGlbSha256,+ camera: input.camera,+ cameraFidelity: "echo-validated",+ ...result.captureCache ? { captureCache: result.captureCache } : {}+ }};- }+ }, limits);+ return {+ ok: true,+ png: grid.png,+ rendererId,+ capture: grid.capture,+ width: grid.width,+ height: grid.height,+ cameraShots: grid.cameraShots,+ derivativeReceipts: grid.derivativeReceipts,+ perFramePngs: grid.perFramePngs,+ ...grid.captureCache ? { captureCache: grid.captureCache } : {}+ };+ } catch (error) {+ return { ok: false, reason: error instanceof Error ? error.message : String(error) };}}- 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);+ let resolved;+ try {+ execution?.signal?.throwIfAborted();+ resolved = resolveGridCapture(capture, process.env["KILN_GRID_VARIANT"]);+ enforceCapturePixels(resolved.views.length, 384, resolved.cols, limits);+ } catch (err) {+ return { ok: false, reason: err instanceof Error ? err.message : String(err) };}- 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 THREE56.PlaneGeometry(1, 1);- if (centerX !== 0.5 || centerY !== 0.5) {- geometry.translate(0.5 - centerX, 0.5 - centerY, 0);- }- if (rotation !== 0)- geometry.rotateZ(rotation);- gtMesh = bridgeGeometry(doc, buf, geometry, gtMat, sprite.name || "sprite-quad", atlas);- meshCache.set(cacheKey, gtMesh);+ const views = resolved.views;+ const shape = {+ preset: resolved.preset,+ cols: resolved.cols,+ cells: views.length,+ backdrop: resolved.backdrop+ };+ let cameras;+ if (resolved.zooms.some((z) => z !== undefined)) {+ try {+ await Promise.resolve().then(() => init_views());+ const loaded = await loadGlbReviewScene(Uint8Array.from(glb));+ const bounds = measureBounds(loaded.root);+ cameras = views.map((view, i) => cameraFromBounds(bounds, view.dir, resolved.zooms[i] ?? 1));+ } catch (error) {+ return { ok: false, reason: error instanceof Error ? error.message : String(error) };}- 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);+ const result = await captureViewPngsViaPort(port, glb, timeoutMs, views.map((view) => view.dir), 384, cameras, limits, resolved.backdrop, execution);+ if (!result.ok)+ return result;+ try {+ const grid = compositeViewPngGrid(result.pngs, resolved.cols, views);+ enforceCaptureBytes([grid.png], limits);+ return {+ ok: true,+ png: grid.png,+ rendererId: result.rendererId,+ ...result.captureCache ? { captureCache: result.captureCache } : {},+ capture: shape,+ width: grid.width,+ height: grid.height+ };+ } catch (err) {+ return { ok: false, reason: err instanceof Error ? err.message : String(err) };}- return gtNode;-}-function animationInterpolation(track) {- if (isCubicSplineTrack(track))- return "CUBICSPLINE";- const mode = track.getInterpolation();- if (mode === THREE56.InterpolateDiscrete)- return "STEP";- if (mode === THREE56.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;+var DEFAULT_VIEW_RENDER_TIMEOUT_MS = 8000;+var init_port = __esm(() => {+ init_capture_limits();+ init_camera();+ init_capture();+ init_png();+ init_grid();+});++// src/material-map-export-node.ts+import { createHash as createHash9 } from "node:crypto";+import { join as join2, resolve as resolve4 } from "node:path";+import sharp from "sharp";+import * as THREE57 from "three";+async function decodePng2(bytes) {+ const { data, info } = await sharp(bytes, {+ limitInputPixels: MATERIAL_LIBRARY_LIMITS.maxRecordPixels,+ failOn: "warning"+ }).ensureAlpha().raw({ depth: "uchar" }).toBuffer({ resolveWithObject: true });+ if (info.channels !== 4)+ throw new Error("Material map must decode to RGBA");+ return { pixels: new Uint8Array(data), width: info.width, height: info.height };+}+function validateMaterialMapExportOptions(options, material) {+ const limits = MATERIAL_MAP_EXPORT_LIMITS;+ const { size } = options;+ if (!Number.isInteger(size) || size < limits.minSize || size > limits.maxSize)+ throw new Error(`size must be an integer from ${limits.minSize} to ${limits.maxSize} pixels`);+ const tiles = options.tiles ?? limits.defaultTiles;+ if (!Number.isInteger(tiles) || tiles < 1 || tiles > limits.maxTiles)+ throw new Error(`tiles must be an integer from 1 to ${limits.maxTiles}`);+ let repeat = options.repeatMeters;+ if (repeat === undefined && material) {+ const physical = material.physicalSizeMeters;+ if (!physical || physical.width !== physical.height)+ throw new Error(`repeatMeters is required: material ${material.materialId} records no square physicalSizeMeters (CLI: --repeat <metres>)`);+ repeat = physical.width;+ }+ if (repeat !== undefined && (!Number.isFinite(repeat) || repeat <= 0 || repeat > limits.maxRepeatMeters))+ throw new Error(`repeatMeters must be a positive number of metres up to ${limits.maxRepeatMeters}`);+ return { size, tiles, ...repeat !== undefined ? { repeat } : {} };+}+function axisTaps(source, target, wrap) {+ const scale = source / target;+ const stretch = Math.max(1, scale);+ const support = 2 * stretch;+ const kernel = (x) => {+ const a = Math.abs(x);+ if (a < 1)+ return 1.5 * a * a * a - 2.5 * a * a + 1;+ if (a < 2)+ return -0.5 * a * a * a + 2.5 * a * a - 4 * a + 2;+ return 0;+ };+ const address = (index) => {+ if (wrap === "repeat")+ return (index % source + source) % source;+ if (wrap === "mirrored-repeat") {+ const period = 2 * source;+ const folded = (index % period + period) % period;+ return folded < source ? folded : period - 1 - folded;+ }+ return Math.min(source - 1, Math.max(0, index));+ };+ const taps = [];+ for (let out = 0;out < target; out++) {+ const center = (out + 0.5) * scale - 0.5;+ const first = Math.ceil(center - support);+ const last = Math.floor(center + support);+ const index = new Int32Array(last - first + 1);+ const weight = new Float64Array(last - first + 1);+ let total = 0;+ for (let i = first;i <= last; i++) {+ const w = kernel((i - center) / stretch);+ index[i - first] = address(i);+ weight[i - first] = w;+ total += w;+ }+ for (let i = 0;i < weight.length; i++)+ weight[i] /= total;+ taps.push({ index, weight });+ }+ return taps;+}+function resampleMaterialMapPixels(pixels, width, height, target, options) {+ const horizontal = axisTaps(width, target, options.wrap.s);+ const vertical = axisTaps(height, target, options.wrap.t);+ const srgb = options.colorSpace === "srgb";+ const decode = (channel, value) => srgb && channel < 3 ? SRGB_TO_LINEAR[value] : value / 255;+ const column = new Float64Array(width * 4);+ const row = new Float64Array(4);+ const out = new Uint8Array(target * target * 4);+ for (let y = 0;y < target; y++) {+ const { index: rows, weight: rowWeights } = vertical[y];+ column.fill(0);+ for (let tap = 0;tap < rows.length; tap++) {+ const offset = rows[tap] * width * 4;+ const w = rowWeights[tap];+ for (let i = 0;i < width * 4; i++)+ column[i] += decode(i & 3, pixels[offset + i]) * w;+ }+ for (let x = 0;x < target; x++) {+ const { index: cols, weight: colWeights } = horizontal[x];+ row.fill(0);+ for (let tap = 0;tap < cols.length; tap++) {+ const offset = cols[tap] * 4;+ const w = colWeights[tap];+ for (let c = 0;c < 4; c++)+ row[c] += column[offset + c] * w;+ }+ const o = (y * target + x) * 4;+ if (options.normal) {+ let nx = row[0] * 2 - 1;+ let ny = row[1] * 2 - 1;+ let nz = row[2] * 2 - 1;+ const length = Math.hypot(nx, ny, nz);+ if (length > 0.000001) {+ nx /= length;+ ny /= length;+ nz /= length;+ } else+ [nx, ny, nz] = [0, 0, 1];+ out[o] = toByte(nx * 0.5 + 0.5);+ out[o + 1] = toByte(ny * 0.5 + 0.5);+ out[o + 2] = toByte(nz * 0.5 + 0.5);+ } else+ for (let c = 0;c < 3; c++)+ out[o + c] = toByte(srgb ? linearToSrgb3(row[c]) : row[c]);+ out[o + 3] = toByte(row[3]);}- return copied;- });+ }+ return out;}-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;+function regenerableRecipe(map) {+ if ("procedural" in map && map.procedural && !map.procedural.derive)+ return map.procedural.spec;+ if ("recipe" in map && map.recipe?.kind === "procedural" && map.recipe.compilerId === "kiln.procedural-texture.v2" && !map.recipe.derive && map.recipe.spec.schemaVersion === 2)+ return map.recipe.spec;+ return;+}+async function exportMap(record, map, size) {+ const manifest = record.manifest;+ const stored = record.files[map.file];+ const fallbackWrap = manifest.tileable ? "repeat" : "clamp-to-edge";+ const wrap = "sampler" in map && map.sampler ? { s: map.sampler.wrapS, t: map.sampler.wrapT } : { s: fallbackWrap, t: fallbackWrap };+ let bytes;+ let pixels;+ let method;+ let recipe;+ const spec = regenerableRecipe(map);+ if (map.width === size && map.height === size) {+ bytes = stored.slice();+ pixels = (await decodePng2(bytes)).pixels;+ method = "copy";+ } else if (spec && size <= 1024 && (size & size - 1) === 0) {+ const compiled = compileProceduralTextureSpecV2({ ...spec, size });+ pixels = compiled.pixels;+ bytes = await encodePng2(pixels, size, size);+ method = "recipe";+ recipe = { compilerId: "kiln.procedural-texture.v2", recipeHash: compiled.recipeHash };+ } else {+ const decoded = await decodePng2(stored);+ pixels = resampleMaterialMapPixels(decoded.pixels, decoded.width, decoded.height, size, {+ colorSpace: map.colorSpace,+ normal: map.slot === "normal",+ wrap+ });+ bytes = await encodePng2(pixels, size, size);+ method = "resampled";+ }+ return {+ bytes,+ pixels,+ entry: {+ slot: map.slot,+ usage: map.usage,+ colorSpace: map.colorSpace,+ ...map.normalConvention ? { normalConvention: map.normalConvention } : {},+ ...map.channelPacking ? { channelPacking: map.channelPacking } : {},+ width: size,+ height: size,+ bytes: bytes.length,+ sha256: digest2(bytes),+ method,+ wrap,+ ...recipe ? { recipe } : {},+ source: {+ file: map.file,+ sha256: map.sha256,+ width: map.width,+ height: map.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);}- if (anim.listChannels().length === 0)- anim.dispose();+ };+}+async function previewGlb(manifest, maps, tiles, planeMeters) {+ const textures = new Map;+ for (const map of maps)+ textures.set(map.slot, await loadTexture(map.png, {+ usage: map.usage,+ name: `${manifest.materialId}.${map.slot}`+ }));+ const p = manifest.parameters;+ const options = {+ roughness: p.roughness,+ metalness: p.metalness,+ emissiveIntensity: p.emissiveIntensity,+ alphaMode: p.alphaMode,+ ...p.alphaMode === "mask" ? { alphaCutoff: p.alphaCutoff } : {},+ doubleSided: p.doubleSided,+ ...textures.get("baseColor") ? { albedo: textures.get("baseColor") } : p.baseColor !== undefined ? { albedo: p.baseColor } : {},+ ...textures.get("normal") ? { normal: textures.get("normal") } : {},+ ...textures.get("metallicRoughness") ? { metallicRoughness: textures.get("metallicRoughness") } : {},+ ...textures.get("emissive") ? { emissive: textures.get("emissive") } : p.emissive !== undefined ? { emissive: p.emissive } : {},+ ...textures.get("occlusion") ? { aoMap: textures.get("occlusion") } : {}+ };+ const material = pbrMaterial(options);+ material.name = manifest.name;+ if (textures.has("baseColor") && p.baseColor !== undefined)+ material.color.setHex(p.baseColor);+ if (textures.has("emissive") && p.emissive !== undefined)+ material.emissive.setHex(p.emissive);+ const geometry = new THREE57.PlaneGeometry(planeMeters, planeMeters);+ geometry.rotateX(-Math.PI / 2);+ const uv = geometry.getAttribute("uv");+ for (let i = 0;i < uv.count; i++)+ uv.setXY(i, uv.getX(i) * tiles, uv.getY(i) * tiles);+ const root = new THREE57.Group;+ root.name = `${manifest.materialId}-preview`;+ const mesh = new THREE57.Mesh(geometry, material);+ mesh.name = "tiles";+ root.add(mesh);+ await Promise.resolve().then(() => init_render());+ return (await renderSceneToGLB(root, { derivative: true })).bytes;+}+async function renderPreview(glb, options) {+ await Promise.resolve().then(() => init_port());+ const capture = { preset: "1x1", cells: [{ ...PREVIEW_CAMERA }] };+ const inputGlbSha256 = await sha256Bytes(glb);+ let degradeReason = "material-faithful view render port unavailable";+ if (options.viewRenderPort) {+ const ported = await captureViewsViaPort(options.viewRenderPort, glb, options.viewRenderTimeoutMs ?? DEFAULT_VIEW_RENDER_TIMEOUT_MS, capture);+ if (ported.ok)+ return {+ png: new Uint8Array(ported.png),+ rendererId: ported.rendererId,+ viewFidelity: {+ version: "kiln.view-fidelity.v1",+ requested: "full-preferred",+ delivered: "full-material",+ materialFaithful: true,+ exactArtifact: false,+ rendererId: ported.rendererId,+ inputGlbSha256,+ degraded: false+ }+ };+ degradeReason = ported.reason;}+ if (options.viewRenderRequired)+ throw new Error(`Required GPU render failed: ${degradeReason}`);+ await Promise.resolve().then(() => init_views());+ const grid = await renderGlbViewGrid(glb, { capture });+ return {+ png: new Uint8Array(grid.png),+ rendererId: CPU_RASTER_RENDERER_ID,+ viewFidelity: {+ version: "kiln.view-fidelity.v1",+ requested: "full-preferred",+ delivered: "geometry-flat",+ materialFaithful: false,+ exactArtifact: false,+ rendererId: CPU_RASTER_RENDERER_ID,+ inputGlbSha256: grid.inputGlbSha256,+ degraded: true,+ degradeReason,+ reasonCodes: ["FULL_MATERIAL_RENDER_UNAVAILABLE", ...grid.reasonCodes]+ }+ };}-function clipLoopIntent(clip) {- const intent = clip.userData?.kilnLoopIntent;- return intent === "loop" || intent === "once" ? intent : undefined;+async function createMaterialMapExport(record, options) {+ if (typeof options.outDir !== "string" || !options.outDir)+ throw new Error("outDir must name a directory");+ validateMaterialMapExportOptions(options);+ const manifest = validateMaterialRecordShapeAny(record);+ const checked = validateMaterialMapExportOptions(options, manifest);+ const { size, tiles } = checked;+ const repeat = checked.repeat;+ for (const map of manifest.maps)+ if (digest2(record.files[map.file]) !== map.sha256)+ throw new Error(`Material integrity hash mismatch: ${map.file}`);+ const id = manifest.materialId;+ const ordered = MATERIAL_LIBRARY_SLOTS.flatMap((slot) => manifest.maps.filter((map) => map.slot === slot));+ const files = [];+ const maps = [];+ const previewMaps = [];+ const previewSize = Math.min(size, MATERIAL_MAP_EXPORT_LIMITS.maxPreviewMapSize);+ for (const map of ordered) {+ const exported = await exportMap(record, map, size);+ const file = `${id}.${map.slot}.png`;+ const { slot, ...entry } = exported.entry;+ maps.push({ slot, file, ...entry });+ files.push({ name: file, bytes: exported.bytes });+ previewMaps.push({+ slot: map.slot,+ usage: map.usage,+ png: previewSize === size ? exported.bytes : await encodePng2(resampleMaterialMapPixels(exported.pixels, size, size, previewSize, {+ colorSpace: map.colorSpace,+ normal: map.slot === "normal",+ wrap: exported.entry.wrap+ }), previewSize, previewSize)+ });+ }+ const planeMeters = tiles * repeat;+ const rendered = await renderPreview(await previewGlb(manifest, previewMaps, tiles, planeMeters), options);+ const previewFile = `${id}.preview.png`;+ files.push({ name: previewFile, bytes: rendered.png });+ const sidecar = {+ version: "kiln.material-maps.v1",+ material: {+ materialId: id,+ revisionId: manifest.revisionId,+ name: manifest.name,+ tileable: manifest.tileable,+ ...manifest.physicalSizeMeters ? { physicalSizeMeters: { ...manifest.physicalSizeMeters } } : {},+ parameters: structuredClone(manifest.parameters),+ sources: structuredClone(manifest.sources)+ },+ size: { width: size, height: size },+ repeatMeters: { width: repeat, height: repeat },+ resampleFilter: MATERIAL_MAP_RESAMPLE_FILTER,+ maps,+ preview: {+ file: previewFile,+ sha256: digest2(rendered.png),+ bytes: rendered.png.length,+ ...materialPngDimensions(rendered.png),+ tiles,+ planeMeters,+ mapSize: previewSize,+ camera: { ...PREVIEW_CAMERA },+ rendererId: rendered.rendererId,+ viewFidelity: rendered.viewFidelity+ }+ };+ files.push({+ name: `${id}.maps.json`,+ bytes: new TextEncoder().encode(`${JSON.stringify(sidecar, null, 2)}+`)+ });+ return { sidecar, files };}-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;+async function exportMaterialMaps(record, options) {+ const created = await createMaterialMapExport(record, options);+ const directory = resolve4(options.outDir);+ const outputs = created.files.map(({ name, bytes }) => ({+ path: join2(directory, name),+ data: bytes+ }));+ await writeNewDestinationsAtomic(outputs);+ return {+ directory,+ sidecarPath: outputs.at(-1).path,+ previewPath: outputs.at(-2).path,+ files: outputs.map(({ path }) => path),+ sidecar: created.sidecar+ };+}+var MATERIAL_MAP_EXPORT_LIMITS, MATERIAL_MAP_RESAMPLE_FILTER = "catmull-rom", PREVIEW_CAMERA, digest2 = (bytes) => `sha256:${createHash9("sha256").update(bytes).digest("hex")}`, encodePng2 = async (pixels, width, height) => new Uint8Array(await sharp(pixels, { raw: { width, height, channels: 4 } }).png({ compressionLevel: 9, adaptiveFiltering: false }).toBuffer()), SRGB_TO_LINEAR, linearToSrgb3 = (value) => {+ const c = Math.min(1, Math.max(0, value));+ return c <= 0.0031308 ? c * 12.92 : 1.055 * c ** (1 / 2.4) - 0.055;+}, toByte = (value) => Math.round(Math.min(1, Math.max(0, value)) * 255);+var init_material_map_export_node = __esm(() => {+ init_cli_output();+ init_material_library();+ init_procedural_texture();+ init_textures();+ MATERIAL_MAP_EXPORT_LIMITS = Object.freeze({+ minSize: 4,+ maxSize: MATERIAL_LIBRARY_LIMITS.maxMapEdge,+ maxRepeatMeters: 1e5,+ defaultTiles: 3,+ maxTiles: 8,+ maxPreviewMapSize: 1024+ });+ PREVIEW_CAMERA = Object.freeze({ azimuthDeg: 30, elevationDeg: 50 });+ SRGB_TO_LINEAR = Float64Array.from({ length: 256 }, (_, value) => {+ const c = value / 255;+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;+ });+});++// src/material-library-node.ts+import { createHash as createHash10, randomUUID as randomUUID2 } from "node:crypto";+import { lstat as lstat3, mkdir as mkdir2, readFile as readFile2, readdir, realpath as realpath2, rm, writeFile as writeFile2 } from "node:fs/promises";+import { dirname as dirname2, join as join3, relative, resolve as resolve5, sep } from "node:path";+import sharp2 from "sharp";+import { DataTexture as DataTexture4 } from "three";+function revisionHash(manifest) {+ const { revisionId: _, ...content } = manifest;+ return digest3(canonicalMaterialJson(content));}-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;+function snapshot(record) {+ validateMaterialRecordShape(record);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) };- })- }))+ manifest: structuredClone(record.manifest),+ files: Object.fromEntries(Object.entries(record.files).map(([name, bytes]) => [name, Uint8Array.from(bytes)]))};}-function resolveOptimize(opt) {- if (opt)- return opt;- const env = process.env["KILN_BAKE_OPTIMIZE"];- return env === "auto" || env === "palette" || env === "full" ? env : "off";+function exactKeys(value, keys) {+ if (Object.keys(value).some((key) => !keys.includes(key)))+ throw new Error("Unknown material draft field");}-function resolveInstance(opt) {- if (opt)- return opt;- const env = process.env["KILN_BAKE_INSTANCE"];- return env === "off" || env === "auto" || env === "on" ? env : "auto";+function derivedNormalPixels(compiled, size, derive) {+ if (!derive)+ return compiled;+ materialNormalDerivationSchema.parse(derive);+ if (size.usage !== "normal")+ throw new Error("Height derivation requires a normal map slot");+ const height = new DataTexture4(compiled.pixels, size.width, size.height);+ const normal = normalMapFromHeight(height, { strength: derive.strength });+ if (!(normal.image.data instanceof Uint8Array))+ throw new Error("Normal derivation must produce RGBA8 pixels");+ const pixels = Uint8Array.from(normal.image.data);+ height.dispose();+ normal.dispose();+ return { ...compiled, pixels };}-function hasJointPivots(doc) {- return doc.getRoot().listNodes().some((n) => /^joint[_-]/i.test(n.getName()));+function materialPixels(spec, derive) {+ const compiled = compileProceduralTextureSpecV2(spec);+ const { size, usage } = compiled.spec;+ return derivedNormalPixels(compiled, { width: size, height: size, usage }, derive);}-function hasNodeLevelsOfDetail(doc) {- return doc.getRoot().listNodes().some((n) => n.getExtension(MSFT_LOD) !== null);+function materialPixelsV3(spec, derive) {+ const compiled = compileProceduralTextureSpecV3(spec);+ return derivedNormalPixels(compiled, compiled.spec, derive);}-function hasPreservedNodeState(doc) {- return doc.getRoot().listNodes().some((node) => node.getExtension("KHR_node_visibility") !== null || Object.keys(node.getExtras()).length > 0);+async function createMaterialRecordV1(draft) {+ assertMaterialJson(draft, true);+ exactKeys(draft, [+ "materialId",+ "name",+ "tags",+ "tileable",+ "physicalSizeMeters",+ "parameters",+ "sources",+ "maps"+ ]);+ if (!Array.isArray(draft.maps) || !draft.maps.length || draft.maps.length > 5)+ throw new Error("Material requires 1..5 maps");+ const files = {};+ const maps = [];+ let totalPixels = 0;+ for (const input of draft.maps) {+ exactKeys(input, [+ "slot",+ "sourceId",+ "transforms",+ "normalConvention",+ "channelPacking",+ "bytes",+ "originalFile",+ "procedural",+ "derive"+ ]);+ if (!MATERIAL_LIBRARY_SLOTS.includes(input.slot))+ throw new Error("Unsupported material map slot");+ if (input.bytes !== undefined === (input.procedural !== undefined))+ throw new Error("Supply exactly one map byte source or procedural recipe");+ let bytes;+ let procedural;+ if (input.procedural) {+ const compiled = materialPixels(input.procedural, input.derive);+ if (compiled.spec.usage !== MATERIAL_LIBRARY_USAGE[input.slot])+ throw new Error("Procedural map usage mismatch");+ bytes = new Uint8Array(await sharp2(compiled.pixels, {+ raw: { width: compiled.spec.size, height: compiled.spec.size, channels: 4 }+ }).png({ compressionLevel: 9, adaptiveFiltering: false }).toBuffer());+ procedural = {+ compiler: "kiln.procedural-texture.v2",+ spec: compiled.spec,+ ...input.derive ? { derive: structuredClone(input.derive) } : {},+ recipeHash: compiled.recipeHash,+ pixelHash: digest3(compiled.pixels),+ encoder+ };+ } else {+ if ("derive" in input)+ throw new Error("External maps cannot declare a procedural derivation");+ if (!(input.bytes instanceof Uint8Array))+ throw new Error("Material map bytes must be Uint8Array");+ bytes = Uint8Array.from(input.bytes);+ }+ if (bytes.length > MATERIAL_LIBRARY_LIMITS.maxMapBytes)+ throw new Error("Material map exceeds encoded byte limit");+ const dimensions = materialPngDimensions(bytes);+ totalPixels += dimensions.width * dimensions.height;+ if (dimensions.width < 1 || dimensions.height < 1 || dimensions.width > MATERIAL_LIBRARY_LIMITS.maxMapEdge || dimensions.height > MATERIAL_LIBRARY_LIMITS.maxMapEdge || totalPixels > MATERIAL_LIBRARY_LIMITS.maxRecordPixels)+ throw new Error("Material maps exceed pixel budget");+ const file = `${input.slot}.png`;+ if (files[file])+ throw new Error("Duplicate material map slot");+ files[file] = bytes;+ maps.push({+ slot: input.slot,+ file,+ ...dimensions,+ sha256: digest3(bytes),+ bytes: bytes.length,+ usage: MATERIAL_LIBRARY_USAGE[input.slot],+ colorSpace: input.slot === "baseColor" || input.slot === "emissive" ? "srgb" : "linear",+ ...input.slot === "normal" ? { normalConvention: input.normalConvention ?? (procedural ? "opengl" : undefined) } : {},+ ...input.slot === "metallicRoughness" ? {+ channelPacking: input.channelPacking ?? (procedural ? "r-occlusion-g-roughness-b-metallic" : undefined)+ } : {},+ sourceId: input.sourceId,+ ...input.originalFile ? { originalFile: input.originalFile } : {},+ transforms: structuredClone(input.transforms),+ ...procedural ? { procedural } : {}+ });+ }+ const manifest = materialManifestSchema.parse({+ schemaVersion: 1,+ materialId: draft.materialId,+ revisionId: `sha256:${"0".repeat(64)}`,+ name: draft.name,+ tags: draft.tags ?? [],+ tileable: draft.tileable,+ ...draft.physicalSizeMeters ? { physicalSizeMeters: draft.physicalSizeMeters } : {},+ parameters: draft.parameters ?? {},+ sources: draft.sources,+ maps+ });+ manifest.revisionId = revisionHash(manifest);+ const record = { manifest, files };+ await verifyMaterialRecordV1(record);+ return record;}-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;+async function verifyMaterialRecordV1(record) {+ const manifest = validateMaterialRecordShape(record);+ if (revisionHash(manifest) !== manifest.revisionId)+ throw new Error("Material identity hash mismatch");+ for (const map of manifest.maps) {+ const bytes = record.files[map.file];+ if (digest3(bytes) !== map.sha256)+ throw new Error(`Material integrity hash mismatch: ${map.file}`);+ const { data, info } = await sharp2(bytes, {+ limitInputPixels: MATERIAL_LIBRARY_LIMITS.maxRecordPixels,+ failOn: "warning"+ }).ensureAlpha().raw().toBuffer({ resolveWithObject: true });+ if (info.width !== map.width || info.height !== map.height || info.channels !== 4)+ throw new Error("Material decoded image mismatch");+ if (map.procedural) {+ const compiled = materialPixels(map.procedural.spec, map.procedural.derive);+ if (compiled.recipeHash !== map.procedural.recipeHash || digest3(compiled.pixels) !== map.procedural.pixelHash || digest3(data) !== map.procedural.pixelHash)+ throw new Error("Procedural material recipe or pixel hash mismatch");+ }}- if (batches === 0)- return;- const after = collectGlbMetrics(doc);- return { batches, instances, drawsBefore: before.drawCalls, drawsAfter: after.drawCalls };}-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 } : {}- };+function validateMaterialLibraryPayload(value) {+ assertMaterialJson(value);+ if (!value || typeof value !== "object" || Array.isArray(value))+ throw new Error("Invalid material resource payload");+ const payload = value;+ if (Object.keys(payload).some((key) => !["schemaVersion", "records"].includes(key)) || payload.schemaVersion !== 1 || !Array.isArray(payload.records) || payload.records.length > MATERIAL_LIBRARY_LIMITS.maxPayloadRecords)+ throw new Error("Invalid material resource payload");+ let total = 0;+ let pixels = 0;+ const identities = new Set;+ for (const wire of payload.records) {+ if (!wire || typeof wire !== "object" || Object.keys(wire).some((key) => !["manifest", "files"].includes(key)))+ throw new Error("Invalid material resource record");+ const manifest = materialManifestSchema.parse(wire.manifest);+ if (identities.has(manifest.revisionId))+ throw new Error("Duplicate material resource revision");+ identities.add(manifest.revisionId);+ if (!wire.files || typeof wire.files !== "object" || Array.isArray(wire.files) || Object.keys(wire.files).length !== manifest.maps.length)+ throw new Error("Material payload inventory mismatch");+ for (const map of manifest.maps) {+ const encoded = wire.files[map.file];+ if (typeof encoded !== "string" || encoded.length !== Math.ceil(map.bytes / 3) * 4 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encoded))+ throw new Error("Invalid material map base64");+ total += map.bytes;+ pixels += map.width * map.height;+ }+ }+ if (total > MATERIAL_LIBRARY_LIMITS.maxPayloadBytes || pixels > MATERIAL_LIBRARY_LIMITS.maxPayloadPixels)+ throw new Error("Material resource payload exceeds byte or pixel budget");+ return payload;}-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 createMaterialLibraryPayloadV1(records) {+ const snapshots = records.map(snapshot);+ for (const record of snapshots)+ await verifyMaterialRecordV1(record);+ return validateMaterialLibraryPayload({+ schemaVersion: 1,+ records: snapshots.map((record) => ({+ manifest: record.manifest,+ files: Object.fromEntries(Object.entries(record.files).map(([name, bytes]) => [+ name,+ Buffer.from(bytes).toString("base64")+ ]))+ }))+ });}-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 decodeMaterialLibraryPayloadV1(value) {+ const payload = validateMaterialLibraryPayload(value);+ const records = payload.records.map((wire) => ({+ manifest: structuredClone(wire.manifest),+ files: Object.fromEntries(Object.entries(wire.files).map(([name, encoded]) => [+ name,+ new Uint8Array(Buffer.from(encoded, "base64"))+ ]))+ }));+ for (const record of records)+ await verifyMaterialRecordV1(record);+ return records;+}+async function createMaterialLibraryTextureResolver(records, fallback = DEFAULT_TEXTURE_RESOLVER) {+ const snapshots = await decodeMaterialLibraryPayload(await createMaterialLibraryPayload(records));+ const maps = new Map;+ for (const record of snapshots)+ for (const map of record.manifest.maps)+ maps.set(materialLibraryResourceId(record.manifest, map.slot), { record, map });+ return Object.freeze({+ pinnedMaterialMaps: createPinnedMaterialMapPort(snapshots),+ describeApprovedTexture(id) {+ const entry = typeof id === "string" ? maps.get(id) : undefined;+ return entry ? { usage: entry.map.usage, allowedSlots: [entry.map.slot] } : fallback.describeApprovedTexture?.(id);+ },+ async loadApprovedTexture(id) {+ const entry = typeof id === "string" ? maps.get(id) : undefined;+ if (!entry)+ return fallback.loadApprovedTexture(id);+ const texture = await loadTexture(entry.record.files[entry.map.file].slice(), {+ usage: entry.map.usage,+ name: id+ });+ texture.userData["kilnMaterialResource"] = {+ schemaVersion: entry.record.manifest.schemaVersion,+ materialId: entry.record.manifest.materialId,+ revisionId: entry.record.manifest.revisionId,+ resourceId: id,+ map: structuredClone(entry.map),+ sources: structuredClone(entry.record.manifest.sources),+ ...entry.record.manifest.physicalSizeMeters ? { physicalSizeMeters: { ...entry.record.manifest.physicalSizeMeters } } : {}+ };+ if ("sampler" in entry.map)+ applyPortableSamplerV1(texture, entry.map.sampler);+ if ("recipe" in entry.map && entry.map.recipe?.kind === "atlas")+ texture.userData["kilnAtlas"] = {+ spec: structuredClone(entry.map.recipe.spec),+ manifest: structuredClone(entry.map.recipe.manifest)+ };+ return texture;+ },+ async preparePortableTexture(id, context) {+ context?.signal?.throwIfAborted();+ const entry = typeof id === "string" ? maps.get(id) : undefined;+ if (!entry) {+ if (!fallback.preparePortableTexture)+ throw new Error("Portable texture preparation unavailable");+ return fallback.preparePortableTexture(id, context);}- }), "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 { record, map } = entry;+ return {+ descriptor: {+ resourceId: id,+ usage: map.usage,+ allowedSlots: [map.slot],+ colorSpace: map.colorSpace,+ width: map.width,+ height: map.height,+ encodedByteLength: map.bytes,+ imageSha256: map.sha256+ },+ bytes: record.files[map.file].slice(),+ userData: {+ ..."recipe" in map && map.recipe?.kind === "atlas" ? {+ kilnAtlas: {+ spec: structuredClone(map.recipe.spec),+ manifest: structuredClone(map.recipe.manifest)+ }+ } : {},+ kilnMaterialResource: {+ schemaVersion: record.manifest.schemaVersion,+ materialId: record.manifest.materialId,+ revisionId: record.manifest.revisionId,+ resourceId: id,+ map: structuredClone(map),+ sources: structuredClone(record.manifest.sources),+ ...record.manifest.physicalSizeMeters ? { physicalSizeMeters: structuredClone(record.manifest.physicalSizeMeters) } : {}+ }+ }+ };+ },+ materialRecipe: (id, overrides) => fallback.materialRecipe(id, overrides)+ });+}++class FileMaterialLibrary {+ root;+ constructor(root) {+ this.root = resolve5(root);}- 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 });+ async path(...parts) {+ await mkdir2(this.root, { recursive: true });+ const canonical = await realpath2(this.root);+ let current = canonical;+ for (const part of parts) {+ if (!/^[a-z0-9][a-z0-9_-]{0,79}$/.test(part))+ throw new Error("Invalid material path identity");+ current = join3(current, part);+ try {+ const stat = await lstat3(current);+ if (stat.isSymbolicLink() || !stat.isDirectory())+ throw new Error("Material library requires real directories");+ const rel = relative(canonical, await realpath2(current));+ if (rel === ".." || rel.startsWith(`..${sep}`))+ throw new Error("Material path escapes library");+ } catch (error) {+ if (error.code !== "ENOENT")+ throw error;+ }}+ return current;}- 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(dedup2());- } catch (err) {- warnings.push(`dedup transform failed: ${err instanceof Error ? err.message : String(err)}`);- }+ async file(dir, name, limit) {+ const path = join3(dir, name);+ const stat = await lstat3(path);+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > limit)+ throw new Error("Invalid material library file");+ return new Uint8Array(await readFile2(path));}- 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)}`);+ async readManifest(materialId, revisionId) {+ materialLibraryIdSchema.parse(materialId);+ materialLibraryHashSchema.parse(revisionId);+ const dir = await this.path(materialId, revisionId.slice(7));+ const manifest = validateMaterialManifestIdentityAny(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(await this.file(dir, "manifest.json", MATERIAL_LIBRARY_LIMITS.maxManifestBytes))));+ if (manifest.materialId !== materialId || manifest.revisionId !== revisionId)+ throw new Error("Material identity mismatch");+ return manifest;}- const optimizeMode = resolveOptimize(opts.optimize);- let effectiveOptimize = optimizeMode === "auto" ? "off" : optimizeMode;- if (optimizeMode === "auto" && collectGlbMetrics(doc, tris).uniqueMaterials >= PALETTE_MIN) {- effectiveOptimize = "palette";+ async readRecordFiles(materialId, revisionId) {+ const manifest = await this.readManifest(materialId, revisionId);+ const dir = await this.path(materialId, revisionId.slice(7));+ const files = {};+ for (const map of manifest.maps)+ files[map.file] = await this.file(dir, map.file, MATERIAL_LIBRARY_LIMITS.maxMapBytes);+ const record = { manifest, files };+ validateMaterialRecordShapeAny(record);+ for (const map of manifest.maps)+ if (digest3(files[map.file]) !== map.sha256)+ throw new Error("Material integrity hash mismatch");+ return record;}- 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)}`);+ async read(materialId, revisionId) {+ const root = await this.readManifest(materialId, revisionId);+ if (root.schemaVersion === 1) {+ const record = await this.readRecordFiles(materialId, revisionId);+ await verifyMaterialRecordV1(record);+ return record;}- }- 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"+ const closure = await resolveMaterialRecordClosure([root], {+ readManifest: this.readManifest.bind(this),+ read: this.readRecordFiles.bind(this)});- } 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}`);+ return closure.find((record) => record.manifest.materialId === materialId && record.manifest.revisionId === revisionId);}- 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)));+ async list() {+ const manifests = [];+ for (const material of await readdir(await this.path(), { withFileTypes: true })) {+ if (!material.isDirectory() || !materialLibraryIdSchema.safeParse(material.name).success)+ continue;+ for (const revision of await readdir(await this.path(material.name), {+ withFileTypes: true+ })) {+ if (!revision.isDirectory() || !/^[a-f0-9]{64}$/.test(revision.name))+ continue;+ manifests.push((await this.read(material.name, `sha256:${revision.name}`)).manifest);+ }}- if (requirements.requirements.requirements.mobility?.state === "requested") {- await Promise.resolve().then(() => init_views());- diagnosticViews.push(...captureVehicleDiagnosticViews(root));+ return manifests.sort((a, b) => a.materialId.localeCompare(b.materialId) || a.revisionId.localeCompare(b.revisionId));+ }+ async import(records, options) {+ if (!Array.isArray(records) || !records.length || records.length > 100)+ throw new Error("Material import requires 1..100 records");+ let snapshots;+ if (records.every((record) => record.manifest.schemaVersion === 1) && !options?.materials) {+ snapshots = records.map(snapshot);+ for (const record of snapshots)+ await verifyMaterialRecordV1(record);+ } else {+ const candidates = [...records, ...options?.materials ?? []];+ if (new Set(candidates.map((record) => identity(record.manifest))).size > 1024)+ throw new Error("Material import context count limit exceeded");+ const context = await resolveMaterialRecordClosure(records.map((r) => r.manifest), recordClosureReader(candidates, this), {+ maxRecords: 1024,+ maxBytes: 256 * 1024 * 1024,+ maxPixels: 1024 * MATERIAL_LIBRARY_LIMITS.maxRecordPixels+ });+ const admitted = new Map(context.map((record) => [identity(record.manifest), record]));+ snapshots = records.map((record) => admitted.get(identity(record.manifest)));}- } finally {- for (const [parent, children] of diagnosticParents) {- parent.clear();- parent.add(...children);+ for (const record of snapshots) {+ const { manifest, files } = record;+ const dest = await this.path(manifest.materialId, manifest.revisionId.slice(7));+ const parent = dirname2(dest);+ await mkdir2(parent, { recursive: true });+ const stage = join3(parent, `.stage-${randomUUID2()}`);+ await mkdir2(stage);+ try {+ for (const [name, bytes] of Object.entries(files))+ await writeFile2(join3(stage, name), bytes, { flag: "wx" });+ await writeFile2(join3(stage, "manifest.json"), canonicalMaterialJson(manifest), {+ flag: "wx"+ });+ try {+ await renameDirectoryAtomically(stage, dest);+ } catch (error) {+ const existing = await this.read(manifest.materialId, manifest.revisionId).catch(() => {+ return;+ });+ if (!existing || canonicalMaterialJson(existing.manifest) !== canonicalMaterialJson(manifest))+ throw error;+ }+ } finally {+ const rel = relative(parent, resolve5(stage));+ if (rel.startsWith(".stage-") && !rel.includes(sep))+ await rm(stage, { recursive: true, force: true });+ }}+ return snapshots.map((record) => record.manifest);}- 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 } : {}- };}-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;+function validateMaterialManifestIdentityAny(value) {+ const manifest = validateMaterialManifestAny(value);+ if (revisionHash(manifest) !== manifest.revisionId)+ throw new Error("Material identity hash mismatch");+ return manifest;+}+function snapshotAny(record) {+ validateMaterialRecordShapeAny(record);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- },- 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+ manifest: structuredClone(record.manifest),+ files: Object.fromEntries(Object.entries(record.files).map(([name, bytes]) => [name, bytes.slice()]))};}-function resolveEvaluatorMode(env = process.env) {- const value = env["KILN_EVALUATOR_MODE"];- if (value === undefined || value === "" || value === "in-process")- return "in-process";- if (value === "subprocess")- return "subprocess";- if (value === "isolated")- return "isolated";- throw new Error("Invalid KILN_EVALUATOR_MODE.");-}-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}"`);- }- }- }- 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)) {+async function resolveMaterialRecordClosure(roots, reader, limits = {+ maxRecords: MATERIAL_LIBRARY_LIMITS.maxPayloadRecords,+ maxBytes: MATERIAL_LIBRARY_LIMITS.maxPayloadBytes,+ maxPixels: MATERIAL_LIBRARY_LIMITS.maxPayloadPixels+}) {+ for (const n of Object.values(limits))+ if (!Number.isSafeInteger(n) || n < 1)+ throw new Error("Invalid material closure limits");+ const manifests = new Map, active = new Set;+ let bytes = 0, pixels = 0;+ const visit = async (value) => {+ const manifest = validateMaterialManifestIdentityAny(value), key = identity(manifest);+ if (active.has(key))+ throw new Error("Material dependency cycle");+ const existing = manifests.get(key);+ if (existing) {+ if (canonicalMaterialJson(existing) !== canonicalMaterialJson(manifest))+ throw new Error("Conflicting material dependency identity");return;}- const center = new THREE56.Vector3;- const size = new THREE56.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 THREE56.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;- }- 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 THREE56.Box3;- for (const m of meshes)- all.union(m.box);- const size = new THREE56.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.`);+ manifests.set(key, structuredClone(manifest));+ active.add(key);+ for (const map of manifest.maps) {+ bytes += map.bytes;+ pixels += map.width * map.height;}- }- 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.`);+ if (manifests.size > limits.maxRecords || bytes > limits.maxBytes || pixels > limits.maxPixels)+ throw new Error("Material closure count/byte/pixel limit exceeded");+ for (const pin of materialRecordDependencyPins(manifest)) {+ const child = await reader.readManifest(pin.resourceId, pin.revisionId);+ if (child.materialId !== pin.resourceId || child.revisionId !== pin.revisionId || pin.sha256 !== pin.revisionId)+ throw new Error("Material dependency pin mismatch");+ await visit(child);}+ active.delete(key);+ };+ for (const root of roots)+ await visit(root);+ const records = [];+ for (const [key, manifest] of manifests) {+ const record = snapshotAny(await reader.read(manifest.materialId, manifest.revisionId));+ if (identity(record.manifest) !== key || canonicalMaterialJson(record.manifest) !== canonicalMaterialJson(manifest))+ throw new Error("Material closure manifest changed during read");+ validateMaterialManifestIdentityAny(record.manifest);+ for (const map of record.manifest.maps)+ if (digest3(record.files[map.file]) !== map.sha256)+ throw new Error("Material integrity hash mismatch");+ records.push(record);}- 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;+ for (const record of records)+ await verifyMaterialRecordContents(record, { materials: records });+ return records;+}+function recordClosureReader(records, fallback) {+ const byId = new Map;+ const duplicates = new Map;+ for (const record of records) {+ const key = identity(record.manifest), existing = byId.get(key);+ if (existing && canonicalMaterialJson(existing.manifest) !== canonicalMaterialJson(record.manifest))+ throw new Error("Conflicting material record identity");+ if (!existing)+ byId.set(key, record);+ else if (existing !== record)+ duplicates.set(key, [...duplicates.get(key) ?? [], record]);+ }+ return {+ async readManifest(id, revision) {+ const record = byId.get(`${id}/${revision}`);+ if (record)+ return record.manifest;+ if (fallback)+ return fallback.readManifest(id, revision);+ throw new Error(`Missing pinned material revision: ${id} at ${revision}`);+ },+ async read(id, revision) {+ const key = `${id}/${revision}`, record = byId.get(key);+ if (record) {+ for (const candidate of [record, ...duplicates.get(key) ?? []]) {+ const manifest = validateMaterialRecordShapeAny(candidate);+ if (canonicalMaterialJson(manifest) !== canonicalMaterialJson(record.manifest))+ throw new Error("Conflicting material record identity");+ for (const map of manifest.maps)+ if (digest3(candidate.files[map.file]) !== map.sha256)+ throw new Error("Conflicting material record encoded integrity hash");}+ return record;}- 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).`);- }- warnings.push(`Floating parts (no mesh overlap with any sibling, 2cm tol): ${entries.join(" | ")}`);+ if (fallback)+ return fallback.readRecordFiles(id, revision);+ throw new Error(`Missing pinned material revision: ${id} at ${revision}`);}- 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.`);+ };+}+function createPinnedMaterialMapPort(records) {+ const entries = new Map;+ for (const record of records) {+ validateMaterialRecordShapeAny(record);+ validateMaterialManifestIdentityAny(record.manifest);+ for (const map of record.manifest.maps) {+ if (digest3(record.files[map.file]) !== map.sha256)+ throw new Error("Material integrity hash mismatch");+ entries.set(`${identity(record.manifest)}/${materialLibraryResourceId(record.manifest, map.slot)}`, { record, map });}}- return warnings;-}-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 = {- [THREE56.NearestFilter]: 9728,- [THREE56.LinearFilter]: 9729,- [THREE56.NearestMipmapNearestFilter]: 9984,- [THREE56.LinearMipmapNearestFilter]: 9985,- [THREE56.NearestMipmapLinearFilter]: 9986,- [THREE56.LinearMipmapLinearFilter]: 9987+ const find = (resourceId, pin) => {+ if (typeof resourceId !== "string" || pin.sha256 !== pin.revisionId)+ return;+ return entries.get(`${pin.resourceId}/${pin.revisionId}/${resourceId}`);};- GLTF_MAG_FILTER = { [THREE56.NearestFilter]: 9728, [THREE56.LinearFilter]: 9729 };- GLTF_WRAP = {- [THREE56.ClampToEdgeWrapping]: 33071,- [THREE56.MirroredRepeatWrapping]: 33648,- [THREE56.RepeatWrapping]: 10497+ const describe = (resourceId, pin) => {+ const entry = find(resourceId, pin);+ if (!entry)+ return;+ const { record, map } = entry;+ return {+ materialId: record.manifest.materialId,+ revisionId: record.manifest.revisionId,+ resourceId,+ slot: map.slot,+ usage: map.usage,+ colorSpace: map.colorSpace,+ width: map.width,+ height: map.height,+ encodedByteLength: map.bytes,+ imageSha256: map.sha256,+ ..."pixelHash" in map ? { decodedPixelHash: map.pixelHash } : {}+ };};- REVIEW_CLIP_LIMITS2 = {- clips: 32,- tracks: 256,- samplesPerTrack: 4096,- valuesPerTrack: 16384+ return {+ describePinnedMaterialMap: describe,+ async resolvePinnedMaterialMapPixels(resourceId, pin, context) {+ context?.signal?.throwIfAborted();+ const descriptor = describe(resourceId, pin), entry = find(resourceId, pin);+ if (!descriptor || !entry)+ throw new Error("Missing verified pinned-library map; approved resources cannot be atlas sources");+ const { data, info } = await sharp2(entry.record.files[entry.map.file], {+ limitInputPixels: MATERIAL_LIBRARY_LIMITS.maxRecordPixels,+ failOn: "warning"+ }).ensureAlpha().raw().toBuffer({ resolveWithObject: true });+ context?.signal?.throwIfAborted();+ if (info.width !== descriptor.width || info.height !== descriptor.height || info.channels !== 4)+ throw new Error("Pinned material decoded dimensions mismatch");+ const decodedPixelHash = digest3(data);+ if (descriptor.decodedPixelHash && descriptor.decodedPixelHash !== decodedPixelHash)+ throw new Error("Pinned material pixel hash mismatch");+ return { descriptor, pixels: Uint8Array.from(data), decodedPixelHash };+ }};-});--// src/evaluator/protocol.ts-import { createHash as createHash9 } from "node:crypto";-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.");+async function verifyMaterialRecordContents(record, options) {+ if (record.manifest.schemaVersion === 1)+ return verifyMaterialRecordV1(record);+ const manifest = validateMaterialRecordShapeAny(record);+ validateMaterialManifestIdentityAny(manifest);+ const pins = new Set(materialRecordDependencyPins(manifest).map((pin) => `${pin.resourceId}/${pin.revisionId}`));+ pins.add(identity(manifest));+ const resources = createPinnedMaterialMapPort((options?.materials ?? [record]).filter((candidate) => pins.has(identity(candidate.manifest))));+ admitMaterialManifestRecipes(manifest, resources);+ for (const map of manifest.maps) {+ const bytes = record.files[map.file];+ if (digest3(bytes) !== map.sha256)+ throw new Error("Material integrity hash mismatch");+ const { data, info } = await sharp2(bytes, {+ limitInputPixels: MATERIAL_LIBRARY_LIMITS.maxRecordPixels,+ failOn: "warning"+ }).ensureAlpha().raw().toBuffer({ resolveWithObject: true });+ if (info.width !== map.width || info.height !== map.height || info.channels !== 4 || digest3(data) !== map.pixelHash)+ throw new Error("Material decoded pixel hash/dimensions mismatch");+ const recipe = map.recipe;+ if (!recipe)+ continue;+ if (recipe.kind === "atlas") {+ const compiled = await compileTextureAtlasSpecV1(recipe.spec, { resources });+ if (canonicalMaterialJson(compiled.manifest) !== canonicalMaterialJson(recipe.manifest) || digest3(compiled.pixels) !== map.pixelHash)+ throw new Error("Atlas recipe/manifest/pixel hash mismatch");+ } else {+ const compiled = recipe.spec.schemaVersion === 3 ? materialPixelsV3(recipe.spec, recipe.derive) : materialPixels(recipe.spec, recipe.derive);+ if (compiled.recipeHash !== recipe.recipeHash || digest3(compiled.pixels) !== recipe.pixelHash)+ throw new Error("Procedural recipe/pixel hash mismatch");+ }}- return trustedInProcessEvaluatorPortV2;-}-function isRecord6(value) {- return typeof value === "object" && value !== null && !Array.isArray(value);-}-function hasExactKeys(value, allowed) {- return Object.keys(value).every((key) => allowed.includes(key));-}-function fail10(kind) {- throw new Error(`invalid evaluator ${kind}`);}-function validRequestId(value) {- return typeof value === "string" && /^[A-Za-z0-9._-]{1,64}$/.test(value);-}-function validInteger(value, min, max) {- return Number.isInteger(value) && Number(value) >= min && Number(value) <= max;+async function verifyMaterialRecord(record, options) {+ if (record.manifest.schemaVersion === 1)+ return verifyMaterialRecordV1(record);+ await resolveMaterialRecordClosure([record.manifest], recordClosureReader([record, ...options?.materials ?? []]));}-function validRequirementsQaReport(value) {- try {- validateRequirementsQaReport(value);- return true;- } catch {- return false;+function admitMaterialManifestRecipes(manifest, resources) {+ let texels = 0, work = 0, allocation = 0, encoded = 0;+ for (const map of manifest.maps) {+ encoded += map.bytes;+ const recipe = map.recipe;+ if (recipe?.kind === "procedural") {+ if (recipe.spec.schemaVersion === 3) {+ const a = admitProceduralTextureSpecV3(recipe.spec);+ const derived = normalDerivationBudget(recipe.derive ? a.spec.width * a.spec.height : 0);+ texels += a.spec.width * a.spec.height;+ work += a.estimatedWorkUnits + derived.work;+ allocation += a.conservativePixelAllocationBytes + derived.allocation;+ } else {+ texels += recipe.spec.size ** 2;+ work += recipe.spec.size ** 2 * recipe.spec.layers.length * 16;+ allocation += recipe.spec.size ** 2 * 12;+ }+ } else if (recipe?.kind === "atlas") {+ const a = admitTextureAtlasSpecV1(recipe.spec, { resources });+ texels += a.spec.width * a.spec.height + a.budget.sourceTexels;+ work += a.budget.workUnits;+ allocation += a.budget.conservativePixelAllocationBytes;+ encoded += a.budget.encodedBytes;+ } else {+ texels += map.width * map.height;+ work += map.width * map.height * 12 + map.bytes * 8;+ allocation += map.width * map.height * 12 + map.bytes * 2;+ }}+ if (texels > PORTABLE_MATERIAL_V3_LIMITS.maxTexels || work > PORTABLE_MATERIAL_V3_LIMITS.maxWork || allocation > PORTABLE_MATERIAL_V3_LIMITS.maxTransientBytes || encoded > PORTABLE_MATERIAL_V3_LIMITS.maxEncodedBytes)+ throw new Error("Material recipe aggregate texel/work/allocation/encoded budget exceeded");}-function validGltfValidation(value) {- const issues = isRecord6(value) && isRecord6(value.issues) ? value.issues : undefined;- if (!issues || !Array.isArray(issues.messages)) {- return false;+function validateMaterialLibraryPayloadAny(value) {+ assertMaterialJson(value);+ if (!value || typeof value !== "object" || Array.isArray(value))+ throw new Error("Invalid material resource payload");+ if (value["schemaVersion"] === 1)+ return validateMaterialLibraryPayload(value);+ const payload = value;+ if (Object.keys(payload).some((k) => !["schemaVersion", "records"].includes(k)) || payload.schemaVersion !== 2 || !Array.isArray(payload.records) || payload.records.length > MATERIAL_LIBRARY_LIMITS.maxPayloadRecords)+ throw new Error("Invalid material resource payload");+ let bytes = 0, pixels = 0;+ const seen = new Set;+ for (const wire of payload.records) {+ if (!wire || typeof wire !== "object" || Object.keys(wire).some((k) => !["manifest", "files"].includes(k)))+ throw new Error("Invalid material resource record");+ const manifest = validateMaterialManifestIdentityAny(wire.manifest), key = identity(manifest);+ if (seen.has(key))+ throw new Error("Duplicate material resource revision");+ seen.add(key);+ if (!wire.files || typeof wire.files !== "object" || Array.isArray(wire.files) || Object.keys(wire.files).length !== manifest.maps.length)+ throw new Error("Material payload inventory mismatch");+ for (const map of manifest.maps) {+ const encoded = wire.files[map.file];+ if (typeof encoded !== "string" || encoded.length !== Math.ceil(map.bytes / 3) * 4 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encoded))+ throw new Error("Invalid material map base64");+ bytes += map.bytes;+ pixels += map.width * map.height;+ }}- return ["numErrors", "numWarnings", "numInfos", "numHints"].every((key) => validInteger(issues[key], 0, Number.MAX_SAFE_INTEGER)) && issues.messages.length <= 1000 && issues.messages.every((issue) => isRecord6(issue) && typeof issue.code === "string" && typeof issue.message === "string" && typeof issue.severity === "number" && Number.isFinite(issue.severity));+ if (bytes > MATERIAL_LIBRARY_LIMITS.maxPayloadBytes || pixels > MATERIAL_LIBRARY_LIMITS.maxPayloadPixels)+ throw new Error("Material resource payload exceeds byte/pixel budget");+ return payload;}-function encodeRenderResultV2(requestId, render) {- const { glb, diagnosticViews, buildCache: _hostCacheReceipt, ...rest } = render;- return {- version: EVALUATOR_RESULT_VERSION,- requestId,- ok: true,- render: {- ...rest,- glbBase64: glb.toString("base64"),- ...diagnosticViews ? {- diagnosticViews: diagnosticViews.map(({ png, ...view }) => ({- ...view,- pngBase64: Buffer.from(png).toString("base64")- }))- } : {}+async function createMaterialLibraryPayload(records) {+ if (records.every((r) => r.manifest.schemaVersion === 1))+ return createMaterialLibraryPayloadV1(records);+ let bytes = 0, pixels = 0;+ if (records.length > MATERIAL_LIBRARY_LIMITS.maxPayloadRecords)+ throw new Error("Material payload record limit exceeded");+ for (const record of records)+ for (const map of validateMaterialManifestIdentityAny(record.manifest).maps) {+ bytes += map.bytes;+ pixels += map.width * map.height;}- };-}-function isSha256(value) {- return typeof value === "string" && /^sha256:[a-f0-9]{64}$/.test(value);+ if (bytes > MATERIAL_LIBRARY_LIMITS.maxPayloadBytes || pixels > MATERIAL_LIBRARY_LIMITS.maxPayloadPixels)+ throw new Error("Material payload byte/pixel budget exceeded");+ const admitted = await resolveMaterialRecordClosure(records.map((r) => r.manifest), recordClosureReader(records));+ const byIdentity = new Map(admitted.map((r) => [identity(r.manifest), r]));+ const snapshots = records.map((r) => byIdentity.get(identity(r.manifest)));+ return validateMaterialLibraryPayloadAny({+ schemaVersion: 2,+ records: snapshots.map((r) => ({+ manifest: r.manifest,+ files: Object.fromEntries(Object.entries(r.files).map(([name, bytes]) => [+ name,+ Buffer.from(bytes).toString("base64")+ ]))+ }))+ });}-function decodeEvaluatorResultV2(json, maxGlbBytes, expectedRequestId) {- let value;- try {- value = JSON.parse(json);- } catch {- return fail10("result");- }- if (!isRecord6(value) || !hasExactKeys(value, ["version", "requestId", "ok", "render", "error"]) || value.version !== EVALUATOR_RESULT_VERSION || !validRequestId(value.requestId) || typeof value.ok !== "boolean") {- return fail10("result");- }- if (expectedRequestId !== undefined && value.requestId !== expectedRequestId)- fail10("result");- if (!value.ok) {- if (value.render !== undefined)- return fail10("result");- if (!isRecord6(value.error) || !hasExactKeys(value.error, ["code", "message", "qa", "diagnostic", "solid"])) {- return fail10("result");- }- const codes = [- "INPUT_INVALID",- "EXECUTION_REJECTED",- "QA_BLOCKED",- "DEADLINE_EXCEEDED",- "CANCELLED",- "OUTPUT_LIMIT_EXCEEDED",- "ISOLATION_UNAVAILABLE",- "WORKER_FAILED",- "PROTOCOL_ERROR"- ];- if (!codes.includes(value.error.code) || typeof value.error.message !== "string" || value.error.message !== evaluatorOutcomeMessage(value.error.code)) {- return fail10("result");+async function decodeMaterialLibraryPayload(value) {+ const payload = validateMaterialLibraryPayloadAny(value);+ if (payload.schemaVersion === 1)+ return decodeMaterialLibraryPayloadV1(payload);+ const wires = payload.records.map((w) => ({+ manifest: validateMaterialManifestIdentityAny(w.manifest),+ files: { ...w.files }+ }));+ const byIdentity = new Map(wires.map((w) => [identity(w.manifest), w]));+ const reader = {+ async readManifest(id, revision) {+ const wire = byIdentity.get(`${id}/${revision}`);+ if (!wire)+ throw new Error("Missing pinned material revision");+ return wire.manifest;+ },+ async read(id, revision) {+ const wire = byIdentity.get(`${id}/${revision}`);+ if (!wire)+ throw new Error("Missing pinned material revision");+ return {+ manifest: wire.manifest,+ files: Object.fromEntries(Object.entries(wire.files).map(([name, encoded]) => [+ name,+ new Uint8Array(Buffer.from(encoded, "base64"))+ ]))+ };}- if (value.error.diagnostic !== undefined && (value.error.code !== "EXECUTION_REJECTED" || value.error.diagnostic !== "UNBOUND_VARIABLE" && value.error.diagnostic !== "GEAR_RADII_ORDER" && value.error.diagnostic !== "ROUNDED_BOX_RADIUS" && value.error.diagnostic !== "PROCEDURAL_TEXTURE_UNKNOWN_KEY" && value.error.diagnostic !== "PROCEDURAL_TEXTURE_BLEND" && value.error.diagnostic !== "PROCEDURAL_TEXTURE_USAGE" && value.error.diagnostic !== "PROCEDURAL_TEXTURE_V3_CONTRACT" && value.error.diagnostic !== "PORTABLE_MATERIAL_V3_CONTRACT" && value.error.diagnostic !== "TEXTURE_ATLAS_CONTRACT" && value.error.diagnostic !== "MATERIAL_FRACTION_RANGE" && value.error.diagnostic !== "MATERIAL_RECIPE_TEXTURE_BINDING" && value.error.diagnostic !== "PORTABLE_TEXTURE_REFERENCE" && value.error.diagnostic !== "PORTABLE_COLOR_ARGUMENT" && value.error.diagnostic !== "PARAMETRIC_PERIODIC_ENDPOINT" && value.error.diagnostic !== "PROFILE_HOLES_UNSUPPORTED" && value.error.diagnostic !== "PROFILE_BEVEL_COLLAPSE" && value.error.diagnostic !== "PROFILE_SOLID_FAILED" && value.error.diagnostic !== "PROFILE_CORRESPONDENCE_COLLAPSE" && value.error.diagnostic !== "REMOVED_HELPER" && value.error.diagnostic !== "TUBE_RADIUS" && value.error.diagnostic !== "TAPER_CONE_AXIS" && value.error.diagnostic !== "SOLID_FLOAT32_COLLAPSE" && value.error.diagnostic !== "MESH_DATA_NONFINITE" && value.error.diagnostic !== "MATERIAL_ALPHA_MODE" && value.error.diagnostic !== "MATERIAL_COLOR_ARGUMENT" && value.error.diagnostic !== "PART_NAME_ARGUMENT" && value.error.diagnostic !== "PART_GEOMETRY_ARGUMENT" && value.error.diagnostic !== "PART_MATERIAL_ARGUMENT" && value.error.diagnostic !== "MATERIAL_PACKED_CHANNELS" && value.error.diagnostic !== "UNINITIALIZED_BINDING" && value.error.diagnostic !== "BUILD_RESULT" && value.error.diagnostic !== "MATERIAL_RECIPE_OVERRIDE" && value.error.diagnostic !== "PROGRAM_TYPE_ERROR" && value.error.diagnostic !== "PROGRAM_RANGE_ERROR" && value.error.diagnostic !== "LOD_SET" && value.error.diagnostic !== "OPEN_SHELL" && value.error.diagnostic !== "DELIVERY_CONTRACT" && value.error.diagnostic !== "REQUIRE_SOLID" && value.error.diagnostic !== "EXPORT_MATERIAL_SIDE_UNSUPPORTED" && value.error.diagnostic !== "BONE_CHAIN_ARGUMENT" && value.error.diagnostic !== "SKIN_BINDING_ARGUMENT"))- return fail10("result");- if (value.error.solid !== undefined && (value.error.diagnostic !== "REQUIRE_SOLID" || !validSolidFailureDetails(value.error.solid)))- return fail10("result");- if (value.error.qa !== undefined) {- if (value.error.code !== "QA_BLOCKED" || !isRecord6(value.error.qa) || !hasExactKeys(value.error.qa, ["report", "stage", "gltfValidation"]) || !validRequirementsQaReport(value.error.qa.report) || !["scene", "final-glb"].includes(String(value.error.qa.stage)) || value.error.qa.gltfValidation !== undefined && !validGltfValidation(value.error.qa.gltfValidation)) {- return fail10("result");+ };+ const admitted = await resolveMaterialRecordClosure(wires.map((w) => w.manifest), reader);+ const result = new Map(admitted.map((r) => [identity(r.manifest), r]));+ return wires.map((w) => result.get(identity(w.manifest)));+}+async function createMaterialRecordV2(draft, options) {+ assertMaterialJson(draft, true);+ if (!draft || typeof draft !== "object" || Array.isArray(draft))+ throw new Error("Invalid material draft");+ exactKeys(draft, [+ "schemaVersion",+ "materialId",+ "name",+ "tags",+ "tileable",+ "physicalSizeMeters",+ "parameters",+ "sources",+ "maps"+ ]);+ const input = draft;+ if (input["schemaVersion"] !== 2 || !Array.isArray(input["maps"]) || input["maps"].length < 1 || input["maps"].length > 5)+ throw new Error("V2 material requires schemaVersion2 and1..5 maps");+ const candidates = options?.materials ?? [];+ if (candidates.length > MATERIAL_LIBRARY_LIMITS.maxPayloadRecords)+ throw new Error("Material source closure count limit exceeded");+ const records = candidates.length ? await resolveMaterialRecordClosure(candidates.map((r) => r.manifest), recordClosureReader(candidates)) : [];+ const resources = createPinnedMaterialMapPort(records), prepared = [];+ let texels = 0, work = 0, allocation = 0, encoded = 0;+ for (const value of input["maps"]) {+ if (!value || typeof value !== "object" || Array.isArray(value))+ throw new Error("Invalid material map draft");+ exactKeys(value, [+ "slot",+ "sourceId",+ "transforms",+ "normalConvention",+ "channelPacking",+ "sampler",+ "bytes",+ "originalFile",+ "procedural",+ "derive",+ "atlas"+ ]);+ const raw = value, slot = raw["slot"];+ if (!MATERIAL_LIBRARY_SLOTS.includes(slot))+ throw new Error("Unsupported material map slot");+ const sampler = canonicalizePortableSamplerV1(raw["sampler"]);+ if (["bytes", "procedural", "atlas"].filter((k) => raw[k] !== undefined).length !== 1)+ throw new Error("Supply exactly one map bytes/procedural/atlas source");+ if (raw["procedural"] !== undefined) {+ const spec = raw["procedural"];+ if (spec.schemaVersion === 3) {+ const a = admitProceduralTextureSpecV3(spec);+ if (a.spec.usage !== MATERIAL_LIBRARY_USAGE[slot])+ throw new Error("Procedural usage mismatch");+ if (raw["derive"] !== undefined && slot !== "normal")+ throw new Error("Height derivation requires a normal map slot");+ const derived = normalDerivationBudget(raw["derive"] !== undefined ? a.spec.width * a.spec.height : 0);+ texels += a.spec.width * a.spec.height;+ work += a.estimatedWorkUnits + derived.work;+ allocation += a.conservativePixelAllocationBytes + derived.allocation;+ prepared.push({ raw, slot, sampler, procedural: a.spec });+ } else {+ const canonical = canonicalizeProceduralTextureSpecV2(spec);+ if (canonical.usage !== MATERIAL_LIBRARY_USAGE[slot])+ throw new Error("Procedural usage mismatch");+ texels += canonical.size ** 2;+ work += canonical.size ** 2 * canonical.layers.length * 16;+ allocation += canonical.size ** 2 * 12;+ prepared.push({ raw, slot, sampler, procedural: canonical });}- } else if (value.error.code === "QA_BLOCKED") {- return fail10("result");+ } else if (raw["atlas"] !== undefined) {+ if (raw["derive"] !== undefined)+ throw new Error("Atlas derivation unsupported");+ const a = admitTextureAtlasSpecV1(raw["atlas"], { resources });+ if (a.spec.usage !== MATERIAL_LIBRARY_USAGE[slot] || canonicalMaterialJson(a.spec.sampler) !== canonicalMaterialJson(sampler))+ throw new Error("Atlas usage/sampler mismatch");+ texels += a.spec.width * a.spec.height + a.budget.sourceTexels;+ work += a.budget.workUnits;+ allocation += a.budget.conservativePixelAllocationBytes;+ encoded += a.budget.encodedBytes;+ prepared.push({ raw, slot, sampler, atlas: a.spec });+ } else {+ if (raw["derive"] !== undefined || !(raw["bytes"] instanceof Uint8Array))+ throw new Error("Invalid external map bytes/derivation");+ const bytes = raw["bytes"];+ if (bytes.length > MATERIAL_LIBRARY_LIMITS.maxMapBytes)+ throw new Error("Material map encoded byte limit");+ const d = materialPngDimensions(bytes);+ if (d.width < 1 || d.height < 1 || d.width > 4096 || d.height > 4096)+ throw new Error("Material map dimensions limit");+ texels += d.width * d.height;+ encoded += bytes.length;+ work += d.width * d.height * 12 + bytes.length * 8;+ allocation += d.width * d.height * 12 + bytes.length * 2;+ prepared.push({ raw, slot, sampler, bytes });}- return value;- }- if (value.error !== undefined || !isRecord6(value.render))- fail10("result");- const renderKeys = [- "glbBase64",- "artifactGlbSha256",- "tris",- "meta",- "warnings",- "diagnosticViews",- "materialMetrics",- "materialRecipeApplications",- "materialResourceProvenance",- "materialLibraryDependencies",- "bakedTextures",- "integrationManifest",- "requirements",- "rebuildOptions"- ];- if (!hasExactKeys(value.render, renderKeys) || typeof value.render.glbBase64 !== "string" || !validInteger(value.render.tris, 0, Number.MAX_SAFE_INTEGER) || !isRecord6(value.render.meta) || !Array.isArray(value.render.warnings) || !value.render.warnings.every((warning) => typeof warning === "string") || !isRecord6(value.render.integrationManifest)) {- fail10("result");}- let requirements;- if (value.render.rebuildOptions !== undefined && !rebuildOptionsSchema.strict().safeParse(value.render.rebuildOptions).success)- fail10("result");- if (value.render.materialLibraryDependencies !== undefined) {- if (!Array.isArray(value.render.materialLibraryDependencies) || value.render.materialLibraryDependencies.length > 16)- fail10("result");- try {- for (const manifest of value.render.materialLibraryDependencies)- validateMaterialManifestIdentityAny(manifest);- } catch {- return fail10("result");+ if (texels > 4 * 1024 * 1024 || work > PORTABLE_MATERIAL_V3_LIMITS.maxWork || allocation > 64 * 1024 * 1024 || encoded > 16 * 1024 * 1024)+ throw new Error("Material aggregate texel/work/allocation limit exceeded");+ const maps = [], files = {}, pins = new Map;+ for (const item of prepared) {+ const { raw, slot, sampler } = item;+ let bytes, pixelHash, recipe;+ if (item.procedural !== undefined) {+ const spec = item.procedural;+ const derive = raw["derive"];+ const compiled = spec.schemaVersion === 3 ? materialPixelsV3(spec, derive) : materialPixels(spec, derive);+ const d = compiled.spec.schemaVersion === 3 ? { width: compiled.spec.width, height: compiled.spec.height } : { width: compiled.spec.size, height: compiled.spec.size };+ pixelHash = digest3(compiled.pixels);+ bytes = new Uint8Array(await sharp2(compiled.pixels, { raw: { ...d, channels: 4 } }).png({ compressionLevel: 9, adaptiveFiltering: false }).toBuffer());+ recipe = {+ kind: "procedural",+ compilerId: compiled.spec.schemaVersion === 3 ? PROCEDURAL_TEXTURE_V3_COMPILER_ID : "kiln.procedural-texture.v2",+ spec: compiled.spec,+ recipeHash: compiled.recipeHash,+ pixelHash,+ encoder,+ ...raw["derive"] ? {+ derive: structuredClone(raw["derive"])+ } : {}+ };+ } else if (item.atlas !== undefined) {+ const compiled = await compileTextureAtlasSpecV1(item.atlas, { resources });+ pixelHash = compiled.manifest.decodedPixelHash;+ bytes = new Uint8Array(await sharp2(compiled.pixels, {+ raw: { width: compiled.spec.width, height: compiled.spec.height, channels: 4 }+ }).png({ compressionLevel: 9, adaptiveFiltering: false }).toBuffer());+ recipe = {+ kind: "atlas",+ compilerId: compiled.manifest.compilerId,+ spec: compiled.spec,+ manifest: compiled.manifest,+ encoder+ };+ for (const r of compiled.spec.regions)+ if (r.source.kind === "resource")+ pins.set(`${r.source.pin.resourceId}/${r.source.pin.revisionId}`, r.source.pin);+ } else {+ bytes = item.bytes.slice();+ const decoded = await sharp2(bytes, {+ limitInputPixels: MATERIAL_LIBRARY_LIMITS.maxRecordPixels,+ failOn: "warning"+ }).ensureAlpha().raw().toBuffer();+ pixelHash = digest3(decoded);}+ const d = materialPngDimensions(bytes), file = `${slot}.png`;+ if (files[file])+ throw new Error("Duplicate material map slot");+ files[file] = bytes;+ maps.push({+ slot,+ file,+ ...d,+ sha256: digest3(bytes),+ bytes: bytes.length,+ usage: MATERIAL_LIBRARY_USAGE[slot],+ colorSpace: slot === "baseColor" || slot === "emissive" ? "srgb" : "linear",+ sampler,+ pixelHash,+ sourceId: raw["sourceId"],+ transforms: structuredClone(raw["transforms"]),+ ...slot === "normal" ? {+ normalConvention: raw["normalConvention"] ?? (recipe ? "opengl" : undefined)+ } : {},+ ...slot === "metallicRoughness" ? {+ channelPacking: raw["channelPacking"] ?? (recipe ? "r-occlusion-g-roughness-b-metallic" : undefined)+ } : {},+ ...raw["originalFile"] ? { originalFile: raw["originalFile"] } : {},+ ...recipe ? { recipe } : {}+ });}- try {- requirements = validateRequirementsContext(value.render.requirements);- validateRequirementsQaReport(value.render.meta.qaReport, requirements);- } catch {- return fail10("result");- }- const glb = Buffer.from(value.render.glbBase64, "base64");- if (glb.byteLength > maxGlbBytes || glb.toString("base64") !== value.render.glbBase64)- fail10("result");- if (!isSha256(value.render.artifactGlbSha256))- fail10("result");- const actualHash = `sha256:${createHash9("sha256").update(glb).digest("hex")}`;- if (actualHash !== value.render.artifactGlbSha256)- fail10("result");- const diagnosticViews = value.render.diagnosticViews;- if (diagnosticViews !== undefined && !Array.isArray(diagnosticViews))- fail10("result");- const decodedViews = diagnosticViews?.map((candidate) => {- if (!isRecord6(candidate) || typeof candidate.pngBase64 !== "string")- return fail10("result");- const png = Buffer.from(candidate.pngBase64, "base64");- if (png.toString("base64") !== candidate.pngBase64)- return fail10("result");- const { pngBase64: _, ...view } = candidate;- return { ...view, png };+ const manifest = materialManifestV2Schema.parse({+ ...input,+ schemaVersion: 2,+ revisionId: `sha256:${"0".repeat(64)}`,+ tags: input["tags"] ?? [],+ parameters: input["parameters"] ?? {},+ maps,+ dependencies: [...pins.values()]});- const { glbBase64: _, diagnosticViews: __, ...rest } = value.render;- return {- version: EVALUATOR_RESULT_VERSION,- requestId: value.requestId,- ok: true,- render: {- ...rest,- glb,- ...decodedViews ? { diagnosticViews: decodedViews } : {}- }- };-}-function assertEvaluatorResultMaterialResources(result, expected) {- if (!result.ok)- return;- const actual = result.render.materialLibraryDependencies ?? [];- const wanted = expected?.records.map((record) => record.manifest) ?? [];- const identity = (manifest) => `${manifest.materialId}/${manifest.revisionId}`;- if (new Set(actual.map(identity)).size !== actual.length || JSON.stringify(actual.map(canonicalMaterialJson).sort()) !== JSON.stringify(wanted.map(canonicalMaterialJson).sort()))- throw new EvaluatorPortError("PROTOCOL_ERROR");-}-function assertEvaluatorResultRequirements(result, expected) {- try {- if (result.ok) {- if (!requirementsContextsEqual(result.render.requirements, expected))- throw new Error("Requirements mismatch.");- } else if (result.error.code === "QA_BLOCKED" && result.error.qa) {- validateRequirementsQaReport(result.error.qa.report, expected);- }- } catch {- throw new EvaluatorPortError("PROTOCOL_ERROR", "Evaluator requirements context differs from the host request.");- }+ manifest.revisionId = revisionHash(manifest);+ const record = { manifest, files };+ await verifyMaterialRecord(record, { materials: [...records, record] });+ return record;}-var EVALUATOR_REQUEST_VERSION = "kiln.evaluator.request.v2", EVALUATOR_RESULT_VERSION = "kiln.evaluator.result.v2", 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();+var digest3 = (bytes) => `sha256:${createHash10("sha256").update(bytes).digest("hex")}`, encoder, normalDerivationBudget = (texels) => ({ work: texels * 16, allocation: texels * 8 }), identity = (manifest) => `${manifest.materialId}/${manifest.revisionId}`;+var init_material_library_node = __esm(() => {+ init_atomic_directory();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;- }- };+ init_portable_sampler();+ init_portable_sampler_runtime();+ init_procedural_texture_v3();+ init_procedural_texture_v3_contract();+ init_texture_atlas_pixels();+ init_procedural_texture();+ init_procedural_material_v2();+ init_textures();+ init_texture_resolver();+ init_procedural_material_v3();+ init_material_map_export_node();+ encoder = { name: "sharp", version: sharp2.versions.sharp };});// src/evaluator/subprocess.ts@@ -41062,12 +41654,12 @@ var init_subprocess = __esm(() => {});// src/workspace-location.ts-import { dirname as dirname3, join as join3, resolve as resolve5 } from "node:path";+import { dirname as dirname3, join as join4, resolve as resolve6 } from "node:path";function localWorkspaceRoot(env = process.env) {- return env.KILN_WORKSPACE ? resolve5(env.KILN_WORKSPACE) : env.KILN_PROGRAM_STORE ? dirname3(dirname3(resolve5(env.KILN_PROGRAM_STORE))) : process.cwd();+ return env.KILN_WORKSPACE ? resolve6(env.KILN_WORKSPACE) : env.KILN_PROGRAM_STORE ? dirname3(dirname3(resolve6(env.KILN_PROGRAM_STORE))) : process.cwd();}function localProgramStoreDirectory(env = process.env) {- return env.KILN_PROGRAM_STORE ? resolve5(env.KILN_PROGRAM_STORE) : join3(localWorkspaceRoot(env), ".kiln", "programs");+ return env.KILN_PROGRAM_STORE ? resolve6(env.KILN_PROGRAM_STORE) : join4(localWorkspaceRoot(env), ".kiln", "programs");}var init_workspace_location = () => {};@@ -41167,7 +41759,7 @@ __export(exports_program_store_node, {});import { link as link2, lstat as lstat4, mkdir as mkdir3, readFile as readFile3, readdir as readdir2, stat as stat2, unlink as unlink2, writeFile as writeFile3 } from "node:fs/promises";import { randomUUID as randomUUID3 } from "node:crypto";-import { join as join4 } from "node:path";+import { join as join5 } from "node:path";class FileProgramStore {directory;@@ -41183,7 +41775,7 @@ class FileProgramStore {if (!entry.isFile() || !/^[a-f0-9]{64}\.js$/.test(entry.name))continue;try {- bytes += (await stat2(join4(this.directory, entry.name))).size;+ bytes += (await stat2(join5(this.directory, entry.name))).size;entries++;} catch (error) {if (error.code !== "ENOENT")@@ -41201,7 +41793,7 @@ class FileProgramStore {const canonical = ref.startsWith("p_") ? await this.readHandle(ref) : ref;if (canonical === undefined)throw this.notFound(ref);- const path = join4(this.directory, `${canonical.slice(7)}.js`);+ const path = join5(this.directory, `${canonical.slice(7)}.js`);let code;try {if ((await stat2(path)).size > MAX_PROGRAM_BYTES)@@ -41220,7 +41812,7 @@ class FileProgramStore {return programNotFound(ref, "This program store has no such reference; it was issued by another store (KILN_PROGRAM_STORE selects which) or its store was removed.");}async readHandle(handle) {- const path = join4(this.directory, "refs", `${handle}.ref`);+ const path = join5(this.directory, "refs", `${handle}.ref`);try {const info = await lstat4(path);if (!info.isFile() || info.size !== 71)@@ -41239,7 +41831,7 @@ class FileProgramStore {await this.get(ref);if (ref.startsWith("p_"))return ref;- const directory = join4(this.directory, "refs");+ const directory = join5(this.directory, "refs");await mkdir3(directory, { recursive: true });for (const handle of shortProgramRefCandidates(ref)) {const owner = await this.readHandle(handle);@@ -41247,11 +41839,11 @@ class FileProgramStore {return handle;if (owner !== undefined)continue;- const temporary = join4(directory, `.write-${randomUUID3()}`);+ const temporary = join5(directory, `.write-${randomUUID3()}`);await writeFile3(temporary, ref, { encoding: "utf8", flag: "wx", mode: 384 });try {try {- await link2(temporary, join4(directory, `${handle}.ref`));+ await link2(temporary, join5(directory, `${handle}.ref`));return handle;} catch (error) {if (error.code !== "EEXIST")@@ -41268,8 +41860,8 @@ class FileProgramStore {async put(code) {const ref = await programReference(code);await mkdir3(this.directory, { recursive: true });- const target = join4(this.directory, `${ref.slice(7)}.js`);- const temporary = join4(this.directory, `.write-${randomUUID3()}`);+ const target = join5(this.directory, `${ref.slice(7)}.js`);+ const temporary = join5(this.directory, `.write-${randomUUID3()}`);await writeFile3(temporary, code, { encoding: "utf8", flag: "wx", mode: 384 });try {try {@@ -41294,7 +41886,7 @@ var init_program_store_node = __esm(() => {});// src/build-cache.ts-import { createHash as createHash10 } from "node:crypto";+import { createHash as createHash11 } from "node:crypto";import * as acorn2 from "acorn";import * as walk5 from "acorn-walk";function sourceHasAmbientInputs(code) {@@ -41440,7 +42032,7 @@ function createCachedEvaluatorPort(evaluator, options) {} catch {return evaluator.render(code, renderOptions, controls);}- const key = `sha256:${createHash10("sha256").update(serialized).digest("hex")}`;+ const key = `sha256:${createHash11("sha256").update(serialized).digest("hex")}`;const cached = await options.cache.get(key).catch(() => {return;});@@ -41491,7 +42083,7 @@ var init_build_cache = __esm(() => {});// src/build-cache-node.ts-import { createHash as createHash11, randomUUID as randomUUID4 } from "node:crypto";+import { createHash as createHash12, randomUUID as randomUUID4 } from "node:crypto";import {mkdir as mkdir4,readFile as readFile4,@@ -41502,21 +42094,21 @@ import {utimes,writeFile as writeFile4} from "node:fs/promises";-import { join as join5, resolve as resolve6 } from "node:path";+import { join as join6, resolve as resolve7 } from "node:path";class FileBuildCache {maxBytes;directory;constructor(directory, maxBytes = 128 * 1024 * 1024) {this.maxBytes = maxBytes;- this.directory = resolve6(directory);+ this.directory = resolve7(directory);if (!Number.isSafeInteger(maxBytes) || maxBytes < 0 || maxBytes > 1024 * 1024 * 1024)throw new Error("File build cache size must be 0..1 GiB.");}path(key) {if (!keyPattern.test(key))throw new Error("Invalid build cache key.");- return join5(this.directory, `${key.slice(7)}.json`);+ return join6(this.directory, `${key.slice(7)}.json`);}async get(key) {const path = this.path(key);@@ -41525,7 +42117,7 @@ class FileBuildCache {if (entry.size > this.maxBytes || entry.size > 96 * 1024 * 1024)return;const envelope = JSON.parse(await readFile4(path, "utf8"));- if (envelope.version !== 1 || envelope.key !== key || typeof envelope.payload !== "string" || envelope.checksum !== digest3(envelope.payload))+ if (envelope.version !== 1 || envelope.key !== key || typeof envelope.payload !== "string" || envelope.checksum !== digest4(envelope.payload))return;const decoded = decodeEvaluatorResultV2(envelope.payload, 64 * 1024 * 1024);if (!decoded.ok)@@ -41540,11 +42132,11 @@ class FileBuildCache {async put(key, result) {const path = this.path(key);const payload = JSON.stringify(encodeRenderResultV2("cached-build", result));- const bytes = JSON.stringify({ version: 1, key, payload, checksum: digest3(payload) });+ const bytes = JSON.stringify({ version: 1, key, payload, checksum: digest4(payload) });if (Buffer.byteLength(bytes) > Math.min(this.maxBytes, 96 * 1024 * 1024))return;await mkdir4(this.directory, { recursive: true });- const temporary = join5(this.directory, `.write-${randomUUID4()}`);+ const temporary = join6(this.directory, `.write-${randomUUID4()}`);await writeFile4(temporary, bytes, { encoding: "utf8", flag: "wx", mode: 384 });try {await rename3(temporary, path);@@ -41558,7 +42150,7 @@ class FileBuildCache {for (const name of await readdir3(this.directory)) {if (!filePattern.test(name))continue;- const path = join5(this.directory, name);+ const path = join6(this.directory, name);try {const item = await stat3(path);entries.push({ path, size: item.size, used: item.mtimeMs });@@ -41574,7 +42166,7 @@ class FileBuildCache {}}}-var keyPattern, filePattern, digest3 = (text) => createHash11("sha256").update(text).digest("hex");+var keyPattern, filePattern, digest4 = (text) => createHash12("sha256").update(text).digest("hex");var init_build_cache_node = __esm(() => {init_protocol();keyPattern = /^sha256:[a-f0-9]{64}$/;@@ -41582,17 +42174,17 @@ var init_build_cache_node = __esm(() => {});// src/runtime-identity.ts-import { createHash as createHash12 } from "node:crypto";+import { createHash as createHash13 } from "node:crypto";import { lstat as lstat5, readFile as readFile5, readdir as readdir4, realpath as realpath3, stat as stat4 } from "node:fs/promises";import { createRequire } from "node:module";-import { dirname as dirname4, join as join6, relative as relative2 } from "node:path";+import { dirname as dirname4, join as join7, relative as relative2 } from "node:path";async function installedRuntimeIdentity(root, limits = {}) {let bytes = 0;let files = 0;const absentPackages = [];const maxBytes = limits.maxBytes ?? 512 * 1024 * 1024;const maxFiles = limits.maxFiles ?? 40000;- const manifest = async (directory) => JSON.parse(await readFile5(join6(directory, "package.json"), "utf8"));+ const manifest = async (directory) => JSON.parse(await readFile5(join7(directory, "package.json"), "utf8"));let readers = 0;const waiting = [];const read = async (path) => {@@ -41618,17 +42210,17 @@ async function installedRuntimeIdentity(root, limits = {}) {const pkg = await manifest(root);if (pkg.name !== "@instruktlabs/kiln")throw new Error("Not a Kiln installation.");- const build = JSON.parse(await readFile5(join6(root, "dist", "build.json"), "utf8"));+ const build = JSON.parse(await readFile5(join7(root, "dist", "build.json"), "utf8"));const worker = build.entries?.worker;if (build.schemaVersion !== 1 || worker?.file !== "evaluator-worker.mjs" || !/^sha256:[a-f0-9]{64}$/.test(worker.identity))throw new Error("No valid packaged worker identity.");- const workerHash = `sha256:${digest4(await read(join6(root, "dist", worker.file)))}`;+ const workerHash = `sha256:${digest5(await read(join7(root, "dist", worker.file)))}`;if (worker.bundleHash !== workerHash)throw new Error("Packaged worker differs from its build manifest.");const records = [];const visited = new Map;async function resolvePackage(parent, name) {- const require2 = createRequire(join6(parent, "package.json"));+ const require2 = createRequire(join7(parent, "package.json"));let found;try {found = require2.resolve(`${name}/package.json`);@@ -41637,7 +42229,7 @@ async function installedRuntimeIdentity(root, limits = {}) {found = require2.resolve(name);} catch {for (const modules of require2.resolve.paths(name) ?? []) {- const candidate = join6(modules, name);+ const candidate = join7(modules, name);try {await lstat5(candidate);} catch (error) {@@ -41669,13 +42261,13 @@ async function installedRuntimeIdentity(root, limits = {}) {return (await Promise.all(entries.map(async (entry) => {if (entry.name === "node_modules" || entry.name === ".git")return [];- const path = join6(directory, entry.name);+ const path = join7(directory, entry.name);if (entry.isSymbolicLink())throw new Error("Dependency contains an untracked internal symlink.");if (entry.isDirectory())return tree(path, base);if (entry.isFile())- return [[relative2(base, path).replaceAll("\\", "/"), digest4(await read(path))]];+ return [[relative2(base, path).replaceAll("\\", "/"), digest5(await read(path))]];throw new Error("Dependency contains a non-file runtime input.");}))).flat();}@@ -41688,7 +42280,7 @@ async function installedRuntimeIdentity(root, limits = {}) {}visited.set(canonical, path);const metadata = await manifest(canonical);- records.push([path, digest4(JSON.stringify(await tree(canonical, canonical)))]);+ records.push([path, digest5(JSON.stringify(await tree(canonical, canonical)))]);await dependencies(canonical, metadata, path);}async function dependencies(directory, metadata, prefix) {@@ -41729,7 +42321,7 @@ async function installedRuntimeIdentity(root, limits = {}) {dependencies: records};return {- identity: `sha256:${digest4(JSON.stringify(inputs))}`,+ identity: `sha256:${digest5(JSON.stringify(inputs))}`,buildIdentity: worker.identity,files,bytes,@@ -41744,7 +42336,7 @@ async function installedRuntimeIdentity(root, limits = {}) {};}}-var digest4 = (bytes) => createHash12("sha256").update(bytes).digest("hex"), compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;+var digest5 = (bytes) => createHash13("sha256").update(bytes).digest("hex"), compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;var init_runtime_identity = () => {};// src/projects.ts@@ -41916,9 +42508,9 @@ var init_projects = __esm(() => {});// src/projects-node.ts-import { createHash as createHash13, randomUUID as randomUUID5 } from "node:crypto";+import { createHash as createHash14, randomUUID as randomUUID5 } from "node:crypto";import { link as link3, lstat as lstat6, mkdir as mkdir5, open as open3, readdir as readdir5, realpath as realpath4, unlink as unlink4 } from "node:fs/promises";-import { join as join7, relative as relative3, resolve as resolve7, sep as sep2 } from "node:path";+import { join as join8, relative as relative3, resolve as resolve8, sep as sep2 } from "node:path";function sequenceOf(revisionId) {projectRevisionIdSchema.parse(revisionId);const sequence = Number(revisionId.slice(2, 12));@@ -41926,9 +42518,9 @@ function sequenceOf(revisionId) {throw new Error("Invalid project revision sequence");return sequence;}-function digest5(record) {+function digest6(record) {const { revisionId: _, ...payload } = record;- return createHash13("sha256").update(JSON.stringify(payload)).digest("hex");+ return createHash14("sha256").update(JSON.stringify(payload)).digest("hex");}class FileProjectStore {@@ -41937,8 +42529,8 @@ class FileProjectStore {constructor(workspace) {if (!workspace.trim())throw new Error("A workspace directory is required");- this.workspace = resolve7(workspace);- this.directory = join7(this.workspace, ".kiln", "projects");+ this.workspace = resolve8(workspace);+ this.directory = join8(this.workspace, ".kiln", "projects");}async path(projectId, create = false) {if (projectId !== undefined)@@ -41948,7 +42540,7 @@ class FileProjectStore {const canonical = await realpath4(this.workspace);let path = this.workspace;for (const part of [".kiln", "projects", ...projectId ? [projectId, "revisions"] : []]) {- path = join7(path, part);+ path = join8(path, part);if (create)await mkdir5(path).catch((error) => {if (!exists(error))@@ -41980,7 +42572,7 @@ class FileProjectStore {return latest;}async load(projectId, directory, sequence) {- const path = join7(directory, filename(sequence));+ const path = join8(directory, filename(sequence));const info = await lstat6(path);if (!info.isFile() || info.isSymbolicLink() || info.size > MAX_PROJECT_BYTES)throw new Error("Invalid or oversized project revision file");@@ -42004,7 +42596,7 @@ class FileProjectStore {await handle.close();}const record = projectRevisionSchema.parse(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)));- if (record.projectId !== projectId || sequenceOf(record.revisionId) !== sequence || record.revisionId.slice(13) !== digest5(record))+ if (record.projectId !== projectId || sequenceOf(record.revisionId) !== sequence || record.revisionId.slice(13) !== digest6(record))throw new Error("Project revision integrity failure");if (sequence === 1 && record.parentRevision !== undefined || sequence > 1 && (!record.parentRevision || sequenceOf(record.parentRevision) !== sequence - 1))throw new Error("Project revision parent integrity failure");@@ -42063,7 +42655,7 @@ class FileProjectStore {for (const revision of new Set(record.reviews.map((review) => review.projectRevisionId)))await this.read(record.projectId, revision);const directory = await this.path(record.projectId, true);- const temporary = join7(directory, `.write-${randomUUID5()}`);+ const temporary = join8(directory, `.write-${randomUUID5()}`);const handle = await open3(temporary, "wx", 384);try {try {@@ -42073,7 +42665,7 @@ class FileProjectStore {await handle.close();}try {- await link3(temporary, join7(directory, filename(sequenceOf(record.revisionId))));+ await link3(temporary, join8(directory, filename(sequenceOf(record.revisionId))));} catch (error) {if (!exists(error))throw error;@@ -42099,7 +42691,7 @@ class FileProjectStore {parentRevision,createdAt: new Date().toISOString()});- record.revisionId = `${prefix}${digest5(record)}`;+ record.revisionId = `${prefix}${digest6(record)}`;return record;}async create(draft) {@@ -42151,7 +42743,7 @@ var init_workspace = __esm(() => {// src/workspace-node.tsimport { AsyncLocalStorage } from "node:async_hooks";-import { join as join8 } from "node:path";+import { join as join9 } from "node:path";class FileWorkspace {root;@@ -42163,7 +42755,7 @@ class FileWorkspace {this.root = root;this.defaultProjectId = defaultProjectId;this.projects = new FileProjectStore(root);- this.materials = new FileMaterialLibrary(join8(root, ".kiln", "materials"));+ this.materials = new FileMaterialLibrary(join9(root, ".kiln", "materials"));}current() {return this.active.getStore();@@ -42449,7 +43041,7 @@ var init_assets = __esm(() => {// src/live-review-node.tsimport { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";-import { createHash as createHash14, randomUUID as randomUUID6 } from "node:crypto";+import { createHash as createHash15, randomUUID as randomUUID6 } from "node:crypto";import {link as link4,mkdir as mkdir6,@@ -42462,7 +43054,7 @@ import {writeFile as writeFile5,realpath as realpath5} from "node:fs/promises";-import { join as join9, resolve as resolve8, relative as relative4, sep as sep3 } from "node:path";+import { join as join10, resolve as resolve9, relative as relative4, sep as sep3 } from "node:path";import { z as z10 } from "zod";function notify(run) {try {@@ -42634,8 +43226,8 @@ class FileLiveReview {storedSizes = new WeakMap;unreportedIssues = [];constructor(workspace, options = {}) {- this.workspace = resolve8(workspace);- this.directory = join9(this.workspace, ".kiln", "review");+ this.workspace = resolve9(workspace);+ this.directory = join10(this.workspace, ".kiln", "review");this.maxOperations = options.maxOperations ?? 200;this.maxBytes = options.maxBytes ?? 256 * 1024 * 1024;this.maxQueuedBytes = options.maxQueuedBytes ?? 128 * 1024 * 1024;@@ -42658,7 +43250,7 @@ class FileLiveReview {path(operationId, file) {if (!operationPattern.test(operationId))throw new Error("Invalid operation ID");- return join9(this.directory, operationId, ...file ? [file] : []);+ return join10(this.directory, operationId, ...file ? [file] : []);}async root(create = false) {if (create)@@ -42666,7 +43258,7 @@ class FileLiveReview {const canonical = await realpath5(this.workspace);let path = this.workspace;for (const part of [".kiln", "review"]) {- path = join9(path, part);+ path = join10(path, part);if (create)await mkdir6(path).catch((error) => {if (!collision(error))@@ -42704,7 +43296,7 @@ class FileLiveReview {async locked(run) {await this.root(true);const token = randomUUID6();- const directory = join9(this.directory, ".locks");+ const directory = join10(this.directory, ".locks");await mkdir6(directory).catch((error) => {if (!collision(error))throw error;@@ -42712,7 +43304,7 @@ class FileLiveReview {const info = await lstat7(directory);if (!info.isDirectory() || info.isSymbolicLink())throw new Error("Unsafe live lock directory");- const candidate = join9(directory, `.candidate-${process.pid}-${token}.tmp`);+ const candidate = join10(directory, `.candidate-${process.pid}-${token}.tmp`);const owner = JSON.stringify({ pid: process.pid, token });await writeFile5(candidate, owner, { flag: "wx", mode: 384 });const generations = async () => (await readdir6(directory)).filter((name) => /^[0-9]{16}\.lock$/.test(name)).sort();@@ -42729,8 +43321,8 @@ class FileLiveReview {throw new Error("Live lock generation exhausted");if (latest) {try {- const prior = z10.object({ pid: z10.number().int().positive(), token: z10.string().uuid() }).strict().parse(JSON.parse(new TextDecoder().decode(await this.boundedFile(join9(directory, latest), 1024))));- const released = await lstat7(join9(directory, `${latest}.released`)).then((entry) => {+ const prior = z10.object({ pid: z10.number().int().positive(), token: z10.string().uuid() }).strict().parse(JSON.parse(new TextDecoder().decode(await this.boundedFile(join10(directory, latest), 1024))));+ const released = await lstat7(join10(directory, `${latest}.released`)).then((entry) => {if (!entry.isFile() || entry.isSymbolicLink() || entry.size !== 0)throw new Error("Invalid lock release");return true;@@ -42751,9 +43343,9 @@ class FileLiveReview {}const name = `${String(sequence).padStart(16, "0")}.lock`;try {- await link4(candidate, join9(directory, name));+ await link4(candidate, join10(directory, name));if ((await generations()).at(-1) !== name) {- await unlink5(join9(directory, name));+ await unlink5(join10(directory, name));continue;}acquired = name;@@ -42763,8 +43355,8 @@ class FileLiveReview {}}for (const name of (await generations()).slice(0, -3)) {- await unlink5(join9(directory, name));- await unlink5(join9(directory, `${name}.released`)).catch((error) => {+ await unlink5(join10(directory, name));+ await unlink5(join10(directory, `${name}.released`)).catch((error) => {if (!missing2(error))throw error;});@@ -42772,18 +43364,18 @@ class FileLiveReview {for (const name of await readdir6(directory)) {const match = /^\.candidate-([0-9]+)-[a-f0-9-]+\.tmp$/.exec(name);if (match && dead(Number(match[1])))- await unlink5(join9(directory, name)).catch(() => {});+ await unlink5(join10(directory, name)).catch(() => {});}await this.limits(true);return await run();} finally {if (acquired)- await writeFile5(join9(directory, `${acquired}.released`), "", { flag: "wx", mode: 384 });+ await writeFile5(join10(directory, `${acquired}.released`), "", { flag: "wx", mode: 384 });await unlink5(candidate).catch(() => {});}}async limits(create = false) {- const path = join9(this.directory, "limits.json");+ const path = join10(this.directory, "limits.json");try {const value = JSON.parse(new TextDecoder().decode(await this.boundedFile(path, 1024)));const parsed = z10.object({@@ -42857,7 +43449,7 @@ class FileLiveReview {try {await this.locked(async () => {const previous = await this.health();- await this.atomic(join9(this.directory, "health.json"), JSON.stringify([...new Set([...previous, ...issues])].slice(-20)));+ await this.atomic(join10(this.directory, "health.json"), JSON.stringify([...new Set([...previous, ...issues])].slice(-20)));});this.unreportedIssues = this.unreportedIssues.filter((value) => !issues.includes(value));} catch {}@@ -43020,7 +43612,7 @@ class FileLiveReview {const info = await lstat7(directory);if (!info.isDirectory() || info.isSymbolicLink())throw new Error("Unsafe live directory");- const raw = JSON.parse(new TextDecoder().decode(await this.boundedFile(join9(directory, "record.json"), metadataLimit)));+ const raw = JSON.parse(new TextDecoder().decode(await this.boundedFile(join10(directory, "record.json"), metadataLimit)));const state = stateSchema.parse(jsonValue(raw, metadataLimit));if (state.operation.operationId !== operationId)throw new Error("Invalid live identity");@@ -43039,7 +43631,7 @@ class FileLiveReview {throw new Error("Invalid artifact descriptor");if (state.operation.captures.some((file) => !/^capture-\d{1,2}\.png$/.test(file.name)))throw new Error("Invalid capture descriptor");- state.operation.pinned = await lstat7(join9(directory, "pinned")).then((s) => {+ state.operation.pinned = await lstat7(join10(directory, "pinned")).then((s) => {if (!s.isFile() || s.isSymbolicLink())throw new Error("Invalid live pin");return true;@@ -43061,7 +43653,7 @@ class FileLiveReview {for (const entry of await readdir6(directory, { withFileTypes: true })) {if (!entry.isFile() || entry.isSymbolicLink())throw new Error("Invalid live directory entry");- bytes += (await lstat7(join9(directory, entry.name))).size;+ bytes += (await lstat7(join10(directory, entry.name))).size;}this.storedSizes.set(state, bytes);return state;@@ -43112,7 +43704,7 @@ class FileLiveReview {}async health() {try {- return z10.array(z10.string().max(500)).max(20).parse(JSON.parse(new TextDecoder().decode(await this.boundedFile(join9(this.directory, "health.json"), 16384))));+ return z10.array(z10.string().max(500)).max(20).parse(JSON.parse(new TextDecoder().decode(await this.boundedFile(join10(this.directory, "health.json"), 16384))));} catch (error) {if (missing2(error))return [];@@ -43179,8 +43771,8 @@ class FileLiveReview {if ((await lstat7(directory)).isSymbolicLink())throw new Error("Unsafe live directory");for (const [name, data] of Object.entries(blobs))- await this.atomic(join9(directory, name), data);- await this.atomic(join9(directory, "record.json"), JSON.stringify(state));+ await this.atomic(join10(directory, name), data);+ await this.atomic(join10(directory, "record.json"), JSON.stringify(state));await this.cleanupRecord(await this.record(state.operation.operationId));}async remove(operationId) {@@ -43243,7 +43835,7 @@ class FileLiveReview {});}}-var operationPattern, filePattern2, hash5 = (value) => `sha256:${createHash14("sha256").update(value).digest("hex")}`, metadataLimit, evaluationLimit, staleMs = 120000, terminal = (op) => !["running", "evaluated"].includes(op.status), missing2 = (error) => error.code === "ENOENT", collision = (error) => error.code === "EEXIST", fileLimit = (name) => name === "asset.glb" ? ASSET_LIMIT : name === "source.kiln.js" ? 1024 * 1024 : name === "evaluation.json" ? evaluationLimit : 16 * 1024 * 1024, descriptorSchema, operationSchema, stateSchema;+var operationPattern, filePattern2, hash5 = (value) => `sha256:${createHash15("sha256").update(value).digest("hex")}`, metadataLimit, evaluationLimit, staleMs = 120000, terminal = (op) => !["running", "evaluated"].includes(op.status), missing2 = (error) => error.code === "ENOENT", collision = (error) => error.code === "EEXIST", fileLimit = (name) => name === "asset.glb" ? ASSET_LIMIT : name === "source.kiln.js" ? 1024 * 1024 : name === "evaluation.json" ? evaluationLimit : 16 * 1024 * 1024, descriptorSchema, operationSchema, stateSchema;var init_live_review_node = __esm(() => {init_assets();operationPattern = /^op_[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;@@ -43349,11 +43941,11 @@ __export(exports_assets_node, {localAssetLibrary: () => localAssetLibrary,verifyAssetRecord: () => verifyAssetRecord});-import { createHash as createHash15, randomUUID as randomUUID7 } from "node:crypto";+import { createHash as createHash16, randomUUID as randomUUID7 } from "node:crypto";import { readFileSync as readFileSync2 } from "node:fs";import { link as link5, lstat as lstat8, mkdir as mkdir7, readFile as readFile7, readdir as readdir7, realpath as realpath6, rm as rm3, writeFile as writeFile6 } from "node:fs/promises";import { homedir, platform } from "node:os";-import { dirname as dirname5, join as join10, relative as relative5, resolve as resolve9, sep as sep4, win32 } from "node:path";+import { dirname as dirname5, join as join11, relative as relative5, resolve as resolve10, sep as sep4, win32 } from "node:path";function assertMaterialAllocation(records) {let bytes = 0;for (const record of records)@@ -43367,7 +43959,7 @@ function assertMaterialAllocation(records) {async function verifyAssetRecord(record) {for (const [name, info] of Object.entries(record.manifest.files)) {const bytes = record.files[name];- if (!bytes || bytes.length !== info.bytes || digest6(bytes) !== info.sha256)+ if (!bytes || bytes.length !== info.bytes || digest7(bytes) !== info.sha256)throw new Error(`Asset integrity failure: ${name}`);}validateRecordShape(record);@@ -43382,7 +43974,7 @@ class FileAssetLibrary {this.materials = materials;if (!Object.keys(roots).length)throw new Error("Configure at least one collection");- this.roots = Object.fromEntries(Object.entries(roots).map(([id, path]) => [assetIdSchema.parse(id), resolve9(path)]));+ this.roots = Object.fromEntries(Object.entries(roots).map(([id, path]) => [assetIdSchema.parse(id), resolve10(path)]));}collections() {return Object.keys(this.roots).map((id) => ({@@ -43397,7 +43989,7 @@ class FileAssetLibrary {return root;}revisionDirectory(collection, assetId, revisionId) {- return join10(this.directory(collection), assetIdSchema.parse(assetId), "revisions", assetIdSchema.parse(revisionId));+ return join11(this.directory(collection), assetIdSchema.parse(assetId), "revisions", assetIdSchema.parse(revisionId));}async path(collection, ...parts) {const root = this.directory(collection);@@ -43406,7 +43998,7 @@ class FileAssetLibrary {let path = root;for (const part of parts) {assetIdSchema.parse(part);- path = join10(path, part);+ path = join11(path, part);try {const entry = await lstat8(path);if (entry.isSymbolicLink())@@ -43449,7 +44041,7 @@ class FileAssetLibrary {return records.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || a.revisionId.localeCompare(b.revisionId));}async file(dir, name, limit = ASSET_LIMIT) {- const path = join10(dir, name);+ const path = join11(dir, name);const info = await lstat8(path);if (!info.isFile() || info.isSymbolicLink() || info.size > limit)throw new Error("Invalid collection file");@@ -43518,7 +44110,7 @@ class FileAssetLibrary {editable: draft.code !== undefined,files: Object.fromEntries(Object.entries(files).map(([name, bytes]) => [name,- { sha256: digest6(bytes), bytes: bytes.length }+ { sha256: digest7(bytes), bytes: bytes.length }])),build: draft.build ? { ...draft.build, rebuild: draft.build.rebuild ?? "engine-required" } : undefined,preview: draft.previewInfo@@ -43570,14 +44162,14 @@ class FileAssetLibrary {const dest = await this.path(collection, manifest.assetId, "revisions", manifest.revisionId);const parent = dirname5(dest);await mkdir7(parent, { recursive: true });- const stage = join10(parent, `.write-${randomUUID7()}`);+ const stage = join11(parent, `.write-${randomUUID7()}`);await mkdir7(stage);try {for (const [name, bytes] of Object.entries(files))- await writeFile6(join10(stage, name), bytes, { flag: "wx" });+ await writeFile6(join11(stage, name), bytes, { flag: "wx" });if (record.materialResources)- await writeFile6(join10(stage, ASSET_MATERIAL_FILE), JSON.stringify(record.materialResources), { flag: "wx" });- await writeFile6(join10(stage, "manifest.json"), `${JSON.stringify(manifest, null, 2)}+ await writeFile6(join11(stage, ASSET_MATERIAL_FILE), JSON.stringify(record.materialResources), { flag: "wx" });+ await writeFile6(join11(stage, "manifest.json"), `${JSON.stringify(manifest, null, 2)}`, {flag: "wx"});@@ -43591,7 +44183,7 @@ class FileAssetLibrary {throw error;if (record.materialResources && !existing.materialResources) {try {- await link5(join10(stage, ASSET_MATERIAL_FILE), join10(dest, ASSET_MATERIAL_FILE));+ await link5(join11(stage, ASSET_MATERIAL_FILE), join11(dest, ASSET_MATERIAL_FILE));} catch (enrichmentError) {if (enrichmentError.code !== "EEXIST")throw enrichmentError;@@ -43609,17 +44201,17 @@ class FileAssetLibrary {}}function collectionConfigPath(env = process.env) {- return join10(localWorkspaceRoot(env), ".kiln", "collections.json");+ return join11(localWorkspaceRoot(env), ".kiln", "collections.json");}function defaultUserLibraryRoot(env = process.env, home = homedir(), operatingSystem = platform()) {const dataRoot = env.XDG_DATA_HOME?.trim();if (dataRoot)- return join10(dataRoot, "kiln", "library");+ return join11(dataRoot, "kiln", "library");if (operatingSystem === "darwin")- return join10(home, "Library", "Application Support", "Kiln", "library");+ return join11(home, "Library", "Application Support", "Kiln", "library");if (operatingSystem === "win32")- return join10(env.LOCALAPPDATA?.trim() || join10(home, "AppData", "Local"), "Kiln", "library");- return join10(home, ".local", "share", "kiln", "library");+ return join11(env.LOCALAPPDATA?.trim() || join11(home, "AppData", "Local"), "Kiln", "library");+ return join11(home, ".local", "share", "kiln", "library");}function assertCollectionRoot(id, path, operatingSystem = platform(), source) {if (operatingSystem !== "win32" || windowsDrivePath.test(path) || windowsSharePath.test(path))@@ -43638,10 +44230,10 @@ function configuredRoots(text, source, operatingSystem) {}function localAssetLibrary(env = process.env, operatingSystem = platform()) {if (env.KILN_COLLECTIONS)- return new FileAssetLibrary(configuredRoots(env.KILN_COLLECTIONS, "KILN_COLLECTIONS", operatingSystem), new FileMaterialLibrary(join10(localWorkspaceRoot(env), ".kiln", "materials")));+ return new FileAssetLibrary(configuredRoots(env.KILN_COLLECTIONS, "KILN_COLLECTIONS", operatingSystem), new FileMaterialLibrary(join11(localWorkspaceRoot(env), ".kiln", "materials")));const config = collectionConfigPath(env);const workspace = dirname5(dirname5(config));- const materials = new FileMaterialLibrary(join10(workspace, ".kiln", "materials"));+ const materials = new FileMaterialLibrary(join11(workspace, ".kiln", "materials"));let text;try {text = readFileSync2(config, "utf8");@@ -43655,11 +44247,11 @@ function localAssetLibrary(env = process.env, operatingSystem = platform()) {return new FileAssetLibrary(configuredRoots(text, config, operatingSystem), materials);}return new FileAssetLibrary({- project: join10(workspace, "assets", "kiln"),+ project: join11(workspace, "assets", "kiln"),library: defaultUserLibraryRoot(env, homedir(), operatingSystem)}, materials);}-var digest6 = (bytes) => `sha256:${createHash15("sha256").update(bytes).digest("hex")}`, windowsDrivePath, windowsSharePath;+var digest7 = (bytes) => `sha256:${createHash16("sha256").update(bytes).digest("hex")}`, windowsDrivePath, windowsSharePath;var init_assets_node = __esm(() => {init_workspace_location();init_assets();@@ -43673,15 +44265,15 @@ var init_assets_node = __esm(() => {});// src/ktx2-basis.ts-import { createHash as createHash16 } from "node:crypto";+import { createHash as createHash17 } from "node:crypto";import { readFile as readFile8 } from "node:fs/promises";-import { dirname as dirname6, join as join11 } from "node:path";+import { dirname as dirname6, join as join12 } from "node:path";import { fileURLToPath as fileURLToPath4, pathToFileURL } from "node:url";async function packageDirectory() {let directory = dirname6(fileURLToPath4(import.meta.resolve(KTX2_ENCODER_PACKAGE.name)));for (let depth = 0;depth < 6; depth++) {try {- const manifest = JSON.parse(await readFile8(join11(directory, "package.json"), "utf8"));+ const manifest = JSON.parse(await readFile8(join12(directory, "package.json"), "utf8"));if (manifest.name === KTX2_ENCODER_PACKAGE.name)return directory;} catch {}@@ -43699,14 +44291,14 @@ async function loadKtx2Encoder(importer = () => import("ktx2-encoder")) {if (typeof module?.encodeToKTX2 !== "function")throw new Error(`${KTX2_ENCODER_PACKAGE.name} has no encodeToKTX2 export. ${INSTALL}`);const directory = await packageDirectory();- const { version } = JSON.parse(await readFile8(join11(directory, "package.json"), "utf8"));+ const { version } = JSON.parse(await readFile8(join12(directory, "package.json"), "utf8"));if (version !== KTX2_ENCODER_PACKAGE.version)throw new Error(`${KTX2_ENCODER_PACKAGE.name} ${version} is installed; Kiln's KTX2 settings are qualified on ${KTX2_ENCODER_PACKAGE.version}. ${INSTALL}`);let basisWasmSha256;try {- basisWasmSha256 = `sha256:${hex2(await readFile8(join11(directory, "dist", "basis", "basis_encoder.wasm")))}`;+ basisWasmSha256 = `sha256:${hex2(await readFile8(join12(directory, "dist", "basis", "basis_encoder.wasm")))}`;} catch {}- const internal = (path) => import(pathToFileURL(join11(directory, "dist", path)).href);+ const internal = (path) => import(pathToFileURL(join12(directory, "dist", path)).href);const [factory, core] = await Promise.all([internal("basis/basis_encoder.js"),internal("encodeCore.js")@@ -43738,7 +44330,7 @@ async function createKtx2Encoder(options = {}) {};return Object.assign(encode, { identity });}-var KTX2_ENCODER_PACKAGE, INSTALL, SETTINGS, profile = (input) => input.colorSpace === "srgb" ? SETTINGS.srgb : input.slot === "normal" ? SETTINGS.normal : SETTINGS.linear, hex2 = (bytes) => createHash16("sha256").update(bytes).digest("hex"), basis, decode = async (buffer) => {+var KTX2_ENCODER_PACKAGE, INSTALL, SETTINGS, profile = (input) => input.colorSpace === "srgb" ? SETTINGS.srgb : input.slot === "normal" ? SETTINGS.normal : SETTINGS.linear, hex2 = (bytes) => createHash17("sha256").update(bytes).digest("hex"), basis, decode = async (buffer) => {const { default: sharp } = await import("sharp");const { data, info } = await sharp(buffer).ensureAlpha().raw().toBuffer({ resolveWithObject: true });return { data: new Uint8Array(data), width: info.width, height: info.height };@@ -44344,7 +44936,7 @@ var init_project_bundle = __esm(() => {// src/project-bundle-node.tsimport { randomUUID as randomUUID8 } from "node:crypto";import { link as link6, lstat as lstat9, mkdir as mkdir8, readFile as readFile9, realpath as realpath7, unlink as unlink6, writeFile as writeFile7 } from "node:fs/promises";-import { join as join12, relative as relative6, resolve as resolve10, sep as sep5 } from "node:path";+import { join as join13, relative as relative6, resolve as resolve11, sep as sep5 } from "node:path";async function assetMaterials(workspace, asset) {return resolveSavedAssetMaterials(asset, workspace.materials);}@@ -44436,12 +45028,12 @@ async function exportWorkspaceProjectBundle(workspace, library, projectId, optioreturn encodeProjectBundle({ project, assets, materials }, profile);}async function retainArchive(workspace, bytes, digest) {- const root = resolve10(workspace.root);+ const root = resolve11(workspace.root);await mkdir8(root, { recursive: true });const canonical = await realpath7(root);let directory = root;for (const part of [".kiln", "imports"]) {- directory = join12(directory, part);+ directory = join13(directory, part);await mkdir8(directory).catch((error) => {if (error.code !== "EEXIST")throw error;@@ -44451,8 +45043,8 @@ async function retainArchive(workspace, bytes, digest) {if (!info.isDirectory() || info.isSymbolicLink() || rel === ".." || rel.startsWith(`..${sep5}`))throw new Error("Unsafe project import directory");}- const file = join12(directory, `${digest.slice(7)}.zip`);- const temporary = join12(directory, `.import-${randomUUID8()}.tmp`);+ const file = join13(directory, `${digest.slice(7)}.zip`);+ const temporary = join13(directory, `.import-${randomUUID8()}.tmp`);await writeFile7(temporary, bytes, { flag: "wx", mode: 384 });try {try {@@ -44610,7 +45202,7 @@ var init_source_check = __esm(() => {// src/local-runtime.tsimport { readFile as readFile10, stat as stat5 } from "node:fs/promises";-import { dirname as dirname7, isAbsolute, join as join13, resolve as resolve11 } from "node:path";+import { dirname as dirname7, isAbsolute, join as join14, resolve as resolve12 } from "node:path";import { fileURLToPath as fileURLToPath5 } from "node:url";import { Console } from "node:console";function workspaceSourceReader(root) {@@ -44618,7 +45210,7 @@ function workspaceSourceReader(root) {const segments = file.split(/[\\/]/u);if (!file || isAbsolute(file) || /^[A-Za-z]:/u.test(file) || segments.includes("..") || segments.includes(""))throw new Error('file must name a program inside the workspace, relative to its root: no absolute path and no "..". Use a path such as assets/asset.kiln.js, or pass code or programRef.');- const path = resolve11(root, file);+ const path = resolve12(root, file);const info = await stat5(path).catch(() => {return;});@@ -44636,7 +45228,7 @@ function integer4(env, name, fallback, min, max) {return value;}function createLocalToolContext(base = {}, env = process.env) {- const workspaceRoot = env.KILN_WORKSPACE ? resolve11(env.KILN_WORKSPACE) : base.programStore instanceof FileProgramStore ? dirname7(dirname7(base.programStore.directory)) : localWorkspaceRoot(env);+ const workspaceRoot = env.KILN_WORKSPACE ? resolve12(env.KILN_WORKSPACE) : base.programStore instanceof FileProgramStore ? dirname7(dirname7(base.programStore.directory)) : localWorkspaceRoot(env);const workspace = base.workspace ?? new FileWorkspace(workspaceRoot, env.KILN_PROJECT);const projectStore = base.projectStore ?? (workspace instanceof FileWorkspace ? workspace.projects : undefined);const liveReview = base.liveReview ?? (env.KILN_LIVE_REVIEW === "off" ? undefined : new FileLiveReview(workspaceRoot, {@@ -44801,7 +45393,7 @@ async function createPackagedLocalToolContext(base = {}, env = process.env, inst}const cacheBytes = integer4(env, "KILN_BUILD_CACHE_MB", 128, 0, 1024) * 1024 * 1024;const store = context.programStore;- const directory = resolve11(env.KILN_BUILD_CACHE_DIR ?? join13(store instanceof FileProgramStore ? dirname7(store.directory) : ".kiln", "cache", "builds"));+ const directory = resolve12(env.KILN_BUILD_CACHE_DIR ?? join14(store instanceof FileProgramStore ? dirname7(store.directory) : ".kiln", "cache", "builds"));context.buildCache = new FileBuildCache(directory, cacheBytes);context.evaluatorCacheIdentity = `${identity.identity}:${JSON.stringify({execution: context.localExecution,@@ -51490,225 +52082,17 @@ var init_view_render_timeout = __esm(() => {// src/asset-widget-uri.tsvar KILN_ASSET_WIDGET_URI = "ui://kiln/asset-v6.html";-// src/views/port.ts-async function sha256Bytes(bytes) {- const input = new Uint8Array(bytes.byteLength);- input.set(bytes);- const digest = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", input));- return `sha256:${[...digest].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;-}-async function captureViewPngsViaPort(port, glb, timeoutMs, viewDirs, size, cameras, limits, backdrop, execution) {- let timer;- const controller = new AbortController;- let abort;- try {- execution?.signal?.throwIfAborted();- const exactCameras = cameras?.map(validateResolvedAssetCamera);- if (exactCameras && exactCameras.length !== viewDirs.length)- throw new Error("camera and view count mismatch");- const requestGlb = Uint8Array.from(glb);- const inputGlbSha256 = await sha256Bytes(requestGlb);- execution?.signal?.throwIfAborted();- const deadline = new Promise((_, reject) => {- abort = () => {- const error = execution?.signal?.reason ?? new Error("View request cancelled.");- reject(error);- controller.abort(error);- };- execution?.signal?.addEventListener("abort", abort, { once: true });- timer = setTimeout(() => {- const error = new Error(`view render port timed out after ${timeoutMs}ms`);- reject(error);- controller.abort(error);- }, timeoutMs);- });- const result = await Promise.race([- port({- glb: requestGlb,- ...backdrop ? { backdrop } : {},- ...exactCameras ? { cameras: exactCameras, width: size, height: size } : { viewDirs: viewDirs.map((dir) => [...dir]), size }- }, { signal: controller.signal }),- deadline- ]);- execution?.signal?.throwIfAborted();- if (!result?.ok) {- return { ok: false, reason: result?.error ?? "view render port returned ok: false" };- }- if (typeof result.rendererId !== "string" || !result.rendererId.trim()) {- return { ok: false, reason: "view render port returned no rendererId" };- }- if (!result.viewsPng || result.viewsPng.length !== viewDirs.length) {- return {- ok: false,- reason: `view render port returned ${result.viewsPng?.length ?? 0} view PNGs, expected ${viewDirs.length}`- };- }- if (exactCameras) {- if (result.width !== size || result.height !== size || !result.cameras || result.cameras.length !== exactCameras.length)- return { ok: false, reason: "camera receipt missing or dimensions mismatch" };- for (let i = 0;i < exactCameras.length; i++) {- const echoed = validateResolvedAssetCamera(result.cameras[i]);- const wanted = exactCameras[i];- for (const key of Object.keys(wanted))- if (JSON.stringify(echoed[key]) !== JSON.stringify(wanted[key]))- return { ok: false, reason: "camera receipt does not match requested camera" };- }- }- if (result.derivativeFidelity && result.derivativeFidelity.inputGlbSha256 !== inputGlbSha256) {- return {- ok: false,- reason: `view render port derivative receipt hash mismatch (${result.derivativeFidelity.inputGlbSha256} != ${inputGlbSha256})`- };- }- enforcePngCaptureBudget(result.viewsPng, limits);- for (const png of result.viewsPng) {- const decoded = decodePng(png);- if (exactCameras && (decoded.width !== size || decoded.height !== size))- return { ok: false, reason: "camera PNG dimensions mismatch" };- if (decoded.width !== decoded.height) {- return {- ok: false,- reason: `view render port returned non-square ${decoded.width}x${decoded.height} PNG`- };- }- }- return {- ok: true,- pngs: result.viewsPng.map((png) => Uint8Array.from(png)),- rendererId: result.rendererId,- ...result.captureCache ? { captureCache: result.captureCache } : {},- derivativeFidelityAttested: result.derivativeFidelity?.materialFaithful === true,- ...result.derivativeFidelity ? { inputGlbSha256 } : {}- };- } catch (err) {- return { ok: false, reason: err instanceof Error ? err.message : String(err) };- } finally {- if (timer !== undefined)- clearTimeout(timer);- if (abort)- execution?.signal?.removeEventListener("abort", abort);- }-}-async function captureViewsViaPort(port, glb, timeoutMs = DEFAULT_VIEW_RENDER_TIMEOUT_MS, capture, limits, execution) {- if (capture?.shots || capture?.version) {- try {- execution?.signal?.throwIfAborted();- await Promise.resolve().then(() => init_views());- await Promise.resolve().then(() => init_camera_capture());- await Promise.resolve().then(() => init_camera());- await Promise.resolve().then(() => init_render());- const loaded = await loadGlbReviewScene(Uint8Array.from(glb));- let rendererId = "";- const grid = await renderCaptureGrid(loaded.root, capture, async (input) => {- execution?.signal?.throwIfAborted();- const derivative = await renderSceneToGLB(withoutHiddenMeshes(input.root), { derivative: true, gltfExporter: "three" });- const result = await captureViewPngsViaPort(port, derivative.bytes, timeoutMs, [input.view.dir], input.size, [input.camera], limits, input.backdrop, execution);- if (!result.ok)- throw new Error(result.reason);- if (!result.derivativeFidelityAttested || !result.inputGlbSha256)- throw new Error("advanced capture requires derivative material receipt");- if (rendererId && rendererId !== result.rendererId)- throw new Error("capture renderer changed between cells");- rendererId = result.rendererId;- return {- png: Buffer.from(result.pngs[0]),- receipt: {- version: "kiln.view-fidelity.v1",- derivativeLabel: input.label,- requested: "full-preferred",- delivered: "full-material",- exactArtifact: false,- rendererId: result.rendererId,- materialFaithful: true,- degraded: false,- inputGlbSha256: result.inputGlbSha256,- camera: input.camera,- cameraFidelity: "echo-validated",- ...result.captureCache ? { captureCache: result.captureCache } : {}- }- };- }, limits);- return {- ok: true,- png: grid.png,- rendererId,- capture: grid.capture,- width: grid.width,- height: grid.height,- cameraShots: grid.cameraShots,- derivativeReceipts: grid.derivativeReceipts,- perFramePngs: grid.perFramePngs,- ...grid.captureCache ? { captureCache: grid.captureCache } : {}- };- } catch (error) {- return { ok: false, reason: error instanceof Error ? error.message : String(error) };- }- }- let resolved;- try {- execution?.signal?.throwIfAborted();- resolved = resolveGridCapture(capture, process.env["KILN_GRID_VARIANT"]);- enforceCapturePixels(resolved.views.length, 384, resolved.cols, limits);- } catch (err) {- return { ok: false, reason: err instanceof Error ? err.message : String(err) };- }- const views = resolved.views;- const shape = {- preset: resolved.preset,- cols: resolved.cols,- cells: views.length,- backdrop: resolved.backdrop- };- let cameras;- if (resolved.zooms.some((z) => z !== undefined)) {- try {- await Promise.resolve().then(() => init_views());- const loaded = await loadGlbReviewScene(Uint8Array.from(glb));- const bounds = measureBounds(loaded.root);- cameras = views.map((view, i) => cameraFromBounds(bounds, view.dir, resolved.zooms[i] ?? 1));- } catch (error) {- return { ok: false, reason: error instanceof Error ? error.message : String(error) };- }- }- const result = await captureViewPngsViaPort(port, glb, timeoutMs, views.map((view) => view.dir), 384, cameras, limits, resolved.backdrop, execution);- if (!result.ok)- return result;- try {- const grid = compositeViewPngGrid(result.pngs, resolved.cols, views);- enforceCaptureBytes([grid.png], limits);- return {- ok: true,- png: grid.png,- rendererId: result.rendererId,- ...result.captureCache ? { captureCache: result.captureCache } : {},- capture: shape,- width: grid.width,- height: grid.height- };- } catch (err) {- return { ok: false, reason: err instanceof Error ? err.message : String(err) };- }-}-var DEFAULT_VIEW_RENDER_TIMEOUT_MS = 8000;-var init_port = __esm(() => {- init_capture_limits();- init_camera();- init_capture();- init_png();- init_grid();-});-// src/views/part-placement.tsvar exports_part_placement = {};__export(exports_part_placement, {createPartPlacementReader: () => createPartPlacementReader});-import * as THREE57 from "three";+import * as THREE58 from "three";function createPartPlacementReader(root) {const bounds = createPartBoundsReader(root);- const position = new THREE57.Vector3;- const quaternion = new THREE57.Quaternion;- const scale = new THREE57.Vector3;+ const position = new THREE58.Vector3;+ const quaternion = new THREE58.Quaternion;+ const scale = new THREE58.Vector3;return (node) => {node.matrixWorld.decompose(position, quaternion, scale);const box = bounds(node);@@ -51933,7 +52317,7 @@ async function accessorFingerprint(accessor) {accessor.getType(),accessor.getComponentType(),accessor.getNormalized(),- await digest7(new Uint8Array(array.buffer, array.byteOffset, array.byteLength))+ await digest8(new Uint8Array(array.buffer, array.byteOffset, array.byteLength))];}function lowerLevels(node) {@@ -51946,7 +52330,7 @@ function bounds(box) {size: box.getSize(new Vector346).toArray()};}-async function digest7(bytes) {+async function digest8(bytes) {const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", Uint8Array.from(bytes)));return `sha256:${[...hash].map((b) => b.toString(16).padStart(2, "0")).join("")}`;}@@ -52064,7 +52448,7 @@ async function snapshot3(bytes) {});}}- return { parts, animation, scenePath, bounds: bounds(box), glbSha256: await digest7(bytes) };+ return { parts, animation, scenePath, bounds: bounds(box), glbSha256: await digest8(bytes) };}function accessorEqual(a, b) {return a === b || Boolean(a && b && a.equals(b, ACCESSOR_IGNORED));@@ -52513,7 +52897,7 @@ __export(exports_draw_diagnostics, {});import { Primitive as Primitive3 } from "@gltf-transform/core";import { cloneDocument as cloneDocument2 } from "@gltf-transform/functions";-import * as THREE58 from "three";+import * as THREE59 from "three";function withinLimits(doc) {const root = doc.getRoot();if (root.listNodes().length > MAX_NODES2 || root.listAccessors().length > 4096 || root.listMaterials().length > 2048 || root.listTextures().length > 256 || root.listScenes().length > 32 || doc.getGraph().listEdges().length > 32768)@@ -52566,7 +52950,7 @@ function collect2(doc, keep) {function overlaps(a, b) {if (Math.abs(a.normal.dot(b.normal)) < 1 - 0.00000001 || !a.bounds.intersectsBox(b.bounds))return false;- const tolerance = Math.max(a.bounds.getSize(new THREE58.Vector3).length(), b.bounds.getSize(new THREE58.Vector3).length(), 0.000000000001) * 0.000001;+ const tolerance = Math.max(a.bounds.getSize(new THREE59.Vector3).length(), b.bounds.getSize(new THREE59.Vector3).length(), 0.000000000001) * 0.000001;if (b.points.some((p) => Math.abs(a.normal.dot(p.clone().sub(a.points[0]))) > tolerance))return false;const normal = a.normal.toArray().map(Math.abs);@@ -52608,7 +52992,7 @@ function observe(uses) {unexaminedPrimitiveUses++;continue;}- const matrix = new THREE58.Matrix4().fromArray(node.getWorldMatrix());+ const matrix = new THREE59.Matrix4().fromArray(node.getWorldMatrix());if (primitive.getAttribute("TANGENT") && matrix.determinant() < 0)mirrored.set(part.id, part);const position = primitive.getAttribute("POSITION");@@ -52622,14 +53006,14 @@ function observe(uses) {const amount = Math.min(count, 8, MAX_SAMPLES - samples.length);for (let i = 0;i < amount; i++) {const start = Math.floor(i * count / amount) * 3;- const points = [0, 1, 2].map((j) => new THREE58.Vector3().fromArray(position.getElement(indices ? indices.getScalar(start + j) : start + j, [])).applyMatrix4(matrix));+ const points = [0, 1, 2].map((j) => new THREE59.Vector3().fromArray(position.getElement(indices ? indices.getScalar(start + j) : start + j, [])).applyMatrix4(matrix));const normal = points[1].clone().sub(points[0]).cross(points[2].clone().sub(points[0]));if (!Number.isFinite(normal.lengthSq()) || normal.lengthSq() === 0)continue;samples.push({points,normal: normal.normalize(),- bounds: new THREE58.Box3().setFromPoints(points),+ bounds: new THREE59.Box3().setFromPoints(points),part});}@@ -52920,7 +53304,7 @@ var init_export_root = __esm(() => {// src/tools/registry.tsimport { z as z25 } from "zod";-import * as THREE59 from "three";+import * as THREE60 from "three";function proceduralTextureMaterialContract(rendered, context) {const required = [...new Set(context.requiredProceduralTextureUsages ?? [])];if (required.length === 0)@@ -53201,8 +53585,8 @@ function collectSceneMetrics(root) {let meshes = 0;const materialSet = new Set;let lowestPart;- const box = new THREE59.Box3;- const point = new THREE59.Vector3;+ const box = new THREE60.Box3;+ const point = new THREE60.Vector3;root.updateWorldMatrix(true, true);root.traverseVisible((node) => {const n = node;@@ -53218,7 +53602,7 @@ function collectSceneMetrics(root) {const mesh = node;const position = mesh.geometry.getAttribute("position");const index = mesh.geometry.index;- const mb = new THREE59.Box3;+ const mb = new THREE60.Box3;if (position) {for (let i = 0;i < (index?.count ?? position.count); i++) {point.fromBufferAttribute(position, index ? index.getX(i) : i);@@ -53233,7 +53617,7 @@ function collectSceneMetrics(root) {});let bbox;if (!box.isEmpty()) {- const size = new THREE59.Vector3;+ const size = new THREE60.Vector3;box.getSize(size);bbox = {min: [box.min.x, box.min.y, box.min.z],@@ -54622,18 +55006,18 @@ var init_registry2 = __esm(() => {});// render-service/src/instance.mjs-import { createHash as createHash17 } from "node:crypto";+import { createHash as createHash18 } from "node:crypto";import { readFileSync as readFileSync3, readdirSync, statSync } from "node:fs";-import { join as join14, relative as relative7 } from "node:path";+import { join as join15, relative as relative7 } from "node:path";function fingerprintSourceDir(dir) {- const hash = createHash17("sha256");+ const hash = createHash18("sha256");hash.update("kiln.render-service-source.v1");const visit = (path) => {if (statSync(path).isDirectory()) {for (const name of readdirSync(path).sort()) {if (name === "node_modules")continue;- visit(join14(path, name));+ visit(join15(path, name));}return;}@@ -54647,9 +55031,9 @@ function fingerprintSourceDir(dir) {var init_instance = () => {};// render-service/src/build-identity.mjs-import { createHash as createHash18 } from "node:crypto";+import { createHash as createHash19 } from "node:crypto";import { readFileSync as readFileSync4 } from "node:fs";-import { dirname as dirname8, join as join15 } from "node:path";+import { dirname as dirname8, join as join16 } from "node:path";import { createRequire as createRequire2 } from "node:module";function compatibilityFingerprint({ sourceFingerprint, dependencies }) {if (typeof sourceFingerprint !== "string" || !/^sha256:[a-f0-9]{64}$/.test(sourceFingerprint))@@ -54659,7 +55043,7 @@ function compatibilityFingerprint({ sourceFingerprint, dependencies }) {throw new Error(`Missing renderer dependency identity: ${name}`);return [name, dependencies[name]];}));- return `sha256:${createHash18("sha256").update(JSON.stringify({+ return `sha256:${createHash19("sha256").update(JSON.stringify({version: "kiln.render-service-build.v1",sourceFingerprint,dependencies: pins@@ -54677,7 +55061,7 @@ function resolvedRendererDependencies(anchorUrl = import.meta.url) {let found;for (;; ) {try {- const pkg = JSON.parse(readFileSync4(join15(dir, "package.json"), "utf8"));+ const pkg = JSON.parse(readFileSync4(join16(dir, "package.json"), "utf8"));if (pkg.name === name) {found = pkg.version;break;@@ -54709,7 +55093,7 @@ var init_build_identity = __esm(() => {});// src/render-service-client.ts-import { createHash as createHash19 } from "node:crypto";+import { createHash as createHash20 } from "node:crypto";import { existsSync as existsSync2 } from "node:fs";import { fileURLToPath as fileURLToPath6 } from "node:url";function packagedRendererSourceFingerprint() {@@ -54728,12 +55112,12 @@ function validateRenderServiceHealth(value) {if (typeof raw.authRequired !== "boolean")return bad("renderer authentication policy is missing or invalid");const instance = raw.instance;- if (instance?.version !== "kiln.render-service-instance.v2" || !pid(instance.pid) || !(instance.ownerPid === null || pid(instance.ownerPid)) || !nonempty(instance.startedAt) || !Number.isFinite(Date.parse(instance.startedAt)) || !nonempty(instance.sourceDir) || !digest8(instance.sourceFingerprint) || !(instance.mode === "manual" && instance.idleTimeoutMs === null || instance.mode === "managed" && typeof instance.idleTimeoutMs === "number" && Number.isSafeInteger(instance.idleTimeoutMs) && instance.idleTimeoutMs > 0))+ if (instance?.version !== "kiln.render-service-instance.v2" || !pid(instance.pid) || !(instance.ownerPid === null || pid(instance.ownerPid)) || !nonempty(instance.startedAt) || !Number.isFinite(Date.parse(instance.startedAt)) || !nonempty(instance.sourceDir) || !digest9(instance.sourceFingerprint) || !(instance.mode === "manual" && instance.idleTimeoutMs === null || instance.mode === "managed" && typeof instance.idleTimeoutMs === "number" && Number.isSafeInteger(instance.idleTimeoutMs) && instance.idleTimeoutMs > 0))return bad("renderer instance identity is missing or invalid");if (!Array.isArray(raw.capabilities) || !REQUIRED_RENDER_CAPABILITIES.every((name) => raw.capabilities.includes(name)))return bad("renderer required capabilities are missing");const build = raw.compatibility;- if (build?.version !== "kiln.render-service-build.v1" || !digest8(build.sourceFingerprint) || !digest8(build.fingerprint) || build.sourceFingerprint !== instance.sourceFingerprint)+ if (build?.version !== "kiln.render-service-build.v1" || !digest9(build.sourceFingerprint) || !digest9(build.fingerprint) || build.sourceFingerprint !== instance.sourceFingerprint)return bad("renderer build identity is missing or inconsistent");for (const [name, expected] of Object.entries(RENDER_SERVICE_DEPENDENCIES))if (build.dependencies?.[name] !== expected)@@ -54741,7 +55125,7 @@ function validateRenderServiceHealth(value) {if (build.fingerprint !== compatibilityFingerprint(build))return bad("renderer build fingerprint is invalid");const capture = raw.captureIdentity;- if (capture?.version !== "kiln.capture-producer.v1" || !digest8(capture.fingerprint) || !nonempty(capture.instanceId))+ if (capture?.version !== "kiln.capture-producer.v1" || !digest9(capture.fingerprint) || !nonempty(capture.instanceId))return bad("renderer capture identity is missing or invalid");return { kind: "service", health: raw };}@@ -54798,7 +55182,7 @@ function makeRemoteRenderPort(url, token, sourceFingerprint) {return async (req, execution) => {const health = await verifiedHealth(url, token, sourceFingerprint, execution?.signal);execution?.signal?.throwIfAborted();- const inputGlbSha256 = `sha256:${createHash19("sha256").update(req.glb).digest("hex")}`;+ const inputGlbSha256 = `sha256:${createHash20("sha256").update(req.glb).digest("hex")}`;const body = {glb_base64: Buffer.from(req.glb).toString("base64"),input_glb_sha256: inputGlbSha256,@@ -54845,7 +55229,7 @@ function makeRemoteRenderPort(url, token, sourceFingerprint) {};};}-var digest8 = (value) => typeof value === "string" && /^sha256:[a-f0-9]{64}$/.test(value), nonempty = (value) => typeof value === "string" && value.trim().length > 0, pid = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0;+var digest9 = (value) => typeof value === "string" && /^sha256:[a-f0-9]{64}$/.test(value), nonempty = (value) => typeof value === "string" && value.trim().length > 0, pid = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0;var init_render_service_client = __esm(() => {init_build_identity();init_instance();@@ -54854,7 +55238,7 @@ var init_render_service_client = __esm(() => {// src/render-service-windows.tsimport { spawn as spawn2 } from "node:child_process";-import { join as join16 } from "node:path";+import { join as join17 } from "node:path";function powerShellLiteral(value) {return `'${value.replaceAll("'", "''")}'`;}@@ -54869,7 +55253,7 @@ function launchWindowsRenderService(executable, args, directory, env) {].join(``);const systemRoot = env.SystemRoot ?? env.SYSTEMROOT;- const powerShell = systemRoot ? join16(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe") : "powershell.exe";+ const powerShell = systemRoot ? join17(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe") : "powershell.exe";const child = spawn2(powerShell, ["-NoProfile","-NonInteractive",@@ -54920,7 +55304,7 @@ var init_render_service_windows = () => {};import { spawn as spawn3, spawnSync } from "node:child_process";import { existsSync as existsSync3 } from "node:fs";import { fileURLToPath as fileURLToPath7, pathToFileURL as pathToFileURL2 } from "node:url";-import { join as join17 } from "node:path";+import { join as join18 } from "node:path";function localRenderServicePort(env = process.env) {const raw = Number(env["KILN_RENDER_SERVICE_PORT"]);return Number.isInteger(raw) && raw > 0 && raw < 65536 ? raw : DEFAULT_LOCAL_RENDER_SERVICE_PORT;@@ -54938,18 +55322,18 @@ function namesLocalRenderService(url, env = process.env) {function renderServiceNodeArguments(dir) {return ["--import",- pathToFileURL2(join17(dir, "src/register-hooks.mjs")).href,- join17(dir, "src/server.mjs")+ pathToFileURL2(join18(dir, "src/register-hooks.mjs")).href,+ join18(dir, "src/server.mjs")];}function renderServiceDir() {return process.env["KILN_RENDER_SERVICE_DIR"] || fileURLToPath7(new URL("../render-service", import.meta.url));}function localRenderServiceState(dir = renderServiceDir()) {- if (!existsSync3(join17(dir, "src/server.mjs")) || !existsSync3(join17(dir, "package.json")))+ if (!existsSync3(join18(dir, "src/server.mjs")) || !existsSync3(join18(dir, "package.json")))return "not-packaged";try {- const anchor = pathToFileURL2(join17(dir, "src/server.mjs")).href;+ const anchor = pathToFileURL2(join18(dir, "src/server.mjs")).href;if (process.versions.bun) {const moduleUrl = new URL("../render-service/src/build-identity.mjs", import.meta.url).href;const result = spawnSync(nodeBinary(), [@@ -54980,7 +55364,7 @@ function explainRenderServiceState(state, dir) {return "renderer dependencies are missing; reinstall the official Kiln package with optional dependencies enabled";}function renderServiceSourceFingerprint(dir) {- const source = join17(dir, "src");+ const source = join18(dir, "src");return existsSync3(source) ? fingerprintSourceDir(source) : undefined;}async function inspectLocalRenderService(url, dir = renderServiceDir(), timeoutMs = 1500) {@@ -55371,7 +55755,7 @@ var init_cli_render_mode = __esm(() => {// src/workspace-cli.tsimport { open as open4 } from "node:fs/promises";-import { resolve as resolve12 } from "node:path";+import { resolve as resolve13 } from "node:path";function cliWorkspaceSelection(projectId, projectRevision, noProject = false) {if (noProject && (projectId !== undefined || projectRevision !== undefined))throw new Error("--no-project cannot be combined with --project or --project-revision.");@@ -55381,7 +55765,7 @@ function cliWorkspaceSelection(projectId, projectRevision, noProject = false) {});}async function readMaterialDependencies(path) {- const file = await open4(resolve12(path), "r");+ const file = await open4(resolve13(path), "r");try {const limit = 1024 * 1024;const info = await file.stat();@@ -55594,7 +55978,7 @@ var init_workspace_http = __esm(() => {// src/asset-viewer.tsimport { createServer } from "node:http";import { readFile as readFile11 } from "node:fs/promises";-import { dirname as dirname9, join as join18 } from "node:path";+import { dirname as dirname9, join as join19 } from "node:path";import { fileURLToPath as fileURLToPath8 } from "node:url";function quoted(value) {if (value === undefined)@@ -55607,7 +55991,7 @@ function refuse(res, message) {`);}async function startAssetViewer(library, options = {}) {- const staticDirectory = options.staticDirectory ?? (!import.meta.url.endsWith(".mjs") ? join18(dirname9(fileURLToPath8(import.meta.url)), "..", "dist", "viewer") : join18(dirname9(fileURLToPath8(import.meta.url)), "viewer"));+ const staticDirectory = options.staticDirectory ?? (!import.meta.url.endsWith(".mjs") ? join19(dirname9(fileURLToPath8(import.meta.url)), "..", "dist", "viewer") : join19(dirname9(fileURLToPath8(import.meta.url)), "viewer"));const server = createServer(async (req, res) => {res.setHeader("X-Content-Type-Options", "nosniff");res.setHeader("Referrer-Policy", "no-referrer");@@ -55677,7 +56061,7 @@ async function startAssetViewer(library, options = {}) {return;}res.setHeader("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' blob: data:; connect-src 'self' blob: data:; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'");- return send(await readFile11(join18(staticDirectory, file[0])), file[1]);+ return send(await readFile11(join19(staticDirectory, file[0])), file[1]);} catch (error) {res.statusCode = error instanceof WorkspaceHttpError ? error.status : error && typeof error === "object" && ("code" in error) && error.code === "PROJECT_CONFLICT" ? 409 : 400;send(JSON.stringify({ error: error instanceof Error ? error.message : "Asset unavailable" }));@@ -55747,9 +56131,9 @@ __export(exports_asset_cli, {assetMain: () => assetMain});import { readFile as readFile12, writeFile as writeFile8, stat as stat6, mkdir as mkdir9, rename as rename5 } from "node:fs/promises";-import { basename as basename2, resolve as resolve13, dirname as dirname10, isAbsolute as isAbsolute2 } from "node:path";+import { basename as basename2, resolve as resolve14, dirname as dirname10, isAbsolute as isAbsolute2 } from "node:path";import { randomUUID as randomUUID9 } from "node:crypto";-import { createHash as createHash20 } from "node:crypto";+import { createHash as createHash21 } from "node:crypto";async function assetMain(argv) {const command = argv[0];const positional = [];@@ -55790,7 +56174,7 @@ async function assetMain(argv) {const path = argv[++i];if (command !== "view" || !path || path.startsWith("--") || observeWorkspaces.length >= 32)throw new Error("view accepts up to 32 --observe-workspace directories");- observeWorkspaces.push(resolve13(path));+ observeWorkspaces.push(resolve14(path));continue;}if (arg === "--all") {@@ -55853,11 +56237,11 @@ async function assetMain(argv) {if (!name || !directory)throw new Error("collections add requires name and directory");assetIdSchema.parse(name);- assertCollectionRoot(name, isAbsolute2(directory) ? directory : resolve13(directory));+ assertCollectionRoot(name, isAbsolute2(directory) ? directory : resolve14(directory));const roots = Object.fromEntries(library.collections().map((c) => [c.id, library.directory(c.id)]));- if (roots[name] && roots[name] !== resolve13(directory))+ if (roots[name] && roots[name] !== resolve14(directory))throw new Error("Collection name already points to another directory");- roots[name] = resolve13(directory);+ roots[name] = resolve14(directory);const path = collectionConfigPath();await mkdir9(dirname10(path), { recursive: true });const temporary = `${path}.${randomUUID9()}.tmp`;@@ -55937,10 +56321,10 @@ async function assetMain(argv) {try {context.liveReview?.artifact(code, rendered);} catch {}- await writeNewDestinationsAtomic([{ path: resolve13(flags.out), data: rendered.glb }]);+ await writeNewDestinationsAtomic([{ path: resolve14(flags.out), data: rendered.glb }]);return {ok: true,- file: resolve13(flags.out),+ file: resolve14(flags.out),artifactGlbSha256: rendered.artifactGlbSha256,savedArtifactGlbSha256: record.manifest.files["asset.glb"].sha256,matchesSavedArtifact: rendered.artifactGlbSha256 === record.manifest.files["asset.glb"].sha256,@@ -56020,7 +56404,7 @@ async function assetMain(argv) {if (profile === "runtime") {if (format !== (gltfLayout ? "gltf" : "glb"))throw new Error(gltfLayout ? "--textures external writes gltf format" : "Runtime profile requires GLB format; use editable for source or bundle");- const destination = resolve13(flags.out);+ const destination = resolve14(flags.out);const extension = gltfLayout ? ".gltf" : ".glb";if (!destination.toLowerCase().endsWith(extension))throw new Error(`Runtime output must end in ${extension}`);@@ -56039,18 +56423,18 @@ async function assetMain(argv) {});if (output.profile !== "runtime")throw new Error("Expected runtime export");- const metadataPath = resolve13(dirname10(destination), output.metadata.name);+ const metadataPath = resolve14(dirname10(destination), output.metadata.name);drawGlb = output.glb;if (flags.ktx2)ktx2Receipt = JSON.parse(new TextDecoder().decode(output.metadata.bytes)).delivery?.ktx2;if (output.layout === "gltf") {const directory = dirname10(destination);const files = output.textures.map(({ uri, bytes }) => ({- path: resolve13(directory, ...uri.split("/")),+ path: resolve14(directory, ...uri.split("/")),data: bytes}));const buffers = output.buffers.map(({ uri, bytes }) => ({- path: resolve13(directory, uri),+ path: resolve14(directory, uri),data: bytes}));const published = await writeExternalTextureExport(files, [@@ -56075,7 +56459,7 @@ async function assetMain(argv) {const bytes = format === "bundle" ? await library.exportBundle([record]) : record.files[format === "glb" ? "asset.glb" : "source.kiln.js"];if (!bytes)throw new Error("Source unavailable");- const destination = resolve13(flags.out);+ const destination = resolve14(flags.out);await writeNewDestinationsAtomic([{ path: destination, data: bytes }]);written.push({ kind: format, path: destination, data: bytes });}@@ -56102,7 +56486,7 @@ async function assetMain(argv) {kind,path,bytes: data.byteLength,- sha256: `sha256:${createHash20("sha256").update(data).digest("hex")}`,+ sha256: `sha256:${createHash21("sha256").update(data).digest("hex")}`,...reused === undefined ? {} : { reused }}))}, null, 2));@@ -56129,7 +56513,7 @@ async function assetMain(argv) {if (file) {if ((await stat6(file)).isDirectory()) {await Promise.resolve().then(() => init_assets_node());- target = new FileAssetLibrary({ project: resolve13(file) });+ target = new FileAssetLibrary({ project: resolve14(file) });} elsestandalone = { name: basename2(file), bytes: await fileBytes(file) };}@@ -56148,7 +56532,7 @@ async function assetMain(argv) {const canonical = await realpath(path);if (canonical === currentRoot)continue;- const id = `w_${createHash20("sha256").update(canonical).digest("hex").slice(0, 16)}`;+ const id = `w_${createHash21("sha256").update(canonical).digest("hex").slice(0, 16)}`;reviewSources[id] = { label: basename2(canonical), review: new FileLiveReview(canonical) };}const viewer = await startAssetViewer(target, {@@ -56253,9 +56637,9 @@ __export(exports_project_cli, {projectMain: () => projectMain});import { open as open5 } from "node:fs/promises";-import { resolve as resolve14 } from "node:path";+import { resolve as resolve15 } from "node:path";async function inputFile(path, limit) {- const file = await open5(resolve14(path), "r");+ const file = await open5(resolve15(path), "r");try {const stat = await file.stat();if (!stat.isFile())@@ -56280,6 +56664,62 @@ async function inputFile(path, limit) {async function jsonFile(path, limit) {return JSON.parse((await inputFile(path, limit)).toString("utf8").replace(/^\uFEFF/, ""));}+async function exportMaterialMapsCommand(materials, positional, flags) {+ const integer = (name) => {+ const value = flags[name];+ if (value === undefined)+ return;+ if (!/^[0-9]+$/.test(value))+ throw new Error(`--${name} must be a whole number`);+ return Number(value);+ };+ const size = integer("size");+ if (size === undefined)+ throw new Error("material export --maps requires --size <px>");+ const repeat = flags.repeat;+ if (repeat !== undefined && !/^(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)$/.test(repeat))+ throw new Error("--repeat must be a decimal number of metres");+ const tiles = integer("tiles");+ validateMaterialMapExportOptions({+ size,+ ...repeat !== undefined ? { repeatMeters: Number(repeat) } : {},+ ...tiles !== undefined ? { tiles } : {}+ });+ const record = await materials.read(positional[0], positional[1]);+ const context = await buildRenderPort(resolveRenderMode(flags.render), undefined);+ const result = await exportMaterialMaps(record, {+ outDir: flags.maps,+ size,+ ...repeat !== undefined ? { repeatMeters: Number(repeat) } : {},+ ...tiles !== undefined ? { tiles } : {},+ ...context.viewRenderPort ? { viewRenderPort: context.viewRenderPort } : {},+ ...context.viewRenderTimeoutMs ? { viewRenderTimeoutMs: context.viewRenderTimeoutMs } : {},+ ...context.viewRenderRequired ? { viewRenderRequired: true } : {}+ });+ const { preview } = result.sidecar;+ return {+ materialId: result.sidecar.material.materialId,+ revisionId: result.sidecar.material.revisionId,+ directory: result.directory,+ sidecar: result.sidecarPath,+ files: result.files,+ size: result.sidecar.size,+ repeatMeters: result.sidecar.repeatMeters,+ maps: result.sidecar.maps.map(({ slot, file, colorSpace, method }) => ({+ slot,+ file,+ colorSpace,+ method+ })),+ preview: {+ file: result.previewPath,+ rendererId: preview.rendererId,+ materialFaithful: preview.viewFidelity.materialFaithful,+ delivered: preview.viewFidelity.delivered,+ ...preview.viewFidelity.degradeReason ? { degradeReason: preview.viewFidelity.degradeReason } : {}+ }+ };+}async function projectMain(argv) {const [family, action] = argv;if (argv.some((value) => value === "--help" || value === "-h")) {@@ -56304,7 +56744,7 @@ async function projectMain(argv) {"material:get": [],"material:procedural": ["file"],"material:import": ["file"],- "material:export": ["out"]+ "material:export": ["out", "maps", "size", "repeat", "tiles", "render"]};const flags = {};const positional = [];@@ -56337,7 +56777,7 @@ async function projectMain(argv) {if (profile !== "editable" && profile !== "runtime")throw new Error("Project profile must be editable or runtime");const bytes = await exportWorkspaceProjectBundle(workspace, localAssetLibrary(), positional[0], { revisionId: flags.revision, profile });- const path = resolve14(flags.out);+ const path = resolve15(flags.out);await writeNewDestinationsAtomic([{ path, data: bytes }]);console.log(JSON.stringify({ ok: true, profile, path, bytes: bytes.length }));return 0;@@ -56404,15 +56844,22 @@ async function projectMain(argv) {manifest,portableSpec: materialLibraryPortableSpec(manifest)};- else {+ else if (flags.maps !== undefined) {+ if (flags.out)+ throw new Error("Use --out or --maps, not both");+ output = await exportMaterialMapsCommand(materials, positional, flags);+ } else {+ for (const name of ["size", "repeat", "tiles", "render"])+ if (flags[name] !== undefined)+ throw new Error(`--${name} applies only to material export --maps`);if (!flags.out)- throw new Error("material export requires --out");+ throw new Error("material export requires --out or --maps");const records = await resolveMaterialRecordClosure([manifest], {readManifest: (id, revision) => materials.readManifest(id, revision),read: (id, revision) => materials.readRecordFiles(id, revision)});const payload = await createMaterialLibraryPayload(records);- const path = resolve14(flags.out);+ const path = resolve15(flags.out);await writeNewDestinationsAtomic([{ path, data: JSON.stringify(payload, null, 2) }]);output = {file: path,@@ -56453,6 +56900,8 @@ MATERIALSkiln material procedural --file <procedural-material-draft.json>kiln material import --file <portable-material-payload.json>kiln material export <id> <sha256:revision> --out <portable-material-payload.json>+ kiln material export <id> <sha256:revision> --maps <dir> --size <px> [--repeat <metres>]+ [--tiles <n>] [--render auto|cpu|gpu]Project changes create immutable revisions. Updates require the current expectedrevision; supplied top-level fields replace their previous values.@@ -56469,6 +56918,14 @@ Projects are optional. Authoring stays standalone unless --project or KILN_PROJEselects a project; --no-project overrides that configured default. Use --materialswith an array of exact resourceId/revisionId/sha256 pins for standalone materials.All commands return JSON; export refuses to overwrite an existing destination.++Material export --maps writes <id>.<slot>.png for each map at --size pixels square,+<id>.preview.png (the material on a lit plane repeated --tiles × --tiles, default 3)+and the <id>.maps.json sidecar: each map's slot, colour space, size, sha256 and how it+was produced. A V2 layer recipe is recompiled at a power-of-two size up to 1024; other+sizes resample with a wrapped Catmull-Rom filter. --repeat is the real-world edge of one+tile in metres; it defaults to a square recorded physical size. The sidecar records the+preview's renderer and viewFidelity: a CPU preview shows geometry, not material.`;var init_project_cli = __esm(() => {init_workspace_node();@@ -56478,6 +56935,8 @@ var init_project_cli = __esm(() => {init_material_library();init_material_library_node();init_material_authoring_node();+ init_material_map_export_node();+ init_cli_render_mode();init_cli_output();init_assets_node();init_project_bundle_node();@@ -56849,9 +57308,9 @@ __export(exports_animation_cli, {animationMain: () => animationMain});import { open as open6, readFile as readFile13 } from "node:fs/promises";-import { extname, resolve as resolve15 } from "node:path";+import { extname, resolve as resolve16 } from "node:path";async function readReviewJson(path, option) {- const file = await open6(resolve15(path), "r");+ const file = await open6(resolve16(path), "r");try {const limit = 1024 * 1024;const info = await file.stat();@@ -56972,7 +57431,7 @@ async function animationMain(argv) {...await buildRenderPort(args.render, args.renderPort),requirements});- const source = programRefPattern.test(args.source) ? { programRef: args.source } : { code: await readFile13(resolve15(args.source), "utf8") };+ const source = programRefPattern.test(args.source) ? { programRef: args.source } : { code: await readFile13(resolve16(args.source), "utf8") };const tool = createKilnProgramToolRegistry(context).find((t) => t.name === "kiln_screenshot_animation");let output;try {@@ -56998,7 +57457,7 @@ async function animationMain(argv) {const suffix = extname(args.views);const stem = suffix ? args.views.slice(0, -suffix.length) : args.views;const images = pngs.map((_, i) => ({- path: resolve15(separate ? `${stem}.frame-${String(i + 1).padStart(2, "0")}.png` : args.views),+ path: resolve16(separate ? `${stem}.frame-${String(i + 1).padStart(2, "0")}.png` : args.views),...separate ? { phase: output.frameTimes?.[i] } : {}}));const inputPaths = [@@ -57007,7 +57466,7 @@ async function animationMain(argv) {args.measureParts,args.requirements,args.materials- ].filter((p) => p !== undefined).map((p) => resolve15(p));+ ].filter((p) => p !== undefined).map((p) => resolve16(p));const samePath = (a, b) => process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;if (images.some((image) => inputPaths.some((path) => samePath(path, image.path))))throw new Error("Animation image destinations must differ from the input files.");@@ -57080,9 +57539,9 @@ __export(exports_edit_cli, {editMain: () => editMain});import { open as open7 } from "node:fs/promises";-import { resolve as resolve16 } from "node:path";+import { resolve as resolve17 } from "node:path";async function readEdits(path) {- const file = await open7(resolve16(path), "r");+ const file = await open7(resolve17(path), "r");try {const limit = 1024 * 1024;const info = await file.stat();@@ -57195,9 +57654,9 @@ __export(exports_inspect_cli, {inspectMain: () => inspectMain});import { open as open8, readFile as readFile14 } from "node:fs/promises";-import { resolve as resolve17 } from "node:path";+import { resolve as resolve18 } from "node:path";async function readControls(path) {- const file = await open8(resolve17(path), "r");+ const file = await open8(resolve18(path), "r");try {const limit = 1024 * 1024;const info = await file.stat();@@ -57282,7 +57741,7 @@ async function inspectMain(argv) {if (controls.image === false && args.views)throw new Error("--views cannot be combined with image:false.");if (args.views) {- const normalize = (path) => process.platform === "win32" ? resolve17(path).toLowerCase() : resolve17(path);+ const normalize = (path) => process.platform === "win32" ? resolve18(path).toLowerCase() : resolve18(path);if ([args.source, args.request, args.requirements, args.materials].some((path) => path && normalize(path) === normalize(args.views)))throw new Error("Inspection image destination must differ from the input files.");}@@ -57291,7 +57750,7 @@ async function inspectMain(argv) {...controls.image === false ? {} : await buildRenderPort(args.render, args.renderPort),requirements});- const source = programRefPattern.test(args.source) ? { programRef: args.source } : { code: await readFile14(resolve17(args.source), "utf8") };+ const source = programRefPattern.test(args.source) ? { programRef: args.source } : { code: await readFile14(resolve18(args.source), "utf8") };const tool = createKilnProgramToolRegistry(context).find((t) => t.name === "kiln_inspect");let output;try {@@ -57314,7 +57773,7 @@ async function inspectMain(argv) {const media = tool.media?.(output);if (!media && controls.image !== false)throw new Error("Inspection returned no image.");- const images = args.views ? [{ path: resolve17(args.views) }] : [];+ const images = args.views ? [{ path: resolve18(args.views) }] : [];if (args.views)await writeDestinationAtomic(args.views, media.png);if (args.json)@@ -57775,8 +58234,8 @@ __export(exports_migration_rebuild, {migrationRebuildMain: () => migrationRebuildMain});import { open as open9 } from "node:fs/promises";-import { createHash as createHash21 } from "node:crypto";-import { resolve as resolve18 } from "node:path";+import { createHash as createHash22 } from "node:crypto";+import { resolve as resolve19 } from "node:path";function parse6(argv) {if (argv.length === 1 && ["--help", "-h"].includes(argv[0]))return { help: true };@@ -57865,7 +58324,7 @@ async function rebuildLegacyAsset(context, input) {authority,original: structuredClone(record.manifest),...conversion.recoveredIntent ? { recoveredIntent: conversion.recoveredIntent } : {},- originalManifestCanonicalSha256: `sha256:${createHash21("sha256").update(canonical6(record.manifest)).digest("hex")}`,+ originalManifestCanonicalSha256: `sha256:${createHash22("sha256").update(canonical6(record.manifest)).digest("hex")}`,proposedRequirements: conversion.proposal.requirements,policyChanges: changes,ruleDispositions: resolved.filter((issue) => issue.code === "RULE_MIGRATION_UNQUALIFIED").map((issue) => ({@@ -57875,7 +58334,7 @@ async function rebuildLegacyAsset(context, input) {})),retainedBuildOptions: conversion.proposal.retainedBuildOptions,sourceChanged: code !== originalCode,- rebuiltSourceSha256: `sha256:${createHash21("sha256").update(code, "utf8").digest("hex")}`+ rebuiltSourceSha256: `sha256:${createHash22("sha256").update(code, "utf8").digest("hex")}`};const draft = await buildProgramAssetDraft(code, currentContext, record.manifest.preview?.backdrop);const asset = await library.save(input.collection, {@@ -57901,7 +58360,7 @@ async function rebuildLegacyAsset(context, input) {};}async function readMigrationText(path, option) {- const file = await open9(resolve18(path), "r");+ const file = await open9(resolve19(path), "r");try {const info = await file.stat();if (!info.isFile() || info.size > 1024 * 1024)@@ -57987,8 +58446,8 @@ __export(exports_migration_cli, {migrationMain: () => migrationMain});import { open as open10 } from "node:fs/promises";-import { resolve as resolve19 } from "node:path";-import { createHash as createHash22 } from "node:crypto";+import { resolve as resolve20 } from "node:path";+import { createHash as createHash23 } from "node:crypto";function parse7(argv) {if (argv.length === 1 && ["--help", "-h"].includes(argv[0]))return { help: true };@@ -58023,7 +58482,7 @@ async function migrationMain(argv) {}try {const limit = 1048576;- const path = resolve19(args.input);+ const path = resolve20(args.input);const file = await open10(path, "r");let bytes;try {@@ -58057,14 +58516,14 @@ async function migrationMain(argv) {input: {path,bytes: bytes.length,- sha256: `sha256:${createHash22("sha256").update(bytes).digest("hex")}`+ sha256: `sha256:${createHash23("sha256").update(bytes).digest("hex")}`},conversion};const json = `${JSON.stringify(receipt, null, 2)}`;if (args.out)- await writeNewDestinationsAtomic([{ path: resolve19(args.out), data: json }]);+ await writeNewDestinationsAtomic([{ path: resolve20(args.out), data: json }]);console.log(json.trimEnd());console.error("Migration not activated. Review the proposed changes and every unresolved obligation in docs/migration.md.");return conversion.status === "invalid" ? 1 : 3;diff --git a/dist/evaluator-worker.mjs b/dist/evaluator-worker.mjsindex 9ecfa047..7239d519 100644--- a/dist/evaluator-worker.mjs+++ b/dist/evaluator-worker.mjs@@ -32674,9 +32674,36 @@ var init_material_library = __esm(() => {]);});+// src/cli-output.ts+var init_cli_output = () => {};++// src/material-map-export-node.ts+import sharp from "sharp";+import * as THREE53 from "three";+var MATERIAL_MAP_EXPORT_LIMITS, PREVIEW_CAMERA, SRGB_TO_LINEAR;+var init_material_map_export_node = __esm(() => {+ init_cli_output();+ init_material_library();+ init_procedural_texture();+ init_textures();+ MATERIAL_MAP_EXPORT_LIMITS = Object.freeze({+ minSize: 4,+ maxSize: MATERIAL_LIBRARY_LIMITS.maxMapEdge,+ maxRepeatMeters: 1e5,+ defaultTiles: 3,+ maxTiles: 8,+ maxPreviewMapSize: 1024+ });+ PREVIEW_CAMERA = Object.freeze({ azimuthDeg: 30, elevationDeg: 50 });+ SRGB_TO_LINEAR = Float64Array.from({ length: 256 }, (_, value) => {+ const c = value / 255;+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;+ });+});+// src/material-library-node.tsimport { createHash as createHash6, randomUUID } from "node:crypto";-import sharp from "sharp";+import sharp2 from "sharp";import { DataTexture as DataTexture4 } from "three";function revisionHash(manifest) {const { revisionId: _, ...content } = manifest;@@ -32721,7 +32748,7 @@ async function verifyMaterialRecordV1(record) {const bytes = record.files[map.file];if (digest(bytes) !== map.sha256)throw new Error(`Material integrity hash mismatch: ${map.file}`);- const { data, info } = await sharp(bytes, {+ const { data, info } = await sharp2(bytes, {limitInputPixels: MATERIAL_LIBRARY_LIMITS.maxRecordPixels,failOn: "warning"}).ensureAlpha().raw().toBuffer({ resolveWithObject: true });@@ -33022,7 +33049,7 @@ function createPinnedMaterialMapPort(records) {const descriptor = describe(resourceId, pin), entry = find(resourceId, pin);if (!descriptor || !entry)throw new Error("Missing verified pinned-library map; approved resources cannot be atlas sources");- const { data, info } = await sharp(entry.record.files[entry.map.file], {+ const { data, info } = await sharp2(entry.record.files[entry.map.file], {limitInputPixels: MATERIAL_LIBRARY_LIMITS.maxRecordPixels,failOn: "warning"}).ensureAlpha().raw().toBuffer({ resolveWithObject: true });@@ -33049,7 +33076,7 @@ async function verifyMaterialRecordContents(record, options) {const bytes = record.files[map.file];if (digest(bytes) !== map.sha256)throw new Error("Material integrity hash mismatch");- const { data, info } = await sharp(bytes, {+ const { data, info } = await sharp2(bytes, {limitInputPixels: MATERIAL_LIBRARY_LIMITS.maxRecordPixels,failOn: "warning"}).ensureAlpha().raw().toBuffer({ resolveWithObject: true });@@ -33207,7 +33234,8 @@ var init_material_library_node = __esm(() => {init_textures();init_texture_resolver();init_procedural_material_v3();- encoder = { name: "sharp", version: sharp.versions.sharp };+ init_material_map_export_node();+ encoder = { name: "sharp", version: sharp2.versions.sharp };});// src/evaluator/protocol.ts@@ -33409,7 +33437,7 @@ var init_renderer_id = __esm(() => {});// src/views/scene-raster.ts-import * as THREE53 from "three";+import * as THREE54 from "three";var DEG2;var init_scene_raster = __esm(() => {init_evaluator();@@ -33421,18 +33449,18 @@ var init_scene_raster = __esm(() => {});// src/views/vehicle.ts-import * as THREE54 from "three";+import * as THREE55 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 THREE54.Box3;+ const bounds = new THREE55.Box3;let found = false;root.traverse((node) => {if (!hasRole2(node, "chassis"))return;node.traverse((part) => {- if (!(part instanceof THREE54.Mesh) || !(part.geometry instanceof THREE54.BufferGeometry))+ if (!(part instanceof THREE55.Mesh) || !(part.geometry instanceof THREE55.BufferGeometry))return;part.geometry.computeBoundingBox();const box = part.geometry.boundingBox;@@ -33442,7 +33470,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 THREE54.Vector3(x, y, z).applyMatrix4(matrix));+ bounds.expandByPoint(new THREE55.Vector3(x, y, z).applyMatrix4(matrix));found = true;}});@@ -33510,33 +33538,33 @@ function tagDiagnostic(node, role) {stampSemanticMetadataV1(node, { roles: [role] });}function rod(name, start, end, radius, color, role) {- const from = new THREE54.Vector3(...start);- const to = new THREE54.Vector3(...end);+ const from = new THREE55.Vector3(...start);+ const to = new THREE55.Vector3(...end);const direction = to.clone().sub(from);const length = direction.length();- const geometry = length > 0.000000001 ? new THREE54.CylinderGeometry(radius, radius, length, 8) : new THREE54.SphereGeometry(radius, 8, 6);- const result = new THREE54.Mesh(geometry, new THREE54.MeshBasicMaterial({ color }));+ const geometry = length > 0.000000001 ? new THREE55.CylinderGeometry(radius, radius, length, 8) : new THREE55.SphereGeometry(radius, 8, 6);+ const result = new THREE55.Mesh(geometry, new THREE55.MeshBasicMaterial({ color }));result.name = name;result.position.copy(from).add(to).multiplyScalar(0.5);if (length > 0.000000001) {- result.quaternion.setFromUnitVectors(new THREE54.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));+ result.quaternion.setFromUnitVectors(new THREE55.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));}tagDiagnostic(result, role);return result;}function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnostics(root)) {- const overlay = new THREE54.Group;+ const overlay = new THREE55.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 THREE54.Group;+ const arrow = new THREE55.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 THREE54.Mesh(new THREE54.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE54.MeshBasicMaterial({ color: 16724804 }));+ const arrowHead = new THREE55.Mesh(new THREE55.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE55.MeshBasicMaterial({ color: 16724804 }));arrowHead.name = "Diagnostic_Forward_Head";arrowHead.position.set(descriptor.forwardArrow.end[0] - 0.12, 0, 0);- arrowHead.quaternion.setFromUnitVectors(new THREE54.Vector3(0, 1, 0), new THREE54.Vector3(1, 0, 0));+ arrowHead.quaternion.setFromUnitVectors(new THREE55.Vector3(0, 1, 0), new THREE55.Vector3(1, 0, 0));tagDiagnostic(arrowHead, "diagnostic.vehicle.forward");arrow.add(arrowHead);overlay.add(arrow);@@ -33544,18 +33572,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 THREE54.Mesh(new THREE54.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE54.MeshBasicMaterial({ color: 16763955 }));+ const ring = new THREE55.Mesh(new THREE55.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE55.MeshBasicMaterial({ color: 16763955 }));ring.name = `Diagnostic_Wheel_${wheel.id}`;ring.position.set(...wheel.center);- const axle = new THREE54.Vector3(...wheel.axle);+ const axle = new THREE55.Vector3(...wheel.axle);if (axle.lengthSq() > 0.000000000001) {- ring.quaternion.setFromUnitVectors(new THREE54.Vector3(0, 0, 1), axle.normalize());+ ring.quaternion.setFromUnitVectors(new THREE55.Vector3(0, 0, 1), axle.normalize());}tagDiagnostic(ring, `diagnostic.vehicle.wheel.${wheel.id}`);overlay.add(ring);}if (descriptor.chassisBox) {- const chassis = new THREE54.Group;+ const chassis = new THREE55.Group;chassis.name = "Diagnostic_ChassisBox";tagDiagnostic(chassis, "diagnostic.vehicle.chassis");const { min, max } = descriptor.chassisBox;@@ -33589,7 +33617,7 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnooverlay.add(chassis);}if (descriptor.supportPlaneY !== undefined) {- const plane = new THREE54.Group;+ const plane = new THREE55.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;@@ -33918,7 +33946,7 @@ var init_views = __esm(() => {});// src/views/character-capture.ts-import * as THREE55 from "three";+import * as THREE56 from "three";function drawLine2(rgb, width, height, from, to, color) {let x0 = Math.round(from[0]);let y0 = Math.round(from[1]);@@ -33955,22 +33983,22 @@ function drawCross(rgb, width, height, point, color, radius = 3) {}function projector(root, cameraId, size) {root.updateMatrixWorld(true);- const bounds = new THREE55.Box3().setFromObject(root);+ const bounds = new THREE56.Box3().setFromObject(root);if (bounds.isEmpty())- bounds.set(new THREE55.Vector3(-0.5, 0, -0.5), new THREE55.Vector3(0.5, 1, 0.5));- const center = bounds.getCenter(new THREE55.Vector3);- const camera = cameraId === "front" ? new THREE55.Vector3(1, 0, 0) : new THREE55.Vector3(0, 0, 1);- const upHint = new THREE55.Vector3(0, 1, 0);- const xAxis = new THREE55.Vector3().crossVectors(upHint, camera).normalize();- const yAxis = new THREE55.Vector3().crossVectors(camera, xAxis).normalize();+ bounds.set(new THREE56.Vector3(-0.5, 0, -0.5), new THREE56.Vector3(0.5, 1, 0.5));+ const center = bounds.getCenter(new THREE56.Vector3);+ const camera = cameraId === "front" ? new THREE56.Vector3(1, 0, 0) : new THREE56.Vector3(0, 0, 1);+ const upHint = new THREE56.Vector3(0, 1, 0);+ const xAxis = new THREE56.Vector3().crossVectors(upHint, camera).normalize();+ const yAxis = new THREE56.Vector3().crossVectors(camera, xAxis).normalize();let extent = 0.000001;for (let corner = 0;corner < 8; corner++) {- const point = new THREE55.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 THREE56.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 THREE55.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);+ const world = new THREE56.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);return [size / 2 + world.dot(xAxis) * scale, size / 2 - world.dot(yAxis) * scale];};}@@ -34096,7 +34124,7 @@ var init_character_capture = __esm(() => {});// src/render.ts-import * as THREE56 from "three";+import * as THREE57 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";@@ -34323,7 +34351,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache, authorExtras, atlas)} else if (stdMat.transparent) {mat.setAlphaMode("BLEND");}- if (stdMat.side === THREE56.DoubleSide) {+ if (stdMat.side === THREE57.DoubleSide) {mat.setDoubleSided(true);}if (stdMat.map) {@@ -34400,7 +34428,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache, authorExtras, atlas)} else if (common.transparent || (common.opacity ?? 1) < 1) {mat.setAlphaMode("BLEND");}- if (threeMat.side === THREE56.DoubleSide)+ if (threeMat.side === THREE57.DoubleSide)mat.setDoubleSided(true);if (common.map && !mat.getBaseColorTexture()) {const texture = bridgeTexture(doc, common.map, textureCache);@@ -34563,7 +34591,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 THREE56.PlaneGeometry(1, 1);+ const geometry = new THREE57.PlaneGeometry(1, 1);if (centerX !== 0.5 || centerY !== 0.5) {geometry.translate(0.5 - centerX, 0.5 - centerY, 0);}@@ -34587,9 +34615,9 @@ function animationInterpolation(track) {if (isCubicSplineTrack(track))return "CUBICSPLINE";const mode = track.getInterpolation();- if (mode === THREE56.InterpolateDiscrete)+ if (mode === THREE57.InterpolateDiscrete)return "STEP";- if (mode === THREE56.InterpolateLinear)+ if (mode === THREE57.InterpolateLinear)return "LINEAR";throw new Error(`Unsupported animation interpolation on ${track.name}; use LINEAR, STEP or CUBICSPLINE.`);}@@ -35154,8 +35182,8 @@ function collectMeshStats(root) {if (!Number.isFinite(box.min.x) || !Number.isFinite(box.max.x)) {return;}- const center = new THREE56.Vector3;- const size = new THREE56.Vector3;+ const center = new THREE57.Vector3;+ const size = new THREE57.Vector3;box.getCenter(center);box.getSize(size);out.push({@@ -35171,7 +35199,7 @@ function collectMeshStats(root) {return out;}function minimalGapVector(a, b) {- const v = new THREE56.Vector3;+ const v = new THREE57.Vector3;for (const axis of ["x", "y", "z"]) {if (a.min[axis] > b.max[axis])v[axis] = b.max[axis] - a.min[axis];@@ -35189,10 +35217,10 @@ function inspectSceneStructure(root, opts = {}) {return warnings;const cat = opts.category?.toLowerCase();if (cat === "vehicle" || cat === "weapon" || cat === "boat" || cat === "aircraft") {- const all = new THREE56.Box3;+ const all = new THREE57.Box3;for (const m of meshes)all.union(m.box);- const size = new THREE56.Vector3;+ const size = new THREE57.Vector3;all.getSize(size);if (cat === "aircraft") {if (size.y > size.x * 1.2) {@@ -35317,18 +35345,18 @@ var init_render = __esm(() => {engineIO = createGltfIO;ACCESSOR_TYPES = [TYPE_SCALAR, TYPE_VEC2, TYPE_VEC3, TYPE_VEC4];GLTF_MIN_FILTER = {- [THREE56.NearestFilter]: 9728,- [THREE56.LinearFilter]: 9729,- [THREE56.NearestMipmapNearestFilter]: 9984,- [THREE56.LinearMipmapNearestFilter]: 9985,- [THREE56.NearestMipmapLinearFilter]: 9986,- [THREE56.LinearMipmapLinearFilter]: 9987- };- GLTF_MAG_FILTER = { [THREE56.NearestFilter]: 9728, [THREE56.LinearFilter]: 9729 };+ [THREE57.NearestFilter]: 9728,+ [THREE57.LinearFilter]: 9729,+ [THREE57.NearestMipmapNearestFilter]: 9984,+ [THREE57.LinearMipmapNearestFilter]: 9985,+ [THREE57.NearestMipmapLinearFilter]: 9986,+ [THREE57.LinearMipmapLinearFilter]: 9987+ };+ GLTF_MAG_FILTER = { [THREE57.NearestFilter]: 9728, [THREE57.LinearFilter]: 9729 };GLTF_WRAP = {- [THREE56.ClampToEdgeWrapping]: 33071,- [THREE56.MirroredRepeatWrapping]: 33648,- [THREE56.RepeatWrapping]: 10497+ [THREE57.ClampToEdgeWrapping]: 33071,+ [THREE57.MirroredRepeatWrapping]: 33648,+ [THREE57.RepeatWrapping]: 10497};REVIEW_CLIP_LIMITS = {clips: 32,diff --git a/dist/mcp-engine.mjs b/dist/mcp-engine.mjsindex d49388be..d0952abf 100644--- a/dist/mcp-engine.mjs+++ b/dist/mcp-engine.mjs@@ -5799,11 +5799,103 @@ var init_procedural_material_v3 = __esm(() => {};});-// src/material-library-node.ts+// src/cli-output.tsimport { createHash as createHash2, randomUUID } from "node:crypto";-import { lstat as lstat2, mkdir, readFile, readdir, realpath, rm, writeFile } from "node:fs/promises";-import { dirname as dirname2, join as join2, relative, resolve as resolve2, sep } from "node:path";+import {+ chmod,+ lstat as lstat2,+ link,+ mkdir,+ open,+ readFile,+ realpath,+ rename as rename2,+ stat,+ unlink,+ writeFile+} from "node:fs/promises";+import { basename, dirname as dirname2, join as join2, resolve as resolve2 } from "node:path";+async function prepareDestination(path) {+ await mkdir(dirname2(path), { recursive: true });+ return path;+}+async function writeNewDestinationsAtomic(outputs) {+ const paths = outputs.map(({ path }) => {+ const absolute = resolve2(path);+ return process.platform === "win32" ? absolute.toLowerCase() : absolute;+ });+ if (new Set(paths).size !== paths.length)+ throw new Error("Export destinations must be distinct");+ const staged = [];+ try {+ for (const { path, data } of outputs) {+ await prepareDestination(path);+ const temporary = join2(dirname2(path), `.kiln-write-${randomUUID()}.tmp`);+ const file = await open(temporary, "wx");+ staged.push({ path, temporary, published: false });+ try {+ await writeFile(file, data);+ } finally {+ await file.close();+ }+ }+ for (const output of staged) {+ try {+ await link(output.temporary, output.path);+ } catch (error) {+ if (error.code !== "EEXIST")+ throw error;+ throw Object.assign(new Error(`${output.path} already exists and is never replaced; choose a new output path or remove the file.`), { code: "EEXIST" });+ }+ output.published = true;+ }+ } catch (error) {+ for (const output of staged.filter((item) => item.published).reverse()) {+ try {+ const [destination, temporary] = await Promise.all([+ lstat2(output.path),+ lstat2(output.temporary)+ ]);+ if (destination.dev === temporary.dev && destination.ino === temporary.ino)+ await unlink(output.path);+ } catch {}+ }+ throw error;+ } finally {+ await Promise.all(staged.map(({ temporary }) => unlink(temporary).catch(() => {})));+ }+}+var init_cli_output = () => {};++// src/material-map-export-node.tsimport sharp from "sharp";+import * as THREE4 from "three";+var MATERIAL_MAP_EXPORT_LIMITS, PREVIEW_CAMERA, SRGB_TO_LINEAR;+var init_material_map_export_node = __esm(() => {+ init_cli_output();+ init_material_library();+ init_procedural_texture();+ init_textures();+ MATERIAL_MAP_EXPORT_LIMITS = Object.freeze({+ minSize: 4,+ maxSize: MATERIAL_LIBRARY_LIMITS.maxMapEdge,+ maxRepeatMeters: 1e5,+ defaultTiles: 3,+ maxTiles: 8,+ maxPreviewMapSize: 1024+ });+ PREVIEW_CAMERA = Object.freeze({ azimuthDeg: 30, elevationDeg: 50 });+ SRGB_TO_LINEAR = Float64Array.from({ length: 256 }, (_, value) => {+ const c = value / 255;+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;+ });+});++// src/material-library-node.ts+import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";+import { lstat as lstat3, mkdir as mkdir2, readFile as readFile2, readdir, realpath as realpath2, rm, writeFile as writeFile2 } from "node:fs/promises";+import { dirname as dirname3, join as join3, relative, resolve as resolve3, sep } from "node:path";+import sharp2 from "sharp";import { DataTexture as DataTexture3 } from "three";function revisionHash(manifest) {const { revisionId: _, ...content } = manifest;@@ -5883,7 +5975,7 @@ async function createMaterialRecordV1(draft) {const compiled = materialPixels(input.procedural, input.derive);if (compiled.spec.usage !== MATERIAL_LIBRARY_USAGE[input.slot])throw new Error("Procedural map usage mismatch");- bytes = new Uint8Array(await sharp(compiled.pixels, {+ bytes = new Uint8Array(await sharp2(compiled.pixels, {raw: { width: compiled.spec.size, height: compiled.spec.size, channels: 4 }}).png({ compressionLevel: 9, adaptiveFiltering: false }).toBuffer());procedural = {@@ -5954,7 +6046,7 @@ async function verifyMaterialRecordV1(record) {const bytes = record.files[map.file];if (digest(bytes) !== map.sha256)throw new Error(`Material integrity hash mismatch: ${map.file}`);- const { data, info } = await sharp(bytes, {+ const { data, info } = await sharp2(bytes, {limitInputPixels: MATERIAL_LIBRARY_LIMITS.maxRecordPixels,failOn: "warning"}).ensureAlpha().raw().toBuffer({ resolveWithObject: true });@@ -6111,21 +6203,21 @@ async function createMaterialLibraryTextureResolver(records, fallback = DEFAULT_class FileMaterialLibrary {root;constructor(root) {- this.root = resolve2(root);+ this.root = resolve3(root);}async path(...parts) {- await mkdir(this.root, { recursive: true });- const canonical = await realpath(this.root);+ await mkdir2(this.root, { recursive: true });+ const canonical = await realpath2(this.root);let current = canonical;for (const part of parts) {if (!/^[a-z0-9][a-z0-9_-]{0,79}$/.test(part))throw new Error("Invalid material path identity");- current = join2(current, part);+ current = join3(current, part);try {- const stat = await lstat2(current);+ const stat = await lstat3(current);if (stat.isSymbolicLink() || !stat.isDirectory())throw new Error("Material library requires real directories");- const rel = relative(canonical, await realpath(current));+ const rel = relative(canonical, await realpath2(current));if (rel === ".." || rel.startsWith(`..${sep}`))throw new Error("Material path escapes library");} catch (error) {@@ -6136,11 +6228,11 @@ class FileMaterialLibrary {return current;}async file(dir, name, limit) {- const path = join2(dir, name);- const stat = await lstat2(path);+ const path = join3(dir, name);+ const stat = await lstat3(path);if (!stat.isFile() || stat.isSymbolicLink() || stat.size > limit)throw new Error("Invalid material library file");- return new Uint8Array(await readFile(path));+ return new Uint8Array(await readFile2(path));}async readManifest(materialId, revisionId) {materialLibraryIdSchema.parse(materialId);@@ -6215,14 +6307,14 @@ class FileMaterialLibrary {for (const record of snapshots) {const { manifest, files } = record;const dest = await this.path(manifest.materialId, manifest.revisionId.slice(7));- const parent = dirname2(dest);- await mkdir(parent, { recursive: true });- const stage = join2(parent, `.stage-${randomUUID()}`);- await mkdir(stage);+ const parent = dirname3(dest);+ await mkdir2(parent, { recursive: true });+ const stage = join3(parent, `.stage-${randomUUID2()}`);+ await mkdir2(stage);try {for (const [name, bytes] of Object.entries(files))- await writeFile(join2(stage, name), bytes, { flag: "wx" });- await writeFile(join2(stage, "manifest.json"), canonicalMaterialJson(manifest), {+ await writeFile2(join3(stage, name), bytes, { flag: "wx" });+ await writeFile2(join3(stage, "manifest.json"), canonicalMaterialJson(manifest), {flag: "wx"});try {@@ -6235,7 +6327,7 @@ class FileMaterialLibrary {throw error;}} finally {- const rel = relative(parent, resolve2(stage));+ const rel = relative(parent, resolve3(stage));if (rel.startsWith(".stage-") && !rel.includes(sep))await rm(stage, { recursive: true, force: true });}@@ -6391,7 +6483,7 @@ function createPinnedMaterialMapPort(records) {const descriptor = describe(resourceId, pin), entry = find(resourceId, pin);if (!descriptor || !entry)throw new Error("Missing verified pinned-library map; approved resources cannot be atlas sources");- const { data, info } = await sharp(entry.record.files[entry.map.file], {+ const { data, info } = await sharp2(entry.record.files[entry.map.file], {limitInputPixels: MATERIAL_LIBRARY_LIMITS.maxRecordPixels,failOn: "warning"}).ensureAlpha().raw().toBuffer({ resolveWithObject: true });@@ -6418,7 +6510,7 @@ async function verifyMaterialRecordContents(record, options) {const bytes = record.files[map.file];if (digest(bytes) !== map.sha256)throw new Error("Material integrity hash mismatch");- const { data, info } = await sharp(bytes, {+ const { data, info } = await sharp2(bytes, {limitInputPixels: MATERIAL_LIBRARY_LIMITS.maxRecordPixels,failOn: "warning"}).ensureAlpha().raw().toBuffer({ resolveWithObject: true });@@ -6674,7 +6766,7 @@ async function createMaterialRecordV2(draft, options) {const compiled = spec.schemaVersion === 3 ? materialPixelsV3(spec, derive) : materialPixels(spec, derive);const d = compiled.spec.schemaVersion === 3 ? { width: compiled.spec.width, height: compiled.spec.height } : { width: compiled.spec.size, height: compiled.spec.size };pixelHash = digest(compiled.pixels);- bytes = new Uint8Array(await sharp(compiled.pixels, { raw: { ...d, channels: 4 } }).png({ compressionLevel: 9, adaptiveFiltering: false }).toBuffer());+ bytes = new Uint8Array(await sharp2(compiled.pixels, { raw: { ...d, channels: 4 } }).png({ compressionLevel: 9, adaptiveFiltering: false }).toBuffer());recipe = {kind: "procedural",compilerId: compiled.spec.schemaVersion === 3 ? PROCEDURAL_TEXTURE_V3_COMPILER_ID : "kiln.procedural-texture.v2",@@ -6689,7 +6781,7 @@ async function createMaterialRecordV2(draft, options) {} else if (item.atlas !== undefined) {const compiled = await compileTextureAtlasSpecV1(item.atlas, { resources });pixelHash = compiled.manifest.decodedPixelHash;- bytes = new Uint8Array(await sharp(compiled.pixels, {+ bytes = new Uint8Array(await sharp2(compiled.pixels, {raw: { width: compiled.spec.width, height: compiled.spec.height, channels: 4 }}).png({ compressionLevel: 9, adaptiveFiltering: false }).toBuffer());recipe = {@@ -6704,7 +6796,7 @@ async function createMaterialRecordV2(draft, options) {pins.set(`${r.source.pin.resourceId}/${r.source.pin.revisionId}`, r.source.pin);} else {bytes = item.bytes.slice();- const decoded = await sharp(bytes, {+ const decoded = await sharp2(bytes, {limitInputPixels: MATERIAL_LIBRARY_LIMITS.maxRecordPixels,failOn: "warning"}).ensureAlpha().raw().toBuffer();@@ -6750,7 +6842,7 @@ async function createMaterialRecordV2(draft, options) {await verifyMaterialRecord(record, { materials: [...records, record] });return record;}-var digest = (bytes) => `sha256:${createHash2("sha256").update(bytes).digest("hex")}`, encoder, normalDerivationBudget = (texels) => ({ work: texels * 16, allocation: texels * 8 }), identity = (manifest) => `${manifest.materialId}/${manifest.revisionId}`;+var digest = (bytes) => `sha256:${createHash3("sha256").update(bytes).digest("hex")}`, encoder, normalDerivationBudget = (texels) => ({ work: texels * 16, allocation: texels * 8 }), identity = (manifest) => `${manifest.materialId}/${manifest.revisionId}`;var init_material_library_node = __esm(() => {init_atomic_directory();init_material_library();@@ -6764,7 +6856,8 @@ var init_material_library_node = __esm(() => {init_textures();init_texture_resolver();init_procedural_material_v3();- encoder = { name: "sharp", version: sharp.versions.sharp };+ init_material_map_export_node();+ encoder = { name: "sharp", version: sharp2.versions.sharp };});// src/runtime-textures.ts@@ -7942,7 +8035,7 @@ var init_geometry_budget = __esm(() => {});// src/delivery.ts-import * as THREE4 from "three";+import * as THREE5 from "three";import { ConvexGeometry } from "three/addons/geometries/ConvexGeometry.js";function fail3(helper, detail) {throw new AuthoringDiagnosticError("DELIVERY_CONTRACT", `${helper}: ${detail}`);@@ -7970,7 +8063,7 @@ function place(helper, node, options) {node.position.set(...triple(helper, "position", options.position));if (options.rotation !== undefined) {const [x, y, z] = triple(helper, "rotation", options.rotation);- node.rotation.set(THREE4.MathUtils.degToRad(x), THREE4.MathUtils.degToRad(y), THREE4.MathUtils.degToRad(z));+ node.rotation.set(THREE5.MathUtils.degToRad(x), THREE5.MathUtils.degToRad(y), THREE5.MathUtils.degToRad(z));}if (options.parent !== undefined) {if (!isObject3D(options.parent))@@ -7999,10 +8092,10 @@ function addSemanticRoles(node, roles) {});}function proxyMaterial() {- return new THREE4.MeshBasicMaterial({ name: COLLIDER_PROXY_MATERIAL_NAME, color: 16711935 });+ return new THREE5.MeshBasicMaterial({ name: COLLIDER_PROXY_MATERIAL_NAME, color: 16711935 });}function proxy(shape, id, geometry) {- const mesh = new THREE4.Mesh(geometry, proxyMaterial());+ const mesh = new THREE5.Mesh(geometry, proxyMaterial());mesh.name = `Collider_${shape}_${id}`;mesh.visible = false;addSemanticRoles(mesh, [@@ -8017,7 +8110,7 @@ function colliderBox(size, opts) {const dims = typeof size === "number" ? [size, size, size] : triple(helper, "size", size).map((value) => value);for (const [index, value] of dims.entries())finitePositive2(helper, `size[${index}]`, value);- const mesh = proxy("box", id, new THREE4.BoxGeometry(1, 1, 1));+ const mesh = proxy("box", id, new THREE5.BoxGeometry(1, 1, 1));mesh.scale.set(dims[0], dims[1], dims[2]);place(helper, mesh, settings);return mesh;@@ -8030,7 +8123,7 @@ function colliderCapsule(radius, height, opts) {finitePositive2(helper, "height", height);if (height < 2 * radius)fail3(helper, `height is the total height including both caps and must be at least 2 * radius (${2 * radius}), got ${height}.`);- const geometry = new THREE4.CapsuleGeometry(radius, height - 2 * radius, 4, 12);+ const geometry = new THREE5.CapsuleGeometry(radius, height - 2 * radius, 4, 12);geometry.scale(1 / (2 * radius), 1 / height, 1 / (2 * radius));const mesh = proxy("capsule", id, geometry);mesh.scale.set(2 * radius, height, 2 * radius);@@ -8049,7 +8142,7 @@ function colliderHull(mesh, opts) {fail3(helper, `mesh has ${position.count} vertices; a hull proxy reads at most ${GEOMETRY_ALLOCATION_LIMITS.colliderHullVertices}.`);const points = [];for (let i = 0;i < position.count; i++)- points.push(new THREE4.Vector3().fromBufferAttribute(position, i));+ points.push(new THREE5.Vector3().fromBufferAttribute(position, i));let geometry;try {geometry = new ConvexGeometry(points);@@ -8075,7 +8168,7 @@ function anchor(kind, id, opts) {const settings = options(helper, opts);const kindSegment = segment(helper, "kind", kind);const idSegment = segment(helper, "id", id);- const node = new THREE4.Object3D;+ const node = new THREE5.Object3D;node.name = `Anchor_${kindSegment}_${idSegment}`;node.visible = false;addSemanticRoles(node, [semanticRole(KILN_SEMANTIC_ROLES.anchor, kindSegment, idSegment)]);@@ -8119,7 +8212,7 @@ function port(id, opts) {const helper = "port(id, opts?)";const settings = options(helper, opts);const idSegment = segment(helper, "id", id);- const node = new THREE4.Object3D;+ const node = new THREE5.Object3D;node.name = `Port_${idSegment}`;addSemanticRoles(node, [semanticRole(KILN_SEMANTIC_ROLES.kitPort, idSegment)]);place(helper, node, settings);@@ -8487,7 +8580,7 @@ function writtenNodeResolver(root, doc, purpose) {// src/node-visibility.tsimport { KHRNodeVisibility } from "@gltf-transform/extensions";-import * as THREE5 from "three";+import * as THREE6 from "three";function applyNodeVisibility(root, doc) {const hidden = [];root.traverse((node) => {@@ -8530,7 +8623,7 @@ function drawnSceneBounds(scene) {return;const mesh = node.getMesh();if (mesh) {- const base = new THREE5.Matrix4().fromArray(node.getWorldMatrix());+ const base = new THREE6.Matrix4().fromArray(node.getWorldMatrix());const instances = node.getExtension("EXT_mesh_gpu_instancing");const translation = instances?.getAttribute("TRANSLATION");const rotation = instances?.getAttribute("ROTATION");@@ -8541,7 +8634,7 @@ function drawnSceneBounds(scene) {const t = translation?.getElement(i, []) ?? [0, 0, 0];const r = rotation?.getElement(i, []) ?? [0, 0, 0, 1];const s = scale?.getElement(i, []) ?? [1, 1, 1];- const localMatrix = new THREE5.Matrix4().compose(new THREE5.Vector3().fromArray(t), new THREE5.Quaternion().fromArray(r), new THREE5.Vector3().fromArray(s));+ const localMatrix = new THREE6.Matrix4().compose(new THREE6.Vector3().fromArray(t), new THREE6.Quaternion().fromArray(r), new THREE6.Vector3().fromArray(s));matrices.push(base.clone().multiply(localMatrix).toArray());}const local = [0, 0, 0];@@ -8582,12 +8675,12 @@ var init_node_visibility = __esm(() => {});// src/delivery-inspect.ts-import * as THREE6 from "three";+import * as THREE7 from "three";import { PropertyType as PropertyType2 } from "@gltf-transform/core";function decompose(matrix) {- const translation = new THREE6.Vector3;- const rotation = new THREE6.Quaternion;- const scale = new THREE6.Vector3;+ const translation = new THREE7.Vector3;+ const rotation = new THREE7.Quaternion;+ const scale = new THREE7.Vector3;matrix.decompose(translation, rotation, scale);const clean = (value) => Object.is(value, -0) ? 0 : value;return {@@ -8599,7 +8692,7 @@ function decompose(matrix) {function drawnTriangles(visited) {const values = [];const local = [0, 0, 0];- const point = new THREE6.Vector3;+ const point = new THREE7.Vector3;for (const { node, roles, hidden } of visited) {const mesh = node.getMesh();if (!mesh || hidden || roles.some((role) => role.startsWith("collider.")))@@ -8612,7 +8705,7 @@ function drawnTriangles(visited) {const copies = translation?.getCount() ?? rotation?.getCount() ?? scale?.getCount() ?? 1;const matrices = [];for (let i = 0;i < copies; i++) {- const instance = new THREE6.Matrix4().compose(new THREE6.Vector3().fromArray(translation?.getElement(i, []) ?? [0, 0, 0]), new THREE6.Quaternion().fromArray(rotation?.getElement(i, []) ?? [0, 0, 0, 1]), new THREE6.Vector3().fromArray(scale?.getElement(i, []) ?? [1, 1, 1]));+ const instance = new THREE7.Matrix4().compose(new THREE7.Vector3().fromArray(translation?.getElement(i, []) ?? [0, 0, 0]), new THREE7.Quaternion().fromArray(rotation?.getElement(i, []) ?? [0, 0, 0, 1]), new THREE7.Vector3().fromArray(scale?.getElement(i, []) ?? [1, 1, 1]));matrices.push(base.clone().multiply(instance));}for (const primitive of mesh.listPrimitives()) {@@ -8643,20 +8736,20 @@ function triangleOverlapsBox(a, b, c, h, tolerance) {return false;}const e = [- new THREE6.Vector3().subVectors(b, a),- new THREE6.Vector3().subVectors(c, b),- new THREE6.Vector3().subVectors(a, c)+ new THREE7.Vector3().subVectors(b, a),+ new THREE7.Vector3().subVectors(c, b),+ new THREE7.Vector3().subVectors(a, c)];- const normal = new THREE6.Vector3().crossVectors(e[0], e[1]);+ const normal = new THREE7.Vector3().crossVectors(e[0], e[1]);const axes = [normal];const units = [- new THREE6.Vector3(1, 0, 0),- new THREE6.Vector3(0, 1, 0),- new THREE6.Vector3(0, 0, 1)+ new THREE7.Vector3(1, 0, 0),+ new THREE7.Vector3(0, 1, 0),+ new THREE7.Vector3(0, 0, 1)];for (const unit of units)for (const edge of e)- axes.push(new THREE6.Vector3().crossVectors(unit, edge));+ axes.push(new THREE7.Vector3().crossVectors(unit, edge));for (const axis of axes) {if (axis.lengthSq() < 0.000000000000000000000001)continue;@@ -8668,14 +8761,14 @@ function triangleOverlapsBox(a, b, c, h, tolerance) {return true;}function closestPointOnTriangle(p, a, b, c) {- const ab = new THREE6.Vector3().subVectors(b, a);- const ac = new THREE6.Vector3().subVectors(c, a);- const ap = new THREE6.Vector3().subVectors(p, a);+ const ab = new THREE7.Vector3().subVectors(b, a);+ const ac = new THREE7.Vector3().subVectors(c, a);+ const ap = new THREE7.Vector3().subVectors(p, a);const d1 = ab.dot(ap);const d2 = ac.dot(ap);if (d1 <= 0 && d2 <= 0)return a.clone();- const bp = new THREE6.Vector3().subVectors(p, b);+ const bp = new THREE7.Vector3().subVectors(p, b);const d3 = ab.dot(bp);const d4 = ac.dot(bp);if (d3 >= 0 && d4 <= d3)@@ -8683,7 +8776,7 @@ function closestPointOnTriangle(p, a, b, c) {const vc = d1 * d4 - d3 * d2;if (vc <= 0 && d1 >= 0 && d3 <= 0)return a.clone().addScaledVector(ab, d1 / (d1 - d3));- const cp = new THREE6.Vector3().subVectors(p, c);+ const cp = new THREE7.Vector3().subVectors(p, c);const d5 = ab.dot(cp);const d6 = ac.dot(cp);if (d6 >= 0 && d5 <= d6)@@ -8693,14 +8786,14 @@ function closestPointOnTriangle(p, a, b, c) {return a.clone().addScaledVector(ac, d2 / (d2 - d6));const va = d3 * d6 - d5 * d4;if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0)- return b.clone().addScaledVector(new THREE6.Vector3().subVectors(c, b), (d4 - d3) / (d4 - d3 + (d5 - d6)));+ return b.clone().addScaledVector(new THREE7.Vector3().subVectors(c, b), (d4 - d3) / (d4 - d3 + (d5 - d6)));const denominator = 1 / (va + vb + vc);return a.clone().addScaledVector(ab, vb * denominator).addScaledVector(ac, vc * denominator);}function segmentSegmentDistanceSq(p1, q1, p2, q2) {- const d1 = new THREE6.Vector3().subVectors(q1, p1);- const d2 = new THREE6.Vector3().subVectors(q2, p2);- const r = new THREE6.Vector3().subVectors(p1, p2);+ const d1 = new THREE7.Vector3().subVectors(q1, p1);+ const d2 = new THREE7.Vector3().subVectors(q2, p2);+ const r = new THREE7.Vector3().subVectors(p1, p2);const a = d1.dot(d1);const e = d2.dot(d2);const f = d2.dot(r);@@ -8709,22 +8802,22 @@ function segmentSegmentDistanceSq(p1, q1, p2, q2) {if (a <= 0.000000000000000000000001 && e <= 0.000000000000000000000001)return r.lengthSq();if (a <= 0.000000000000000000000001)- t = THREE6.MathUtils.clamp(f / e, 0, 1);+ t = THREE7.MathUtils.clamp(f / e, 0, 1);else {const c = d1.dot(r);if (e <= 0.000000000000000000000001)- s = THREE6.MathUtils.clamp(-c / a, 0, 1);+ s = THREE7.MathUtils.clamp(-c / a, 0, 1);else {const b = d1.dot(d2);const denominator = a * e - b * b;- s = denominator !== 0 ? THREE6.MathUtils.clamp((b * f - c * e) / denominator, 0, 1) : 0;+ s = denominator !== 0 ? THREE7.MathUtils.clamp((b * f - c * e) / denominator, 0, 1) : 0;t = (b * s + f) / e;if (t < 0) {t = 0;- s = THREE6.MathUtils.clamp(-c / a, 0, 1);+ s = THREE7.MathUtils.clamp(-c / a, 0, 1);} else if (t > 1) {t = 1;- s = THREE6.MathUtils.clamp((b - c) / a, 0, 1);+ s = THREE7.MathUtils.clamp((b - c) / a, 0, 1);}}}@@ -8733,8 +8826,8 @@ function segmentSegmentDistanceSq(p1, q1, p2, q2) {return c1.distanceToSquared(c2);}function segmentCrossesTriangle(p, q, a, b, c) {- const hit = new THREE6.Vector3;- const ray = new THREE6.Ray(p, new THREE6.Vector3().subVectors(q, p));+ const hit = new THREE7.Vector3;+ const ray = new THREE7.Ray(p, new THREE7.Vector3().subVectors(q, p));const length = ray.direction.length();if (length === 0)return false;@@ -8851,9 +8944,9 @@ function inspectDelivery(doc) {visit(scene.listChildren(), segment3(scene.getName() || "Scene", 0), false, undefined);const finding = (code, path, message) => summary.diagnostics.push({ code, path, message });const { min, max } = drawnSceneBounds(scene);- const bounds = new THREE6.Box3(new THREE6.Vector3(...min), new THREE6.Vector3(...max));+ const bounds = new THREE7.Box3(new THREE7.Vector3(...min), new THREE7.Vector3(...max));const finiteBounds = [...min, ...max].every(Number.isFinite);- const diagonal = finiteBounds ? bounds.getSize(new THREE6.Vector3).length() : 0;+ const diagonal = finiteBounds ? bounds.getSize(new THREE7.Vector3).length() : 0;const tolerance = Math.max(0.0001, diagonal * 0.0001);const colliderNodes = [];for (const entry of visited) {@@ -8932,23 +9025,23 @@ function inspectDelivery(doc) {const triangles = colliderNodes.some(({ record }) => record.shape.kind !== "hull") ? drawnTriangles(visited) : new Float64Array;const triangleCount = triangles.length / 9;let overlapTests = 0;- const a = new THREE6.Vector3;- const b = new THREE6.Vector3;- const c = new THREE6.Vector3;+ const a = new THREE7.Vector3;+ const b = new THREE7.Vector3;+ const c = new THREE7.Vector3;for (const { visit: entry, record } of colliderNodes) {if (!entry.hidden)finding("DELIVERY_COLLIDER_NOT_HIDDEN", record.path, "collider proxy draws; hide it (the delivery helpers do) so importers that ignore roles draw only the asset.");const matrix = worldMatrix(entry.node);- const proxyBounds = new THREE6.Box3;+ const proxyBounds = new THREE7.Box3;const mesh = entry.node.getMesh();const local = [0, 0, 0];for (const primitive of mesh?.listPrimitives() ?? []) {const position = primitive.getAttribute("POSITION");for (let i = 0;i < (position?.getCount() ?? 0); i++)- proxyBounds.expandByPoint(new THREE6.Vector3().fromArray(position.getElement(i, local)).applyMatrix4(matrix));+ proxyBounds.expandByPoint(new THREE7.Vector3().fromArray(position.getElement(i, local)).applyMatrix4(matrix));}if (proxyBounds.isEmpty())- proxyBounds.expandByPoint(new THREE6.Vector3().setFromMatrixPosition(matrix));+ proxyBounds.expandByPoint(new THREE7.Vector3().setFromMatrixPosition(matrix));const expanded = bounds.clone().expandByScalar(tolerance);if (!finiteBounds || !expanded.containsBox(proxyBounds))finding("DELIVERY_COLLIDER_OUTSIDE_BOUNDS", record.path, "collider proxy reaches outside the bounds of the drawn asset.");@@ -8959,11 +9052,11 @@ function inspectDelivery(doc) {continue;}overlapTests += triangleCount;- const toLocal = new THREE6.Matrix4;+ const toLocal = new THREE7.Matrix4;let touches = false;if (record.shape.kind === "box") {toLocal.copy(matrix).invert();- const half = new THREE6.Vector3(0.5, 0.5, 0.5);+ const half = new THREE7.Vector3(0.5, 0.5, 0.5);const scale = Math.max(...record.transform.scale.map(Math.abs), 0.000000001);for (let t = 0;t < triangleCount && !touches; t++) {a.fromArray(triangles, t * 9).applyMatrix4(toLocal);@@ -8973,10 +9066,10 @@ function inspectDelivery(doc) {}} else {const { translation, rotation } = record.transform;- toLocal.compose(new THREE6.Vector3(...translation), new THREE6.Quaternion(...rotation), new THREE6.Vector3(1, 1, 1)).invert();+ toLocal.compose(new THREE7.Vector3(...translation), new THREE7.Quaternion(...rotation), new THREE7.Vector3(1, 1, 1)).invert();const { radius, height } = record.shape;- const p = new THREE6.Vector3(0, -height / 2 + radius, 0);- const q = new THREE6.Vector3(0, height / 2 - radius, 0);+ const p = new THREE7.Vector3(0, -height / 2 + radius, 0);+ const q = new THREE7.Vector3(0, height / 2 - radius, 0);for (let t = 0;t < triangleCount && !touches; t++) {a.fromArray(triangles, t * 9).applyMatrix4(toLocal);b.fromArray(triangles, t * 9 + 3).applyMatrix4(toLocal);@@ -8995,7 +9088,7 @@ function inspectDelivery(doc) {finding("DELIVERY_PORT_WITHOUT_MODULE", record.path, "port is not under a valid kit module; place ports under the root defineModule marked.");continue;}- const point = new THREE6.Vector3(...record.transform.translation).applyMatrix4(worldMatrix(moduleEntry.node).invert());+ const point = new THREE7.Vector3(...record.transform.translation).applyMatrix4(worldMatrix(moduleEntry.node).invert());const [width, depth] = spec.footprint;const [x0, x1, z0, z1] = spec.origin === "corner" ? [0, width, 0, depth] : [-width / 2, width / 2, -depth / 2, depth / 2];const slack = Math.max(0.0001, Math.max(width, depth, spec.height) * 0.00001);@@ -9009,7 +9102,7 @@ function inspectDelivery(doc) {}return summary;}-var DELIVERY_OVERLAP_TEST_LIMIT = 50000000, segment3 = (name, occurrence) => `/${encodeURIComponent(name)}[${occurrence}]`, roleTail = (role, base) => role.startsWith(`${base}.`) ? role.slice(base.length + 1) : undefined, worldMatrix = (node) => new THREE6.Matrix4().fromArray(node.getWorldMatrix());+var DELIVERY_OVERLAP_TEST_LIMIT = 50000000, segment3 = (name, occurrence) => `/${encodeURIComponent(name)}[${occurrence}]`, roleTail = (role, base) => role.startsWith(`${base}.`) ? role.slice(base.length + 1) : undefined, worldMatrix = (node) => new THREE7.Matrix4().fromArray(node.getWorldMatrix());var init_delivery_inspect = __esm(() => {init_gltf_io();init_semantic();@@ -9241,10 +9334,10 @@ var init_budget = __esm(() => {});// src/gltf-texture-binding.ts-import * as THREE7 from "three";+import * as THREE8 from "three";function restoreGltfTextureBinding(texture, info) {texture.minFilter = MIN[info.getMinFilter() ?? 9729];- texture.magFilter = info.getMagFilter() === 9728 ? THREE7.NearestFilter : THREE7.LinearFilter;+ texture.magFilter = info.getMagFilter() === 9728 ? THREE8.NearestFilter : THREE8.LinearFilter;texture.wrapS = WRAP[info.getWrapS()];texture.wrapT = WRAP[info.getWrapT()];texture.generateMipmaps = [9984, 9985, 9986, 9987].includes(info.getMinFilter() ?? 9729);@@ -9281,22 +9374,22 @@ function gltfTextureBindingKey(info) {var MIN, WRAP;var init_gltf_texture_binding = __esm(() => {MIN = {- 9728: THREE7.NearestFilter,- 9729: THREE7.LinearFilter,- 9984: THREE7.NearestMipmapNearestFilter,- 9985: THREE7.LinearMipmapNearestFilter,- 9986: THREE7.NearestMipmapLinearFilter,- 9987: THREE7.LinearMipmapLinearFilter+ 9728: THREE8.NearestFilter,+ 9729: THREE8.LinearFilter,+ 9984: THREE8.NearestMipmapNearestFilter,+ 9985: THREE8.LinearMipmapNearestFilter,+ 9986: THREE8.NearestMipmapLinearFilter,+ 9987: THREE8.LinearMipmapLinearFilter};WRAP = {- 33071: THREE7.ClampToEdgeWrapping,- 33648: THREE7.MirroredRepeatWrapping,- 10497: THREE7.RepeatWrapping+ 33071: THREE8.ClampToEdgeWrapping,+ 33648: THREE8.MirroredRepeatWrapping,+ 10497: THREE8.RepeatWrapping};});// src/atlas-provenance.ts-import * as THREE8 from "three";+import * as THREE9 from "three";function fail5(message) {throw new TypeError(`atlas provenance: ${message}`);}@@ -9458,7 +9551,7 @@ function collectAtlasProvenance(root) {"aoMap"]) {const texture = mat[slot];- if (!(texture instanceof THREE8.Texture))+ if (!(texture instanceof THREE9.Texture))continue;let ref = textures.get(texture);if (!ref) {@@ -9712,7 +9805,7 @@ import {KHRTextureBasisu} from "@gltf-transform/extensions";import { cloneDocument, dedup, prune, quantize, reorder } from "@gltf-transform/functions";-import * as THREE9 from "three";+import * as THREE10 from "three";function meshSignature(mesh, ids) {const id = (property) => {if (!property)@@ -9860,8 +9953,8 @@ function isCoreMaterialUse(parent) {return parent.propertyType === PropertyType4.MATERIAL;}function decomposeDelta(before, after) {- const delta = new THREE9.Matrix4().fromArray(before).invert().multiply(new THREE9.Matrix4().fromArray(after));- const position = new THREE9.Vector3, quaternion = new THREE9.Quaternion, scale = new THREE9.Vector3;+ const delta = new THREE10.Matrix4().fromArray(before).invert().multiply(new THREE10.Matrix4().fromArray(after));+ const position = new THREE10.Vector3, quaternion = new THREE10.Quaternion, scale = new THREE10.Vector3;delta.decompose(position, quaternion, scale);return {scale: scale.x,@@ -9889,12 +9982,12 @@ function positionGridSteps(doc, bits) {if (level.propertyType === PropertyType4.NODE)lodBase.set(level, node);const world = (node) => {- const matrix = new THREE9.Matrix4().fromArray(node.getWorldMatrix());+ const matrix = new THREE10.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;+ return placed ? new THREE10.Matrix4().fromArray(placed.getWorldMatrix()).multiply(matrix) : matrix;};const halfExtent = (mesh) => {const min = [Infinity, Infinity, Infinity];@@ -10042,7 +10135,7 @@ async function deliverRuntimeThreeGlb(bytes, meshoptEncoder, options = {}, layouconst original = matrices.get(node);const moved = original === undefined;const split = moved || proxyNodes.has(node);- const reference = moved ? new THREE9.Matrix4().identity().toArray() : original;+ const reference = moved ? new THREE10.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))@@ -10917,7 +11010,7 @@ var init_registry = __esm(() => {});// src/qa/atlas.ts-import * as THREE10 from "three";+import * as THREE11 from "three";function own(value, key) {if (!value || typeof value !== "object")return;@@ -10956,7 +11049,7 @@ function inspectAtlasScene(root) {nodesChecked: 0,truncated: false};- if (!(root instanceof THREE10.Object3D))+ if (!(root instanceof THREE11.Object3D))return result;let encountered = false, metadataBytes = 0, metadataFull = false;const cache = new Map;@@ -11061,7 +11154,7 @@ function inspectAtlasScene(root) {continue;for (const [slot, allowed] of slots) {const texture = material[slot];- if (!(texture instanceof THREE10.Texture))+ if (!(texture instanceof THREE11.Texture))continue;let p = cache.get(texture);if (!cache.has(texture)) {@@ -11162,7 +11255,7 @@ function inspectAtlasScene(root) {throw Error("invalid override version");sampler = canonicalizePortableSamplerV1(own(override, "sampler"));}- const expected = applyPortableSamplerV1(new THREE10.Texture, sampler);+ const expected = applyPortableSamplerV1(new THREE11.Texture, sampler);if (texture.minFilter !== expected.minFilter || texture.magFilter !== expected.magFilter || texture.wrapS !== expected.wrapS || texture.wrapT !== expected.wrapT || texture.generateMipmaps !== expected.generateMipmaps)finding("ATLAS_SAMPLER_MISMATCH", "Actual atlas filtering, wrapping or mip policy differs from its declared sampler.", path, entry);} catch {@@ -11231,7 +11324,7 @@ function inspectAtlasScene(root) {continue;}const texture = entry.texture;- const matrix = texture.matrixAutoUpdate ? new THREE10.Matrix3().setUvTransform(texture.offset.x, texture.offset.y, texture.repeat.x, texture.repeat.y, texture.rotation, texture.center.x, texture.center.y) : texture.matrix.clone();+ const matrix = texture.matrixAutoUpdate ? new THREE11.Matrix3().setUvTransform(texture.offset.x, texture.offset.y, texture.repeat.x, texture.repeat.y, texture.rotation, texture.center.x, texture.center.y) : texture.matrix.clone();if (!matrix.elements.every(Number.isFinite)) {finding("ATLAS_BINDING_TRANSFORM", "Atlas texture transform is nonfinite.", path, entry);continue;@@ -11241,7 +11334,7 @@ function inspectAtlasScene(root) {const minY = (region.content.y + center) / entry.p.manifest.height, maxY = (region.content.y + region.content.height - center) / entry.p.manifest.height;const tolerance = 4 * 2 ** -23;let invalid = false;- const point = new THREE10.Vector2;+ const point = new THREE11.Vector2;for (const range of ranges) {if ((range.materialIndex ?? 0) !== entry.materialIndex)continue;@@ -11337,7 +11430,7 @@ var init_atlas = __esm(() => {});// src/qa/material.ts-import * as THREE11 from "three";+import * as THREE12 from "three";function textureMeta(texture) {return texture.userData["kilnTexture"];}@@ -11385,7 +11478,7 @@ function validateTextureSlot(findings, mesh, material, texture, slot, expected)if (!texture)return;const meta = textureMeta(texture);- const actual = texture.colorSpace === THREE11.SRGBColorSpace ? "srgb" : texture.colorSpace === THREE11.NoColorSpace ? "linear" : meta?.colorSpace ?? "linear";+ const actual = texture.colorSpace === THREE12.SRGBColorSpace ? "srgb" : texture.colorSpace === THREE12.NoColorSpace ? "linear" : meta?.colorSpace ?? "linear";if (!meta || !encodedTextureIsExportable(texture)) {findings.push({code: "MAT_TEXTURE_DECODE_FAILED",@@ -11486,7 +11579,7 @@ function validateMaterial(mesh, material, requiresPrecomputedTangents) {}if (mesh.geometry.userData["kilnGeometryRole"] === "foliageCard") {const validMask = standard.alphaTest > 0 && !standard.transparent;- if (!standard.map || !textureHasAlpha(standard.map) || !validMask || standard.side !== THREE11.DoubleSide || !mesh.geometry.getAttribute("uv")) {+ if (!standard.map || !textureHasAlpha(standard.map) || !validMask || standard.side !== THREE12.DoubleSide || !mesh.geometry.getAttribute("uv")) {findings.push({code: "MAT_FOLIAGE_CARD_CONTRACT",disposition: "block",@@ -11604,7 +11697,7 @@ var init_architecture_repairs = __esm(() => {});// src/qa/architecture.ts-import * as THREE12 from "three";+import * as THREE13 from "three";function hasRoofDimensions(value) {return value.footprint !== undefined && value.roof?.ridgeAxis !== undefined && value.roof.rise !== undefined && value.roof.overhang !== undefined;}@@ -11614,7 +11707,7 @@ function semanticMetadata(node) {function markerBounds(matrix) {const bounds = emptyBounds();for (let corner = 0;corner < 8; corner++) {- expandBounds(bounds, new THREE12.Vector3(corner & 1 ? 0.5 : -0.5, corner & 2 ? 0.5 : -0.5, corner & 4 ? 0.5 : -0.5).applyMatrix4(matrix));+ expandBounds(bounds, new THREE13.Vector3(corner & 1 ? 0.5 : -0.5, corner & 2 ? 0.5 : -0.5, corner & 4 ? 0.5 : -0.5).applyMatrix4(matrix));}return bounds;}@@ -11623,7 +11716,7 @@ function geometryPlaneNormal(geometry, relativeMatrix) {const local = geometry.boundingBox;if (!local)return;- const size = local.getSize(new THREE12.Vector3);+ const size = local.getSize(new THREE13.Vector3);const dimensions = [["x", size.x],["y", size.y],@@ -11633,7 +11726,7 @@ function geometryPlaneNormal(geometry, relativeMatrix) {const axis = dimensions[0]?.[0];if (!axis)return;- const normal = new THREE12.Vector3(axis === "x" ? 1 : 0, axis === "y" ? 1 : 0, axis === "z" ? 1 : 0).transformDirection(relativeMatrix);+ const normal = new THREE13.Vector3(axis === "x" ? 1 : 0, axis === "y" ? 1 : 0, axis === "z" ? 1 : 0).transformDirection(relativeMatrix);if (normal.y < 0)normal.multiplyScalar(-1);return normal.normalize();@@ -11645,7 +11738,7 @@ function geometryEvidence(geometry, relativeMatrix) {if (position?.itemSize !== 3)return { bounds, vertices, triangles: [] };for (let index = 0;index < position.count; index++) {- const point = new THREE12.Vector3(position.getX(index), position.getY(index), position.getZ(index));+ const point = new THREE13.Vector3(position.getX(index), position.getY(index), position.getZ(index));point.applyMatrix4(relativeMatrix);vertices.push(point);expandBounds(bounds, point);@@ -11672,7 +11765,7 @@ function geometryEvidence(geometry, relativeMatrix) {return { bounds, vertices, triangles, ...planeNormal ? { planeNormal } : {} };}function collectArchitectureEvidence(scene) {- if (!(scene instanceof THREE12.Object3D))+ if (!(scene instanceof THREE13.Object3D))return;scene.updateMatrixWorld(true);const rootInverse = scene.matrixWorld.clone().invert();@@ -11692,7 +11785,7 @@ function collectArchitectureEvidence(scene) {const nodePath = parentPath ? `${parentPath}/${segment}` : segment;const relativeMatrix = rootInverse.clone().multiply(node.matrixWorld);const mesh = node;- const isMesh = mesh.isMesh === true && mesh.geometry instanceof THREE12.BufferGeometry;+ const isMesh = mesh.isMesh === true && mesh.geometry instanceof THREE13.BufferGeometry;const evidence = isMesh ? geometryEvidence(mesh.geometry, relativeMatrix) : {bounds: markerBounds(relativeMatrix),vertices: [],@@ -11751,7 +11844,7 @@ function architectureFinding(context, value) {function averageNormal(normals) {if (normals.length === 0)return;- const result = normals.reduce((sum, normal) => sum.add(normal), new THREE12.Vector3);+ const result = normals.reduce((sum, normal) => sum.add(normal), new THREE13.Vector3);return result.lengthSq() > EPSILON ? result.normalize() : undefined;}function intervalCoverage(min, max, expectedMin, expectedMax) {@@ -12462,8 +12555,8 @@ function evaluateArchitectureQa(context) {});}var PROFILE_RULE_ID = "ARCHITECTURE_PROFILE", EPSILON = 0.000001, ARCHITECTURE_REALISTIC_SCALE_BANDS, emptyBounds = () => ({- min: new THREE12.Vector3(Infinity, Infinity, Infinity),- max: new THREE12.Vector3(-Infinity, -Infinity, -Infinity)+ min: new THREE13.Vector3(Infinity, Infinity, Infinity),+ max: new THREE13.Vector3(-Infinity, -Infinity, -Infinity)}), expandBounds = (bounds, point) => {bounds.min.min(point);bounds.max.max(point);@@ -12507,7 +12600,7 @@ var init_architecture = __esm(() => {});// src/skin-binding.ts-import * as THREE13 from "three";+import * as THREE14 from "three";function topRoot(node) {while (node.parent)node = node.parent;@@ -12527,7 +12620,7 @@ function createSkinnedPart(name, geometry, material, options) {}}function buildSkinnedPart(name, geometry, material, options) {- if (typeof name !== "string" || !name.trim() || THREE13.PropertyBinding.sanitizeNodeName(name) !== name)+ if (typeof name !== "string" || !name.trim() || THREE14.PropertyBinding.sanitizeNodeName(name) !== name)throw new TypeError("createSkinnedPart name must be nonempty and free of animation binding punctuation.");if (!geometry?.isBufferGeometry)throw new TypeError("createSkinnedPart requires BufferGeometry.");@@ -12545,7 +12638,7 @@ function buildSkinnedPart(name, geometry, material, options) {for (const bone of bones) {if (!bone?.isBone || topRoot(bone) !== top || members.has(bone))throw new TypeError("createSkinnedPart bones must be distinct Bones in the parent hierarchy.");- if (!bone.name || THREE13.PropertyBinding.sanitizeNodeName(bone.name) !== bone.name || names.has(bone.name))+ if (!bone.name || THREE14.PropertyBinding.sanitizeNodeName(bone.name) !== bone.name || names.has(bone.name))throw new TypeError("createSkinnedPart bones need unique animation-safe names.");members.add(bone);names.add(bone.name);@@ -12592,9 +12685,9 @@ function buildSkinnedPart(name, geometry, material, options) {for (const key of ["position", "rotation", "scale"])if (options[key] !== undefined)assertFiniteTriple(`createSkinnedPart ${key}`, options[key]);- const local = new THREE13.Matrix4().compose(new THREE13.Vector3(...options.position ?? [0, 0, 0]), new THREE13.Quaternion().setFromEuler(new THREE13.Euler(...(options.rotation ?? [0, 0, 0]).map(THREE13.MathUtils.degToRad))), new THREE13.Vector3(...options.scale ?? [1, 1, 1]));+ const local = new THREE14.Matrix4().compose(new THREE14.Vector3(...options.position ?? [0, 0, 0]), new THREE14.Quaternion().setFromEuler(new THREE14.Euler(...(options.rotation ?? [0, 0, 0]).map(THREE14.MathUtils.degToRad))), new THREE14.Vector3(...options.scale ?? [1, 1, 1]));top.updateWorldMatrix(true, true);- const bind = new THREE13.Matrix4().multiplyMatrices(parent.matrixWorld, local);+ const bind = new THREE14.Matrix4().multiplyMatrices(parent.matrixWorld, local);assertMatrix(bind, "mesh");for (const bone of bones) {assertMatrix(bone.matrixWorld, `bone ${bone.name}`);@@ -12609,19 +12702,19 @@ function buildSkinnedPart(name, geometry, material, options) {}}const owned = geometry.clone();- owned.setAttribute("skinIndex", new THREE13.BufferAttribute(skinIndices, 4));- owned.setAttribute("skinWeight", new THREE13.BufferAttribute(skinWeights, 4));- const mesh = new THREE13.SkinnedMesh(owned, Array.isArray(material) ? [...material] : material);+ owned.setAttribute("skinIndex", new THREE14.BufferAttribute(skinIndices, 4));+ owned.setAttribute("skinWeight", new THREE14.BufferAttribute(skinWeights, 4));+ const mesh = new THREE14.SkinnedMesh(owned, Array.isArray(material) ? [...material] : material);mesh.name = `Mesh_${name}`;if (options.position)mesh.position.fromArray(options.position);if (options.rotation)- mesh.rotation.set(...options.rotation.map(THREE13.MathUtils.degToRad));+ mesh.rotation.set(...options.rotation.map(THREE14.MathUtils.degToRad));if (options.scale)mesh.scale.fromArray(options.scale);if (options.semantic)stampSemanticMetadataV1(mesh, options.semantic);- const skeleton = new THREE13.Skeleton([...bones], bones.map((bone) => bone.matrixWorld.clone().invert()));+ const skeleton = new THREE14.Skeleton([...bones], bones.map((bone) => bone.matrixWorld.clone().invert()));mesh.bind(skeleton, bind);parent.add(mesh);mesh.updateWorldMatrix(true, false);@@ -12634,7 +12727,7 @@ var init_skin_binding = __esm(() => {});// src/character.ts-import * as THREE14 from "three";+import * as THREE15 from "three";function validRole(value) {return typeof value === "string" && /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(value);}@@ -12915,7 +13008,7 @@ function readCharacterRigGraphV1(target) {return result.valid ? result.value : undefined;}function axisQuaternion(from, to) {- const value = new THREE14.Quaternion().setFromUnitVectors(new THREE14.Vector3(...from), new THREE14.Vector3(...to));+ const value = new THREE15.Quaternion().setFromUnitVectors(new THREE15.Vector3(...from), new THREE15.Vector3(...to));return [value.x, value.y, value.z, value.w];}function stampCharacterJointDescriptorV1(target, input) {@@ -13020,7 +13113,7 @@ function createJointChain(chainName, segments, options = {}) {endEffector: segment.endEffector,contact: segment.contact});- const node = new THREE14.Object3D;+ const node = new THREE15.Object3D;node.name = characterJointNodeName(chainName, segment.role);node.position.fromArray(descriptor.rest.translation);node.quaternion.fromArray(descriptor.rest.rotation);@@ -13100,7 +13193,7 @@ function buildBoneChain(chainName, segments, options = {}) {return descriptor;});const nodes = descriptors.map((descriptor) => {- const node = new THREE14.Bone;+ const node = new THREE15.Bone;node.name = characterJointNodeName(chainName, descriptor.role);node.position.fromArray(descriptor.rest.translation);node.quaternion.fromArray(descriptor.rest.rotation);@@ -13419,7 +13512,7 @@ var init_character_repairs = __esm(() => {});// src/qa/character.ts-import * as THREE15 from "three";+import * as THREE16 from "three";function isClipLike(value) {if (typeof value !== "object" || value === null)return false;@@ -13657,7 +13750,7 @@ function contactFindings(input, root) {const planeY = input.groundPlaneY ?? 0;const findings = [];for (const contact of contacts) {- const point = contact.node.getWorldPosition(new THREE15.Vector3).applyMatrix4(rootInverse);+ const point = contact.node.getWorldPosition(new THREE16.Vector3).applyMatrix4(rootInverse);const offset = point.y - planeY;if (offset > tolerance) {findings.push(block(input, "CHAR_CONTACT_FLOATING", `Ground contact ${contact.descriptor.role} is ${offset.toFixed(6)} m above asset-local ground.`, {@@ -13922,13 +14015,13 @@ function declaredHeldItem(nodes) {function characterJointScale(root) {root.updateMatrixWorld(true);const inverse = root.matrixWorld.clone().invert();- const bounds = new THREE15.Box3;+ const bounds = new THREE16.Box3;for (const joint of collectCharacterJointNodes(root)) {- bounds.expandByPoint(joint.node.getWorldPosition(new THREE15.Vector3).applyMatrix4(inverse));+ bounds.expandByPoint(joint.node.getWorldPosition(new THREE16.Vector3).applyMatrix4(inverse));}if (bounds.isEmpty())return 1;- const size = bounds.getSize(new THREE15.Vector3);+ const size = bounds.getSize(new THREE16.Vector3);return Math.max(size.x, size.y, size.z, 1);}function heldItemMotionFindings(input, root, clips) {@@ -13964,8 +14057,8 @@ function heldItemMotionFindings(input, root, clips) {if (!cloneItem || !cloneAttachment)continue;const inverse = clone.matrixWorld.clone().invert();- const itemPoint = cloneItem.getWorldPosition(new THREE15.Vector3).applyMatrix4(inverse);- const gripPoint = cloneAttachment.getWorldPosition(new THREE15.Vector3).applyMatrix4(inverse);+ const itemPoint = cloneItem.getWorldPosition(new THREE16.Vector3).applyMatrix4(inverse);+ const gripPoint = cloneAttachment.getWorldPosition(new THREE16.Vector3).applyMatrix4(inverse);const distance = itemPoint.distanceTo(gripPoint);baseline ??= distance;const drift = Math.abs(distance - baseline);@@ -13998,7 +14091,7 @@ function heldItemMotionFindings(input, root, clips) {function inspectRig(context) {if (!context.rig)return [];- const root = context.scene instanceof THREE15.Object3D ? context.scene : undefined;+ const root = context.scene instanceof THREE16.Object3D ? context.scene : undefined;const clips = (context.clips ?? []).filter(isClipLike);const findings = [];if (root) {@@ -14048,7 +14141,7 @@ var init_character2 = __esm(() => {});// src/qa/character-advisory.ts-import * as THREE16 from "three";+import * as THREE17 from "three";function isClipLike2(value) {if (typeof value !== "object" || value === null)return false;@@ -14071,16 +14164,16 @@ function jointPoints(root) {const inverse = rootInverse(root);return collectCharacterJointNodes(root).map((evidence) => ({evidence,- local: evidence.node.getWorldPosition(new THREE16.Vector3).applyMatrix4(inverse)+ local: evidence.node.getWorldPosition(new THREE17.Vector3).applyMatrix4(inverse)}));}function characterScale(points) {if (points.length === 0)return 1;- const bounds = new THREE16.Box3;+ const bounds = new THREE17.Box3;for (const point of points)bounds.expandByPoint(point.local);- const size = bounds.getSize(new THREE16.Vector3);+ const size = bounds.getSize(new THREE17.Vector3);return Math.max(size.x, size.y, size.z, 1);}function pairKey(descriptor) {@@ -14179,12 +14272,12 @@ function restChainFindings(context, root) {}function forwardMarkerFindings(context, root) {root.updateMatrixWorld(true);- const expected = new THREE16.Vector3(1, 0, 0).transformDirection(root.matrixWorld);+ const expected = new THREE17.Vector3(1, 0, 0).transformDirection(root.matrixWorld);const markers = collectCharacterJointNodes(root).filter((joint) => /(?:^|[._-])(?:toe|muzzle|head)(?:$|[._-])/i.test(joint.descriptor.role));return markers.flatMap((marker) => {- const quaternion = marker.node.getWorldQuaternion(new THREE16.Quaternion);- const actual = new THREE16.Vector3(...marker.descriptor.localForwardAxis).applyQuaternion(quaternion).normalize();- const angle = THREE16.MathUtils.radToDeg(Math.acos(THREE16.MathUtils.clamp(actual.dot(expected), -1, 1)));+ const quaternion = marker.node.getWorldQuaternion(new THREE17.Quaternion);+ const actual = new THREE17.Vector3(...marker.descriptor.localForwardAxis).applyQuaternion(quaternion).normalize();+ const angle = THREE17.MathUtils.radToDeg(Math.acos(THREE17.MathUtils.clamp(actual.dot(expected), -1, 1)));if (angle <= FORWARD_ANGLE_DEGREES)return [];return [@@ -14238,7 +14331,7 @@ function sampleClip(root, clip) {byRole: new Map(collectCharacterJointNodes(clone).map((evidence) => [evidence.descriptor.role,{- point: evidence.node.getWorldPosition(new THREE16.Vector3).applyMatrix4(inverse),+ point: evidence.node.getWorldPosition(new THREE17.Vector3).applyMatrix4(inverse),evidence}]))@@ -14350,12 +14443,12 @@ function phaseOppositionFindings(context, root, clips) {return findings;}function signedBendDegrees(descriptor, quaternion) {- const rest = new THREE16.Quaternion(...descriptor.rest.rotation);+ const rest = new THREE17.Quaternion(...descriptor.rest.rotation);const delta = rest.invert().multiply(quaternion).normalize();- const axis = new THREE16.Vector3(delta.x, delta.y, delta.z);- const signedMagnitude = axis.dot(new THREE16.Vector3(...descriptor.localBendAxis));+ const axis = new THREE17.Vector3(delta.x, delta.y, delta.z);+ const signedMagnitude = axis.dot(new THREE17.Vector3(...descriptor.localBendAxis));const angle = 2 * Math.atan2(signedMagnitude, delta.w);- return THREE16.MathUtils.radToDeg(THREE16.MathUtils.euclideanModulo(angle + Math.PI, Math.PI * 2) - Math.PI);+ return THREE17.MathUtils.radToDeg(THREE17.MathUtils.euclideanModulo(angle + Math.PI, Math.PI * 2) - Math.PI);}function bendDirectionFindings(context, root, clips) {const joints = collectCharacterJointNodes(root).filter((joint) => /(?:^|[._-])(?:knee|elbow)(?:$|[._-])/i.test(joint.descriptor.role));@@ -14369,7 +14462,7 @@ function bendDirectionFindings(context, root, clips) {let maximumFraction = 0;for (const fraction of SAMPLE_FRACTIONS) {const value = track.createInterpolant().evaluate(fraction * clip.duration);- const bend = signedBendDegrees(joint.descriptor, new THREE16.Quaternion().fromArray(value).normalize());+ const bend = signedBendDegrees(joint.descriptor, new THREE17.Quaternion().fromArray(value).normalize());if (Math.abs(bend) > Math.abs(maximum)) {maximum = bend;maximumFraction = fraction;@@ -14452,7 +14545,7 @@ function footSlideFindings(context, root, clips) {return findings;}function inspectRigAdvisory(context) {- if (!context.rig || !(context.scene instanceof THREE16.Object3D)) {+ if (!context.rig || !(context.scene instanceof THREE17.Object3D)) {return [];}const root = context.scene;@@ -14506,7 +14599,7 @@ var init_character_advisory = __esm(() => {});// src/vehicle.ts-import * as THREE17 from "three";+import * as THREE18 from "three";function assertId(value, name) {if (!ID_PATTERN.test(value))throw new TypeError(`${name} must be a stable identifier`);@@ -14541,7 +14634,7 @@ function createTypedSocket(kind, input, parent) {if (!input.position.every(Number.isFinite))throw new TypeError(`${kind}.${id} position must be finite`);const rotation = normalizedQuaternion(input.rotation);- const node = new THREE17.Object3D;+ const node = new THREE18.Object3D;node.name = `Socket_${kind}_${id}`;node.position.set(...input.position);node.quaternion.set(...rotation);@@ -14562,7 +14655,7 @@ function createTypedSocket(kind, input, parent) {return node;}function createVehicleFrame(name, options = {}) {- const root = new THREE17.Object3D;+ const root = new THREE18.Object3D;root.name = name;stampSemanticMetadataV1(root, semantic2([KILN_SEMANTIC_ROLES.vehicleFrame, KILN_SEMANTIC_ROLES.vehicleForward], {frames: [@@ -14587,7 +14680,7 @@ function createVehicleFrame(name, options = {}) {};}function cylinderZ(radius, width, segments = 16) {- const geometry = new THREE17.CylinderGeometry(radius, radius, width, segments);+ const geometry = new THREE18.CylinderGeometry(radius, radius, width, segments);geometry.rotateX(Math.PI / 2);return geometry;}@@ -14604,14 +14697,14 @@ function defaultTireGeometry(radius, width) {if (width >= radius * 2)throw new RangeError("default wheel tire width must be less than its diameter");const tube = width / 2;- return new THREE17.TorusGeometry(radius - tube, tube, 8, 20);+ return new THREE18.TorusGeometry(radius - tube, tube, 8, 20);}function checkWheelGeometry(part, geometry, radius, width) {const positions = geometry.getAttribute("position");if (positions?.itemSize !== 3 || positions.count < 1 || positions.count > 2000000)throw new RangeError(`wheel ${part} position must have 1..2000000 three-component samples.`);- const bounds = new THREE17.Box3;- const point = new THREE17.Vector3;+ const bounds = new THREE18.Box3;+ const point = new THREE18.Vector3;let actualRadius = 0;for (let i = 0;i < positions.count; i++) {point.fromBufferAttribute(positions, i);@@ -14621,7 +14714,7 @@ function checkWheelGeometry(part, geometry, radius, width) {actualRadius = Math.max(actualRadius, Math.hypot(point.x, point.y));}const actualWidth = bounds.max.z - bounds.min.z;- const center = bounds.getCenter(new THREE17.Vector3);+ const center = bounds.getCenter(new THREE18.Vector3);const tolerance = 0.00001 * Math.max(radius, width, actualRadius, actualWidth);const differences = [];if (Math.abs(actualRadius - radius) > tolerance)@@ -14666,11 +14759,11 @@ function createWheelAssembly(name, materials, options) {const index = assertId(String(options.index), "wheel index");const key = `${options.side}.${index}`;const parent = options.parent;- const root = new THREE17.Object3D;+ const root = new THREE18.Object3D;root.name = `${name}_Assembly_${options.side}_${index}`;let steeringPivot;if (options.steering) {- steeringPivot = new THREE17.Object3D;+ steeringPivot = new THREE18.Object3D;steeringPivot.name = `SteeringPivot_${options.side}_${index}`;steeringPivot.position.set(...options.position ?? [0, 0, 0]);stampSemanticMetadataV1(steeringPivot, semantic2([semanticRole(ROLE.steeringPivot, key)], {@@ -14681,7 +14774,7 @@ function createWheelAssembly(name, materials, options) {}));root.add(steeringPivot);}- const spinPivot = new THREE17.Object3D;+ const spinPivot = new THREE18.Object3D;spinPivot.name = `WheelPivot_${options.side}_${index}`;if (!steeringPivot)spinPivot.position.set(...options.position ?? [0, 0, 0]);@@ -14702,9 +14795,9 @@ function createWheelAssembly(name, materials, options) {]}));(steeringPivot ?? root).add(spinPivot);- const tire = new THREE17.Mesh(options.geometries?.tire ?? defaultTireGeometry(radius, width), materials.tire);- const rim = new THREE17.Mesh(options.geometries?.rim ?? cylinderZ(rimRadius, rimWidth), materials.rim);- const hub = new THREE17.Mesh(options.geometries?.hub ?? cylinderZ(hubRadius, hubWidth), materials.hub ?? materials.rim);+ const tire = new THREE18.Mesh(options.geometries?.tire ?? defaultTireGeometry(radius, width), materials.tire);+ const rim = new THREE18.Mesh(options.geometries?.rim ?? cylinderZ(rimRadius, rimWidth), materials.rim);+ const hub = new THREE18.Mesh(options.geometries?.hub ?? cylinderZ(hubRadius, hubWidth), materials.hub ?? materials.rim);tire.name = `Tire_${options.side}_${index}`;rim.name = `Rim_${options.side}_${index}`;hub.name = `Hub_${options.side}_${index}`;@@ -14724,7 +14817,7 @@ function createWheelAssembly(name, materials, options) {]}));spinPivot.add(tire, rim, hub);- const contact = new THREE17.Object3D;+ const contact = new THREE18.Object3D;contact.name = `Contact_${options.side}_${index}`;contact.position.y = -radius;stampSemanticMetadataV1(contact, semantic2([semanticRole(ROLE.wheelContact, key), semanticRole(ROLE.contact, key)], {@@ -14782,10 +14875,10 @@ function objectBoundsInFrame(object, frame) {object.updateWorldMatrix(true, true);frame.updateWorldMatrix(true, false);const worldToFrame = frame.matrixWorld.clone().invert();- const bounds = new THREE17.Box3;+ const bounds = new THREE18.Box3;let found = false;object.traverse((node) => {- if (!(node instanceof THREE17.Mesh) || !(node.geometry instanceof THREE17.BufferGeometry))+ if (!(node instanceof THREE18.Mesh) || !(node.geometry instanceof THREE18.BufferGeometry))return;node.geometry.computeBoundingBox();const local = node.geometry.boundingBox;@@ -14795,7 +14888,7 @@ function objectBoundsInFrame(object, frame) {for (const x of [local.min.x, local.max.x])for (const y of [local.min.y, local.max.y])for (const z of [local.min.z, local.max.z]) {- bounds.expandByPoint(new THREE17.Vector3(x, y, z).applyMatrix4(matrix));+ bounds.expandByPoint(new THREE18.Vector3(x, y, z).applyMatrix4(matrix));found = true;}});@@ -14807,9 +14900,9 @@ function dimensions(object, frame) {const bounds = objectBoundsInFrame(object, frame);if (!bounds)return;- const size = bounds.getSize(new THREE17.Vector3);+ const size = bounds.getSize(new THREE18.Vector3);return {- center: bounds.getCenter(new THREE17.Vector3),+ center: bounds.getCenter(new THREE18.Vector3),radius: Math.max(size.x, size.y) / 2,width: size.z};@@ -14819,7 +14912,7 @@ function resolved(source, id, root, pivot, parts) {const tire = dimensions(parts.tire, pivot);const rim = dimensions(parts.rim, pivot);const hub = dimensions(parts.hub, pivot);- const centerLocal = tire?.center ?? rim?.center ?? hub?.center ?? new THREE17.Vector3;+ const centerLocal = tire?.center ?? rim?.center ?? hub?.center ?? new THREE18.Vector3;const toWorld = (value) => value.clone().applyMatrix4(pivot.matrixWorld);return {id,@@ -14834,11 +14927,11 @@ function resolved(source, id, root, pivot, parts) {...parts.hub ? { hub: parts.hub } : {},...parts.contact ? { contact: parts.contact } : {},centerWorld: toWorld(centerLocal),- pivotCenterWorld: new THREE17.Vector3().setFromMatrixPosition(pivot.matrixWorld),+ pivotCenterWorld: new THREE18.Vector3().setFromMatrixPosition(pivot.matrixWorld),...tire ? { tireCenterWorld: toWorld(tire.center) } : {},...rim ? { rimCenterWorld: toWorld(rim.center) } : {},...hub ? { hubCenterWorld: toWorld(hub.center) } : {},- spinAxisWorld: new THREE17.Vector3(0, 0, 1).transformDirection(pivot.matrixWorld),+ spinAxisWorld: new THREE18.Vector3(0, 0, 1).transformDirection(pivot.matrixWorld),...tire ? { radius: tire.radius, width: tire.width } : {},...rim ? { rimRadius: rim.radius, rimWidth: rim.width } : {},...hub ? { hubRadius: hub.radius, hubWidth: hub.width } : {},@@ -15175,7 +15268,7 @@ var EPSILON2 = 0.0000000001, DEFAULT_TOLERANCE = 0.000001, finiteVector = (value];// src/qa/vehicle-advisory.ts-import * as THREE18 from "three";+import * as THREE19 from "three";function advisory2(context, value) {return {...value,@@ -15249,7 +15342,7 @@ function isFender(node) {return semanticRoles(node).some((role) => /(?:^|\.)(?:fender|wheel-arch)(?:\.|$)/i.test(role)) || /fender|wheel[ _.-]?arch/i.test(node.name);}function isChassisMesh(node) {- if (!(node instanceof THREE18.Mesh) || isFender(node))+ if (!(node instanceof THREE19.Mesh) || isFender(node))return false;return semanticRoles(node).some((role) => /^(?:vehicle\.)?(?:chassis|body|hull)(?:\.|$)/i.test(role)) || /chassis|vehicle[ _.-]?body|fuselage|hull/i.test(node.name);}@@ -15257,10 +15350,10 @@ function objectBoundsInFrame2(object, frame) {object.updateWorldMatrix(true, true);frame.updateWorldMatrix(true, false);const worldToFrame = frame.matrixWorld.clone().invert();- const bounds = new THREE18.Box3;+ const bounds = new THREE19.Box3;let found = false;object.traverseVisible((part) => {- if (!(part instanceof THREE18.Mesh) || !(part.geometry instanceof THREE18.BufferGeometry))+ if (!(part instanceof THREE19.Mesh) || !(part.geometry instanceof THREE19.BufferGeometry))return;part.geometry.computeBoundingBox();const box = part.geometry.boundingBox;@@ -15270,7 +15363,7 @@ function objectBoundsInFrame2(object, frame) {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 THREE18.Vector3(x, y, z).applyMatrix4(matrix));+ bounds.expandByPoint(new THREE19.Vector3(x, y, z).applyMatrix4(matrix));found = true;}});@@ -15281,15 +15374,15 @@ function tuple2(value) {}function probeBox(id, root, bounds) {root.updateWorldMatrix(true, false);- const center = bounds.getCenter(new THREE18.Vector3).applyMatrix4(root.matrixWorld);- const size = bounds.getSize(new THREE18.Vector3);- const position = new THREE18.Vector3;- const quaternion = new THREE18.Quaternion;- const scale = new THREE18.Vector3;+ const center = bounds.getCenter(new THREE19.Vector3).applyMatrix4(root.matrixWorld);+ const size = bounds.getSize(new THREE19.Vector3);+ const position = new THREE19.Vector3;+ const quaternion = new THREE19.Quaternion;+ const scale = new THREE19.Vector3;root.matrixWorld.decompose(position, quaternion, scale);- const xAxis = new THREE18.Vector3(1, 0, 0).applyQuaternion(quaternion).normalize();- const yAxis = new THREE18.Vector3(0, 1, 0).applyQuaternion(quaternion).normalize();- const zAxis = new THREE18.Vector3(0, 0, 1).applyQuaternion(quaternion).normalize();+ const xAxis = new THREE19.Vector3(1, 0, 0).applyQuaternion(quaternion).normalize();+ const yAxis = new THREE19.Vector3(0, 1, 0).applyQuaternion(quaternion).normalize();+ const zAxis = new THREE19.Vector3(0, 0, 1).applyQuaternion(quaternion).normalize();return createOrientedProbeBox3({id,frame: createProbeLocalFrame3({@@ -15358,7 +15451,7 @@ function orientationFindings(context, root, intent) {const bounds = wholeAssetBounds(root);if (!bounds)return [];- const size = bounds.getSize(new THREE18.Vector3);+ const size = bounds.getSize(new THREE19.Vector3);const ratio = size.z / Math.max(size.x, 0.000000001);if (ratio <= ORIENTATION_RATIO)return [];@@ -15402,13 +15495,13 @@ function weldedBoundaryEdges(root, loop) {let triangleCount = 0;const vertexKey = (point) => [point.x, point.y, point.z].map((value) => Math.round(value * 1e6)).join(",");loop.traverseVisible((node) => {- if (!(node instanceof THREE18.Mesh) || !(node.geometry instanceof THREE18.BufferGeometry))+ if (!(node instanceof THREE19.Mesh) || !(node.geometry instanceof THREE19.BufferGeometry))return;const positions = node.geometry.getAttribute("position");if (!positions)return;const matrix = inverse.clone().multiply(node.matrixWorld);- const keys = Array.from({ length: positions.count }, (_, index) => vertexKey(new THREE18.Vector3().fromBufferAttribute(positions, index).applyMatrix4(matrix)));+ const keys = Array.from({ length: positions.count }, (_, index) => vertexKey(new THREE19.Vector3().fromBufferAttribute(positions, index).applyMatrix4(matrix)));const index = node.geometry.getIndex();const indices = index ? Array.from(index.array, Number) : Array.from({ length: positions.count }, (_, value) => value);for (let offset = 0;offset + 2 < indices.length; offset += 3) {@@ -15478,7 +15571,7 @@ function trackProfileFindings(context, root, intent) {const wheelBounds = objectBoundsInFrame2(roadWheel, root);if (!wheelBounds)continue;- const center = wheelBounds.getCenter(new THREE18.Vector3);+ const center = wheelBounds.getCenter(new THREE19.Vector3);if (expanded.containsPoint(center))continue;const clamped = center.clone().clamp(expanded.min, expanded.max);@@ -15504,7 +15597,7 @@ function trackProfileFindings(context, root, intent) {return findings;}function inspectMobilityAdvisory(context) {- if (!(context.scene instanceof THREE18.Object3D)) {+ if (!(context.scene instanceof THREE19.Object3D)) {return [];}const intent = context.mobility;@@ -15551,7 +15644,7 @@ var init_vehicle_advisory = __esm(() => {});// src/qa/vehicle.ts-import * as THREE19 from "three";+import * as THREE20 from "three";function finding(context, value) {return {...value,@@ -15568,7 +15661,7 @@ function rootAxis(root, axis) {return axis.clone().transformDirection(root.matrixWorld);}function angleDegrees(a, b) {- return THREE19.MathUtils.radToDeg(Math.acos(THREE19.MathUtils.clamp(a.clone().normalize().dot(b.clone().normalize()), -1, 1)));+ return THREE20.MathUtils.radToDeg(Math.acos(THREE20.MathUtils.clamp(a.clone().normalize().dot(b.clone().normalize()), -1, 1)));}function isDescendant(node, ancestor) {let current = node;@@ -15616,7 +15709,7 @@ function wheelCountFindings(context, intent, wheels) {}function wheelGeometryFindings(context, root, wheels) {const findings = [];- const expectedAxle = rootAxis(root, new THREE19.Vector3(0, 0, 1));+ const expectedAxle = rootAxis(root, new THREE20.Vector3(0, 0, 1));for (const wheel of wheels) {const disposition = componentDisposition(wheel);const centerTolerance = Math.max(CENTER_MINIMUM, (wheel.radius ?? 0) * CENTER_RATIO);@@ -15805,7 +15898,7 @@ function contactFindings2(context, root, intent, wheels) {function renderableMinYInRoot(rootInverse, node) {let minimum = Infinity;node.traverseVisible((part) => {- if (!(part instanceof THREE19.Mesh) || !(part.geometry instanceof THREE19.BufferGeometry))+ if (!(part instanceof THREE20.Mesh) || !(part.geometry instanceof THREE20.BufferGeometry))return;part.geometry.computeBoundingBox();const bounds = part.geometry.boundingBox;@@ -15815,7 +15908,7 @@ function renderableMinYInRoot(rootInverse, node) {for (const x of [bounds.min.x, bounds.max.x]) {for (const y of [bounds.min.y, bounds.max.y]) {for (const z of [bounds.min.z, bounds.max.z]) {- minimum = Math.min(minimum, new THREE19.Vector3(x, y, z).applyMatrix4(matrix).y);+ minimum = Math.min(minimum, new THREE20.Vector3(x, y, z).applyMatrix4(matrix).y);}}}@@ -15833,7 +15926,7 @@ function supportContactFindings(context, root, intent) {if (!isWheelContact && roles.some((role) => role.startsWith("contact."))) {explicitContacts.push({node,- contactY: localPoint2(inverse, new THREE19.Vector3().setFromMatrixPosition(node.matrixWorld)).y,+ contactY: localPoint2(inverse, new THREE20.Vector3().setFromMatrixPosition(node.matrixWorld)).y,source: "contact"});}@@ -15913,7 +16006,7 @@ function steeringFindings(context, root, intent, wheels) {return [];root.updateWorldMatrix(true, false);const inverse = root.matrixWorld.clone().invert();- const expectedAxis = rootAxis(root, new THREE19.Vector3(0, 1, 0));+ const expectedAxis = rootAxis(root, new THREE20.Vector3(0, 1, 0));const localCenters = wheels.map((wheel) => ({wheel,center: localPoint2(inverse, wheel.centerWorld)@@ -15923,8 +16016,8 @@ function steeringFindings(context, root, intent, wheels) {const findings = [];for (const { wheel } of targets) {const steering = wheel.steeringPivot;- const centerDelta = steering ? localPoint2(inverse, new THREE19.Vector3().setFromMatrixPosition(steering.matrixWorld)).distanceTo(localPoint2(inverse, wheel.centerWorld)) : Infinity;- const axisAngle = steering ? angleDegrees(new THREE19.Vector3(0, 1, 0).transformDirection(steering.matrixWorld), expectedAxis) : Infinity;+ const centerDelta = steering ? localPoint2(inverse, new THREE20.Vector3().setFromMatrixPosition(steering.matrixWorld)).distanceTo(localPoint2(inverse, wheel.centerWorld)) : Infinity;+ const axisAngle = steering ? angleDegrees(new THREE20.Vector3(0, 1, 0).transformDirection(steering.matrixWorld), expectedAxis) : Infinity;if (!steering || !isDescendant(wheel.pivot, steering) || centerDelta > CENTER_MINIMUM || axisAngle > AXIS_TOLERANCE_DEGREES) {const axisInvalid = axisAngle > AXIS_TOLERANCE_DEGREES;findings.push(finding(context, {@@ -15979,14 +16072,14 @@ function propulsionFindings(context, root, intent) {}for (const component of candidates) {const pivot = pivots.get(component.id);- const box = new THREE19.Box3().setFromObject(component.node);- const center = box.isEmpty() ? undefined : box.getCenter(new THREE19.Vector3);- const pivotCenter = pivot ? new THREE19.Vector3().setFromMatrixPosition(pivot.matrixWorld) : undefined;+ const box = new THREE20.Box3().setFromObject(component.node);+ const center = box.isEmpty() ? undefined : box.getCenter(new THREE20.Vector3);+ const pivotCenter = pivot ? new THREE20.Vector3().setFromMatrixPosition(pivot.matrixWorld) : undefined;const delta = center && pivotCenter ? localPoint2(rootInverse, center).distanceTo(localPoint2(rootInverse, pivotCenter)) : Infinity;const frameId = kind === "rotor" ? "propulsion-axis.+y" : "propulsion-axis.+x";const axisFrame = readSemanticMetadataV1(pivot ?? component.node)?.frames.find((frame) => frame.id === frameId);- const canonicalAxis = kind === "rotor" ? new THREE19.Vector3(0, 1, 0) : new THREE19.Vector3(1, 0, 0);- const axisAngle = pivot && axisFrame ? angleDegrees(canonicalAxis.clone().applyQuaternion(new THREE19.Quaternion(...axisFrame.rotation)).transformDirection(pivot.matrixWorld), rootAxis(root, canonicalAxis)) : Infinity;+ const canonicalAxis = kind === "rotor" ? new THREE20.Vector3(0, 1, 0) : new THREE20.Vector3(1, 0, 0);+ const axisAngle = pivot && axisFrame ? angleDegrees(canonicalAxis.clone().applyQuaternion(new THREE20.Quaternion(...axisFrame.rotation)).transformDirection(pivot.matrixWorld), rootAxis(root, canonicalAxis)) : Infinity;if (!pivot || !isDescendant(component.node, pivot) || delta > CENTER_MINIMUM || !axisFrame || axisAngle > AXIS_TOLERANCE_DEGREES) {findings.push(finding(context, {code: "VEH_ROTOR_PIVOT",@@ -16008,7 +16101,7 @@ function propulsionFindings(context, root, intent) {return findings;}function inspectMobility(context) {- if (!(context.scene instanceof THREE19.Object3D))+ if (!(context.scene instanceof THREE20.Object3D))return [];const intent = context.mobility;if (!intent)@@ -16081,7 +16174,7 @@ var init_vehicle2 = __esm(() => {});// src/qa/vegetation.ts-import * as THREE20 from "three";+import * as THREE21 from "three";function rolesOf2(node) {return readSemanticMetadataV1(node)?.roles ?? [];}@@ -16097,22 +16190,22 @@ function pathOf(node, root) {return names.reverse().join("/");}function localPoint3(rootInverse, node) {- return node.getWorldPosition(new THREE20.Vector3).applyMatrix4(rootInverse);+ return node.getWorldPosition(new THREE21.Vector3).applyMatrix4(rootInverse);}function meshLocalBox(mesh, rootInverse) {- if (!(mesh.geometry instanceof THREE20.BufferGeometry))+ if (!(mesh.geometry instanceof THREE21.BufferGeometry))return;mesh.geometry.computeBoundingBox();const source = mesh.geometry.boundingBox;if (!source || source.isEmpty())return;const base = rootInverse.clone().multiply(mesh.matrixWorld);- const result = new THREE20.Box3;- const count = mesh instanceof THREE20.InstancedMesh ? mesh.count : 1;+ const result = new THREE21.Box3;+ const count = mesh instanceof THREE21.InstancedMesh ? mesh.count : 1;for (let index = 0;index < count; index++) {const transform = base.clone();- if (mesh instanceof THREE20.InstancedMesh) {- const instance = new THREE20.Matrix4;+ if (mesh instanceof THREE21.InstancedMesh) {+ const instance = new THREE21.Matrix4;mesh.getMatrixAt(index, instance);transform.multiply(instance);}@@ -16125,7 +16218,7 @@ function collectRenderableBounds(root) {const inverse = root.matrixWorld.clone().invert();const values = [];root.traverseVisible((node) => {- if (!(node instanceof THREE20.Mesh))+ if (!(node instanceof THREE21.Mesh))return;const box = meshLocalBox(node, inverse);if (!box)@@ -16143,7 +16236,7 @@ function vegetationIntent(intent) {}function inspectFoliageContact(context) {const trusted = context.foliage;- if (!trusted?.grounded || !(context.scene instanceof THREE20.Object3D))+ if (!trusted?.grounded || !(context.scene instanceof THREE21.Object3D))return [];const planeY = context.groundPlaneY ?? 0;const root = context.scene;@@ -16181,7 +16274,7 @@ function inspectFoliageContact(context) {}const findings = [];for (const contact of contacts) {- const contactPoint = contact.frameTranslation ? new THREE20.Vector3(...contact.frameTranslation).applyMatrix4(contact.node.matrixWorld).applyMatrix4(inverse) : localPoint3(inverse, contact.node);+ const contactPoint = contact.frameTranslation ? new THREE21.Vector3(...contact.frameTranslation).applyMatrix4(contact.node.matrixWorld).applyMatrix4(inverse) : localPoint3(inverse, contact.node);const y = contactPoint.y;const offset = y - planeY;if (Math.abs(offset) <= VEGETATION_CONTACT_TOLERANCE_METERS)@@ -16210,7 +16303,7 @@ function inspectFoliageContact(context) {for (const support of semanticSupports) {let minimumY = Infinity;support.traverseVisible((node) => {- if (!(node instanceof THREE20.Mesh))+ if (!(node instanceof THREE21.Mesh))return;const box = meshLocalBox(node, inverse);if (box)@@ -16238,25 +16331,25 @@ function inspectFoliageContact(context) {return findings;}function materialNames(node) {- if (!(node instanceof THREE20.Mesh))+ if (!(node instanceof THREE21.Mesh))return [];const materials = Array.isArray(node.material) ? node.material : [node.material];return materials.filter(Boolean).map((material) => material.name ?? "");}function inspectFoliageScope(context) {const trusted = context.foliage;- if (!trusted?.standalone || !(context.scene instanceof THREE20.Object3D))+ if (!trusted?.standalone || !(context.scene instanceof THREE21.Object3D))return [];const root = context.scene;const renderables = collectRenderableBounds(root);if (renderables.length === 0)return [];- const overall = renderables.reduce((box, value) => box.union(value.box), new THREE20.Box3);- const overallSize = overall.getSize(new THREE20.Vector3);+ const overall = renderables.reduce((box, value) => box.union(value.box), new THREE21.Box3);+ const overallSize = overall.getSize(new THREE21.Vector3);const findings = [];for (const value of renderables) {- const size = value.box.getSize(new THREE20.Vector3);- const center = value.box.getCenter(new THREE20.Vector3);+ const size = value.box.getSize(new THREE21.Vector3);+ const center = value.box.getCenter(new THREE21.Vector3);const names = [value.node.name, ...value.roles];const nameEvidence = names.some((name) => CLUTTER_NAME.test(name));const roleEvidence = value.roles.some((role) => /(?:terrain|soil|rock|pot|planter|base)/i.test(role));@@ -16293,8 +16386,8 @@ function inspectFoliageScope(context) {function unionVolume(boxes) {if (boxes.length === 0)return 0;- const union = boxes.reduce((result, box) => result.union(box), new THREE20.Box3);- const size = union.getSize(new THREE20.Vector3);+ const union = boxes.reduce((result, box) => result.union(box), new THREE21.Box3);+ const size = union.getSize(new THREE21.Vector3);return size.x * size.y * size.z;}function projectedOccupancy(boxes, axes) {@@ -16364,7 +16457,7 @@ function boxDistanceToPoint(box, point) {function endpointRadius(position, axis, axisValue, tolerance, scale) {const radialAxes = [0, 1, 2].filter((value) => value !== axis);const points = [];- const point = new THREE20.Vector3;+ const point = new THREE21.Vector3;for (let index = 0;index < position.count; index++) {point.fromBufferAttribute(position, index);if (Math.abs(point.getComponent(axis) - axisValue) <= tolerance)@@ -16372,7 +16465,7 @@ function endpointRadius(position, axis, axisValue, tolerance, scale) {}if (points.length === 0)return;- const center = new THREE20.Vector3;+ const center = new THREE21.Vector3;center.setComponent(axis, axisValue);for (const radialAxis of radialAxes) {center.setComponent(radialAxis, points.reduce((sum, value) => sum + value.getComponent(radialAxis), 0) / points.length);@@ -16386,7 +16479,7 @@ function endpointRadius(position, axis, axisValue, tolerance, scale) {return { center, radius };}function growthNodeMeasurement(root, candidate, allCandidates, band) {- if (!(candidate.node instanceof THREE20.Mesh))+ if (!(candidate.node instanceof THREE21.Mesh))return;const geometry = candidate.node.geometry;const position = geometry.getAttribute("position");@@ -16398,9 +16491,9 @@ function growthNodeMeasurement(root, candidate, allCandidates, band) {return;root.updateWorldMatrix(true, true);const relative = root.matrixWorld.clone().invert().multiply(candidate.node.matrixWorld);- const relativeScale = new THREE20.Vector3;- relative.decompose(new THREE20.Vector3, new THREE20.Quaternion, relativeScale);- const size = geometryBox.getSize(new THREE20.Vector3);+ const relativeScale = new THREE21.Vector3;+ relative.decompose(new THREE21.Vector3, new THREE21.Quaternion, relativeScale);+ const size = geometryBox.getSize(new THREE21.Vector3);const scaledSizes = [Math.abs(size.x * relativeScale.x),Math.abs(size.y * relativeScale.y),@@ -16467,7 +16560,7 @@ function measureFoliageGrowth(foliage, root) {};}function inspectFoliageGrowth(context) {- if (!context.foliage || !(context.scene instanceof THREE20.Object3D))+ if (!context.foliage || !(context.scene instanceof THREE21.Object3D))return [];const measured = measureFoliageGrowth(context.foliage, context.scene);const findings = [];@@ -16518,7 +16611,7 @@ function measureVegetationFoliageAttachment(root) {const support = renderables.filter((value) => roleOrNameSource(value, TRUNK_PATTERNS) || roleOrNameSource(value, BRANCH_PATTERNS));const foliage = renderables.filter((value) => roleOrNameSource(value, CANOPY_PATTERNS));const clusters = foliage.map((value) => {- const size = value.box.getSize(new THREE20.Vector3);+ const size = value.box.getSize(new THREE21.Vector3);const threshold = stable3(Math.max(0.03, Math.min(0.18, size.length() * 0.12)));const nearest = support.map((candidate) => ({ candidate, gap: distanceBetweenBoxes(value.box, candidate.box) })).sort((a, b) => a.gap - b.gap || (a.candidate.node.name || "").localeCompare(b.candidate.node.name || ""))[0];const source = roleOrNameSource(value, CANOPY_PATTERNS) ?? "fallback";@@ -16541,7 +16634,7 @@ function measureVegetationFoliageAttachment(root) {};}function inspectFoliageAttachment(context) {- if (!context.foliage || !(context.scene instanceof THREE20.Object3D))+ if (!context.foliage || !(context.scene instanceof THREE21.Object3D))return [];return measureVegetationFoliageAttachment(context.scene).clusters.filter((cluster) => cluster.detached).map((cluster) => finding2(context, {code: "VEG_FOLIAGE_DETACHED",@@ -16561,9 +16654,9 @@ function inspectFoliageAttachment(context) {}function relativeTransformSignature(root, node) {const matrix = root.matrixWorld.clone().invert().multiply(node.matrixWorld);- const scale = new THREE20.Vector3;- const quaternion = new THREE20.Quaternion;- matrix.decompose(new THREE20.Vector3, quaternion, scale);+ const scale = new THREE21.Vector3;+ const quaternion = new THREE21.Quaternion;+ matrix.decompose(new THREE21.Vector3, quaternion, scale);if (quaternion.w < 0)quaternion.set(-quaternion.x, -quaternion.y, -quaternion.z, -quaternion.w);const values = [...scale.toArray(), ...quaternion.toArray()].map((value) => stable3(value));@@ -16584,9 +16677,9 @@ function measureFoliageRepetition(requirements, root) {nodes: values.map((value) => value.node.name || "foliage-cluster").sort()})).sort((a, b) => a.signature.localeCompare(b.signature));const supports = collectRenderableBounds(root).filter((value) => roleOrNameSource(value, TRUNK_PATTERNS));- const centerBox = supports.reduce((box, value) => box.union(value.box), new THREE20.Box3);- const centers = foliage.map((value) => value.box.getCenter(new THREE20.Vector3));- const center = centerBox.isEmpty() ? centers.reduce((result, value) => result.add(value), new THREE20.Vector3).multiplyScalar(centers.length > 0 ? 1 / centers.length : 0) : centerBox.getCenter(new THREE20.Vector3);+ const centerBox = supports.reduce((box, value) => box.union(value.box), new THREE21.Box3);+ const centers = foliage.map((value) => value.box.getCenter(new THREE21.Vector3));+ const center = centerBox.isEmpty() ? centers.reduce((result, value) => result.add(value), new THREE21.Vector3).multiplyScalar(centers.length > 0 ? 1 / centers.length : 0) : centerBox.getCenter(new THREE21.Vector3);const radial = centers.map((value) => ({angle: Math.atan2(value.z - center.z, value.x - center.x),radius: Math.hypot(value.x - center.x, value.z - center.z)@@ -16621,7 +16714,7 @@ function measureFoliageRepetition(requirements, root) {};}function inspectFoliageRepetition(context) {- if (!context.foliage || !(context.scene instanceof THREE20.Object3D))+ if (!context.foliage || !(context.scene instanceof THREE21.Object3D))return [];const measured = measureFoliageRepetition(context.foliage, context.scene);if (measured.suppressedForTopiary)@@ -16679,7 +16772,7 @@ function measureFoliageCanopy(profile, root) {}function inspectFoliageCanopy(context) {const trusted = context.foliage;- if (!trusted?.canopyProfile || !(context.scene instanceof THREE20.Object3D))+ if (!trusted?.canopyProfile || !(context.scene instanceof THREE21.Object3D))return [];const measurements = measureFoliageCanopy(trusted.canopyProfile, context.scene);const bands = PROFILE_BANDS[measurements.profile];@@ -16740,7 +16833,7 @@ function inspectFoliageCanopy(context) {return findings;}function materialValue(material) {- if (!(material instanceof THREE20.MeshStandardMaterial) && !(material instanceof THREE20.MeshBasicMaterial)) {+ if (!(material instanceof THREE21.MeshStandardMaterial) && !(material instanceof THREE21.MeshBasicMaterial)) {return;}const color = material.color;@@ -16750,11 +16843,11 @@ function measureFoliageMaterials(mode, root) {const values = [];let foliageNodeCount = 0;root.traverseVisible((node) => {- if (!(node instanceof THREE20.Mesh))+ if (!(node instanceof THREE21.Mesh))return;const bounds = {node,- box: new THREE20.Box3,+ box: new THREE21.Box3,roles: rolesOf2(node),source: rolesOf2(node).length > 0 ? "semantic" : "fallback"};@@ -16781,7 +16874,7 @@ function measureFoliageMaterials(mode, root) {};}function inspectFoliageMaterial(context) {- if (!context.foliage || !(context.scene instanceof THREE20.Object3D))+ if (!context.foliage || !(context.scene instanceof THREE21.Object3D))return [];if (!context.materialMode)return [];@@ -16937,7 +17030,7 @@ var init_vegetation = __esm(() => {});// src/qa/prop.ts-import * as THREE21 from "three";+import * as THREE22 from "three";function finding3(context, value) {return {...value,@@ -16959,11 +17052,11 @@ function nodePath2(root, node) {return names.reverse().join("/");}function transformedBox(source, transform) {- const result = new THREE21.Box3;+ const result = new THREE22.Box3;for (const x of [source.min.x, source.max.x]) {for (const y of [source.min.y, source.max.y]) {for (const z of [source.min.z, source.max.z]) {- result.expandByPoint(new THREE21.Vector3(x, y, z).applyMatrix4(transform));+ result.expandByPoint(new THREE22.Vector3(x, y, z).applyMatrix4(transform));}}}@@ -16975,9 +17068,9 @@ function collectParts(root, measureVertices = false) {const result = [];root.traverseVisible((node) => {const roles = rolesOf3(node);- const renderable = node instanceof THREE21.Mesh;+ const renderable = node instanceof THREE22.Mesh;let box;- if (renderable && node.geometry instanceof THREE21.BufferGeometry) {+ if (renderable && node.geometry instanceof THREE22.BufferGeometry) {const position = node.geometry.getAttribute("position");node.geometry.computeBoundingBox();if (node.geometry.boundingBox) {@@ -16985,17 +17078,17 @@ function collectParts(root, measureVertices = false) {const measure = (matrix) => {if (!measureVertices || !position)return transformedBox(node.geometry.boundingBox, matrix);- const result = new THREE21.Box3;- const point = new THREE21.Vector3;+ const result = new THREE22.Box3;+ const point = new THREE22.Vector3;for (let i = 0;i < position.count; i++) {point.fromBufferAttribute(position, i).applyMatrix4(matrix);result.expandByPoint(point);}return result;};- if (node instanceof THREE21.InstancedMesh) {- box = new THREE21.Box3;- const instance = new THREE21.Matrix4;+ if (node instanceof THREE22.InstancedMesh) {+ box = new THREE22.Box3;+ const instance = new THREE22.Matrix4;for (let i = 0;i < node.count; i++) {node.getMatrixAt(i, instance);box.union(measure(transform.clone().multiply(instance)));@@ -17005,7 +17098,7 @@ function collectParts(root, measureVertices = false) {}}} else if (roles.length > 0) {- box = transformedBox(new THREE21.Box3(new THREE21.Vector3(-0.5, -0.5, -0.5), new THREE21.Vector3(0.5, 0.5, 0.5)), rootInverse.clone().multiply(node.matrixWorld));+ box = transformedBox(new THREE22.Box3(new THREE22.Vector3(-0.5, -0.5, -0.5), new THREE22.Vector3(0.5, 0.5, 0.5)), rootInverse.clone().multiply(node.matrixWorld));}if (box?.isEmpty())box = undefined;@@ -17089,14 +17182,14 @@ function legacyArticulationEvidence(context, root) {});if (joints.length === 0)return false;- const clips = (context.clips ?? []).filter((clip) => clip instanceof THREE21.AnimationClip);+ const clips = (context.clips ?? []).filter((clip) => clip instanceof THREE22.AnimationClip);if ((context.intent.animation?.clips.length ?? 0) === 0 && clips.length === 0)return true;const targets = new Set(clips.flatMap((clip) => clip.tracks.map((track) => track.name.split(".")[0] ?? "")));return joints.some((joint) => targets.has(joint));}function evaluatePropArticulationQa(context) {- if (context.intent.category !== "prop" || !context.intent.capabilities.includes("articulated") || !(context.scene instanceof THREE21.Object3D)) {+ if (context.intent.category !== "prop" || !context.intent.capabilities.includes("articulated") || !(context.scene instanceof THREE22.Object3D)) {return [];}if (usesExplicitLegacyProfile(context) && motionAssemblies(collectParts(context.scene)).length === 0 && legacyArticulationEvidence(context, context.scene))@@ -17108,7 +17201,7 @@ function evaluatePropArticulationQa(context) {});}function inspectArticulation(input) {- if (!(input.scene instanceof THREE21.Object3D))+ if (!(input.scene instanceof THREE22.Object3D))return [];const root = input.scene;const context = { profile: input.profile ?? "asset.requirements.v1" };@@ -17222,11 +17315,11 @@ function rolePart(parts, expression) {return parts.find((part) => part.roles.some((role) => expression.test(role)));}function interiorUsable(box, minimumExtent) {- const size = box.getSize(new THREE21.Vector3);+ const size = box.getSize(new THREE22.Vector3);return [size.x, size.y, size.z].every((value) => value > 0 && value >= minimumExtent);}function evaluatePropContainerQa(context) {- if (context.intent.category !== "prop" || !(context.scene instanceof THREE21.Object3D))+ if (context.intent.category !== "prop" || !(context.scene instanceof THREE22.Object3D))return [];const explicitlyOpen = context.intent.capabilities.includes("openable");const explicitContainment = /^(?:open-)?(?:container|chest|case|box)$/i.test(context.intent.subtype ?? "");@@ -17248,7 +17341,7 @@ function evaluatePropContainerQa(context) {});}function inspectContainerOpening(input) {- if (!(input.scene instanceof THREE21.Object3D))+ if (!(input.scene instanceof THREE22.Object3D))return [];const root = input.scene;const context = { profile: input.profile ?? "asset.requirements.v1" };@@ -17290,7 +17383,7 @@ function inspectContainerOpening(input) {repairText: "Add a non-rendered scaled prop.container.interior.main marker inside the shell."}));} else if (!interiorUsable(interior.box, minimumExtent)) {- const size = interior.box.getSize(new THREE21.Vector3);+ const size = interior.box.getSize(new THREE22.Vector3);findings.push(finding3(context, {code: "PROP_CONTAINER_INTERIOR_UNUSABLE",disposition: "block",@@ -17348,21 +17441,21 @@ function inspectContainerOpening(input) {return findings;}function horizontalDirection(part, root) {- if (!(part.node instanceof THREE21.Mesh) || !(part.node.geometry instanceof THREE21.BufferGeometry)) {+ if (!(part.node instanceof THREE22.Mesh) || !(part.node.geometry instanceof THREE22.BufferGeometry)) {return;}part.node.geometry.computeBoundingBox();const box = part.node.geometry.boundingBox;if (!box)return;- const size = box.getSize(new THREE21.Vector3);- const axis = size.x >= size.z ? new THREE21.Vector3(1, 0, 0) : new THREE21.Vector3(0, 0, 1);+ const size = box.getSize(new THREE22.Vector3);+ const axis = size.x >= size.z ? new THREE22.Vector3(1, 0, 0) : new THREE22.Vector3(0, 0, 1);root.updateWorldMatrix(true, true);- const rootQuaternion = root.getWorldQuaternion(new THREE21.Quaternion).invert();- return axis.applyQuaternion(part.node.getWorldQuaternion(new THREE21.Quaternion)).applyQuaternion(rootQuaternion).setY(0).normalize();+ const rootQuaternion = root.getWorldQuaternion(new THREE22.Quaternion).invert();+ return axis.applyQuaternion(part.node.getWorldQuaternion(new THREE22.Quaternion)).applyQuaternion(rootQuaternion).setY(0).normalize();}function evaluatePropCircularAssemblyQa(context) {- if (context.intent.category !== "prop" || !(context.scene instanceof THREE21.Object3D))+ if (context.intent.category !== "prop" || !(context.scene instanceof THREE22.Object3D))return [];const root = context.scene;const parts = collectParts(root);@@ -17373,8 +17466,8 @@ function evaluatePropCircularAssemblyQa(context) {const memberParts = parts.filter((part) => part.box && (part.roles.some((role) => role.startsWith("prop.circular.member.")) || namedProfile && /(?:stave|ring[_.-]?segment)/i.test(part.node.name)));if (memberParts.length < 3)return [];- const centers = memberParts.map((part) => part.box.getCenter(new THREE21.Vector3));- const ringCenter = centers.reduce((sum, center) => sum.add(center), new THREE21.Vector3).multiplyScalar(1 / centers.length);+ const centers = memberParts.map((part) => part.box.getCenter(new THREE22.Vector3));+ const ringCenter = centers.reduce((sum, center) => sum.add(center), new THREE22.Vector3).multiplyScalar(1 / centers.length);const members = memberParts.map((part, index) => {const center = centers[index];return {@@ -17413,7 +17506,7 @@ function evaluatePropCircularAssemblyQa(context) {if (!member.horizontalDirection)return false;const radial = member.center.clone().sub(ringCenter).setY(0).normalize();- const tangent = new THREE21.Vector3(-radial.z, 0, radial.x);+ const tangent = new THREE22.Vector3(-radial.z, 0, radial.x);const radialScore = Math.abs(member.horizontalDirection.dot(radial));const tangentScore = Math.abs(member.horizontalDirection.dot(tangent));return expectedOrientation === "tangent" ? tangentScore + 0.1 < radialScore : radialScore + 0.1 < tangentScore;@@ -17440,7 +17533,7 @@ function evaluatePropCircularAssemblyQa(context) {return findings;}function inspectPlacement(input) {- if (!(input.scene instanceof THREE21.Object3D))+ if (!(input.scene instanceof THREE22.Object3D))return [];const placementFinding = (value) => ({...value,@@ -17451,8 +17544,8 @@ function inspectPlacement(input) {const renderable = parts.filter((part) => part.renderable && part.box);if (renderable.length === 0)return [];- const bounds = renderable.reduce((box, part) => box.union(part.box), new THREE21.Box3);- const size = bounds.getSize(new THREE21.Vector3);+ const bounds = renderable.reduce((box, part) => box.union(part.box), new THREE22.Box3);+ const size = bounds.getSize(new THREE22.Vector3);const findings = [];for (const axis of ["x", "y", "z"]) {const expected = input.bounds?.[axis];@@ -17499,7 +17592,7 @@ function inspectPlacement(input) {}const placement = parts.find((part) => part.roles.includes("prop.pivot.placement"));if (placement) {- const point = placement.node.getWorldPosition(new THREE21.Vector3);+ const point = placement.node.getWorldPosition(new THREE22.Vector3);point.applyMatrix4(root.matrixWorld.clone().invert());const horizontalOutside = point.x < bounds.min.x - GROUND_TOLERANCE_METERS || point.x > bounds.max.x + GROUND_TOLERANCE_METERS || point.z < bounds.min.z - GROUND_TOLERANCE_METERS || point.z > bounds.max.z + GROUND_TOLERANCE_METERS;const verticalDelta = Math.abs(point.y - bounds.min.y);@@ -17742,7 +17835,7 @@ var init_lod2 = __esm(() => {});// src/qa/part-connectivity.ts-import * as THREE22 from "three";+import * as THREE23 from "three";function collectParts2(root, exempt, supports) {const parts = [];let lodExcluded = 0;@@ -17760,7 +17853,7 @@ function collectParts2(root, exempt, supports) {exempt.push(name);return;}- const box = new THREE22.Box3().setFromObject(mesh);+ const box = new THREE23.Box3().setFromObject(mesh);if (box.isEmpty())return;const support = restingSupport(mesh, box.min.y, supports);@@ -17855,7 +17948,7 @@ function analyzePartConnectivity(root, supports) {return report;}function inspectPartConnectivity(scene, supports) {- if (!(scene instanceof THREE22.Object3D))+ if (!(scene instanceof THREE23.Object3D))return [];const report = analyzePartConnectivity(scene, supports);const lodNote = report.lodExcluded === 1 ? " 1 part on an LOD level above 0 was not analyzed." : report.lodExcluded > 1 ? ` ${report.lodExcluded} parts on LOD levels above 0 were not analyzed.` : "";@@ -18032,7 +18125,7 @@ var init_open_shell = __esm(() => {});// src/qa/self-intersection.ts-import * as THREE23 from "three";+import * as THREE24 from "three";function boxOverlapRatio(a, b) {const shared = Math.max(0, Math.min(a.max.x, b.max.x) - Math.max(a.min.x, b.min.x)) * Math.max(0, Math.min(a.max.y, b.max.y) - Math.max(a.min.y, b.min.y)) * Math.max(0, Math.min(a.max.z, b.max.z) - Math.max(a.min.z, b.min.z));const ratio = shared / Math.min(boxVolume(a), boxVolume(b));@@ -18083,8 +18176,8 @@ function collectParts3(root, skipped) {const box = mesh.geometry.boundingBox.clone().applyMatrix4(mesh.matrixWorld);if (box.isEmpty())return;- const center = box.getCenter(new THREE23.Vector3);- const size = box.getSize(new THREE23.Vector3);+ const center = box.getCenter(new THREE24.Vector3);+ const size = box.getSize(new THREE24.Vector3);const scale = Math.max(size.x, size.y, size.z);if (![...box.min, ...box.max, scale].every(Number.isFinite) || !(scale > 0) || !Number.isFinite(mesh.matrixWorld.determinant()) || mesh.matrixWorld.determinant() === 0) {skipped.push({@@ -18116,7 +18209,7 @@ function meshToArrays(part) {matrix.elements[12] -= center.x;matrix.elements[13] -= center.y;matrix.elements[14] -= center.z;- const v = new THREE23.Vector3;+ const v = new THREE24.Vector3;const verts = new Float32Array(position.count * 3);for (let i = 0;i < position.count; i++) {v.set(position.getX(i), position.getY(i), position.getZ(i)).applyMatrix4(matrix).divideScalar(scale);@@ -18464,9 +18557,9 @@ var init_self_intersection = __esm(() => {});// src/sweep-analysis.ts-import * as THREE24 from "three";+import * as THREE25 from "three";function segmentHitsTriangle(a, b, tri, epsilon) {- const plane = new THREE24.Plane().setFromCoplanarPoints(tri.a, tri.b, tri.c);+ const plane = new THREE25.Plane().setFromCoplanarPoints(tri.a, tri.b, tri.c);if (plane.normal.lengthSq() === 0)return false;const da = plane.distanceToPoint(a), db = plane.distanceToPoint(b);@@ -18504,7 +18597,7 @@ function recordSweepAnalysis(geometry, rings, profiles, closed) {return result;}const unique = closed ? rings.length - 1 : rings.length;- const centers = rings.map((ring) => ring.reduce((sum, p) => sum.add(p), new THREE24.Vector3).divideScalar(ring.length));+ const centers = rings.map((ring) => ring.reduce((sum, p) => sum.add(p), new THREE25.Vector3).divideScalar(ring.length));for (let i = closed ? 0 : 1;i < (closed ? unique : unique - 1); i++) {const a = centers[(i - 1 + unique) % unique], b = centers[i], c = centers[(i + 1) % unique];const u = b.clone().sub(a), v = c.clone().sub(b);@@ -18518,17 +18611,17 @@ function recordSweepAnalysis(geometry, rings, profiles, closed) {const triangles = new Map;const faces = (index) => {if (!triangles.has(index))- triangles.set(index, THREE24.ShapeUtils.triangulateShape(profiles[index], []).map(([a, b, c]) => new THREE24.Triangle(rings[index][a], rings[index][b], rings[index][c])));+ triangles.set(index, THREE25.ShapeUtils.triangulateShape(profiles[index], []).map(([a, b, c]) => new THREE25.Triangle(rings[index][a], rings[index][b], rings[index][c])));return triangles.get(index);};for (let i = 1;i < rings.length; i++) {- const boundsA = new THREE24.Box3().setFromPoints(rings[i - 1]);- const boundsB = new THREE24.Box3().setFromPoints(rings[i]);+ const boundsA = new THREE25.Box3().setFromPoints(rings[i - 1]);+ const boundsB = new THREE25.Box3().setFromPoints(rings[i]);if (!boundsA.intersectsBox(boundsB)) {result.ringPairsChecked++;continue;}- const epsilon = Math.max(boundsA.getSize(new THREE24.Vector3).length(), boundsB.getSize(new THREE24.Vector3).length()) * 0.0000000001;+ const epsilon = Math.max(boundsA.getSize(new THREE25.Vector3).length(), boundsB.getSize(new THREE25.Vector3).length()) * 0.0000000001;let hit = false;pair:for (const [a, b] of [@@ -18628,7 +18721,7 @@ var init_sweep = __esm(() => {});// src/qa/environment.ts-import * as THREE25 from "three";+import * as THREE26 from "three";function finding4(context, value) {return { ...value, profile: context.profile ?? "asset.requirements.v1" };}@@ -18647,11 +18740,11 @@ function nodePath3(root, node) {return names.reverse().join("/");}function transformedBox2(source, transform) {- const result = new THREE25.Box3;+ const result = new THREE26.Box3;for (const x of [source.min.x, source.max.x]) {for (const y of [source.min.y, source.max.y]) {for (const z of [source.min.z, source.max.z]) {- result.expandByPoint(new THREE25.Vector3(x, y, z).applyMatrix4(transform));+ result.expandByPoint(new THREE26.Vector3(x, y, z).applyMatrix4(transform));}}}@@ -18660,16 +18753,16 @@ function transformedBox2(source, transform) {function orientedBoxFromLocalBounds(root, node, source, relative = root.matrixWorld.clone().invert().multiply(node.matrixWorld)) {if (!relative.elements.every(Number.isFinite))return;- const position = new THREE25.Vector3;- const rotation = new THREE25.Quaternion;- const scale = new THREE25.Vector3;+ const position = new THREE26.Vector3;+ const rotation = new THREE26.Quaternion;+ const scale = new THREE26.Vector3;relative.decompose(position, rotation, scale);- const recomposed = new THREE25.Matrix4().compose(position, rotation, scale);+ const recomposed = new THREE26.Matrix4().compose(position, rotation, scale);const residual = Math.max(...relative.elements.map((component, index) => Math.abs(component - (recomposed.elements[index] ?? component))));if (residual > 0.00001)return;- const center = source.getCenter(new THREE25.Vector3).applyMatrix4(relative);- const sourceHalf = source.getSize(new THREE25.Vector3).multiplyScalar(0.5);+ const center = source.getCenter(new THREE26.Vector3).applyMatrix4(relative);+ const sourceHalf = source.getSize(new THREE26.Vector3).multiplyScalar(0.5);const halfExtents = [Math.abs(sourceHalf.x * scale.x),Math.abs(sourceHalf.y * scale.y),@@ -18690,24 +18783,24 @@ function collectParts4(root) {const result = [];root.traverseVisible((node) => {const roles = rolesOf4(node);- const renderable = node instanceof THREE25.Mesh;+ const renderable = node instanceof THREE26.Mesh;let box;let orientedBox;let source;- if (renderable && node.geometry instanceof THREE25.BufferGeometry) {+ if (renderable && node.geometry instanceof THREE26.BufferGeometry) {node.geometry.computeBoundingBox();if (node.geometry.boundingBox) {source = node.geometry.boundingBox;}} else if (roles.length > 0) {- source = new THREE25.Box3(new THREE25.Vector3(-0.5, -0.5, -0.5), new THREE25.Vector3(0.5, 0.5, 0.5));+ source = new THREE26.Box3(new THREE26.Vector3(-0.5, -0.5, -0.5), new THREE26.Vector3(0.5, 0.5, 0.5));}const relative = rootInverse.clone().multiply(node.matrixWorld);- const count = node instanceof THREE25.InstancedMesh ? node.count : 1;+ const count = node instanceof THREE26.InstancedMesh ? node.count : 1;for (let index = 0;index < count; index++) {const transform = relative.clone();- if (node instanceof THREE25.InstancedMesh) {- const instance = new THREE25.Matrix4;+ if (node instanceof THREE26.InstancedMesh) {+ const instance = new THREE26.Matrix4;node.getMatrixAt(index, instance);transform.multiply(instance);}@@ -18738,9 +18831,9 @@ function resolveSocket(root, node, socket) {return;root.updateWorldMatrix(true, true);const rootInverse = root.matrixWorld.clone().invert();- const point = new THREE25.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);- const rootInverseQuaternion = root.getWorldQuaternion(new THREE25.Quaternion).invert();- const rotation = node.getWorldQuaternion(new THREE25.Quaternion).multiply(new THREE25.Quaternion(...frame.rotation)).premultiply(rootInverseQuaternion).normalize();+ const point = new THREE26.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);+ const rootInverseQuaternion = root.getWorldQuaternion(new THREE26.Quaternion).invert();+ const rotation = node.getWorldQuaternion(new THREE26.Quaternion).multiply(new THREE26.Quaternion(...frame.rotation)).premultiply(rootInverseQuaternion).normalize();return {id: socket.id,type: socket.type,@@ -18769,7 +18862,7 @@ function socketByType(sockets, type) {return sockets.find((socket) => socket.type === type);}function inspectPlacementSockets(context) {- if (!(context.scene instanceof THREE25.Object3D)) {+ if (!(context.scene instanceof THREE26.Object3D)) {return [];}const root = context.scene;@@ -18833,7 +18926,7 @@ function materialSignature(material) {function boundarySamples(root, axis, side, bins = 12) {root.updateWorldMatrix(true, true);const inverse = root.matrixWorld.clone().invert();- const localBounds = new THREE25.Box3;+ const localBounds = new THREE26.Box3;for (const part of collectParts4(root))if (part.renderable && part.box)localBounds.union(part.box);@@ -18847,30 +18940,30 @@ function boundarySamples(root, axis, side, bins = 12) {const crossExtent = Math.max(0.000000001, localBounds.max[crossAxis] - crossMin);const byBin = new Map;root.traverseVisible((node) => {- if (!(node instanceof THREE25.Mesh) || !(node.geometry instanceof THREE25.BufferGeometry))+ if (!(node instanceof THREE26.Mesh) || !(node.geometry instanceof THREE26.BufferGeometry))return;const positions = node.geometry.getAttribute("position");if (positions?.itemSize !== 3)return;const normals = node.geometry.getAttribute("normal");const relative = inverse.clone().multiply(node.matrixWorld);- const count = node instanceof THREE25.InstancedMesh ? node.count : 1;+ const count = node instanceof THREE26.InstancedMesh ? node.count : 1;for (let instanceIndex = 0;instanceIndex < count; instanceIndex++) {const transform = relative.clone();- if (node instanceof THREE25.InstancedMesh) {- const instance = new THREE25.Matrix4;+ if (node instanceof THREE26.InstancedMesh) {+ const instance = new THREE26.Matrix4;node.getMatrixAt(instanceIndex, instance);transform.multiply(instance);}- const normalMatrix = new THREE25.Matrix3().getNormalMatrix(transform);+ const normalMatrix = new THREE26.Matrix3().getNormalMatrix(transform);const material = materialSignature(node.material);for (let index = 0;index < positions.count; index++) {- const point = new THREE25.Vector3(positions.getX(index), positions.getY(index), positions.getZ(index)).applyMatrix4(transform);+ const point = new THREE26.Vector3(positions.getX(index), positions.getY(index), positions.getZ(index)).applyMatrix4(transform);if (Math.abs(point[axis] - edge) > band)continue;- const t = THREE25.MathUtils.clamp((point[crossAxis] - crossMin) / crossExtent, 0, 1);+ const t = THREE26.MathUtils.clamp((point[crossAxis] - crossMin) / crossExtent, 0, 1);const bin = Math.min(bins - 1, Math.floor(t * bins));- const normal = normals ? new THREE25.Vector3(normals.getX(index), normals.getY(index), normals.getZ(index)).applyMatrix3(normalMatrix).normalize() : new THREE25.Vector3(0, 1, 0);+ const normal = normals ? new THREE26.Vector3(normals.getX(index), normals.getY(index), normals.getZ(index)).applyMatrix3(normalMatrix).normalize() : new THREE26.Vector3(0, 1, 0);const current = byBin.get(bin);if (!current || point.y > current.height || point.y === current.height && normal.y > current.normal.y) {byBin.set(bin, { bin, height: point.y, normal, material });@@ -18893,7 +18986,7 @@ function edgePairMeasurements(root, axis, sockets) {...positive.map((sample) => sample.bin)]);const maximumHeightDelta = pairs.length ? Math.max(...pairs.map(([a, b]) => Math.abs(a.height - b.height))) : Number.POSITIVE_INFINITY;- const maximumNormalDeltaDegrees = pairs.length ? Math.max(...pairs.map(([a, b]) => THREE25.MathUtils.radToDeg(Math.acos(THREE25.MathUtils.clamp(a.normal.dot(b.normal), -1, 1))))) : 180;+ const maximumNormalDeltaDegrees = pairs.length ? Math.max(...pairs.map(([a, b]) => THREE26.MathUtils.radToDeg(Math.acos(THREE26.MathUtils.clamp(a.normal.dot(b.normal), -1, 1))))) : 180;const materialMismatch = pairs.some(([a, b]) => a.material !== b.material);const negativeSocket = socketByType(sockets, `environment.tile.${axis}-negative`);const positiveSocket = socketByType(sockets, `environment.tile.${axis}-positive`);@@ -18910,7 +19003,7 @@ function edgePairMeasurements(root, axis, sockets) {};}function inspectTileEdges(context) {- if (context.tileable !== true || !(context.scene instanceof THREE25.Object3D)) {+ if (context.tileable !== true || !(context.scene instanceof THREE26.Object3D)) {return [];}const root = context.scene;@@ -18993,7 +19086,7 @@ function isCorridor(part) {return part.roles.some((role) => /^environment\.(?:navigation\.)?corridor(?:\.|$)/.test(role));}function inspectNavigationClearance(context) {- if (context.navigable !== true || !(context.scene instanceof THREE25.Object3D)) {+ if (context.navigable !== true || !(context.scene instanceof THREE26.Object3D)) {return [];}const root = context.scene;@@ -19123,7 +19216,7 @@ function functionalLayer(part) {return part.roles.some((role) => role.startsWith("environment.functional") || role.startsWith("environment.layer") || role.startsWith("environment.path") || role.startsWith("environment.road") || role.startsWith("environment.bridge") || role.startsWith("environment.gate"));}function inspectSpatialSupport(context) {- if (context.groundPlaneY === undefined || !(context.scene instanceof THREE25.Object3D)) {+ if (context.groundPlaneY === undefined || !(context.scene instanceof THREE26.Object3D)) {return [];}const root = context.scene;@@ -19170,7 +19263,7 @@ function inspectSpatialSupport(context) {}));}}- const size = box.getSize(new THREE25.Vector3);+ const size = box.getSize(new THREE26.Vector3);if (box.min.y < context.groundPlaneY - 0.05 && size.y <= Math.max(0.05, Math.min(size.x, size.z) * 0.03) && Math.max(size.x, size.z) >= 1) {findings.push(finding4(context, {code: "ENV_GROUND_UNDECLARED_SKIRT",@@ -19782,7 +19875,7 @@ var init_breadth2 = __esm(() => {});// src/qa/breadth-evidence.ts-import * as THREE26 from "three";+import * as THREE27 from "three";function record7(value) {return typeof value === "object" && value !== null && !Array.isArray(value);}@@ -19801,7 +19894,7 @@ function isAnimationClip(value) {function localRenderableBox(rootInverse, node) {if (isSpriteNode(node)) {const transform = rootInverse.clone().multiply(node.matrixWorld);- return new THREE26.Box3(new THREE26.Vector3(-0.5, -0.5, -0.0005), new THREE26.Vector3(0.5, 0.5, 0.0005)).applyMatrix4(transform);+ return new THREE27.Box3(new THREE27.Vector3(-0.5, -0.5, -0.0005), new THREE27.Vector3(0.5, 0.5, 0.0005)).applyMatrix4(transform);}if (!isMeshNode(node) || !node.geometry?.isBufferGeometry)return;@@ -19810,11 +19903,11 @@ function localRenderableBox(rootInverse, node) {if (!source || source.isEmpty())return;const transform = rootInverse.clone().multiply(node.matrixWorld);- const result = new THREE26.Box3;+ const result = new THREE27.Box3;for (const x of [source.min.x, source.max.x]) {for (const y of [source.min.y, source.max.y]) {for (const z of [source.min.z, source.max.z]) {- result.expandByPoint(new THREE26.Vector3(x, y, z).applyMatrix4(transform));+ result.expandByPoint(new THREE27.Vector3(x, y, z).applyMatrix4(transform));}}}@@ -19902,10 +19995,10 @@ function isEffectSurface(nodes) {function coverageRatio(boxes, overall) {if (boxes.length === 0 || overall.isEmpty())return 0;- const overallSize = overall.getSize(new THREE26.Vector3);+ const overallSize = overall.getSize(new THREE27.Vector3);const denominator = Math.max(0.000000001, overallSize.x * overallSize.y, overallSize.z * overallSize.y, overallSize.x * overallSize.z);const area = boxes.reduce((sum, box) => {- const size = box.getSize(new THREE26.Vector3);+ const size = box.getSize(new THREE27.Vector3);return sum + Math.max(size.x * size.y, size.z * size.y, size.x * size.z);}, 0);return stable7(Math.min(1, area / denominator));@@ -19914,7 +20007,7 @@ function collectMaterialEvidence(root, intent) {root.updateWorldMatrix(true, true);const inverse = root.matrixWorld.clone().invert();const byMaterial = new Map;- const overall = new THREE26.Box3;+ const overall = new THREE27.Box3;root.traverseVisible((node) => {const box = localRenderableBox(inverse, node);if (!box || !isMeshNode(node) && !isSpriteNode(node))@@ -19939,7 +20032,7 @@ function collectMaterialEvidence(root, intent) {effectSurface: isEffectSurface(value.nodes),alphaMode: mode,alphaData: alphaData(material),- doubleSided: material.side === THREE26.DoubleSide,+ doubleSided: material.side === THREE27.DoubleSide,...mode === "mask" ? { alphaCutoff: standard.alphaTest ?? 0 } : {},screenAreaRatio: coverageRatio(value.boxes, overall),transparentLayers: mode === "blend" ? value.nodes.length : 0,@@ -19967,23 +20060,23 @@ function dominantGeometryAxis(root, mode) {const bounds = node.geometry.boundingBox;if (!bounds || bounds.isEmpty())return;- const size = bounds.getSize(new THREE26.Vector3);+ const size = bounds.getSize(new THREE27.Vector3);const axes = [- { score: size.x, direction: new THREE26.Vector3(1, 0, 0) },- { score: size.y, direction: new THREE26.Vector3(0, 1, 0) },- { score: size.z, direction: new THREE26.Vector3(0, 0, 1) }+ { score: size.x, direction: new THREE27.Vector3(1, 0, 0) },+ { score: size.y, direction: new THREE27.Vector3(0, 1, 0) },+ { score: size.z, direction: new THREE27.Vector3(0, 0, 1) }];const selected = axes.reduce((candidate, value) => mode === "length" ? value.score > candidate.score ? value : candidate : value.score < candidate.score ? value : candidate);const relative = inverse.clone().multiply(node.matrixWorld);const direction = selected.direction.transformDirection(relative);- const score = selected.score * node.getWorldScale(new THREE26.Vector3).length();+ const score = selected.score * node.getWorldScale(new THREE27.Vector3).length();if (!best || (mode === "length" ? score > best.score : score < best.score)) {best = { score, direction };}});if (best)return signedAxis(best.direction);- const overall = new THREE26.Box3;+ const overall = new THREE27.Box3;root.traverseVisible((node) => {const box = localRenderableBox(inverse, node);if (box)@@ -19991,8 +20084,8 @@ function dominantGeometryAxis(root, mode) {});if (overall.isEmpty())return "+X";- const size = overall.getSize(new THREE26.Vector3);- const vector = mode === "length" ? size.x >= size.y && size.x >= size.z ? new THREE26.Vector3(1, 0, 0) : size.y >= size.z ? new THREE26.Vector3(0, 1, 0) : new THREE26.Vector3(0, 0, 1) : size.x <= size.y && size.x <= size.z ? new THREE26.Vector3(1, 0, 0) : size.y <= size.z ? new THREE26.Vector3(0, 1, 0) : new THREE26.Vector3(0, 0, 1);+ const size = overall.getSize(new THREE27.Vector3);+ const vector = mode === "length" ? size.x >= size.y && size.x >= size.z ? new THREE27.Vector3(1, 0, 0) : size.y >= size.z ? new THREE27.Vector3(0, 1, 0) : new THREE27.Vector3(0, 0, 1) : size.x <= size.y && size.x <= size.z ? new THREE27.Vector3(1, 0, 0) : size.y <= size.z ? new THREE27.Vector3(0, 1, 0) : new THREE27.Vector3(0, 0, 1);return signedAxis(vector);}function analyzedFacing(root, intent) {@@ -20026,8 +20119,8 @@ function clipEndpointMatches(clip) {const last = Array.from(track.values.slice(end, end + size));if (![...first, ...last].every(Number.isFinite))return false;- const a = new THREE26.Quaternion().fromArray(first);- const b = new THREE26.Quaternion().fromArray(last);+ const a = new THREE27.Quaternion().fromArray(first);+ const b = new THREE27.Quaternion().fromArray(last);if (a.lengthSq() === 0 || b.lengthSq() === 0)return false;return 1 - Math.abs(a.normalize().dot(b.normalize())) <= 0.000001;@@ -21813,7 +21906,7 @@ var init_rebuild_options = __esm(() => {});// src/qa/breadth-final.ts-import * as THREE27 from "three";+import * as THREE28 from "three";function bytesContainAscii(bytes, value) {const needle = new TextEncoder().encode(value);outer:@@ -21872,7 +21965,7 @@ function finalEffectAxis(nodes, mode) {if (!(semantic?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {continue;}- const matrix = new THREE27.Matrix4().fromArray(node.getWorldMatrix());+ const matrix = new THREE28.Matrix4().fromArray(node.getWorldMatrix());const scale = node.getWorldScale();const scaleMagnitude = Math.hypot(scale[0], scale[1], scale[2]);for (const primitive of node.getMesh()?.listPrimitives() ?? []) {@@ -21882,9 +21975,9 @@ function finalEffectAxis(nodes, mode) {const min = position.getMin([]);const max = position.getMax([]);const axes = [- { score: (max[0] ?? 0) - (min[0] ?? 0), direction: new THREE27.Vector3(1, 0, 0) },- { score: (max[1] ?? 0) - (min[1] ?? 0), direction: new THREE27.Vector3(0, 1, 0) },- { score: (max[2] ?? 0) - (min[2] ?? 0), direction: new THREE27.Vector3(0, 0, 1) }+ { score: (max[0] ?? 0) - (min[0] ?? 0), direction: new THREE28.Vector3(1, 0, 0) },+ { score: (max[1] ?? 0) - (min[1] ?? 0), direction: new THREE28.Vector3(0, 1, 0) },+ { score: (max[2] ?? 0) - (min[2] ?? 0), direction: new THREE28.Vector3(0, 0, 1) }];const selected = axes.reduce((candidate, value) => mode === "length" ? value.score > candidate.score ? value : candidate : value.score < candidate.score ? value : candidate);const candidate = {@@ -22434,7 +22527,7 @@ var init_requirements_run = __esm(() => {});// src/qa/skin-integrity.ts-import * as THREE28 from "three";+import * as THREE29 from "three";function validAttribute(a, count, size) {if (!a || a.itemSize !== size || a.count !== count || !Number.isSafeInteger(count) || count < 1)return false;@@ -22481,9 +22574,9 @@ function inspectSkinIntegrity(root) {}while (chain.length) {const n = chain.pop();- const local = n.matrixAutoUpdate ? new THREE28.Matrix4().compose(n.position, n.quaternion, n.scale) : n.matrix.clone();+ const local = n.matrixAutoUpdate ? new THREE29.Matrix4().compose(n.position, n.quaternion, n.scale) : n.matrix.clone();const parent = n.parent ? worlds.get(n.parent) : undefined;- const value = n.matrixWorldAutoUpdate === false ? n.matrixWorld.clone() : parent ? new THREE28.Matrix4().multiplyMatrices(parent, local) : local;+ const value = n.matrixWorldAutoUpdate === false ? n.matrixWorld.clone() : parent ? new THREE29.Matrix4().multiplyMatrices(parent, local) : local;worlds.set(n, value);}return worlds.get(node);@@ -22533,7 +22626,7 @@ function inspectSkinIntegrity(root) {if (result.truncated)break;}- if (!finiteAffine(mesh.bindMatrix) || !Number.isFinite(mesh.bindMatrix.determinant()) || mesh.bindMatrix.determinant() === 0 || ![THREE28.AttachedBindMode, THREE28.DetachedBindMode].includes(mesh.bindMode)) {+ if (!finiteAffine(mesh.bindMatrix) || !Number.isFinite(mesh.bindMatrix.determinant()) || mesh.bindMatrix.determinant() === 0 || ![THREE29.AttachedBindMode, THREE29.DetachedBindMode].includes(mesh.bindMode)) {add("SKIN_BIND_MATRIX", "Mesh requires a finite invertible affine bind matrix and an attached or detached bind mode.", "bindMatrix");}const position = mesh.geometry?.getAttribute("position"), count = position?.count ?? 0;@@ -22582,7 +22675,7 @@ function inspectSkinIntegrity(root) {add("SKIN_POSE_TRANSFORM", "Current mesh world transform must be finite and affine.");continue;}- const inverse = mesh.bindMode === THREE28.AttachedBindMode ? meshWorld.clone().invert() : mesh.bindMatrix.clone().invert();+ const inverse = mesh.bindMode === THREE29.AttachedBindMode ? meshWorld.clone().invert() : mesh.bindMatrix.clone().invert();const matrices = [];for (let joint = 0;joint < bones.length; joint++) {const boneWorld = world(bones[joint]);@@ -22590,13 +22683,13 @@ function inspectSkinIntegrity(root) {add("SKIN_POSE_TRANSFORM", `Current transform for joint ${joint} must be finite and affine.`, `joints[${joint}]`);break;}- matrices.push(new THREE28.Matrix4().multiplyMatrices(boneWorld, skeleton.boneInverses[joint]).multiply(mesh.bindMatrix));+ matrices.push(new THREE29.Matrix4().multiplyMatrices(boneWorld, skeleton.boneInverses[joint]).multiply(mesh.bindMatrix));}if (result.findings.length !== start)continue;- const base = new THREE28.Vector3, posed = new THREE28.Vector3, temp = new THREE28.Vector3, box = new THREE28.Box3;+ const base = new THREE29.Vector3, posed = new THREE29.Vector3, temp = new THREE29.Vector3, box = new THREE29.Box3;for (let vertex = 0;vertex < count; vertex++) {- THREE28.Mesh.prototype.getVertexPosition.call(mesh, vertex, base);+ THREE29.Mesh.prototype.getVertexPosition.call(mesh, vertex, base);posed.set(0, 0, 0);for (let lane = 0;lane < 4; lane++) {const weight = weights.getComponent(vertex, lane);@@ -22661,7 +22754,7 @@ var init_material_export = __esm(() => {});// src/community-exporter.ts-import * as THREE29 from "three";+import * as THREE30 from "three";import { GLTFExporter } from "three/addons/exporters/GLTFExporter.js";import { GLB_BUFFER } from "@gltf-transform/core";function resolveGltfExporter(value = typeof process !== "undefined" ? process.env["KILN_GLTF_EXPORTER"] : undefined) {@@ -22691,7 +22784,7 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, areturn found;const copy = cleanClone(source);normalizeTextureTransform(copy);- copy.source = new THREE29.TextureSource(source.image);+ copy.source = new THREE30.TextureSource(source.image);textures.set(source, copy);const bytes = source.userData["encoded"];if (bytes?.bytes) {@@ -22700,8 +22793,8 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, aencoded.push((async () => {copy.image = await platform.decode(bytes.bytes);Object.defineProperty(copy, "isDataTexture", { value: true });- copy.format = THREE29.RGBAFormat;- copy.type = THREE29.UnsignedByteType;+ copy.format = THREE30.RGBAFormat;+ copy.type = THREE30.UnsignedByteType;})());}return copy;@@ -22718,7 +22811,7 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, aphysical.sheen = 1;}for (const [key, value] of Object.entries(copy)) {- if (value instanceof THREE29.Texture)+ if (value instanceof THREE30.Texture)copy[key] = texture(value);}materials.set(source, copy);@@ -22734,15 +22827,15 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, aif (!copy.matrixAutoUpdate)copy.matrix.decompose(copy.position, copy.quaternion, copy.scale);if (source.isScene) {- copy = new THREE29.Group;+ copy = new THREE30.Group;copy.copy(shadow, false);}if (source.isSprite) {const sprite = source;- const geometry = new THREE29.PlaneGeometry(1, 1);+ const geometry = new THREE30.PlaneGeometry(1, 1);geometry.translate(0.5 - sprite.center.x, 0.5 - sprite.center.y, 0);geometry.rotateZ(sprite.material.rotation);- const spriteMaterial = new THREE29.MeshBasicMaterial({+ const spriteMaterial = new THREE30.MeshBasicMaterial({name: sprite.material.name,color: sprite.material.color,opacity: sprite.material.opacity,@@ -22753,8 +22846,8 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, a});Object.assign(spriteMaterial.userData, authorExtras?.material(sprite.material));originalMaterials.set(spriteMaterial, sprite.material);- copy = new THREE29.Mesh(geometry, spriteMaterial);- THREE29.Object3D.prototype.copy.call(copy, shadow, false);+ copy = new THREE30.Mesh(geometry, spriteMaterial);+ THREE30.Object3D.prototype.copy.call(copy, shadow, false);}Object.assign(copy.userData, authorExtras?.node(source), rigExtrasForExport(source), openShellExtras(source), kitExtras(source), repeatInstancesExtras(source));const semantic = source.userData[KILN_SEMANTIC_EXTRAS_KEY];@@ -22818,8 +22911,8 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, aif (!context)throw new Error("A 2D canvas is required to prepare export texture channels.");context.putImageData(new ImageData(new Uint8ClampedArray(data), width, height), 0, 0);- const adapted = new THREE29.Texture().copy(map);- adapted.source = new THREE29.TextureSource(canvas);+ const adapted = new THREE30.Texture().copy(map);+ adapted.source = new THREE30.TextureSource(canvas);canvasInputs.set(map, adapted);const direct = directImages.get(map);if (direct)@@ -22828,7 +22921,7 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, a};for (const material of materials.values()) {for (const [key, value] of Object.entries(material)) {- if (value instanceof THREE29.Texture && value.flipY && value.image?.data)+ if (value instanceof THREE30.Texture && value.flipY && value.image?.data)material[key] = canvasInput(value);}const standard = material;@@ -22850,8 +22943,8 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, a}cloned.tracks = cloned.tracks.filter((track) => {try {- const binding = THREE29.PropertyBinding.parseTrackName(track.name);- return ["position", "quaternion", "scale", "morphTargetInfluences"].includes(binding.propertyName) && THREE29.PropertyBinding.findNode(copy, binding.nodeName) !== null;+ const binding = THREE30.PropertyBinding.parseTrackName(track.name);+ return ["position", "quaternion", "scale", "morphTargetInfluences"].includes(binding.propertyName) && THREE30.PropertyBinding.findNode(copy, binding.nodeName) !== null;} catch {return false;}@@ -23046,7 +23139,7 @@ function applyIndexPolicy(doc, policy) {var init_index_policy = () => {};// src/surface-bake.ts-import * as THREE30 from "three";+import * as THREE31 from "three";function settings(value, label) {if (value === false)return;@@ -23088,13 +23181,13 @@ function drawnMeshes(root) {function weld(mesh) {const position = mesh.geometry.getAttribute("position");const world = [];- const box = new THREE30.Box3;+ const box = new THREE31.Box3;for (let i = 0;i < position.count; i++) {- const point = new THREE30.Vector3().fromBufferAttribute(position, i).applyMatrix4(mesh.matrixWorld);+ const point = new THREE31.Vector3().fromBufferAttribute(position, i).applyMatrix4(mesh.matrixWorld);world.push(point);box.expandByPoint(point);}- const size = box.isEmpty() ? 0 : box.getSize(new THREE30.Vector3).length();+ const size = box.isEmpty() ? 0 : box.getSize(new THREE31.Vector3).length();const tolerance = size > 0 ? size * 0.000001 : 0.000000001;const keys = new Map;const ids = new Int32Array(position.count);@@ -23128,7 +23221,7 @@ function bakeEdge(topology, thresholdDegrees, smoothing) {const a = points[triangles[t]];const b = points[triangles[t + 1]];const c = points[triangles[t + 2]];- normals.push(new THREE30.Vector3().subVectors(b, a).cross(new THREE30.Vector3().subVectors(c, a)).normalize());+ normals.push(new THREE31.Vector3().subVectors(b, a).cross(new THREE31.Vector3().subVectors(c, a)).normalize());}const edges = new Map;const neighbours = points.map(() => new Set);@@ -23147,7 +23240,7 @@ function bakeEdge(topology, thresholdDegrees, smoothing) {edges.set(key, list);}}- const threshold = THREE30.MathUtils.degToRad(thresholdDegrees);+ const threshold = THREE31.MathUtils.degToRad(thresholdDegrees);const weights = new Float64Array(points.length);for (const [key, incidences] of edges) {let weight;@@ -23157,10 +23250,10 @@ function bakeEdge(topology, thresholdDegrees, smoothing) {const [[f1], [f2, opposite2]] = incidences;const n1 = normals[f1];const n2 = normals[f2];- const angle = Math.acos(THREE30.MathUtils.clamp(n1.dot(n2), -1, 1));+ const angle = Math.acos(THREE31.MathUtils.clamp(n1.dot(n2), -1, 1));const [u] = key.split(":").map(Number);const scale = Math.max(points[u].distanceTo(points[opposite2]), 0.000000000001);- const side = new THREE30.Vector3().subVectors(points[opposite2], points[u]).dot(n1) / scale;+ const side = new THREE31.Vector3().subVectors(points[opposite2], points[u]).dot(n1) / scale;weight = side < -0.000000001 ? smoothstep2(threshold / 2, threshold, angle) : 0;}for (const id of key.split(":").map(Number))@@ -23322,12 +23415,12 @@ function hemisphereDirections(count) {const phi = i * golden;const x = r * Math.cos(phi);const y = r * Math.sin(phi);- return new THREE30.Vector3(x, y, Math.sqrt(Math.max(0, 1 - x * x - y * y)));+ return new THREE31.Vector3(x, y, Math.sqrt(Math.max(0, 1 - x * x - y * y)));});}function occluderTriangles(occluders, bakedTier) {const values = [];- const point = new THREE30.Vector3;+ const point = new THREE31.Vector3;for (const mesh of drawnMeshes(occluders)) {if (!drawn(mesh, null))continue;@@ -23391,12 +23484,12 @@ function bakeSurfaceAttributes(target, options = {}) {let entry = bvhs.get(key);if (!entry) {const triangles = occluderTriangles(occluders, tier);- const box = new THREE30.Box3;+ const box = new THREE31.Box3;for (let i = 0;i < triangles.length; i += 3)- box.expandByPoint(new THREE30.Vector3(triangles[i], triangles[i + 1], triangles[i + 2]));+ box.expandByPoint(new THREE31.Vector3(triangles[i], triangles[i + 1], triangles[i + 2]));entry = {bvh: new TriangleBvh(triangles),- diagonal: box.isEmpty() ? 0 : box.getSize(new THREE30.Vector3).length()+ diagonal: box.isEmpty() ? 0 : box.getSize(new THREE31.Vector3).length()};bvhs.set(key, entry);}@@ -23413,27 +23506,27 @@ function bakeSurfaceAttributes(target, options = {}) {const welded = bakeEdge(topology, thresholdDegrees, smoothing);const values = new Float32Array(sourceCount);for (let i = 0;i < sourceCount; i++)- values[i] = THREE30.MathUtils.clamp(welded[topology.ids[i]], 0, 1);- geometry.setAttribute("_edge", new THREE30.BufferAttribute(values, 1));+ values[i] = THREE31.MathUtils.clamp(welded[topology.ids[i]], 0, 1);+ geometry.setAttribute("_edge", new THREE31.BufferAttribute(values, 1));record._EDGE = { thresholdDegrees, smoothing };}if (cavityOptions) {const { bvh, diagonal } = occlusion(tierOf(mesh));const radius = cavityOptions.radius ?? SURFACE_BAKE_DEFAULTS.cavity.radiusFactor * diagonal;const epsilon = Math.max(diagonal * 0.00001, 0.0000001);- const normals = topology.points.map(() => new THREE30.Vector3);+ const normals = topology.points.map(() => new THREE31.Vector3);const { points, triangles } = topology;for (let t = 0;t < triangles.length; t += 3) {const a = points[triangles[t]];- const face = new THREE30.Vector3().subVectors(points[triangles[t + 1]], a).cross(new THREE30.Vector3().subVectors(points[triangles[t + 2]], a));+ const face = new THREE31.Vector3().subVectors(points[triangles[t + 1]], a).cross(new THREE31.Vector3().subVectors(points[triangles[t + 2]], a));for (let k = 0;k < 3; k++)normals[triangles[t + k]].add(face);}const exposure = new Float64Array(points.length);- const tangent = new THREE30.Vector3;- const bitangent = new THREE30.Vector3;- const origin = new THREE30.Vector3;- const direction = new THREE30.Vector3;+ const tangent = new THREE31.Vector3;+ const bitangent = new THREE31.Vector3;+ const origin = new THREE31.Vector3;+ const direction = new THREE31.Vector3;points.forEach((point, id) => {const normal = normals[id];if (normal.lengthSq() === 0) {@@ -23455,8 +23548,8 @@ function bakeSurfaceAttributes(target, options = {}) {});const values = new Float32Array(sourceCount);for (let i = 0;i < sourceCount; i++)- values[i] = THREE30.MathUtils.clamp(exposure[topology.ids[i]], 0, 1);- geometry.setAttribute("_cavity", new THREE30.BufferAttribute(values, 1));+ values[i] = THREE31.MathUtils.clamp(exposure[topology.ids[i]], 0, 1);+ geometry.setAttribute("_cavity", new THREE31.BufferAttribute(values, 1));record._CAVITY = { rays, radius };}geometry.userData = { ...geometry.userData, [SURFACE_BAKE_KEY]: record };@@ -23476,7 +23569,7 @@ function surfaceBakeRecord(geometry) {return record;}var SURFACE_ATTRIBUTES, SURFACE_BAKE_KEY = "kilnSurfaceBakeV1", SURFACE_BAKE_DEFAULTS, isObject3D2 = (value) => value?.isObject3D === true, smoothstep2 = (edge0, edge1, x) => {- const t = THREE30.MathUtils.clamp((x - edge0) / (edge1 - edge0), 0, 1);+ const t = THREE31.MathUtils.clamp((x - edge0) / (edge1 - edge0), 0, 1);return t * t * (3 - 2 * t);};var init_surface_bake = __esm(() => {@@ -23490,7 +23583,7 @@ var init_surface_bake = __esm(() => {});// src/geometry.ts-import * as THREE31 from "three";+import * as THREE32 from "three";function finiteArray(values, label, length) {const result = Array.from(values);if (length !== undefined && result.length !== length)@@ -23504,8 +23597,8 @@ function meshGeo(data) {if (positions.length < 9 || positions.length % 3)throw new Error("meshGeo positions: need at least three xyz vertices");const count = positions.length / 3;- const geometry = new THREE31.BufferGeometry;- geometry.setAttribute("position", new THREE31.Float32BufferAttribute(positions, 3));+ const geometry = new THREE32.BufferGeometry;+ geometry.setAttribute("position", new THREE32.Float32BufferAttribute(positions, 3));if (data.indices) {const indices = Array.from(data.indices);if (!indices.length || indices.length % 3)@@ -23517,7 +23610,7 @@ function meshGeo(data) {throw new Error("meshGeo: non-indexed positions must form complete triangles");if (data.normals) {const normals = finiteArray(data.normals, "meshGeo normals", count * 3);- geometry.setAttribute("normal", new THREE31.Float32BufferAttribute(normals, 3));+ geometry.setAttribute("normal", new THREE32.Float32BufferAttribute(normals, 3));for (let i = 0;i < count; i++)if (Math.hypot(normals[i * 3], normals[i * 3 + 1], normals[i * 3 + 2]) === 0)throw new Error("meshGeo normals: zero-length normal");@@ -23525,36 +23618,36 @@ function meshGeo(data) {} elsegeometry.computeVertexNormals();if (data.uvs)- geometry.setAttribute("uv", new THREE31.Float32BufferAttribute(finiteArray(data.uvs, "meshGeo uvs", count * 2), 2));+ geometry.setAttribute("uv", new THREE32.Float32BufferAttribute(finiteArray(data.uvs, "meshGeo uvs", count * 2), 2));if (data.tangents) {const tangents = finiteArray(data.tangents, "meshGeo tangents", count * 4);for (let i = 0;i < count; i++) {if (Math.abs(Math.hypot(tangents[i * 4], tangents[i * 4 + 1], tangents[i * 4 + 2]) - 1) > 0.0001 || Math.abs(tangents[i * 4 + 3]) !== 1)throw new Error("meshGeo tangents: expected unit xyz and handedness +1 or -1");}- geometry.setAttribute("tangent", new THREE31.Float32BufferAttribute(tangents, 4));+ geometry.setAttribute("tangent", new THREE32.Float32BufferAttribute(tangents, 4));}geometry.computeBoundingBox();geometry.computeBoundingSphere();return geometry;}function boundsScale(bounds) {- const size = bounds.getSize(new THREE31.Vector3);+ const size = bounds.getSize(new THREE32.Vector3);const scale = Math.hypot(size.x, size.y, size.z);if (!Number.isFinite(scale))throw new Error("Geometry position extent must be finite");return scale;}function positionFrame(position) {- const bounds = new THREE31.Box3;- const point = new THREE31.Vector3;+ const bounds = new THREE32.Box3;+ const point = new THREE32.Vector3;for (let i = 0;i < position.count; i++) {point.fromBufferAttribute(position, i);if ([point.x, point.y, point.z].every(Number.isFinite))bounds.expandByPoint(point);}return {- origin: bounds.isEmpty() ? new THREE31.Vector3 : bounds.min,+ origin: bounds.isEmpty() ? new THREE32.Vector3 : bounds.min,scale: boundsScale(bounds)};}@@ -23594,11 +23687,11 @@ function geometryDiagnostics(geometry, tolerance) {solid: { closed: false, manifold: true, orientation: "mixed", signedVolume: 0 }};let signedVolume = 0;- const pa = new THREE31.Vector3, pb = new THREE31.Vector3, pc = new THREE31.Vector3;+ const pa = new THREE32.Vector3, pb = new THREE32.Vector3, pc = new THREE32.Vector3;const ids = [];const points = new Map;const finite = [];- const point = new THREE31.Vector3;+ const point = new THREE32.Vector3;for (let i = 0;i < p.count; i++) {point.fromBufferAttribute(p, i);finite[i] = [point.x, point.y, point.z].every(Number.isFinite);@@ -23611,7 +23704,7 @@ function geometryDiagnostics(geometry, tolerance) {}const indices = geometry.index ? Array.from(geometry.index.array) : Array.from({ length: p.count }, (_, i) => i);const edges = new Map;- const a = new THREE31.Vector3, b = new THREE31.Vector3, c = new THREE31.Vector3;+ const a = new THREE32.Vector3, b = new THREE32.Vector3, c = new THREE32.Vector3;for (let i = 0;i < indices.length; i += 3) {result.triangles++;const triangle = indices.slice(i, i + 3);@@ -23696,8 +23789,8 @@ function parametricSurface(sample, options = {}) {if (orientation !== "uv" && orientation !== "vu")throw new Error("parametricSurface orientation must be uv or vu");const positions = [], uvs = [], indices = [];- const sampledBounds = new THREE31.Box3;- const sampledPoint = new THREE31.Vector3;+ const sampledBounds = new THREE32.Box3;+ const sampledPoint = new THREE32.Vector3;for (let j = 0;j <= nv; j++)for (let i = 0;i <= nu; i++) {const point = sample(u[0] + (u[1] - u[0]) * i / nu, v[0] + (v[1] - v[0]) * j / nv);@@ -23739,8 +23832,8 @@ function parametricSurface(sample, options = {}) {const sums = new Map;for (let i = 0;i < normal.count; i++) {const id = find(i);- const sum = sums.get(id) ?? new THREE31.Vector3;- sum.add(new THREE31.Vector3().fromBufferAttribute(normal, i));+ const sum = sums.get(id) ?? new THREE32.Vector3;+ sum.add(new THREE32.Vector3().fromBufferAttribute(normal, i));sums.set(id, sum);}for (let i = 0;i < normal.count; i++) {@@ -23765,13 +23858,13 @@ function creaseNormals(geometry, options = {}) {const keys = [];const faces = [];for (let i = 0;i < position.count; i += 3) {- const a = new THREE31.Vector3().fromBufferAttribute(position, i);- const b = new THREE31.Vector3().fromBufferAttribute(position, i + 1);- const c = new THREE31.Vector3().fromBufferAttribute(position, i + 2);+ const a = new THREE32.Vector3().fromBufferAttribute(position, i);+ const b = new THREE32.Vector3().fromBufferAttribute(position, i + 1);+ const c = new THREE32.Vector3().fromBufferAttribute(position, i + 2);const face = b.sub(a).divideScalar(scale).cross(c.sub(a).divideScalar(scale)).normalize();faces.push(face);for (let j = i;j < i + 3; j++) {- const point = new THREE31.Vector3().fromBufferAttribute(position, j);+ const point = new THREE32.Vector3().fromBufferAttribute(position, j);if (![point.x, point.y, point.z].every(Number.isFinite))throw new Error("creaseNormals positions must be finite");const key = positionKey(point, frame.origin, tolerance);@@ -23782,15 +23875,15 @@ function creaseNormals(geometry, options = {}) {}}const normals = new Float32Array(position.count * 3);- const threshold = Math.cos(THREE31.MathUtils.degToRad(angle));+ const threshold = Math.cos(THREE32.MathUtils.degToRad(angle));for (let i = 0;i < position.count; i++) {- const face = faces[Math.floor(i / 3)], sum = new THREE31.Vector3;+ const face = faces[Math.floor(i / 3)], sum = new THREE32.Vector3;for (const other of adjacent.get(keys[i]))if (face.dot(faces[other]) >= threshold - 0.000000000001)sum.add(faces[other]);sum.normalize().toArray(normals, i * 3);}- out.setAttribute("normal", new THREE31.BufferAttribute(normals, 3));+ out.setAttribute("normal", new THREE32.BufferAttribute(normals, 3));out.deleteAttribute("tangent");out.computeBoundingBox();out.computeBoundingSphere();@@ -24388,16 +24481,16 @@ function buildWallPanels(length, height, thickness, apertures) {}// src/assembly-transform.ts-import * as THREE32 from "three";+import * as THREE33 from "three";function checkedTrs(matrix, label) {const e = matrix.elements;if (!e.every(Number.isFinite) || e[3] !== 0 || e[7] !== 0 || e[11] !== 0 || Math.abs(e[15] - 1) > 16 * Number.EPSILON)throw new Error(`${label}: finite affine TRS is required.`);if (!Number.isFinite(matrix.determinant()) || matrix.determinant() === 0)throw new Error(`${label}: singular/zero-scale transforms are unsupported.`);- const position = new THREE32.Vector3, quaternion = new THREE32.Quaternion, scale = new THREE32.Vector3;+ const position = new THREE33.Vector3, quaternion = new THREE33.Quaternion, scale = new THREE33.Vector3;matrix.decompose(position, quaternion, scale);- const rebuilt = new THREE32.Matrix4().compose(position, quaternion, scale);+ const rebuilt = new THREE33.Matrix4().compose(position, quaternion, scale);if (rebuilt.elements.some((value, i) => !Number.isFinite(value) || Math.abs(value - e[i]) > 0.00000001 * Math.max(1, Math.abs(e[i]))))throw new Error(`${label}: local shear cannot be represented losslessly as TRS.`);return { position, quaternion, scale };@@ -24405,7 +24498,7 @@ function checkedTrs(matrix, label) {var init_assembly_transform = () => {};// src/assembly.ts-import * as THREE33 from "three";+import * as THREE34 from "three";function jsonData(value, label, ancestors = new Set) {if (value === null || typeof value === "string" || typeof value === "boolean")return;@@ -24452,7 +24545,7 @@ function knownMetadata(source, parsed, label) {throw new Error(`${label}: unsupported fields in known metadata would be lost during remapping.`);}function localMatrix(node) {- return node.matrixAutoUpdate ? new THREE33.Matrix4().compose(node.position, node.quaternion, node.scale) : node.matrix.clone();+ return node.matrixAutoUpdate ? new THREE34.Matrix4().compose(node.position, node.quaternion, node.scale) : node.matrix.clone();}function worldMatrix2(node) {const chain = [], seen = new Set;@@ -24462,7 +24555,7 @@ function worldMatrix2(node) {seen.add(cursor);chain.push(cursor);}- const result = new THREE33.Matrix4;+ const result = new THREE34.Matrix4;for (const entry of chain.reverse())result.multiply(localMatrix(entry));return result;@@ -24478,7 +24571,7 @@ function census(root) {const stack = [root];while (stack.length) {const node = stack.pop();- if (!(node instanceof THREE33.Object3D) || ![THREE33.Object3D, THREE33.Group, THREE33.Mesh].includes(node.constructor))+ if (!(node instanceof THREE34.Object3D) || ![THREE34.Object3D, THREE34.Group, THREE34.Mesh].includes(node.constructor))throw new Error("Unsupported assembly node: only ordinary Object3D, Group and Mesh hierarchies are qualified; no skins, instances or custom node classes.");if (matrices.has(node))throw new Error("Assembly must be a tree; duplicate/cyclic children are unsupported.");@@ -24494,21 +24587,21 @@ function census(root) {checkedTrs(matrix, node.name || "unnamed node");nodes.push(node);matrices.set(node, matrix);- if (node.onBeforeRender !== THREE33.Object3D.prototype.onBeforeRender || node.onAfterRender !== THREE33.Object3D.prototype.onAfterRender || node.onBeforeShadow !== THREE33.Object3D.prototype.onBeforeShadow || node.onAfterShadow !== THREE33.Object3D.prototype.onAfterShadow)+ if (node.onBeforeRender !== THREE34.Object3D.prototype.onBeforeRender || node.onAfterRender !== THREE34.Object3D.prototype.onAfterRender || node.onBeforeShadow !== THREE34.Object3D.prototype.onBeforeShadow || node.onAfterShadow !== THREE34.Object3D.prototype.onAfterShadow)throw new Error("Custom node render callbacks are unsupported in assembly replication.");- if (node instanceof THREE33.Mesh) {- if (!(node.geometry instanceof THREE33.BufferGeometry) || node.geometry instanceof THREE33.InstancedBufferGeometry)+ if (node instanceof THREE34.Mesh) {+ if (!(node.geometry instanceof THREE34.BufferGeometry) || node.geometry instanceof THREE34.InstancedBufferGeometry)throw new Error("Unsupported assembly geometry type.");if (Object.values(node.geometry.morphAttributes).some((attributes) => attributes?.length) || node.morphTargetInfluences?.length)throw new Error("Assembly morph target replication is unsupported.");const materials = Array.isArray(node.material) ? node.material : [node.material];- if (materials.length === 0 || materials.some((material) => !(material instanceof THREE33.Material)))+ if (materials.length === 0 || materials.some((material) => !(material instanceof THREE34.Material)))throw new Error("Assembly mesh materials must be Material instances.");}if (!object3(node.userData))throw new Error("Assembly node metadata must be an object.");jsonData(node.userData, node.name);- if (!Array.isArray(node.animations) || node.animations.some((clip) => !(clip instanceof THREE33.AnimationClip)))+ if (!Array.isArray(node.animations) || node.animations.some((clip) => !(clip instanceof THREE34.AnimationClip)))throw new Error("Assembly node animations must contain AnimationClip instances.");if (node.userData[KILN_SEMANTIC_EXTRAS_KEY] !== undefined) {const metadata = readSemanticMetadataV1(node);@@ -24549,11 +24642,11 @@ function describeAssembly(root, options = {}) {const state = census(root), roles = new Map;const frames = [], sockets = [], joints = [], materials = [];const relative = new Map;- const bounds = new THREE33.Box3, point = new THREE33.Vector3;+ const bounds = new THREE34.Box3, point = new THREE34.Vector3;let positionSamples = 0;for (const [index, node] of state.nodes.entries()) {const nodeId = `n${index}`;- const matrix = node === root ? new THREE33.Matrix4 : relative.get(node.parent).clone().multiply(state.matrices.get(node));+ const matrix = node === root ? new THREE34.Matrix4 : relative.get(node.parent).clone().multiply(state.matrices.get(node));relative.set(node, matrix);const metadata = state.semantics.get(node);const descriptor = state.joints.get(node);@@ -24575,7 +24668,7 @@ function describeAssembly(root, options = {}) {for (const role of metadata?.roles ?? [])addIndex(roles, role, node);for (const frame of metadata?.frames ?? []) {- const local = new THREE33.Matrix4().compose(new THREE33.Vector3(...frame.translation), new THREE33.Quaternion(...frame.rotation), new THREE33.Vector3(1, 1, 1));+ const local = new THREE34.Matrix4().compose(new THREE34.Vector3(...frame.translation), new THREE34.Quaternion(...frame.rotation), new THREE34.Vector3(1, 1, 1));frames.push({node,nodeId,@@ -24585,7 +24678,7 @@ function describeAssembly(root, options = {}) {}for (const socket of metadata?.sockets ?? [])sockets.push({ node, nodeId, socket: structuredClone(socket) });- if (!(node instanceof THREE33.Mesh))+ if (!(node instanceof THREE34.Mesh))continue;for (const [materialIndex, material] of (Array.isArray(node.material) ? node.material : [node.material]).entries())materials.push({ node, nodeId, index: materialIndex, material });@@ -24620,7 +24713,7 @@ function describeAssembly(root, options = {}) {space: "root-local",min: bounds.min.toArray(),max: bounds.max.toArray(),- size: bounds.getSize(new THREE33.Vector3).toArray()+ size: bounds.getSize(new THREE34.Vector3).toArray()},clips,ownership: {@@ -24659,7 +24752,7 @@ function replicateAssembly(source, options) {if (value !== undefined && !choices.includes(value))throw new Error(`Unsupported assembly ${key} policy.`);}- if (options.parent !== undefined && !(options.parent instanceof THREE33.Object3D))+ if (options.parent !== undefined && !(options.parent instanceof THREE34.Object3D))throw new Error("Assembly parent must be an Object3D.");const fresh = describeAssembly(source.root, { clips: source.clips }), state = census(source.root);if (options.parent && state.nodes.includes(options.parent))@@ -24692,16 +24785,16 @@ function replicateAssembly(source, options) {throw new Error(`Unsupported custom metadata ${key} on ${node.name}; use copy-json only for inert data whose references you own.`);}jsonData(node.userData, node.name);- if (node instanceof THREE33.Mesh) {+ if (node instanceof THREE34.Mesh) {if (options.geometry === "copy") {jsonData(node.geometry.userData, `${node.name} geometry`);- if (node.geometry.clone !== THREE33.BufferGeometry.prototype.clone || !threeConstructors.has(node.geometry.constructor))+ if (node.geometry.clone !== THREE34.BufferGeometry.prototype.clone || !threeConstructors.has(node.geometry.constructor))throw new Error("Copying custom geometry classes/clone implementations is unsupported; explicitly share the resource.");}if (options.materials === "copy")for (const material of Array.isArray(node.material) ? node.material : [node.material]) {jsonData(material.userData, `${node.name} material`);- if (material.onBeforeCompile !== THREE33.Material.prototype.onBeforeCompile || material.onBeforeRender !== THREE33.Material.prototype.onBeforeRender || material.clone !== THREE33.Material.prototype.clone || !threeConstructors.has(material.constructor) || material.customProgramCacheKey !== THREE33.Material.prototype.customProgramCacheKey || material instanceof THREE33.ShaderMaterial)+ if (material.onBeforeCompile !== THREE34.Material.prototype.onBeforeCompile || material.onBeforeRender !== THREE34.Material.prototype.onBeforeRender || material.clone !== THREE34.Material.prototype.clone || !threeConstructors.has(material.constructor) || material.customProgramCacheKey !== THREE34.Material.prototype.customProgramCacheKey || material instanceof THREE34.ShaderMaterial)throw new Error("Copying custom/shader materials is unsupported; explicit sharing preserves their existing implementation.");}}@@ -24789,9 +24882,9 @@ function replicateAssembly(source, options) {const trackTargets = new Map;const animatedNodes = new Set;for (const clip of fresh.clips) {- if (!(clip instanceof THREE33.AnimationClip))+ if (!(clip instanceof THREE34.AnimationClip))throw new Error("Assembly clips must be AnimationClip instances.");- if (clip.blendMode !== THREE33.NormalAnimationBlendMode)+ if (clip.blendMode !== THREE34.NormalAnimationBlendMode)throw new Error("Additive/other animation blend modes are unsupported in assembly replication.");jsonData(clip.userData, `Clip ${clip.name}`);if (Object.keys(clip.userData).length && options.unknownMetadata !== "copy-json")@@ -24818,7 +24911,7 @@ function replicateAssembly(source, options) {if (options.space === "world") {if (state.joints.has(source.root))throw new Error("World placement of a declared joint root requires rest-transform rebasing; wrap it in an assembly root or use local placement.");- const parentWorld = options.parent ? worldMatrix2(options.parent) : new THREE33.Matrix4;+ const parentWorld = options.parent ? worldMatrix2(options.parent) : new THREE34.Matrix4;if (!Number.isFinite(parentWorld.determinant()) || parentWorld.determinant() === 0)throw new Error("World placement requires an invertible, nonsingular parent transform.");rootMatrix = parentWorld.invert().multiply(worldMatrix2(source.root));@@ -24859,7 +24952,7 @@ function replicateAssembly(source, options) {return materials.get(material);};for (const node of state.nodes) {- const copy = node instanceof THREE33.Mesh ? new THREE33.Mesh(node.geometry, node.material) : node instanceof THREE33.Group ? new THREE33.Group : new THREE33.Object3D;+ const copy = node instanceof THREE34.Mesh ? new THREE34.Mesh(node.geometry, node.material) : node instanceof THREE34.Group ? new THREE34.Group : new THREE34.Object3D;copy.copy(node, false);copy.name = names.get(node);copy.animations = [];@@ -24872,7 +24965,7 @@ function replicateAssembly(source, options) {}copy.matrix.copy(matrix);copy.matrixWorldNeedsUpdate = true;- if (node instanceof THREE33.Mesh && copy instanceof THREE33.Mesh) {+ if (node instanceof THREE34.Mesh && copy instanceof THREE34.Mesh) {if (options.geometry === "copy") {if (!geometries.has(node.geometry))geometries.set(node.geometry, node.geometry.clone());@@ -24937,7 +25030,7 @@ var init_assembly = __esm(() => {KILN_CHARACTER_JOINT_EXTRAS_KEY,KILN_CHARACTER_RIG_EXTRAS_KEY]);- threeConstructors = new Set(Object.values(THREE33));+ threeConstructors = new Set(Object.values(THREE34));});// src/palette-check.ts@@ -25060,7 +25153,7 @@ var init_palette_check = __esm(() => {});// src/animation-cubic.ts-import * as THREE34 from "three";+import * as THREE35 from "three";function useCubicSpline(track) {track.createInterpolant = cubicSplineFactory;return track;@@ -25068,7 +25161,7 @@ function useCubicSpline(track) {var CubicSplineInterpolant, CubicSplineQuaternionInterpolant, cubicSplineFactory;var init_animation_cubic = __esm(() => {init_animation_spline();- CubicSplineInterpolant = class CubicSplineInterpolant extends THREE34.Interpolant {+ CubicSplineInterpolant = class CubicSplineInterpolant extends THREE35.Interpolant {copySampleValue_(index) {const result = this.resultBuffer;const size = this.valueSize;@@ -25096,7 +25189,7 @@ var init_animation_cubic = __esm(() => {});// src/architecture.ts-import * as THREE35 from "three";+import * as THREE36 from "three";function positive4(value, name) {if (!Number.isFinite(value) || value <= 0)throw new RangeError(`${name} must be finite and > 0`);@@ -25161,17 +25254,17 @@ function buildFace(roofRoot, profile, sideSign) {const verticalRun = profile.ridgeY - profile.eaveY;const downhillLength = Math.hypot(horizontalRun, verticalRun);const alongRidge = (profile.ridgeAxis === "x" ? profile.spanX : profile.spanZ) + profile.overhang * 2;- const downhill = profile.ridgeAxis === "x" ? new THREE35.Vector3(0, -verticalRun, sideSign * horizontalRun).normalize() : new THREE35.Vector3(sideSign * horizontalRun, -verticalRun, 0).normalize();- const tangent = profile.ridgeAxis === "x" ? new THREE35.Vector3(sideSign, 0, 0) : new THREE35.Vector3(0, 0, -sideSign);+ const downhill = profile.ridgeAxis === "x" ? new THREE36.Vector3(0, -verticalRun, sideSign * horizontalRun).normalize() : new THREE36.Vector3(sideSign * horizontalRun, -verticalRun, 0).normalize();+ const tangent = profile.ridgeAxis === "x" ? new THREE36.Vector3(sideSign, 0, 0) : new THREE36.Vector3(0, 0, -sideSign);const normal = downhill.clone().cross(tangent).normalize();- const localToRoof = new THREE35.Matrix4().makeBasis(tangent, normal, downhill);+ const localToRoof = new THREE36.Matrix4().makeBasis(tangent, normal, downhill);localToRoof.setPosition(0, profile.ridgeY, 0);const world = () => {roofRoot.updateWorldMatrix(true, false);return roofRoot.matrixWorld.clone().multiply(localToRoof);};const direction = (axis) => axis.clone().transformDirection(world());- const point = (x, z) => new THREE35.Vector3(x, 0, z).applyMatrix4(world());+ const point = (x, z) => new THREE36.Vector3(x, 0, z).applyMatrix4(world());return {side,ridgeAxis: profile.ridgeAxis,@@ -25181,13 +25274,13 @@ function buildFace(roofRoot, profile, sideSign) {return world();},get ridgeTangent() {- return direction(new THREE35.Vector3(1, 0, 0));+ return direction(new THREE36.Vector3(1, 0, 0));},get downhillDirection() {- return direction(new THREE35.Vector3(0, 0, 1));+ return direction(new THREE36.Vector3(0, 0, 1));},get outwardNormal() {- return direction(new THREE35.Vector3(0, 1, 0));+ return direction(new THREE36.Vector3(0, 1, 0));},get ridgeStart() {return point(-alongRidge / 2, 0);@@ -25205,17 +25298,17 @@ function buildFace(roofRoot, profile, sideSign) {};}function buildRoof(name, material, profile, parent) {- const root = new THREE35.Object3D;+ const root = new THREE36.Object3D;root.name = name;if (parent)parent.add(root);stampSemanticMetadataV1(root, roleMetadata([semanticRole(KILN_SEMANTIC_ROLES.roof, "assembly")], [relationship("separable-from", "architecture.shell.gable")]));const faces = [buildFace(root, profile, 1), buildFace(root, profile, -1)];const buildSlope = (face) => {- const geometry = new THREE35.BoxGeometry(face.dimensions.alongRidge, profile.thickness, face.dimensions.downhill);- const mesh = new THREE35.Mesh(geometry, material);+ const geometry = new THREE36.BoxGeometry(face.dimensions.alongRidge, profile.thickness, face.dimensions.downhill);+ const mesh = new THREE36.Mesh(geometry, material);mesh.name = `Mesh_${name}_${face.side}`;- const center = new THREE35.Matrix4().makeTranslation(0, -profile.thickness / 2, face.dimensions.downhill / 2);+ const center = new THREE36.Matrix4().makeTranslation(0, -profile.thickness / 2, face.dimensions.downhill / 2);setTransform(mesh, face.localToRoof.clone().multiply(center));const coveredWall = profile.ridgeAxis === "x" ? face.side === "positive" ? "wall.right" : "wall.left" : face.side === "positive" ? "wall.front" : "wall.back";stampSemanticMetadataV1(mesh, roleMetadata([semanticRole(KILN_SEMANTIC_ROLES.roof, "slope", face.side)], [@@ -25285,7 +25378,7 @@ function createGableEndPanel(name, material, options) {const ridgeAxis = options.ridgeAxis ?? "x";const side = options.side ?? "positive";const half = span / 2;- const shape = new THREE35.Shape;+ const shape = new THREE36.Shape;shape.moveTo(-half, 0);shape.lineTo(half, 0);shape.lineTo(0, rise);@@ -25304,7 +25397,7 @@ function createGableEndPanel(name, material, options) {const right = opening.offset + opening.width / 2;const bottom = opening.bottom;const top = bottom + opening.height;- const hole = new THREE35.Path;+ const hole = new THREE36.Path;hole.moveTo(left, bottom);hole.lineTo(left, top);hole.lineTo(right, top);@@ -25312,7 +25405,7 @@ function createGableEndPanel(name, material, options) {hole.closePath();shape.holes.push(hole);}- const geometry = new THREE35.ExtrudeGeometry(shape, {+ const geometry = new THREE36.ExtrudeGeometry(shape, {depth: thickness,bevelEnabled: false,steps: 1@@ -25321,7 +25414,7 @@ function createGableEndPanel(name, material, options) {if (ridgeAxis === "x")geometry.rotateY(-Math.PI / 2);geometry.computeVertexNormals();- const root = new THREE35.Mesh(geometry, material);+ const root = new THREE36.Mesh(geometry, material);root.name = `Mesh_${name}`;stampSemanticMetadataV1(root, roleMetadata([`roof.gable.${side}`], [relationship("adjacent-to", "roof.slope.positive"),@@ -25337,7 +25430,7 @@ function createGableEndPanel(name, material, options) {}]));const markers = normalized.map((opening, index) => {- const marker = new THREE35.Object3D;+ const marker = new THREE36.Object3D;marker.name = `Opening_${name}_${opening.id ?? index + 1}`;marker.position.set(ridgeAxis === "z" ? opening.offset : 0, opening.bottom + opening.height / 2, ridgeAxis === "x" ? opening.offset : 0);marker.scale.set(ridgeAxis === "x" ? thickness : opening.width, opening.height, ridgeAxis === "x" ? opening.width : thickness);@@ -25357,7 +25450,7 @@ function wallNeighbors(wall) {}function createShellWall(name, wall, material, length, height, thickness, openings) {const axis = wallRunAxis(wall);- const root = new THREE35.Object3D;+ const root = new THREE36.Object3D;root.name = `${name}_Wall_${wall}`;const neighbors = wallNeighbors(wall);stampSemanticMetadataV1(root, roleMetadata([`wall.${wall}`], [@@ -25369,8 +25462,8 @@ function createShellWall(name, wall, material, length, height, thickness, openinconst panel = (suffix, lo, hi, y0, y1) => {if (hi <= lo || y1 <= y0)return;- const geometry = axis === "x" ? new THREE35.BoxGeometry(hi - lo, y1 - y0, thickness) : new THREE35.BoxGeometry(thickness, y1 - y0, hi - lo);- const mesh = new THREE35.Mesh(geometry, material);+ const geometry = axis === "x" ? new THREE36.BoxGeometry(hi - lo, y1 - y0, thickness) : new THREE36.BoxGeometry(thickness, y1 - y0, hi - lo);+ const mesh = new THREE36.Mesh(geometry, material);mesh.name = `Mesh_${name}_${wall}_${suffix}`;mesh.position.set(axis === "x" ? (lo + hi) / 2 : 0, (y0 + y1) / 2, axis === "z" ? (lo + hi) / 2 : 0);root.add(mesh);@@ -25387,7 +25480,7 @@ function createShellWall(name, wall, material, length, height, thickness, openinpanel(singleNames[segment.suffix] ?? segment.suffix.slice(1), segment.left, segment.right, segment.bottom, segment.top);}for (const opening of built.openings) {- const marker = new THREE35.Object3D;+ const marker = new THREE36.Object3D;marker.name = `Opening_${wall}_${opening.id}`;marker.position.set(axis === "x" ? opening.offset : 0, opening.sill + opening.height / 2, axis === "z" ? opening.offset : 0);marker.scale.set(axis === "x" ? opening.width : opening.depth, opening.height, axis === "z" ? opening.width : opening.depth);@@ -25410,7 +25503,7 @@ function createGableShell(name, materials, options) {const closedEnds = options.closedEnds ?? true;const enterable = options.enterable ?? true;const shellOpenings = options.openings ?? (enterable ? [{ wall: "front", kind: "door" }] : []);- const root = new THREE35.Object3D;+ const root = new THREE36.Object3D;root.name = name;stampSemanticMetadataV1(root, roleMetadata(["architecture.shell.gable"], [relationship("contains", "floor"), relationship("contains", "roof.assembly")]));const wallSpecs = {@@ -25428,7 +25521,7 @@ function createGableShell(name, materials, options) {walls[wall] = built.root;openingMarkers.push(...built.openings);}- const floor = new THREE35.Mesh(new THREE35.BoxGeometry(spanX, floorThickness, spanZ), materials.floor ?? materials.wall);+ const floor = new THREE36.Mesh(new THREE36.BoxGeometry(spanX, floorThickness, spanZ), materials.floor ?? materials.wall);floor.name = `Mesh_${name}_Floor`;floor.position.y = -floorThickness / 2;stampSemanticMetadataV1(floor, roleMetadata(["floor"], ["front", "back", "left", "right"].map((wall) => relationship("adjacent-to", `wall.${wall}`))));@@ -25543,13 +25636,13 @@ function createRoofSurfaceLayout(name, material, options) {assertDimension("createRoofSurfaceLayout generated width", spec.width);assertDimension("createRoofSurfaceLayout generated length", spec.length);}- const root = new THREE35.Object3D;+ const root = new THREE36.Object3D;root.name = name;stampSemanticMetadataV1(root, roleMetadata([`roof.surface.${options.kind}`], [relationship("coverage-of", `roof.slope.${options.face.side}`)]));const items = specs.map((spec, index) => {- const mesh = new THREE35.Mesh(new THREE35.BoxGeometry(spec.width, thickness, spec.length), material);+ const mesh = new THREE36.Mesh(new THREE36.BoxGeometry(spec.width, thickness, spec.length), material);mesh.name = `Mesh_${name}_${index + 1}`;- const local = new THREE35.Matrix4().makeTranslation(spec.x, thickness / 2 + 0.002, spec.z);+ const local = new THREE36.Matrix4().makeTranslation(spec.x, thickness / 2 + 0.002, spec.z);setTransform(mesh, faceToRoot.clone().multiply(local));root.add(mesh);return mesh;@@ -25566,7 +25659,7 @@ var init_architecture2 = __esm(() => {});// src/gears.ts-import * as THREE36 from "three";+import * as THREE37 from "three";function gearGeo(opts = {}) {const {teeth = 12,@@ -25665,8 +25758,8 @@ function gearGeo(opts = {}) {indices.push(tA, bA, bB);indices.push(tA, bB, tB);}- const geo = new THREE36.BufferGeometry;- geo.setAttribute("position", new THREE36.Float32BufferAttribute(positions, 3));+ const geo = new THREE37.BufferGeometry;+ geo.setAttribute("position", new THREE37.Float32BufferAttribute(positions, 3));geo.setIndex(indices);const nonIndexed = geo.toNonIndexed();nonIndexed.computeVertexNormals();@@ -25751,8 +25844,8 @@ function bladeGeo(opts = {}) {indices.push(count + i, tip, count + j);}}- const geo = new THREE36.BufferGeometry;- geo.setAttribute("position", new THREE36.Float32BufferAttribute(positions, 3));+ const geo = new THREE37.BufferGeometry;+ geo.setAttribute("position", new THREE37.Float32BufferAttribute(positions, 3));geo.setIndex(indices);const nonIndexed = geo.toNonIndexed();nonIndexed.computeVertexNormals();@@ -25764,7 +25857,7 @@ var init_gears = __esm(() => {});// src/ops.ts-import * as THREE37 from "three";+import * as THREE38 from "three";import { LoopSubdivision } from "three-subdivide/build/index.module.js";import { mergeVertices as threeMergeVertices } from "three/examples/jsm/utils/BufferGeometryUtils.js";function assertFiniteSourceFrame(name, source) {@@ -25798,9 +25891,9 @@ function arrayLinear(namePrefix, source, count, offset, parent) {}function degreesOf(euler) {return [- THREE37.MathUtils.radToDeg(euler.x),- THREE37.MathUtils.radToDeg(euler.y),- THREE37.MathUtils.radToDeg(euler.z)+ THREE38.MathUtils.radToDeg(euler.x),+ THREE38.MathUtils.radToDeg(euler.y),+ THREE38.MathUtils.radToDeg(euler.z)];}function arrayRadial(namePrefix, source, count, axis = "y", parent, center, options = {}) {@@ -25813,12 +25906,12 @@ function arrayRadial(namePrefix, source, count, axis = "y", parent, center, optiif (center)assertFiniteTriple("arrayRadial center", center);const out = [];- const pivot = center ? new THREE37.Vector3(...center) : new THREE37.Vector3;+ const pivot = center ? new THREE38.Vector3(...center) : new THREE38.Vector3;const basePos = source.position.clone().sub(pivot);- const axisVec = axis === "x" ? new THREE37.Vector3(1, 0, 0) : axis === "z" ? new THREE37.Vector3(0, 0, 1) : new THREE37.Vector3(0, 1, 0);+ const axisVec = axis === "x" ? new THREE38.Vector3(1, 0, 0) : axis === "z" ? new THREE38.Vector3(0, 0, 1) : new THREE38.Vector3(0, 1, 0);const positions = [];for (let i = 1;i < count; i++) {- const position = basePos.clone().applyMatrix4(new THREE37.Matrix4().makeRotationAxis(axisVec, i / count * Math.PI * 2)).add(pivot);+ const position = basePos.clone().applyMatrix4(new THREE38.Matrix4().makeRotationAxis(axisVec, i / count * Math.PI * 2)).add(pivot);assertFiniteTriple("arrayRadial resulting position", position.toArray());positions.push(position);}@@ -25857,7 +25950,7 @@ function repeatAlongCurve(source, points, options) {assertFiniteTriple(`${name} points[${i}]`, point);const up = options.up ?? [0, 1, 0];assertFiniteTriple(`${name} up`, up);- const upVector = new THREE37.Vector3(...up);+ const upVector = new THREE38.Vector3(...up);if (upVector.lengthSq() === 0)throw new RangeError(`${name} up must not be zero.`);upVector.normalize();@@ -25896,13 +25989,13 @@ function repeatAlongCurve(source, points, options) {segment++;while (segment < points.length - 2 && cumulative[segment + 1] === cumulative[segment])segment++;- const a = new THREE37.Vector3(...points[segment]);- const b = new THREE37.Vector3(...points[segment + 1]);+ const a = new THREE38.Vector3(...points[segment]);+ const b = new THREE38.Vector3(...points[segment + 1]);const segmentLength = cumulative[segment + 1] - cumulative[segment];const local = segmentLength > 0 ? (s - cumulative[segment]) / segmentLength : 0;const position = a.clone().lerp(b, Math.min(Math.max(local, 0), 1));- const k = THREE37.MathUtils.lerp(scale[0], scale[1], t);- const rotation = new THREE37.Matrix4;+ const k = THREE38.MathUtils.lerp(scale[0], scale[1], t);+ const rotation = new THREE38.Matrix4;let angle = 0;if (align === "tangent") {const tangent = b.clone().sub(a).normalize();@@ -25910,17 +26003,17 @@ function repeatAlongCurve(source, points, options) {if (side.lengthSq() < 0.000000000001)side = previousUp.clone().sub(tangent.clone().multiplyScalar(previousUp.dot(tangent)));if (side.lengthSq() < 0.000000000001)- side = new THREE37.Vector3(Math.abs(tangent.x) < 0.9 ? 1 : 0, Math.abs(tangent.x) < 0.9 ? 0 : 1, 0).sub(tangent.clone().multiplyScalar(Math.abs(tangent.x) < 0.9 ? tangent.x : tangent.y));+ side = new THREE38.Vector3(Math.abs(tangent.x) < 0.9 ? 1 : 0, Math.abs(tangent.x) < 0.9 ? 0 : 1, 0).sub(tangent.clone().multiplyScalar(Math.abs(tangent.x) < 0.9 ? tangent.x : tangent.y));side.normalize();previousUp = side;- rotation.makeBasis(tangent, side, new THREE37.Vector3().crossVectors(tangent, side));- angle = THREE37.MathUtils.degToRad(THREE37.MathUtils.lerp(twist[0], twist[1], t));+ rotation.makeBasis(tangent, side, new THREE38.Vector3().crossVectors(tangent, side));+ angle = THREE38.MathUtils.degToRad(THREE38.MathUtils.lerp(twist[0], twist[1], t));}for (const extra of opposite ? [0, Math.PI] : [0]) {const turned = rotation.clone();if (angle + extra)- turned.multiply(new THREE37.Matrix4().makeRotationX(angle + extra));- const matrix = new THREE37.Matrix4().makeTranslation(position.x, position.y, position.z).multiply(turned).multiply(new THREE37.Matrix4().makeScale(k, k, k));+ turned.multiply(new THREE38.Matrix4().makeRotationX(angle + extra));+ const matrix = new THREE38.Matrix4().makeTranslation(position.x, position.y, position.z).multiply(turned).multiply(new THREE38.Matrix4().makeScale(k, k, k));if (!matrix.elements.every(Number.isFinite))throw new RangeError(`${name} produced a non-finite copy transform.`);frames.push({ matrix, t });@@ -25952,9 +26045,9 @@ function repeatAlongCurve(source, points, options) {const total = perCopy * copies;if (total > GEOMETRY_ALLOCATION_LIMITS.curveRepeatVertices)throw new RangeError(`${name} would produce ${total} vertices; the limit is ${GEOMETRY_ALLOCATION_LIMITS.curveRepeatVertices}. Reduce count, simplify the source, or use merge: false.`);- const merged = new THREE37.BufferGeometry;- const vector = new THREE37.Vector3;- const normalMatrix = new THREE37.Matrix3;+ const merged = new THREE38.BufferGeometry;+ const vector = new THREE38.Vector3;+ const normalMatrix = new THREE38.Matrix3;for (const [key, attribute] of Object.entries(geometry.attributes)) {const size = attribute.itemSize;const transformed = key === "position" || key === "normal" || key === "tangent";@@ -25978,13 +26071,13 @@ function repeatAlongCurve(source, points, options) {}}}- merged.setAttribute(key, new THREE37.BufferAttribute(out, size, transformed ? false : attribute.normalized));+ merged.setAttribute(key, new THREE38.BufferAttribute(out, size, transformed ? false : attribute.normalized));}if (options.along) {const along = new Float32Array(total);for (let copy = 0;copy < copies; copy++)along.fill(frames[copy].t, copy * perCopy, (copy + 1) * perCopy);- merged.setAttribute("_along", new THREE37.BufferAttribute(along, 1));+ merged.setAttribute("_along", new THREE38.BufferAttribute(along, 1));}const index = geometry.getIndex();if (index) {@@ -25992,7 +26085,7 @@ function repeatAlongCurve(source, points, options) {for (let copy = 0;copy < copies; copy++)for (let i = 0;i < index.count; i++)indices[copy * index.count + i] = index.getX(i) + copy * perCopy;- merged.setIndex(new THREE37.BufferAttribute(indices, 1));+ merged.setIndex(new THREE38.BufferAttribute(indices, 1));}merged.computeBoundingBox();merged.computeBoundingSphere();@@ -26001,15 +26094,15 @@ function repeatAlongCurve(source, points, options) {function mirror(name, source, axis, parent) {if (source.matrixAutoUpdate)source.updateMatrix();- const reflected = new THREE37.Matrix4().makeScale(axis === "x" ? -1 : 1, axis === "y" ? -1 : 1, axis === "z" ? -1 : 1).multiply(source.matrix);+ const reflected = new THREE38.Matrix4().makeScale(axis === "x" ? -1 : 1, axis === "y" ? -1 : 1, axis === "z" ? -1 : 1).multiply(source.matrix);if (!reflected.elements.every(Number.isFinite) || reflected.determinant() === 0) {throw new RangeError(`mirror("${name}"): source requires a finite, nonsingular local transform.`);}- const position = new THREE37.Vector3;- const quaternion = new THREE37.Quaternion;- const scale = new THREE37.Vector3;+ const position = new THREE38.Vector3;+ const quaternion = new THREE38.Quaternion;+ const scale = new THREE38.Vector3;reflected.decompose(position, quaternion, scale);- const recomposed = new THREE37.Matrix4().compose(position, quaternion, scale);+ const recomposed = new THREE38.Matrix4().compose(position, quaternion, scale);if (reflected.elements.some((value, i) => Math.abs(value - recomposed.elements[i]) > 0.00000001 * Math.max(1, Math.abs(value)))) {throw new RangeError(`mirror("${name}"): local shear cannot be represented by a reflected TRS.`);}@@ -26025,13 +26118,13 @@ function mergeVertices(geometry, opts = {}) {const { tolerance = 0.0001, positionOnly = false } = typeof opts === "number" ? { tolerance: opts } : opts;if (!positionOnly)return threeMergeVertices(geometry, tolerance);- const stripped = new THREE37.BufferGeometry;+ const stripped = new THREE38.BufferGeometry;const pos = geometry.getAttribute("position");if (!pos)return geometry;- stripped.setAttribute("position", new THREE37.BufferAttribute(new Float32Array(pos.array), pos.itemSize, pos.normalized));+ stripped.setAttribute("position", new THREE38.BufferAttribute(new Float32Array(pos.array), pos.itemSize, pos.normalized));if (geometry.index) {- stripped.setIndex(new THREE37.BufferAttribute(new Uint32Array(geometry.index.array), 1));+ stripped.setIndex(new THREE38.BufferAttribute(new Uint32Array(geometry.index.array), 1));}return threeMergeVertices(stripped, tolerance);}@@ -26066,8 +26159,8 @@ function subdivide(geometry, iterations = 1, opts = {}) {const { weld = true, preserveUV = false, ...subOpts } = opts;const prepared = geometry.clone();prepared.computeBoundingBox();- const center = prepared.boundingBox.getCenter(new THREE37.Vector3);- const extent = prepared.boundingBox.getSize(new THREE37.Vector3);+ const center = prepared.boundingBox.getCenter(new THREE38.Vector3);+ const extent = prepared.boundingBox.getSize(new THREE38.Vector3);const size = Math.max(extent.x, extent.y, extent.z);const normalizationScale = size > 0 ? 1e4 / size : 1;if (!Number.isFinite(normalizationScale) || !center.toArray().every(Number.isFinite))@@ -26097,13 +26190,13 @@ function subdivide(geometry, iterations = 1, opts = {}) {const values = new Float32Array(attribute.count);for (let i = 0;i < attribute.count; i++)values[i] = decoded[i * 4 + component];- input.setAttribute(lane, new THREE37.BufferAttribute(values, 1));+ input.setAttribute(lane, new THREE38.BufferAttribute(values, 1));lanes.push(lane);}input.deleteAttribute(name);fourthComponents.push({ name, lanes });} else- input.setAttribute(name, new THREE37.BufferAttribute(decoded, components));+ input.setAttribute(name, new THREE38.BufferAttribute(decoded, components));}for (const targets of Object.values(input.morphAttributes))for (let target = 0;target < targets.length; target++) {@@ -26112,7 +26205,7 @@ function subdivide(geometry, iterations = 1, opts = {}) {for (let i = 0;i < attribute.count; i++)for (let component = 0;component < 3; component++)decoded[i * 3 + component] = attribute.getComponent(i, component);- targets[target] = new THREE37.BufferAttribute(decoded, 3);+ targets[target] = new THREE38.BufferAttribute(decoded, 3);}if (preserveUV)subOpts.uvSmooth = false;@@ -26126,7 +26219,7 @@ function subdivide(geometry, iterations = 1, opts = {}) {values[i * 4 + component] = lane.getX(i);output.deleteAttribute(lanes[component]);}- output.setAttribute(name, new THREE37.BufferAttribute(values, 4));+ output.setAttribute(name, new THREE38.BufferAttribute(values, 4));}output.scale(1 / normalizationScale, 1 / normalizationScale, 1 / normalizationScale).translate(center.x, center.y, center.z);output.userData = structuredClone(geometry.userData);@@ -26191,9 +26284,9 @@ function assertTubeRadius(radius) {}function curveToMesh(points, radius, tubularSegments = 32, radialSegments = 8, closed = false) {assertTubeRadius(radius);- const vectors = points.map((p) => new THREE37.Vector3(p[0], p[1], p[2]));- const curve = new THREE37.CatmullRomCurve3(vectors, closed);- return new THREE37.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);+ const vectors = points.map((p) => new THREE38.Vector3(p[0], p[1], p[2]));+ const curve = new THREE38.CatmullRomCurve3(vectors, closed);+ return new THREE38.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);}function normalizeSurfaceNormals(geo) {const normal = geo.getAttribute("normal");@@ -26224,15 +26317,15 @@ function lathe(profile, segments = 12) {}function revolveGeo(profile, options = {}) {const { angle = Math.PI * 2, axis = [0, 1, 0], segments = 12 } = options;- const points2d = profile.map((p) => new THREE37.Vector2(p[0], p[1]));- const geo = normalizeSurfaceNormals(new THREE37.LatheGeometry(points2d, segments, 0, angle));- const n = new THREE37.Vector3(axis[0], axis[1], axis[2]);+ const points2d = profile.map((p) => new THREE38.Vector2(p[0], p[1]));+ const geo = normalizeSurfaceNormals(new THREE38.LatheGeometry(points2d, segments, 0, angle));+ const n = new THREE38.Vector3(axis[0], axis[1], axis[2]);if (n.lengthSq() < 0.000000000001) {throw new Error(`revolveGeo: axis must be a non-zero vector (got [${axis.join(",")}]).`);}n.normalize();if (n.x !== 0 || n.y !== 1 || n.z !== 0) {- const q = new THREE37.Quaternion().setFromUnitVectors(new THREE37.Vector3(0, 1, 0), n);+ const q = new THREE38.Quaternion().setFromUnitVectors(new THREE38.Vector3(0, 1, 0), n);geo.applyQuaternion(q);}return geo;@@ -26248,9 +26341,9 @@ function pipeAlongPath(points, radius, options = {}) {const smoothed = [];smoothed.push(points[0]);for (let i = 1;i < points.length - 1; i++) {- const prev = new THREE37.Vector3(...points[i - 1]);- const cur = new THREE37.Vector3(...points[i]);- const next = new THREE37.Vector3(...points[i + 1]);+ const prev = new THREE38.Vector3(...points[i - 1]);+ const cur = new THREE38.Vector3(...points[i]);+ const next = new THREE38.Vector3(...points[i + 1]);const inDir = cur.clone().sub(prev);const outDir = next.clone().sub(cur);const inLen = inDir.length();@@ -26268,12 +26361,12 @@ function pipeAlongPath(points, radius, options = {}) {return curveToMesh(pathPoints, radius, tubularSegments, radialSegments, closed);}function bezierCurve(controlPoints, samples = 32) {- const vecs = controlPoints.map((p) => new THREE37.Vector3(p[0], p[1], p[2]));+ const vecs = controlPoints.map((p) => new THREE38.Vector3(p[0], p[1], p[2]));let curve;if (vecs.length === 3) {- curve = new THREE37.QuadraticBezierCurve3(vecs[0], vecs[1], vecs[2]);+ curve = new THREE38.QuadraticBezierCurve3(vecs[0], vecs[1], vecs[2]);} else if (vecs.length === 4) {- curve = new THREE37.CubicBezierCurve3(vecs[0], vecs[1], vecs[2], vecs[3]);+ curve = new THREE38.CubicBezierCurve3(vecs[0], vecs[1], vecs[2], vecs[3]);} else {throw new Error(`bezierCurve: need 3 or 4 control points, got ${vecs.length}`);}@@ -26286,20 +26379,20 @@ var init_ops = __esm(() => {});// src/deformation-normals.ts-import * as THREE38 from "three";+import * as THREE39 from "three";function recomputeDeformedNormals(source, output) {const original = source.getAttribute("position");const authored = source.getAttribute("normal");const position = output.getAttribute("position");const bounds = (attribute) => {- const box = new THREE38.Box3().setFromBufferAttribute(attribute);+ const box = new THREE39.Box3().setFromBufferAttribute(attribute);return {- center: box.getCenter(new THREE38.Vector3),- size: box.getSize(new THREE38.Vector3).length() || 1+ center: box.getCenter(new THREE39.Vector3),+ size: box.getSize(new THREE39.Vector3).length() || 1};};const before = bounds(original), after = bounds(position);- const point = new THREE38.Vector3, normal = new THREE38.Vector3;+ const point = new THREE39.Vector3, normal = new THREE39.Vector3;const quantized = (attribute, index, frame) => {point.fromBufferAttribute(attribute, index).sub(frame.center).divideScalar(frame.size);return point.toArray().map((value) => Math.round(value * 1e7)).join(",");@@ -26322,7 +26415,7 @@ function recomputeDeformedNormals(source, output) {const sums = new Float64Array(classes.size * 3);const index = output.index;const corners = index?.count ?? position.count;- const a = new THREE38.Vector3, b = new THREE38.Vector3, c = new THREE38.Vector3;+ const a = new THREE39.Vector3, b = new THREE39.Vector3, c = new THREE39.Vector3;for (let t = 0;t < corners; t += 3) {const ia = index ? index.getX(t) : t;const ib = index ? index.getX(t + 1) : t + 1;@@ -26343,17 +26436,17 @@ function recomputeDeformedNormals(source, output) {const offset = ids[i] * 3;normal.set(sums[offset], sums[offset + 1], sums[offset + 2]).normalize().toArray(normals, i * 3);}- output.setAttribute("normal", new THREE38.BufferAttribute(normals, 3));+ output.setAttribute("normal", new THREE39.BufferAttribute(normals, 3));}var init_deformation_normals = () => {};// src/deform.ts-import * as THREE39 from "three";+import * as THREE40 from "three";function geometryFrameMatrix(frame = {}) {const origin = frame.origin ?? [0, 0, 0], rotation = frame.rotation ?? [0, 0, 0];if (origin.length !== 3 || rotation.length !== 3 || ![...origin, ...rotation].every(Number.isFinite))throw new Error("geometry frame requires finite xyz origin and rotation");- return new THREE39.Matrix4().compose(new THREE39.Vector3(...origin), new THREE39.Quaternion().setFromEuler(new THREE39.Euler(...rotation.map(THREE39.MathUtils.degToRad), "XYZ")), new THREE39.Vector3(1, 1, 1));+ return new THREE40.Matrix4().compose(new THREE40.Vector3(...origin), new THREE40.Quaternion().setFromEuler(new THREE40.Euler(...rotation.map(THREE40.MathUtils.degToRad), "XYZ")), new THREE40.Vector3(1, 1, 1));}function deform(geometry, options, map) {const source = geometry.getAttribute("position");@@ -26380,7 +26473,7 @@ function deform(geometry, options, map) {throw new Error("deformation normals must be finite");}const matrix = geometryFrameMatrix(options.frame), inverse = matrix.clone().invert();- const points = Array.from({ length: source.count }, (_, i) => new THREE39.Vector3().fromBufferAttribute(source, i).applyMatrix4(inverse));+ const points = Array.from({ length: source.count }, (_, i) => new THREE40.Vector3().fromBufferAttribute(source, i).applyMatrix4(inverse));if (points.some((p) => ![p.x, p.y, p.z].every(Number.isFinite)))throw new Error("deformation positions must be finite");let low = Infinity, high = -Infinity;@@ -26403,7 +26496,7 @@ function deform(geometry, options, map) {const point = points[i];if (point.y < low - epsilon || point.y > high + epsilon)continue;- const t = length > 0 ? THREE39.MathUtils.clamp((point.y - low) / length, 0, 1) : 0;+ const t = length > 0 ? THREE40.MathUtils.clamp((point.y - low) / length, 0, 1) : 0;const weight = options.falloff?.(t) ?? 1;if (!Number.isFinite(weight) || weight < 0 || weight > 1)throw new Error("deformation falloff must return a finite weight between 0 and 1");@@ -26437,31 +26530,31 @@ function deform(geometry, options, map) {function twist(geometry, options) {if (!Number.isFinite(options.angle))throw new Error("twist angle must be finite degrees");- return deform(geometry, options, (p, t) => p.applyAxisAngle(new THREE39.Vector3(0, 1, 0), THREE39.MathUtils.degToRad(options.angle) * t));+ return deform(geometry, options, (p, t) => p.applyAxisAngle(new THREE40.Vector3(0, 1, 0), THREE40.MathUtils.degToRad(options.angle) * t));}function bend(geometry, options) {if (!Number.isFinite(options.angle))throw new Error("bend angle must be finite degrees");- const angle = THREE39.MathUtils.degToRad(options.angle);+ const angle = THREE40.MathUtils.degToRad(options.angle);return deform(geometry, options, (p, t, low, length) => {if (Math.abs(angle) < 0.0000000001 || length === 0)return p;const radius = length / angle, theta = angle * t;- return new THREE39.Vector3(radius - (radius - p.x) * Math.cos(theta), low + (radius - p.x) * Math.sin(theta), p.z);+ return new THREE40.Vector3(radius - (radius - p.x) * Math.cos(theta), low + (radius - p.x) * Math.sin(theta), p.z);});}function taper(geometry, options) {const start = options.startScale ?? [1, 1], end = options.endScale;if (start.length !== 2 || end.length !== 2 || ![...start, ...end].every((n) => Number.isFinite(n) && n > 0))throw new Error("taper scales must be two finite positive values");- return deform(geometry, options, (p, t) => p.set(p.x * THREE39.MathUtils.lerp(start[0], end[0], t), p.y, p.z * THREE39.MathUtils.lerp(start[1], end[1], t)));+ return deform(geometry, options, (p, t) => p.set(p.x * THREE40.MathUtils.lerp(start[0], end[0], t), p.y, p.z * THREE40.MathUtils.lerp(start[1], end[1], t)));}function displace(geometry, offset, options = {}) {return deform(geometry, options, (p, t) => {const delta = offset([p.x, p.y, p.z], t);if (delta.length !== 3 || !delta.every(Number.isFinite))throw new Error("displace callback must return three finite offsets");- return p.add(new THREE39.Vector3(...delta));+ return p.add(new THREE40.Vector3(...delta));});}var init_deform = __esm(() => {@@ -26469,7 +26562,7 @@ var init_deform = __esm(() => {});// src/sweep.ts-import * as THREE40 from "three";+import * as THREE41 from "three";function rejectHoles(value, label) {if ("holes" in value && value.holes !== undefined)throw new AuthoringDiagnosticError("PROFILE_HOLES_UNSUPPORTED", `${label}: holes are unsupported. Use extrudeProfile for a holed cross-section with optional twist/taper; independently varying contours need explicit geometry or solid subtraction.`);@@ -26477,9 +26570,9 @@ function rejectHoles(value, label) {function profilePoints(profile) {if (profile.length < 3 || profile.some((p) => p.length !== 2 || !p.every(Number.isFinite)))throw new Error("profile requires at least three finite xy points");- const points = profile.map((p) => new THREE40.Vector2(...p));- const bounds = new THREE40.Box2().setFromPoints(points);- const extent = bounds.getSize(new THREE40.Vector2).length();+ const points = profile.map((p) => new THREE41.Vector2(...p));+ const bounds = new THREE41.Box2().setFromPoints(points);+ const extent = bounds.getSize(new THREE41.Vector2).length();if (!(extent > 0) || !Number.isFinite(extent))throw new Error("profile requires a finite nonzero extent");const normalized = points.map((p) => p.clone().sub(bounds.min).divideScalar(extent));@@ -26502,7 +26595,7 @@ function profilePoints(profile) {throw new Error("profile self-intersects or touches itself");}}- const area = THREE40.ShapeUtils.area(normalized);+ const area = THREE41.ShapeUtils.area(normalized);if (Math.abs(area) < 0.000000000001)throw new Error("profile area must be nonzero");if (area < 0)@@ -26516,11 +26609,11 @@ function isCrease(first, second, creaseAngle) {if (!(first.lengthSq() > 0 && second.lengthSq() > 0))return false;const angle = Math.atan2(first.clone().cross(second).length(), first.dot(second));- return THREE40.MathUtils.radToDeg(angle) > creaseAngle + CREASE_TOLERANCE_DEGREES;+ return THREE41.MathUtils.radToDeg(angle) > creaseAngle + CREASE_TOLERANCE_DEGREES;}function buildLoft(rings, profiles, closed, cap, firstFrameForward, creaseAngle) {const n = rings[0].length, positions = [], uvs = [], indices = [];- const centers = rings.map((r) => r.reduce((sum, p) => sum.add(p), new THREE40.Vector3).multiplyScalar(1 / n));+ const centers = rings.map((r) => r.reduce((sum, p) => sum.add(p), new THREE41.Vector3).multiplyScalar(1 / n));const lengths = [0];for (let i = 1;i < centers.length; i++)lengths.push(lengths[i - 1] + centers[i].distanceTo(centers[i - 1]));@@ -26580,13 +26673,13 @@ function buildLoft(rings, profiles, closed, cap, firstFrameForward, creaseAngle)continue;const ring = rings[station], profile = profiles[station];const start = positions.length / 3;- const bounds = new THREE40.Box2().setFromPoints(profile);- const size = bounds.getSize(new THREE40.Vector2);+ const bounds = new THREE41.Box2().setFromPoints(profile);+ const size = bounds.getSize(new THREE41.Vector2);for (let j = 0;j < n; j++) {positions.push(...ring[j].toArray());uvs.push((profile[j].x - bounds.min.x) / (size.x || 1), (profile[j].y - bounds.min.y) / (size.y || 1));}- for (const tri of THREE40.ShapeUtils.triangulateShape(profile, [])) {+ for (const tri of THREE41.ShapeUtils.triangulateShape(profile, [])) {if (station === 0)indices.push(...tri.map((j) => start + j));else@@ -26599,7 +26692,7 @@ function buildLoft(rings, profiles, closed, cap, firstFrameForward, creaseAngle)const out = meshGeo({ positions, indices, uvs });const normal = out.getAttribute("normal");const share = (a, b) => {- const sum = new THREE40.Vector3().fromBufferAttribute(normal, a).add(new THREE40.Vector3().fromBufferAttribute(normal, b)).normalize();+ const sum = new THREE41.Vector3().fromBufferAttribute(normal, a).add(new THREE41.Vector3().fromBufferAttribute(normal, b)).normalize();normal.setXYZ(a, sum.x, sum.y, sum.z);normal.setXYZ(b, sum.x, sum.y, sum.z);};@@ -26637,8 +26730,8 @@ function loftProfiles(sections, options = {}) {if (profiles.some((p) => p.length !== profiles[0].length))throw new Error("loftProfiles sections must have the same point count and correspondence");const frames = sections.map((section) => geometryFrameMatrix(section.frame));- const rings = profiles.map((profile, i) => profile.map((p) => new THREE40.Vector3(p.x, 0, p.y).applyMatrix4(frames[i])));- const out = buildLoft(rings, profiles, false, loftCapEnds(options.cap), new THREE40.Vector3(0, 1, 0).transformDirection(frames[0]));+ const rings = profiles.map((profile, i) => profile.map((p) => new THREE41.Vector3(p.x, 0, p.y).applyMatrix4(frames[i])));+ const out = buildLoft(rings, profiles, false, loftCapEnds(options.cap), new THREE41.Vector3(0, 1, 0).transformDirection(frames[0]));const analysis = recordSweepAnalysis(out, rings, profiles, false);out.userData.kilnGeometryWarnings = analysis.complete ? [] : [{@@ -26661,8 +26754,8 @@ function sweepProfile(profile, path, options = {}) {const cap = sweepCapEnds(options.cap, closed);if (path.length < (closed ? 3 : 2) || path.some((p) => p.length !== 3 || !p.every(Number.isFinite)))throw new Error("sweepProfile requires finite path points (two open or three closed)");- const stations = path.map((p) => new THREE40.Vector3(...p));- const pathExtent = new THREE40.Box3().setFromPoints(stations).getSize(new THREE40.Vector3).length();+ const stations = path.map((p) => new THREE41.Vector3(...p));+ const pathExtent = new THREE41.Box3().setFromPoints(stations).getSize(new THREE41.Vector3).length();if (!(pathExtent > 0) || !Number.isFinite(pathExtent))throw new Error("sweepProfile path stations must be distinct with finite extent");const pathTolerance = pathExtent * 0.0000000001;@@ -26703,7 +26796,7 @@ function sweepProfile(profile, path, options = {}) {});return incoming.clone().add(outgoing).normalize();});- const up = options.up ? new THREE40.Vector3(...options.up) : Math.abs(tangents[0].z) < 0.9 ? new THREE40.Vector3(0, 0, 1) : new THREE40.Vector3(1, 0, 0);+ const up = options.up ? new THREE41.Vector3(...options.up) : Math.abs(tangents[0].z) < 0.9 ? new THREE41.Vector3(0, 0, 1) : new THREE41.Vector3(1, 0, 0);const upLength = Math.hypot(up.x, up.y, up.z);if (!(upLength > 0) || !Number.isFinite(upLength))throw new Error("sweepProfile up must be a finite nonzero vector");@@ -26720,7 +26813,7 @@ function sweepProfile(profile, path, options = {}) {}const distances = [0];for (let i = 1;i < stations.length; i++) {- z = z.clone().applyQuaternion(new THREE40.Quaternion().setFromUnitVectors(tangents[i - 1], tangents[i]));+ z = z.clone().applyQuaternion(new THREE41.Quaternion().setFromUnitVectors(tangents[i - 1], tangents[i]));normals.push(z);distances.push(distances[i - 1] + stations[i].distanceTo(stations[i - 1]));}@@ -26730,7 +26823,7 @@ function sweepProfile(profile, path, options = {}) {correction = Math.atan2(tangents[0].dot(normals[normals.length - 1].clone().cross(normals[0])), normals[normals.length - 1].dot(normals[0]));const rings = stations.map((station, i) => {const tangent = tangents[i], t = distances[i] / total;- const axisZ = normals[i].clone().applyAxisAngle(tangent, (correction + THREE40.MathUtils.degToRad(twist)) * t);+ const axisZ = normals[i].clone().applyAxisAngle(tangent, (correction + THREE41.MathUtils.degToRad(twist)) * t);const axisX = tangent.clone().cross(axisZ).normalize(), scale = scales[i];return points.map((p) => station.clone().addScaledVector(axisX, p.x * scale[0]).addScaledVector(axisZ, p.y * scale[1]));});@@ -26755,7 +26848,7 @@ var init_sweep2 = __esm(() => {});// src/simplify.ts-import * as THREE41 from "three";+import * as THREE42 from "three";function loadSimplifier() {simplifierReady ??= import("meshoptimizer/simplifier").then(async ({ MeshoptSimplifier }) => {await MeshoptSimplifier.ready;@@ -26777,7 +26870,7 @@ function gather(attribute, vertices) {for (let i = 0;i < vertices.length; i++)for (let c = 0;c < attribute.itemSize; c++)values[i * attribute.itemSize + c] = raw(attribute, vertices[i], c);- const out = new THREE41.BufferAttribute(values, attribute.itemSize, attribute.normalized);+ const out = new THREE42.BufferAttribute(values, attribute.itemSize, attribute.normalized);out.name = attribute.name;return out;}@@ -27062,14 +27155,14 @@ async function simplifyGeometry(geometry, options) {indexValues[i] = remap[w];}const sources = Uint32Array.from(used, (w) => representative[w]);- const out = new THREE41.BufferGeometry;+ const out = new THREE42.BufferGeometry;out.name = geometry.name;const outPosition = new Float32Array(sources.length * 3);for (let i = 0;i < used.length; i++)outPosition.set(positions.subarray(used[i] * 3, used[i] * 3 + 3), i * 3);for (const [name, attribute] of Object.entries(geometry.attributes)) {if (name === "position") {- const attr = new THREE41.BufferAttribute(outPosition, 3);+ const attr = new THREE42.BufferAttribute(outPosition, 3);attr.name = attribute.name;out.setAttribute(name, attr);} else@@ -27078,7 +27171,7 @@ async function simplifyGeometry(geometry, options) {for (const [name, targets] of Object.entries(geometry.morphAttributes))out.morphAttributes[name] = targets.map((target) => gather(target, sources));out.morphTargetsRelative = geometry.morphTargetsRelative;- out.setIndex(new THREE41.BufferAttribute(indexValues, 1));+ out.setIndex(new THREE42.BufferAttribute(indexValues, 1));for (const group of outGroups)out.addGroup(group.start, group.count, group.materialIndex);out.computeBoundingBox();@@ -27133,7 +27226,7 @@ var init_simplify = __esm(() => {});// src/solids.ts-import * as THREE42 from "three";+import * as THREE43 from "three";async function getManifoldModule() {if (_module)return _module;@@ -27163,10 +27256,10 @@ function computationFrame(parts) {meshes.push(mesh);});}- const origin = meshes.length ? new THREE42.Vector3().setFromMatrixPosition(meshes[0].matrixWorld) : new THREE42.Vector3;+ const origin = meshes.length ? new THREE43.Vector3().setFromMatrixPosition(meshes[0].matrixWorld) : new THREE43.Vector3;const matrices = new Map;- const bounds = new THREE42.Box3;- const point = new THREE42.Vector3;+ const bounds = new THREE43.Box3;+ const point = new THREE43.Vector3;for (const mesh of meshes) {const matrix = mesh.matrixWorld.clone();matrix.elements[12] -= origin.x;@@ -27183,11 +27276,11 @@ function computationFrame(parts) {bounds.expandByPoint(point);}}- const size = bounds.getSize(new THREE42.Vector3);+ const size = bounds.getSize(new THREE43.Vector3);const scale = Math.hypot(size.x, size.y, size.z);if (!Number.isFinite(scale))throw new Error("CSG: combined operand extent must be finite");- return { origin, center: bounds.getCenter(new THREE42.Vector3), scale: scale || 1, matrices };+ return { origin, center: bounds.getCenter(new THREE43.Vector3), scale: scale || 1, matrices };}function retainNotes(target, notes) {if (!Array.isArray(notes))@@ -27267,7 +27360,7 @@ function threeToManifold(src, mod, label, context) {elsecontext.missingUV.add(mesh.name || label);}- const point = new THREE42.Vector3;+ const point = new THREE43.Vector3;for (let i = 0;i < position.count; i++) {point.fromBufferAttribute(position, i).applyMatrix4(context.frame.matrices.get(mesh)).sub(context.frame.center).divideScalar(context.frame.scale);if (![point.x, point.y, point.z].every((n) => Number.isFinite(Math.fround(n))))@@ -27410,11 +27503,11 @@ function solidMeshToGeometry({ mesh, collapsed }, opts = {}) {if (uvs)uvs.set(mesh.vertProperties.subarray(i + 3, i + 5), v * 2);}- const geometry = new THREE42.BufferGeometry;- geometry.setAttribute("position", new THREE42.BufferAttribute(positions, 3));- geometry.setIndex(new THREE42.BufferAttribute(new Uint32Array(mesh.triVerts), 1));+ const geometry = new THREE43.BufferGeometry;+ geometry.setAttribute("position", new THREE43.BufferAttribute(positions, 3));+ geometry.setIndex(new THREE43.BufferAttribute(new Uint32Array(mesh.triVerts), 1));if (uvs)- geometry.setAttribute("uv", new THREE42.BufferAttribute(uvs, 2));+ geometry.setAttribute("uv", new THREE43.BufferAttribute(uvs, 2));const out = opts.smooth ? geometry : geometry.toNonIndexed();out.computeVertexNormals();if (opts.smooth && uvs) {@@ -27445,7 +27538,7 @@ function firstMaterial(src) {if (!material && mesh.isMesh)material = Array.isArray(mesh.material) ? mesh.material[0] : mesh.material;});- return material ?? new THREE42.MeshStandardMaterial;+ return material ?? new THREE43.MeshStandardMaterial;}function outputMesh(result, name, parts, opts, context, isHull) {const materialized = materializeSolid(result);@@ -27504,7 +27597,7 @@ function outputMesh(result, name, parts, opts, context, isHull) {retainNotes(context.geometryWarnings, geometry.userData.kilnGeometryWarnings);if (context.geometryWarnings.size)geometry.userData.kilnGeometryWarnings = [...context.geometryWarnings.values()];- const output = new THREE42.Mesh(geometry, context.preserve && !isHull && materials.length ? materials : firstMaterial(parts[0]));+ const output = new THREE43.Mesh(geometry, context.preserve && !isHull && materials.length ? materials : firstMaterial(parts[0]));output.name = `Mesh_${name}`;output.position.copy(context.frame.origin);return output;@@ -27913,7 +28006,7 @@ function smoothUnionSpheres(point, spheres, blend) {}// src/organic.ts-import * as THREE43 from "three";+import * as THREE44 from "three";function assertSafePathCount(name, count) {if (!Number.isSafeInteger(count))throw new Error(`${name} derived sample count must be a safe integer; reduce sample counts.`);@@ -27945,8 +28038,8 @@ function catmullRomPath(controlPoints, samplesPerSpan = 8, closed = false) {assertSafePathCount("catmullRomPath", spans * samplesPerSpan + 1);if (controlPoints.some((p) => p.length !== 3 || !p.every(Number.isFinite)))throw new Error("catmullRomPath control points must be finite [x,y,z] triples");- const vectors = controlPoints.map((p) => new THREE43.Vector3(p[0], p[1], p[2]));- const curve = new THREE43.CatmullRomCurve3(vectors, closed);+ const vectors = controlPoints.map((p) => new THREE44.Vector3(p[0], p[1], p[2]));+ const curve = new THREE44.CatmullRomCurve3(vectors, closed);const points = curve.getPoints(spans * samplesPerSpan);if (closed)points.pop();@@ -28000,8 +28093,8 @@ function spiralPath(options) {throw new Error("spiralPath center must be a finite [x,y,z] triple");if (axis.length !== 3 || forward.length !== 3 || ![...axis, ...forward].every(Number.isFinite))throw new Error("spiralPath axis and forward must be finite [x,y,z] triples");- const up = new THREE43.Vector3(...axis);- const fwd = new THREE43.Vector3(...forward);+ const up = new THREE44.Vector3(...axis);+ const fwd = new THREE44.Vector3(...forward);if (up.lengthSq() < 0.000000000001 || fwd.lengthSq() < 0.000000000001)throw new Error("spiralPath axis and forward must be nonzero");up.normalize();@@ -28009,7 +28102,7 @@ function spiralPath(options) {if (horiz.lengthSq() < 0.000000000001)throw new Error("spiralPath forward must not be parallel to axis");horiz.normalize();- const right = new THREE43.Vector3().crossVectors(up, horiz).normalize();+ const right = new THREE44.Vector3().crossVectors(up, horiz).normalize();const out = [];for (let i = 0;i <= samples; i++) {const u = i / samples;@@ -28123,7 +28216,7 @@ var init_seeded_random = __esm(() => {});// src/uv-shapes.ts-import * as THREE44 from "three";+import * as THREE45 from "three";function remapUV(geo, options = {}) {if (!options || typeof options !== "object" || Array.isArray(options) || Object.keys(options).some((key) => !["scale", "offset"].includes(key))) {throw new Error("remapUV: options may contain only scale and offset.");@@ -28152,7 +28245,7 @@ function remapUV(geo, options = {}) {}const cloned = geo.clone();cloned.userData = structuredClone(geo.userData);- cloned.setAttribute("uv", new THREE44.Float32BufferAttribute(values, 2));+ cloned.setAttribute("uv", new THREE45.Float32BufferAttribute(values, 2));if ((scale[0] !== 1 || scale[1] !== 1) && cloned.hasAttribute("tangent")) {cloned.deleteAttribute("tangent");const previous = cloned.userData.kilnAttributeWarnings;@@ -28169,13 +28262,13 @@ function remapUV(geo, options = {}) {var init_uv_shapes = () => {};// src/texture-atlas.ts-import * as THREE45 from "three";+import * as THREE46 from "three";async function textureAtlas(input, options = {}) {const compiled = await compileTextureAtlasSpecV1(input, options);- const texture = new THREE45.DataTexture(compiled.pixels, compiled.spec.width, compiled.spec.height, THREE45.RGBAFormat, THREE45.UnsignedByteType);+ const texture = new THREE46.DataTexture(compiled.pixels, compiled.spec.width, compiled.spec.height, THREE46.RGBAFormat, THREE46.UnsignedByteType);texture.name = "Atlas";texture.flipY = false;- texture.colorSpace = compiled.spec.usage === "albedo" || compiled.spec.usage === "emissive" ? THREE45.SRGBColorSpace : THREE45.NoColorSpace;+ texture.colorSpace = compiled.spec.usage === "albedo" || compiled.spec.usage === "emissive" ? THREE46.SRGBColorSpace : THREE46.NoColorSpace;applyPortableSamplerV1(texture, compiled.spec.sampler);texture.userData.kilnAtlas = { spec: compiled.spec, manifest: compiled.manifest };texture.userData.kilnTexture = {@@ -28226,7 +28319,7 @@ function remapUVToAtlas(geometry, atlas, name, options) {bytes += buffer.byteLength;}} else {- bytes += attribute.array.byteLength * (attribute.constructor === THREE45.BufferAttribute || attribute.constructor === THREE45.InstancedBufferAttribute ? 1 : 2);+ bytes += attribute.array.byteLength * (attribute.constructor === THREE46.BufferAttribute || attribute.constructor === THREE46.InstancedBufferAttribute ? 1 : 2);}};for (const attr of Object.values(geometry.attributes))@@ -28450,7 +28543,7 @@ var init_portable_material_runtime = __esm(() => {});// src/uv-data.ts-import * as THREE46 from "three";+import * as THREE47 from "three";function validateAtlasRemap(mesh, inputIndex, sourceCount) {const count = mesh.vertexCount;if (!Number.isSafeInteger(count) || count < 1 || count > GEOMETRY_ALLOCATION_LIMITS.unwrapVertices)@@ -28485,7 +28578,7 @@ function remapUnwrapAttribute(attribute, oldIndexes) {for (let c = 0;c < attribute.itemSize; c++)array[i * attribute.itemSize + c] = attribute.array[oldIndexes[i] * stride + offset + c];}- const output = attribute.isFloat16BufferAttribute ? new THREE46.Float16BufferAttribute(array, attribute.itemSize, attribute.normalized) : new THREE46.BufferAttribute(array, attribute.itemSize, attribute.normalized);+ const output = attribute.isFloat16BufferAttribute ? new THREE47.Float16BufferAttribute(array, attribute.itemSize, attribute.normalized) : new THREE47.BufferAttribute(array, attribute.itemSize, attribute.normalized);output.name = attribute.name;output.setUsage(interleaved(attribute) ? attribute.data.usage : attribute.usage);if (!interleaved(attribute))@@ -28597,7 +28690,7 @@ var init_uv_data = __esm(() => {});// src/uv.ts-import * as THREE47 from "three";+import * as THREE48 from "three";async function getXatlas() {if (!_xatlasReady) {_xatlasReady = (async () => {@@ -28629,7 +28722,7 @@ async function autoUnwrap(geometry, opts = {}) {if (result.atlasCount !== 1 || !Number.isSafeInteger(result.width) || result.width <= 0 || !Number.isSafeInteger(result.height) || result.height <= 0)throw new Error("autoUnwrap: xatlas must return one valid atlas; multiple atlas pages are unsupported.");const remap = validateAtlasRemap(mesh, prepared.index, geometry.getAttribute("position").count);- const out = new THREE47.BufferGeometry;+ const out = new THREE48.BufferGeometry;for (const [name, attribute] of Object.entries(geometry.attributes)) {if (name === "uv" || name === "tangent" || name === "normal" && !prepared.useNormals)continue;@@ -28639,8 +28732,8 @@ async function autoUnwrap(geometry, opts = {}) {out.morphAttributes[name] = targets.map((attribute) => remapUnwrapAttribute(attribute, remap.oldIndexes));}out.morphTargetsRelative = geometry.morphTargetsRelative;- out.setIndex(new THREE47.BufferAttribute(new Uint32Array(remap.index), 1));- out.setAttribute("uv", new THREE47.BufferAttribute(new Float32Array(remap.uv), 2));+ out.setIndex(new THREE48.BufferAttribute(new Uint32Array(remap.index), 1));+ out.setAttribute("uv", new THREE48.BufferAttribute(new Float32Array(remap.uv), 2));out.name = geometry.name;out.groups = geometry.groups.map((group) => ({ ...group }));out.setDrawRange(geometry.drawRange.start, geometry.drawRange.count);@@ -28675,11 +28768,11 @@ function repairZeroNormals(geo) {if (broken.size === 0)return;const acc = new Float32Array(normal.count * 3);- const a = new THREE47.Vector3;- const b = new THREE47.Vector3;- const c = new THREE47.Vector3;- const face = new THREE47.Vector3;- const edge = new THREE47.Vector3;+ const a = new THREE48.Vector3;+ const b = new THREE48.Vector3;+ const c = new THREE48.Vector3;+ const face = new THREE48.Vector3;+ const edge = new THREE48.Vector3;for (let t = 0;t + 2 < index.count; t += 3) {const tri = [index.getX(t), index.getX(t + 1), index.getX(t + 2)];if (!tri.some((i) => broken.has(i)))@@ -28715,7 +28808,7 @@ var init_uv = __esm(() => {});// src/uv-project.ts-import * as THREE48 from "three";+import * as THREE49 from "three";function projectUV(geometry, options) {if (!options || typeof options !== "object" || Array.isArray(options) || !["planar", "box", "cylindrical"].includes(options.projection) || Object.keys(options).some((key) => !["projection", "frame", "seamDegrees", "angularRange", "caps", "metersPerUnit"].includes(key)))throw new Error("projectUV: select an explicit planar, box or cylindrical projection with documented options.");@@ -28756,15 +28849,15 @@ function projectUV(geometry, options) {throw new Error("projectUV: index contains an invalid vertex reference.");}const points = [];- const bounds = new THREE48.Box3;+ const bounds = new THREE49.Box3;for (let i = 0;i < positions.count; i++) {- const point = new THREE48.Vector3().fromBufferAttribute(positions, i).applyMatrix4(inverse);+ const point = new THREE49.Vector3().fromBufferAttribute(positions, i).applyMatrix4(inverse);if (![point.x, point.y, point.z].every(Number.isFinite))throw new Error("projectUV: frame-local positions must be finite.");points.push(point);bounds.expandByPoint(point);}- const extent = bounds.getSize(new THREE48.Vector3);+ const extent = bounds.getSize(new THREE49.Vector3);const fit = (point, axis) => metric !== undefined ? point[axis] / metric : extent[axis] > 0 ? (point[axis] - bounds.min[axis]) / extent[axis] : 0.5;const flip = (point, axis) => metric !== undefined ? -point[axis] / metric : 1 - fit(point, axis);const outputUVs = new Float32Array(corners * 2);@@ -28779,8 +28872,8 @@ function projectUV(geometry, options) {if (metric !== undefined) {uScale = fullWrap ? Math.max(1, Math.round(2 * Math.PI * radius / metric)) : sweep * radius / metric;}- const normal = new THREE48.Vector3;- const edge = new THREE48.Vector3;+ const normal = new THREE49.Vector3;+ const edge = new THREE49.Vector3;for (let i = 0;i < corners; i += 3) {const triangle = [0, 1, 2].map((offset) => points[index ? index.getX(i + offset) : i + offset]);normal.subVectors(triangle[1], triangle[0]).cross(edge.subVectors(triangle[2], triangle[0])).normalize();@@ -28836,7 +28929,7 @@ function projectUV(geometry, options) {const out = geometry.index ? geometry.toNonIndexed() : geometry.clone();out.userData = structuredClone(geometry.userData);out.setDrawRange(geometry.drawRange.start, geometry.drawRange.count);- out.setAttribute("uv", new THREE48.Float32BufferAttribute(outputUVs, 2));+ out.setAttribute("uv", new THREE49.Float32BufferAttribute(outputUVs, 2));if (out.hasAttribute("tangent")) {out.deleteAttribute("tangent");const previous = out.userData.kilnAttributeWarnings;@@ -28857,17 +28950,17 @@ var init_uv_project = __esm(() => {});// src/primitives.ts-import * as THREE49 from "three";+import * as THREE50 from "three";function vectorToTuple(v) {return [v.x, v.y, v.z];}function createRoot(name) {- const root = new THREE49.Object3D;+ const root = new THREE50.Object3D;root.name = name;return root;}function createPivot(name, position = [0, 0, 0], parent) {- const pivot = new THREE49.Object3D;+ const pivot = new THREE50.Object3D;pivot.name = `Joint_${name}`;pivot.position.set(...position);if (parent)@@ -28899,16 +28992,16 @@ function assertPartArgs(name, geometry2, material) {}function createPart(name, geometry2, material, options = {}) {assertPartArgs(name, geometry2, material);- const mesh = new THREE49.Mesh(geometry2, material);+ const mesh = new THREE50.Mesh(geometry2, material);mesh.name = `Mesh_${name}`;if (options.position)mesh.position.set(...options.position);if (options.rotation)- mesh.rotation.set(THREE49.MathUtils.degToRad(options.rotation[0]), THREE49.MathUtils.degToRad(options.rotation[1]), THREE49.MathUtils.degToRad(options.rotation[2]));+ mesh.rotation.set(THREE50.MathUtils.degToRad(options.rotation[0]), THREE50.MathUtils.degToRad(options.rotation[1]), THREE50.MathUtils.degToRad(options.rotation[2]));if (options.scale)mesh.scale.set(...options.scale);if (options.pivot) {- const pivot = new THREE49.Object3D;+ const pivot = new THREE50.Object3D;pivot.name = `Joint_${name}`;pivot.add(mesh);mesh.position.set(0, 0, 0);@@ -28931,7 +29024,7 @@ function capsuleGeo(radius, height, segments = 6) {assertDimension("capsuleGeo height (straight middle length)", height, true);assertDimension("capsuleGeo outer half-length", height / 2 + radius);assertPrimitiveSegments("capsuleGeo segments", segments, 3);- return new THREE49.CapsuleGeometry(radius, height, 2, segments);+ return new THREE50.CapsuleGeometry(radius, height, 2, segments);}function capsuleXGeo(radius, length, segments = 6) {const geo = capsuleGeo(radius, length, segments);@@ -28950,7 +29043,7 @@ function cylinderGeo(radiusTop, radiusBottom, height, segments = 8) {throw new RangeError("cylinderGeo requires at least one positive radius.");assertDimension("cylinderGeo height", height);assertPrimitiveSegments("cylinderGeo segments", segments, 3);- return new THREE49.CylinderGeometry(radiusTop, radiusBottom, height, segments);+ return new THREE50.CylinderGeometry(radiusTop, radiusBottom, height, segments);}function cylinderXGeo(radiusTop, radiusBottom, length, segments = 8) {const geo = cylinderGeo(radiusTop, radiusBottom, length, segments);@@ -28965,20 +29058,20 @@ function cylinderZGeo(radiusTop, radiusBottom, length, segments = 8) {function boxGeo(width, height, depth) {for (const [name, value] of Object.entries({ width, height, depth }))assertDimension(`boxGeo ${name} (use planeGeo for a sheet)`, value);- return new THREE49.BoxGeometry(width, height, depth);+ return new THREE50.BoxGeometry(width, height, depth);}function sphereGeo(radius, widthSegments = 8, heightSegments = 6) {assertDimension("sphereGeo radius", radius);assertPrimitiveSegments("sphereGeo widthSegments", widthSegments, 3);assertPrimitiveSegments("sphereGeo heightSegments", heightSegments, 2);assertPrimitiveGrid("sphereGeo", widthSegments, heightSegments);- return new THREE49.SphereGeometry(radius, widthSegments, heightSegments);+ return new THREE50.SphereGeometry(radius, widthSegments, heightSegments);}function coneGeo(radius, height, segments = 8) {assertDimension("coneGeo radius", radius);assertDimension("coneGeo height", height);assertPrimitiveSegments("coneGeo segments", segments, 3);- return new THREE49.ConeGeometry(radius, height, segments);+ return new THREE50.ConeGeometry(radius, height, segments);}function coneXGeo(radius, length, segments = 8) {const geo = coneGeo(radius, length, segments);@@ -28995,7 +29088,7 @@ function cylinderOnAxis(center, normal, radiusBottom, height, options = {}) {const segments = options.segments ?? 8;assertFiniteTriple("cylinderOnAxis center", center);assertFiniteTriple("cylinderOnAxis normal", normal);- const n = new THREE49.Vector3(normal[0], normal[1], normal[2]);+ const n = new THREE50.Vector3(normal[0], normal[1], normal[2]);const len = Math.hypot(...normal);if (len < 0.000001) {throw new Error(`cylinderOnAxis: normal must be a non-zero vector (got [${normal.join(",")}]).`);@@ -29003,7 +29096,7 @@ function cylinderOnAxis(center, normal, radiusBottom, height, options = {}) {const magnitude = Math.max(...normal.map(Math.abs));n.set(normal[0] / magnitude, normal[1] / magnitude, normal[2] / magnitude).normalize();const geo = cylinderGeo(radiusTop, radiusBottom, height, segments);- const q = new THREE49.Quaternion().setFromUnitVectors(new THREE49.Vector3(0, 1, 0), n);+ const q = new THREE50.Quaternion().setFromUnitVectors(new THREE50.Vector3(0, 1, 0), n);geo.applyQuaternion(q);geo.translate(center[0], center[1], center[2]);return geo;@@ -29025,7 +29118,7 @@ function torusGeo(radius, tube, radialSegments = 8, tubularSegments = 12) {assertPrimitiveSegments("torusGeo radialSegments", radialSegments, 3);assertPrimitiveSegments("torusGeo tubularSegments", tubularSegments, 3);assertPrimitiveGrid("torusGeo", radialSegments, tubularSegments);- return new THREE49.TorusGeometry(radius, tube, radialSegments, tubularSegments);+ return new THREE50.TorusGeometry(radius, tube, radialSegments, tubularSegments);}function planeGeo(width, height, widthSegments = 1, heightSegments = 1) {assertDimension("planeGeo width", width);@@ -29033,14 +29126,14 @@ function planeGeo(width, height, widthSegments = 1, heightSegments = 1) {assertPrimitiveSegments("planeGeo widthSegments", widthSegments, 1);assertPrimitiveSegments("planeGeo heightSegments", heightSegments, 1);assertPrimitiveGrid("planeGeo", widthSegments, heightSegments);- return new THREE49.PlaneGeometry(width, height, widthSegments, heightSegments);+ return new THREE50.PlaneGeometry(width, height, widthSegments, heightSegments);}function decalBox(width, height, depth = 0.01) {assertDimension("decalBox width", width);assertDimension("decalBox height", height);assertDimension("decalBox depth", depth, true);const d = Math.max(depth, 0.002);- return new THREE49.BoxGeometry(width, height, d);+ return new THREE50.BoxGeometry(width, height, d);}function validateCardFrame(name, width, height, yPivot) {assertDimension(`${name} width`, width);@@ -29054,7 +29147,7 @@ function foliageCardGeo(opts = {}) {const h = opts.height ?? 1;const yPivot = opts.yPivot ?? 0;validateCardFrame("foliageCardGeo", w, h, yPivot);- const geom = new THREE49.PlaneGeometry(w, h);+ const geom = new THREE50.PlaneGeometry(w, h);geom.translate(0, h * (0.5 - yPivot), 0);geom.userData["kilnGeometryRole"] = "foliageCard";return geom;@@ -29070,12 +29163,12 @@ function crossedQuadsGeo(opts = {}) {const geometries = [];for (let i = 0;i < planes; i++) {const angle = i / planes * Math.PI;- const quad = new THREE49.PlaneGeometry(w, h);+ const quad = new THREE50.PlaneGeometry(w, h);quad.translate(0, h * (0.5 - yPivot), 0);quad.rotateY(angle);geometries.push(quad);}- const out = new THREE49.BufferGeometry;+ const out = new THREE50.BufferGeometry;const posCount = geometries.reduce((sum, g) => sum + (g.attributes.position?.count ?? 0), 0);const positions = new Float32Array(posCount * 3);const normals = new Float32Array(posCount * 3);@@ -29102,9 +29195,9 @@ function crossedQuadsGeo(opts = {}) {}vOffset += p.count;}- out.setAttribute("position", new THREE49.BufferAttribute(positions, 3));- out.setAttribute("normal", new THREE49.BufferAttribute(normals, 3));- out.setAttribute("uv", new THREE49.BufferAttribute(uvs, 2));+ out.setAttribute("position", new THREE50.BufferAttribute(positions, 3));+ out.setAttribute("normal", new THREE50.BufferAttribute(normals, 3));+ out.setAttribute("uv", new THREE50.BufferAttribute(uvs, 2));out.setIndex(indices);out.userData["kilnGeometryRole"] = "foliageCard";return out;@@ -29119,7 +29212,7 @@ function octaGridPlane(opts) {const h = opts.height ?? 1;const yPivot = opts.yPivot ?? 0;validateCardFrame("octaGridPlane", w, h, yPivot);- const geom = new THREE49.PlaneGeometry(w, h);+ const geom = new THREE50.PlaneGeometry(w, h);geom.translate(0, h * (0.5 - yPivot), 0);const uv = geom.attributes.uv;const du = 1 / opts.tilesX;@@ -29215,8 +29308,8 @@ function wingGeo(options = {}) {7,6];- const geo = new THREE49.BufferGeometry;- geo.setAttribute("position", new THREE49.BufferAttribute(vertices, 3));+ const geo = new THREE50.BufferGeometry;+ geo.setAttribute("position", new THREE50.BufferAttribute(vertices, 3));geo.setIndex(tipChord === 0 ? [0, 1, 3, 4, 7, 5, 0, 2, 6, 0, 6, 4, 1, 5, 7, 1, 7, 3, 0, 4, 5, 0, 5, 1] : indices);geo.computeVertexNormals();return geo;@@ -29247,17 +29340,17 @@ function createWingPair(name, material, options) {};}function beamBetween(name, start, end, radius, material, options = {}) {- const a = new THREE49.Vector3(...start);- const b = new THREE49.Vector3(...end);+ const a = new THREE50.Vector3(...start);+ const b = new THREE50.Vector3(...end);const direction = b.clone().sub(a);const length = direction.length();if (length <= 0.0001) {throw new Error(`beamBetween("${name}"): start and end must be different points (got start=[${start.join(",")}], end=[${end.join(",")}], delta=${length.toExponential(2)}). Pick two distinct endpoints or switch to cylinderGeo with an explicit length + position.`);}- const mesh = new THREE49.Mesh(cylinderGeo(radius, radius, length, options.segments ?? 8), material);+ const mesh = new THREE50.Mesh(cylinderGeo(radius, radius, length, options.segments ?? 8), material);mesh.name = `Mesh_${name}`;mesh.position.copy(a.add(b).multiplyScalar(0.5));- mesh.quaternion.setFromUnitVectors(new THREE49.Vector3(0, 1, 0), direction.normalize());+ mesh.quaternion.setFromUnitVectors(new THREE50.Vector3(0, 1, 0), direction.normalize());if (options.parent)options.parent.add(mesh);return mesh;@@ -29266,11 +29359,11 @@ function snapTo(part, host, options = {}) {const overlap = options.overlap ?? 0.02;part.updateWorldMatrix(true, true);host.updateWorldMatrix(true, true);- const a = new THREE49.Box3().setFromObject(part);- const b = new THREE49.Box3().setFromObject(host);+ const a = new THREE50.Box3().setFromObject(part);+ const b = new THREE50.Box3().setFromObject(host);if (a.isEmpty() || b.isEmpty())return part;- const delta = new THREE49.Vector3;+ const delta = new THREE50.Vector3;for (const axis of ["x", "y", "z"]) {if (a.min[axis] > b.max[axis])delta[axis] = b.max[axis] - a.min[axis];@@ -29286,7 +29379,7 @@ function snapTo(part, host, options = {}) {delta[dominant] = -overlap;const parent = part.parent;if (parent) {- const p0 = new THREE49.Vector3;+ const p0 = new THREE50.Vector3;part.getWorldPosition(p0);const p1 = p0.clone().add(delta);const l0 = parent.worldToLocal(p0.clone());@@ -29321,8 +29414,8 @@ function createLadder(name, options) {throw new RangeError("createLadder rungCount must be an integer from 0 to 10000.");if (widthAxis !== "x" && widthAxis !== "z")throw new RangeError("createLadder widthAxis must be x or z.");- const bottomVec = new THREE49.Vector3;- const topVec = new THREE49.Vector3(...top).sub(new THREE49.Vector3(...bottom));+ const bottomVec = new THREE50.Vector3;+ const topVec = new THREE50.Vector3(...top).sub(new THREE50.Vector3(...bottom));const length = Math.hypot(topVec.x, topVec.y, topVec.z);assertDimension("createLadder endpoint distance", length);if (length <= 0.0001)@@ -29330,7 +29423,7 @@ function createLadder(name, options) {const along = topVec.clone().divideScalar(length);if (widthDirection !== undefined)assertFiniteTriple("createLadder widthDirection", widthDirection);- let across = widthDirection ? new THREE49.Vector3(...widthDirection) : widthAxis === "x" ? new THREE49.Vector3(1, 0, 0) : new THREE49.Vector3(0, 0, 1);+ let across = widthDirection ? new THREE50.Vector3(...widthDirection) : widthAxis === "x" ? new THREE50.Vector3(1, 0, 0) : new THREE50.Vector3(0, 0, 1);const largest = Math.max(Math.abs(across.x), Math.abs(across.y), Math.abs(across.z));if (!largest)throw new RangeError("createLadder widthDirection must be nonzero.");@@ -29340,19 +29433,19 @@ function createLadder(name, options) {if (widthDirection)throw new RangeError("createLadder widthDirection must not be parallel to the endpoints.");const axes = [- new THREE49.Vector3(1, 0, 0),- new THREE49.Vector3(0, 1, 0),- new THREE49.Vector3(0, 0, 1)+ new THREE50.Vector3(1, 0, 0),+ new THREE50.Vector3(0, 1, 0),+ new THREE50.Vector3(0, 0, 1)];across = axes.reduce((best, axis) => Math.abs(axis.dot(along)) < Math.abs(best.dot(along)) ? axis : best);across.addScaledVector(along, -across.dot(along));}across.normalize();const offset = across.clone().multiplyScalar(width / 2);- const root = new THREE49.Object3D;+ const root = new THREE50.Object3D;root.name = name;root.position.set(...bottom);- const rotation = new THREE49.Quaternion().setFromRotationMatrix(new THREE49.Matrix4().makeBasis(across, along, across.clone().cross(along))).toArray();+ const rotation = new THREE50.Quaternion().setFromRotationMatrix(new THREE50.Matrix4().makeBasis(across, along, across.clone().cross(along))).toArray();stampSemanticMetadataV1(root, {roles: ["ladder"],frames: [@@ -29392,7 +29485,7 @@ function wallWithOpening(name, material, options) {if (opening && openings)throw new TypeError("wallWithOpening: use opening or openings, not both.");const built = buildWallPanels(length, height, thickness, openings ?? (opening ? [opening] : []));- const group = new THREE49.Object3D;+ const group = new THREE50.Object3D;group.name = name;const panel = (suffix, lenStart, lenEnd, yLo, yHi) => {const segLen = lenEnd - lenStart;@@ -29423,7 +29516,7 @@ function room(name, material, options = {}) {parent} = options;const openings = options.openings ?? [{ wall: "front", kind: "door" }];- const root = new THREE49.Object3D;+ const root = new THREE50.Object3D;root.name = name;const wall = (suffix, len, axis, pos, which) => {const w = wallWithOpening(`${name}_Wall${suffix}`, material, {@@ -29477,7 +29570,7 @@ function createStairs(name, material, options) {if (Math.abs(totalRise) < 0.0001 || Math.abs(totalRun) < 0.0001) {throw new Error(`createStairs("${name}"): totalRise and totalRun must be non-zero (got rise=${totalRise}, run=${totalRun}).`);}- const root = new THREE49.Object3D;+ const root = new THREE50.Object3D;root.name = name;const stepRise = totalRise / steps;const stepRun = totalRun / steps;@@ -29507,7 +29600,7 @@ function requireColor(color, fn) {}function gameMaterial(color, options = {}) {requireColor(color, "gameMaterial");- return new THREE49.MeshStandardMaterial({+ return new THREE50.MeshStandardMaterial({color,metalness: options.metalness ?? 0,roughness: options.roughness ?? 0.8,@@ -29518,7 +29611,7 @@ function gameMaterial(color, options = {}) {}function basicMaterial(color, options = {}) {requireColor(color, "basicMaterial");- return new THREE49.MeshBasicMaterial({+ return new THREE50.MeshBasicMaterial({color,transparent: options.transparent ?? false,opacity: options.opacity ?? 1@@ -29526,18 +29619,18 @@ function basicMaterial(color, options = {}) {}function glassMaterial(color, options = {}) {requireColor(color, "glassMaterial");- return new THREE49.MeshStandardMaterial({+ return new THREE50.MeshStandardMaterial({color,transparent: true,opacity: options.opacity ?? 0.35,roughness: options.roughness ?? 0.1,metalness: options.metalness ?? 0,- side: THREE49.DoubleSide+ side: THREE50.DoubleSide});}function lambertMaterial(color, options = {}) {requireColor(color, "lambertMaterial");- return new THREE49.MeshLambertMaterial({+ return new THREE50.MeshLambertMaterial({color,flatShading: options.flatShading ?? true,emissive: options.emissive ?? 0@@ -29547,12 +29640,12 @@ function threeInterpolation(mode) {if (mode !== undefined && !TRACK_INTERPOLATIONS.includes(mode)) {throw new Error(`Animation interpolation must be one of ${TRACK_INTERPOLATIONS.join(", ")}.`);}- return mode === "STEP" ? THREE49.InterpolateDiscrete : THREE49.InterpolateLinear;+ return mode === "STEP" ? THREE50.InterpolateDiscrete : THREE50.InterpolateLinear;}function interpolatedTrack(Type, name, times, values, interpolation) {if (!isCubicInterpolation(interpolation))return new Type(name, times, values, threeInterpolation(interpolation));- const quaternion = Type === THREE49.QuaternionKeyframeTrack;+ const quaternion = Type === THREE50.QuaternionKeyframeTrack;return useCubicSpline(new Type(name, times, cubicSplineValues(times, values, quaternion ? 4 : 3, interpolation, quaternion)));}function animationNumber(value, label) {@@ -29606,15 +29699,15 @@ function rotationTrack(jointName, keyframes, interpolation) {animationKeys(jointName, keyframes, "rotation", interpolation);const times = [];const values = [];- const euler = new THREE49.Euler;- const quat = new THREE49.Quaternion;+ const euler = new THREE50.Euler;+ const quat = new THREE50.Quaternion;for (const kf of keyframes) {times.push(kf.time);- euler.set(THREE49.MathUtils.degToRad(kf.rotation[0]), THREE49.MathUtils.degToRad(kf.rotation[1]), THREE49.MathUtils.degToRad(kf.rotation[2]));+ euler.set(THREE50.MathUtils.degToRad(kf.rotation[0]), THREE50.MathUtils.degToRad(kf.rotation[1]), THREE50.MathUtils.degToRad(kf.rotation[2]));quat.setFromEuler(euler);values.push(quat.x, quat.y, quat.z, quat.w);}- return interpolatedTrack(THREE49.QuaternionKeyframeTrack, `${jointName}.quaternion`, times, values, interpolation);+ return interpolatedTrack(THREE50.QuaternionKeyframeTrack, `${jointName}.quaternion`, times, values, interpolation);}function positionTrack(jointName, keyframes, interpolation) {animationKeys(jointName, keyframes, "position", interpolation);@@ -29624,7 +29717,7 @@ function positionTrack(jointName, keyframes, interpolation) {times.push(kf.time);values.push(...kf.position);}- return interpolatedTrack(THREE49.VectorKeyframeTrack, `${jointName}.position`, times, values, interpolation);+ return interpolatedTrack(THREE50.VectorKeyframeTrack, `${jointName}.position`, times, values, interpolation);}function scaleTrack(jointName, keyframes, interpolation) {animationKeys(jointName, keyframes, "scale", interpolation);@@ -29634,7 +29727,7 @@ function scaleTrack(jointName, keyframes, interpolation) {times.push(kf.time);values.push(...kf.scale);}- return interpolatedTrack(THREE49.VectorKeyframeTrack, `${jointName}.scale`, times, values, interpolation);+ return interpolatedTrack(THREE50.VectorKeyframeTrack, `${jointName}.scale`, times, values, interpolation);}function createClip(name, duration, tracks, options) {if (typeof name !== "string" || !name.trim())@@ -29647,7 +29740,7 @@ function createClip(name, duration, tracks, options) {const loop = clipLoopOption(options);const names = new Set;for (const track of tracks) {- if (!(track instanceof THREE49.KeyframeTrack))+ if (!(track instanceof THREE50.KeyframeTrack))throw new Error("Animation clip tracks must be KeyframeTrack instances.");if (typeof track.name !== "string")throw new Error("Animation track target/channel must use a string name.");@@ -29661,12 +29754,12 @@ function createClip(name, duration, tracks, options) {throw new Error(`Duplicate animation target/channel: ${track.name}.`);names.add(track.name);const quaternion = channel === "quaternion";- const Type = quaternion ? THREE49.QuaternionKeyframeTrack : THREE49.VectorKeyframeTrack;+ const Type = quaternion ? THREE50.QuaternionKeyframeTrack : THREE50.VectorKeyframeTrack;if (!(track instanceof Type))throw new Error(`Animation channel ${channel} requires ${quaternion ? "QuaternionKeyframeTrack" : "VectorKeyframeTrack"}.`);const cubic = isCubicSplineTrack(track);const mode = track.getInterpolation();- if (!cubic && mode !== THREE49.InterpolateLinear && mode !== THREE49.InterpolateDiscrete) {+ if (!cubic && mode !== THREE50.InterpolateLinear && mode !== THREE50.InterpolateDiscrete) {throw new Error("Animation interpolation must be LINEAR, STEP or CUBICSPLINE (the glTF sampler modes); three.js smooth and Bezier interpolants have no glTF form.");}animationTimes(track.times, track.name);@@ -29689,7 +29782,7 @@ function createClip(name, duration, tracks, options) {throw new Error(`Animation clip duration ${duration} does not include every key of ${track.name}.`);}}- const clip = new THREE49.AnimationClip(name, duration, tracks);+ const clip = new THREE50.AnimationClip(name, duration, tracks);if (loop !== undefined)clip.userData.kilnLoopIntent = loop ? "loop" : "once";return clip;@@ -29766,12 +29859,12 @@ function createInstance(name, source, options = {}) {if (!sourceMesh) {throw new Error(`createInstance("${name}"): source "${source.name}" has no Mesh to clone from`);}- const mesh = new THREE49.Mesh(sourceMesh.geometry, sourceMesh.material);+ const mesh = new THREE50.Mesh(sourceMesh.geometry, sourceMesh.material);mesh.name = `Mesh_${name}`;if (options.position)mesh.position.set(...options.position);if (options.rotation)- mesh.rotation.set(THREE49.MathUtils.degToRad(options.rotation[0]), THREE49.MathUtils.degToRad(options.rotation[1]), THREE49.MathUtils.degToRad(options.rotation[2]));+ mesh.rotation.set(THREE50.MathUtils.degToRad(options.rotation[0]), THREE50.MathUtils.degToRad(options.rotation[1]), THREE50.MathUtils.degToRad(options.rotation[2]));if (options.scale)mesh.scale.set(...options.scale);if (options.parent)@@ -30064,7 +30157,7 @@ function buildSandboxGlobals(usage, options = {}) {getJointNames: wrap("getJointNames", getJointNames),materialBudgetAdvisory: wrap("materialBudgetAdvisory", materialBudgetAdvisory),seededRandom: wrap("seededRandom", seededRandom),- THREE: THREE49,+ THREE: THREE50,Math,console: options.console ?? console};@@ -30439,7 +30532,7 @@ import {PropertyType as PropertyType5} from "@gltf-transform/core";import { createTransform, dequantizePrimitive, joinPrimitives } from "@gltf-transform/functions";-import * as THREE50 from "three";+import * as THREE51 from "three";function isSingular(matrix) {const e = matrix.elements;const scale = Math.hypot(e[0], e[1], e[2]) * Math.hypot(e[4], e[5], e[6]) * Math.hypot(e[8], e[9], e[10]);@@ -30557,10 +30650,10 @@ function reverseWinding(prim) {}}function bake(prim, matrix) {- const linear = new THREE50.Matrix3().setFromMatrix4(matrix);- const normalMatrix = new THREE50.Matrix3().getNormalMatrix(matrix);+ const linear = new THREE51.Matrix3().setFromMatrix4(matrix);+ const normalMatrix = new THREE51.Matrix3().getNormalMatrix(matrix);const mirrored = matrix.determinant() < 0;- const v = new THREE50.Vector3;+ const v = new THREE51.Vector3;const each = (semantic, apply) => {const attribute = prim.getAttribute(semantic);const element = [];@@ -30584,7 +30677,7 @@ function destinationOf(entries) {let best = Infinity;let bestScale = Infinity;for (const { node } of entries) {- const linear = new THREE50.Matrix3().setFromMatrix4(worldOf(node));+ const linear = new THREE51.Matrix3().setFromMatrix4(worldOf(node));const norm = Math.hypot(...linear.elements);const inverseNorm = Math.hypot(...linear.clone().invert().elements);const condition = norm * inverseNorm;@@ -30598,9 +30691,9 @@ function destinationOf(entries) {return chosen;}function checkPositionPrecision(input, output, sourceWorld, destinationWorld, reversed) {- const expected = new THREE50.Vector3;- const actual = new THREE50.Vector3;- const bounds = new THREE50.Box3;+ const expected = new THREE51.Vector3;+ const actual = new THREE51.Vector3;+ const bounds = new THREE51.Box3;const element = [];let error = 0;let magnitude = 0;@@ -30921,7 +31014,7 @@ function rigidMerge(options = {}, onSummary) {onSummary?.(summary);});}-var JOINT_PIVOT, RESTART_MODES, BAKED, MAX_VERTICES = 65534, MAX_BYTES_PER_SAVED_DRAW = 4096, hasKeys = (value) => Object.keys(value).length > 0, worldOf = (node) => new THREE50.Matrix4().fromArray(node.getWorldMatrix()), nodeUsers = (mesh) => mesh.listParents().filter((parent) => parent.propertyType === PropertyType5.NODE).length, accessorsOf = (prim) => {+var JOINT_PIVOT, RESTART_MODES, BAKED, MAX_VERTICES = 65534, MAX_BYTES_PER_SAVED_DRAW = 4096, hasKeys = (value) => Object.keys(value).length > 0, worldOf = (node) => new THREE51.Matrix4().fromArray(node.getWorldMatrix()), nodeUsers = (mesh) => mesh.listParents().filter((parent) => parent.propertyType === PropertyType5.NODE).length, accessorsOf = (prim) => {const indices = prim.getIndices();return indices ? [...prim.listAttributes(), indices] : prim.listAttributes();}, primitiveBytes = (primitives) => [...new Set(primitives.flatMap(accessorsOf))].reduce((sum, a) => sum + (a.getArray()?.byteLength ?? 0), 0), countPrimitives = (nodes) => [...nodes].reduce((sum, node) => sum + (node.getMesh()?.listPrimitives().length ?? 0), 0);@@ -33458,7 +33551,7 @@ var init_kit = __esm(() => {// src/texture-bake.tsimport { createHash as createHash12 } from "node:crypto";-import * as THREE51 from "three";+import * as THREE52 from "three";function readPixels(texture) {const image = texture.image;if (!image)@@ -33585,7 +33678,7 @@ async function bakeSceneTextures(root, warnings) {mime: "image/png",bytes};- const colorSpace = entry.texture.colorSpace === THREE51.SRGBColorSpace ? "srgb" : "linear";+ const colorSpace = entry.texture.colorSpace === THREE52.SRGBColorSpace ? "srgb" : "linear";const recipe = entry.texture.userData["kilnProcedural"];const primaryUsage = atlasRecord?.spec.usage ?? recipe?.usage ?? (entry.bindings.some(({ slot }) => slot === "roughnessMap") && entry.bindings.some(({ slot }) => slot === "metalnessMap") ? "metallicRoughness" : entry.bindings[0]?.usage ?? "albedo");if (!encoded)@@ -33668,10 +33761,10 @@ function computeTangentBasis(geometry) {}}const out = new Float32Array(vertexCount * 4);- const n = new THREE51.Vector3;- const t = new THREE51.Vector3;- const tmp = new THREE51.Vector3;- const tmp2 = new THREE51.Vector3;+ const n = new THREE52.Vector3;+ const t = new THREE52.Vector3;+ const tmp = new THREE52.Vector3;+ const tmp2 = new THREE52.Vector3;for (let v = 0;v < vertexCount; v++) {n.set(normal.getX(v), normal.getY(v), normal.getZ(v));t.set(tan1[v * 3], tan1[v * 3 + 1], tan1[v * 3 + 2]);@@ -33691,7 +33784,7 @@ function computeTangentBasis(geometry) {out[v * 4 + 2] = tmp.z;out[v * 4 + 3] = w;}- geometry.setAttribute("tangent", new THREE51.BufferAttribute(out, 4));+ geometry.setAttribute("tangent", new THREE52.BufferAttribute(out, 4));}function ensureNormalMapTangents(root, warnings) {let count = 0;@@ -33809,7 +33902,7 @@ var init_exporter_node = __esm(() => {});// src/views/character.ts-import * as THREE52 from "three";+import * as THREE53 from "three";function rounded(value) {const result = Math.round(value * 1e9) / 1e9;return Object.is(result, -0) ? 0 : result;@@ -33851,9 +33944,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 THREE52.Vector3().setFromMatrixPosition(relative);- const forward = new THREE52.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);- const bend = new THREE52.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);+ const position = new THREE53.Vector3().setFromMatrixPosition(relative);+ const forward = new THREE53.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);+ const bend = new THREE53.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);const chainId = chainIdFor(joint.descriptor, descriptorByRole);return {role: joint.descriptor.role,@@ -35616,7 +35709,7 @@ var init_raster = __esm(() => {// src/views/scene-copy.tsimport {DoubleSide as DoubleSide5,- Group as Group3,+ Group as Group4,Skeleton as Skeleton2} from "three";function cloneReviewScene(root, options = {}) {@@ -35647,7 +35740,7 @@ function cloneReviewScene(root, options = {}) {}const copies = new Map;const copyNode = (node) => {- const copy = !visible.has(node) && !node.isBone ? new Group3().copy(node, false) : node.clone(false);+ const copy = !visible.has(node) && !node.isBone ? new Group4().copy(node, false) : node.clone(false);copies.set(node, copy);if (options.omitHidden)copy.visible = true;@@ -35657,7 +35750,7 @@ function cloneReviewScene(root, options = {}) {return copy;};if (!retained.has(root)) {- const empty = new Group3;+ const empty = new Group4;empty.name = root.name;return empty;}@@ -35683,7 +35776,7 @@ function cloneReviewScene(root, options = {}) {var init_scene_copy = () => {};// src/views/camera.ts-import { Vector3 as Vector339, Matrix4 as Matrix417, Euler as Euler5, Group as Group4 } from "three";+import { Vector3 as Vector339, Matrix4 as Matrix417, Euler as Euler5, Group as Group5 } from "three";function strict(value, keys, label) {for (const key of Object.keys(value))if (!keys.includes(key)) {@@ -36000,7 +36093,7 @@ async function withCameraVisibility(root, shot, run) {}function withoutHiddenMeshes(root) {if (root.visible === false) {- const empty = new Group4;+ const empty = new Group5;empty.name = root.name;return empty;}@@ -36843,9 +36936,9 @@ import {import {BufferAttribute as BufferAttribute13,BufferGeometry as BufferGeometry16,- Group as Group5,+ Group as Group6,Matrix4 as Matrix418,- Mesh as Mesh14,+ Mesh as Mesh15,Bone as Bone2,SkinnedMesh as SkinnedMesh2,Skeleton as Skeleton3,@@ -37168,7 +37261,7 @@ function reviewSceneFromDocument(document) {if (!sourceScene)throw new GlbGeometryFlatError("GLB_FLAT_NO_SCENE", "Final GLB has no scene.");const reasons = new Set;- const root = new Group5;+ const root = new Group6;root.name = sourceScene.getName() || "Scene";const nodeMap = new Map;const atlas = atlasDocumentTable(document);@@ -37188,7 +37281,7 @@ function reviewSceneFromDocument(document) {const existing = nodeMap.get(source);if (existing)return existing;- const target = joints.has(source) ? new Bone2 : new Group5;+ const target = joints.has(source) ? new Bone2 : new Group6;target.name = source.getName();target.position.fromArray(source.getTranslation());target.quaternion.fromArray(source.getRotation());@@ -37309,7 +37402,7 @@ function reviewSceneFromDocument(document) {threeMaterial.aoMapIntensity = material.getOcclusionStrength();}for (const [index, matrix] of matrices.entries()) {- const mesh = source.getSkin() ? new SkinnedMesh2(geometry, threeMaterial) : new Mesh14(geometry, threeMaterial);+ const mesh = source.getSkin() ? new SkinnedMesh2(geometry, threeMaterial) : new Mesh15(geometry, threeMaterial);if (mesh instanceof SkinnedMesh2)pendingSkins.push({ source, mesh });const baseName = source.getName() || sourceMesh.getName() || "Mesh";@@ -37748,7 +37841,7 @@ var init_renderer_id = __esm(() => {});// src/views/scene-raster.ts-import * as THREE53 from "three";+import * as THREE54 from "three";var DEG2;var init_scene_raster = __esm(() => {init_evaluator();@@ -37760,18 +37853,18 @@ var init_scene_raster = __esm(() => {});// src/views/vehicle.ts-import * as THREE54 from "three";+import * as THREE55 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 THREE54.Box3;+ const bounds = new THREE55.Box3;let found = false;root.traverse((node) => {if (!hasRole2(node, "chassis"))return;node.traverse((part) => {- if (!(part instanceof THREE54.Mesh) || !(part.geometry instanceof THREE54.BufferGeometry))+ if (!(part instanceof THREE55.Mesh) || !(part.geometry instanceof THREE55.BufferGeometry))return;part.geometry.computeBoundingBox();const box = part.geometry.boundingBox;@@ -37781,7 +37874,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 THREE54.Vector3(x, y, z).applyMatrix4(matrix));+ bounds.expandByPoint(new THREE55.Vector3(x, y, z).applyMatrix4(matrix));found = true;}});@@ -37849,33 +37942,33 @@ function tagDiagnostic(node, role) {stampSemanticMetadataV1(node, { roles: [role] });}function rod(name, start, end, radius, color, role) {- const from = new THREE54.Vector3(...start);- const to = new THREE54.Vector3(...end);+ const from = new THREE55.Vector3(...start);+ const to = new THREE55.Vector3(...end);const direction = to.clone().sub(from);const length = direction.length();- const geometry = length > 0.000000001 ? new THREE54.CylinderGeometry(radius, radius, length, 8) : new THREE54.SphereGeometry(radius, 8, 6);- const result = new THREE54.Mesh(geometry, new THREE54.MeshBasicMaterial({ color }));+ const geometry = length > 0.000000001 ? new THREE55.CylinderGeometry(radius, radius, length, 8) : new THREE55.SphereGeometry(radius, 8, 6);+ const result = new THREE55.Mesh(geometry, new THREE55.MeshBasicMaterial({ color }));result.name = name;result.position.copy(from).add(to).multiplyScalar(0.5);if (length > 0.000000001) {- result.quaternion.setFromUnitVectors(new THREE54.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));+ result.quaternion.setFromUnitVectors(new THREE55.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));}tagDiagnostic(result, role);return result;}function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnostics(root)) {- const overlay = new THREE54.Group;+ const overlay = new THREE55.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 THREE54.Group;+ const arrow = new THREE55.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 THREE54.Mesh(new THREE54.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE54.MeshBasicMaterial({ color: 16724804 }));+ const arrowHead = new THREE55.Mesh(new THREE55.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE55.MeshBasicMaterial({ color: 16724804 }));arrowHead.name = "Diagnostic_Forward_Head";arrowHead.position.set(descriptor.forwardArrow.end[0] - 0.12, 0, 0);- arrowHead.quaternion.setFromUnitVectors(new THREE54.Vector3(0, 1, 0), new THREE54.Vector3(1, 0, 0));+ arrowHead.quaternion.setFromUnitVectors(new THREE55.Vector3(0, 1, 0), new THREE55.Vector3(1, 0, 0));tagDiagnostic(arrowHead, "diagnostic.vehicle.forward");arrow.add(arrowHead);overlay.add(arrow);@@ -37883,18 +37976,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 THREE54.Mesh(new THREE54.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE54.MeshBasicMaterial({ color: 16763955 }));+ const ring = new THREE55.Mesh(new THREE55.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE55.MeshBasicMaterial({ color: 16763955 }));ring.name = `Diagnostic_Wheel_${wheel.id}`;ring.position.set(...wheel.center);- const axle = new THREE54.Vector3(...wheel.axle);+ const axle = new THREE55.Vector3(...wheel.axle);if (axle.lengthSq() > 0.000000000001) {- ring.quaternion.setFromUnitVectors(new THREE54.Vector3(0, 0, 1), axle.normalize());+ ring.quaternion.setFromUnitVectors(new THREE55.Vector3(0, 0, 1), axle.normalize());}tagDiagnostic(ring, `diagnostic.vehicle.wheel.${wheel.id}`);overlay.add(ring);}if (descriptor.chassisBox) {- const chassis = new THREE54.Group;+ const chassis = new THREE55.Group;chassis.name = "Diagnostic_ChassisBox";tagDiagnostic(chassis, "diagnostic.vehicle.chassis");const { min, max } = descriptor.chassisBox;@@ -37928,7 +38021,7 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnooverlay.add(chassis);}if (descriptor.supportPlaneY !== undefined) {- const plane = new THREE54.Group;+ const plane = new THREE55.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;@@ -38526,7 +38619,7 @@ var init_views = __esm(() => {});// src/views/character-capture.ts-import * as THREE55 from "three";+import * as THREE56 from "three";function drawLine2(rgb, width, height, from, to, color) {let x0 = Math.round(from[0]);let y0 = Math.round(from[1]);@@ -38563,22 +38656,22 @@ function drawCross(rgb, width, height, point, color, radius = 3) {}function projector(root, cameraId, size) {root.updateMatrixWorld(true);- const bounds = new THREE55.Box3().setFromObject(root);+ const bounds = new THREE56.Box3().setFromObject(root);if (bounds.isEmpty())- bounds.set(new THREE55.Vector3(-0.5, 0, -0.5), new THREE55.Vector3(0.5, 1, 0.5));- const center = bounds.getCenter(new THREE55.Vector3);- const camera = cameraId === "front" ? new THREE55.Vector3(1, 0, 0) : new THREE55.Vector3(0, 0, 1);- const upHint = new THREE55.Vector3(0, 1, 0);- const xAxis = new THREE55.Vector3().crossVectors(upHint, camera).normalize();- const yAxis = new THREE55.Vector3().crossVectors(camera, xAxis).normalize();+ bounds.set(new THREE56.Vector3(-0.5, 0, -0.5), new THREE56.Vector3(0.5, 1, 0.5));+ const center = bounds.getCenter(new THREE56.Vector3);+ const camera = cameraId === "front" ? new THREE56.Vector3(1, 0, 0) : new THREE56.Vector3(0, 0, 1);+ const upHint = new THREE56.Vector3(0, 1, 0);+ const xAxis = new THREE56.Vector3().crossVectors(upHint, camera).normalize();+ const yAxis = new THREE56.Vector3().crossVectors(camera, xAxis).normalize();let extent = 0.000001;for (let corner = 0;corner < 8; corner++) {- const point = new THREE55.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 THREE56.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 THREE55.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);+ const world = new THREE56.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);return [size / 2 + world.dot(xAxis) * scale, size / 2 - world.dot(yAxis) * scale];};}@@ -38704,7 +38797,7 @@ var init_character_capture = __esm(() => {});// src/render.ts-import * as THREE56 from "three";+import * as THREE57 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";@@ -38931,7 +39024,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache, authorExtras, atlas)} else if (stdMat.transparent) {mat.setAlphaMode("BLEND");}- if (stdMat.side === THREE56.DoubleSide) {+ if (stdMat.side === THREE57.DoubleSide) {mat.setDoubleSided(true);}if (stdMat.map) {@@ -39008,7 +39101,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache, authorExtras, atlas)} else if (common.transparent || (common.opacity ?? 1) < 1) {mat.setAlphaMode("BLEND");}- if (threeMat.side === THREE56.DoubleSide)+ if (threeMat.side === THREE57.DoubleSide)mat.setDoubleSided(true);if (common.map && !mat.getBaseColorTexture()) {const texture = bridgeTexture(doc, common.map, textureCache);@@ -39171,7 +39264,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 THREE56.PlaneGeometry(1, 1);+ const geometry = new THREE57.PlaneGeometry(1, 1);if (centerX !== 0.5 || centerY !== 0.5) {geometry.translate(0.5 - centerX, 0.5 - centerY, 0);}@@ -39195,9 +39288,9 @@ function animationInterpolation(track) {if (isCubicSplineTrack(track))return "CUBICSPLINE";const mode = track.getInterpolation();- if (mode === THREE56.InterpolateDiscrete)+ if (mode === THREE57.InterpolateDiscrete)return "STEP";- if (mode === THREE56.InterpolateLinear)+ if (mode === THREE57.InterpolateLinear)return "LINEAR";throw new Error(`Unsupported animation interpolation on ${track.name}; use LINEAR, STEP or CUBICSPLINE.`);}@@ -39772,8 +39865,8 @@ function collectMeshStats(root) {if (!Number.isFinite(box.min.x) || !Number.isFinite(box.max.x)) {return;}- const center = new THREE56.Vector3;- const size = new THREE56.Vector3;+ const center = new THREE57.Vector3;+ const size = new THREE57.Vector3;box.getCenter(center);box.getSize(size);out.push({@@ -39789,7 +39882,7 @@ function collectMeshStats(root) {return out;}function minimalGapVector(a, b) {- const v = new THREE56.Vector3;+ const v = new THREE57.Vector3;for (const axis of ["x", "y", "z"]) {if (a.min[axis] > b.max[axis])v[axis] = b.max[axis] - a.min[axis];@@ -39807,10 +39900,10 @@ function inspectSceneStructure(root, opts = {}) {return warnings;const cat = opts.category?.toLowerCase();if (cat === "vehicle" || cat === "weapon" || cat === "boat" || cat === "aircraft") {- const all = new THREE56.Box3;+ const all = new THREE57.Box3;for (const m of meshes)all.union(m.box);- const size = new THREE56.Vector3;+ const size = new THREE57.Vector3;all.getSize(size);if (cat === "aircraft") {if (size.y > size.x * 1.2) {@@ -39935,18 +40028,18 @@ var init_render = __esm(() => {engineIO = createGltfIO;ACCESSOR_TYPES = [TYPE_SCALAR, TYPE_VEC2, TYPE_VEC3, TYPE_VEC4];GLTF_MIN_FILTER = {- [THREE56.NearestFilter]: 9728,- [THREE56.LinearFilter]: 9729,- [THREE56.NearestMipmapNearestFilter]: 9984,- [THREE56.LinearMipmapNearestFilter]: 9985,- [THREE56.NearestMipmapLinearFilter]: 9986,- [THREE56.LinearMipmapLinearFilter]: 9987- };- GLTF_MAG_FILTER = { [THREE56.NearestFilter]: 9728, [THREE56.LinearFilter]: 9729 };+ [THREE57.NearestFilter]: 9728,+ [THREE57.LinearFilter]: 9729,+ [THREE57.NearestMipmapNearestFilter]: 9984,+ [THREE57.LinearMipmapNearestFilter]: 9985,+ [THREE57.NearestMipmapLinearFilter]: 9986,+ [THREE57.LinearMipmapLinearFilter]: 9987+ };+ GLTF_MAG_FILTER = { [THREE57.NearestFilter]: 9728, [THREE57.LinearFilter]: 9729 };GLTF_WRAP = {- [THREE56.ClampToEdgeWrapping]: 33071,- [THREE56.MirroredRepeatWrapping]: 33648,- [THREE56.RepeatWrapping]: 10497+ [THREE57.ClampToEdgeWrapping]: 33071,+ [THREE57.MirroredRepeatWrapping]: 33648,+ [THREE57.RepeatWrapping]: 10497};REVIEW_CLIP_LIMITS2 = {clips: 32,@@ -41035,12 +41128,12 @@ var exports_part_placement = {};__export(exports_part_placement, {createPartPlacementReader: () => createPartPlacementReader});-import * as THREE57 from "three";+import * as THREE58 from "three";function createPartPlacementReader(root) {const bounds = createPartBoundsReader(root);- const position = new THREE57.Vector3;- const quaternion = new THREE57.Quaternion;- const scale = new THREE57.Vector3;+ const position = new THREE58.Vector3;+ const quaternion = new THREE58.Quaternion;+ const scale = new THREE58.Vector3;return (node) => {node.matrixWorld.decompose(position, quaternion, scale);const box = bounds(node);@@ -41845,7 +41938,7 @@ __export(exports_draw_diagnostics, {});import { Primitive as Primitive3 } from "@gltf-transform/core";import { cloneDocument as cloneDocument2 } from "@gltf-transform/functions";-import * as THREE58 from "three";+import * as THREE59 from "three";function withinLimits(doc) {const root = doc.getRoot();if (root.listNodes().length > MAX_NODES2 || root.listAccessors().length > 4096 || root.listMaterials().length > 2048 || root.listTextures().length > 256 || root.listScenes().length > 32 || doc.getGraph().listEdges().length > 32768)@@ -41898,7 +41991,7 @@ function collect2(doc, keep) {function overlaps(a, b) {if (Math.abs(a.normal.dot(b.normal)) < 1 - 0.00000001 || !a.bounds.intersectsBox(b.bounds))return false;- const tolerance = Math.max(a.bounds.getSize(new THREE58.Vector3).length(), b.bounds.getSize(new THREE58.Vector3).length(), 0.000000000001) * 0.000001;+ const tolerance = Math.max(a.bounds.getSize(new THREE59.Vector3).length(), b.bounds.getSize(new THREE59.Vector3).length(), 0.000000000001) * 0.000001;if (b.points.some((p) => Math.abs(a.normal.dot(p.clone().sub(a.points[0]))) > tolerance))return false;const normal = a.normal.toArray().map(Math.abs);@@ -41940,7 +42033,7 @@ function observe(uses) {unexaminedPrimitiveUses++;continue;}- const matrix = new THREE58.Matrix4().fromArray(node.getWorldMatrix());+ const matrix = new THREE59.Matrix4().fromArray(node.getWorldMatrix());if (primitive.getAttribute("TANGENT") && matrix.determinant() < 0)mirrored.set(part.id, part);const position = primitive.getAttribute("POSITION");@@ -41954,14 +42047,14 @@ function observe(uses) {const amount = Math.min(count, 8, MAX_SAMPLES - samples.length);for (let i = 0;i < amount; i++) {const start = Math.floor(i * count / amount) * 3;- const points = [0, 1, 2].map((j) => new THREE58.Vector3().fromArray(position.getElement(indices ? indices.getScalar(start + j) : start + j, [])).applyMatrix4(matrix));+ const points = [0, 1, 2].map((j) => new THREE59.Vector3().fromArray(position.getElement(indices ? indices.getScalar(start + j) : start + j, [])).applyMatrix4(matrix));const normal = points[1].clone().sub(points[0]).cross(points[2].clone().sub(points[0]));if (!Number.isFinite(normal.lengthSq()) || normal.lengthSq() === 0)continue;samples.push({points,normal: normal.normalize(),- bounds: new THREE58.Box3().setFromPoints(points),+ bounds: new THREE59.Box3().setFromPoints(points),part});}@@ -42131,11 +42224,11 @@ import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";import { fileURLToPath as fileURLToPath6 } from "node:url";// src/assets-node.ts-import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";+import { createHash as createHash4, randomUUID as randomUUID3 } from "node:crypto";import { readFileSync } from "node:fs";-import { link, lstat as lstat3, mkdir as mkdir2, readFile as readFile2, readdir as readdir2, realpath as realpath2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";+import { link as link2, lstat as lstat4, mkdir as mkdir3, readFile as readFile3, readdir as readdir2, realpath as realpath3, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";import { homedir, platform } from "node:os";-import { dirname as dirname3, join as join3, relative as relative2, resolve as resolve3, sep as sep2, win32 } from "node:path";+import { dirname as dirname4, join as join4, relative as relative2, resolve as resolve4, sep as sep2, win32 } from "node:path";// src/workspace-location.tsimport { dirname, join, resolve } from "node:path";@@ -42203,7 +42296,7 @@ async function resolveSavedAssetMaterials(asset, library) {// src/assets-node.tsinit_atomic_directory();-var digest2 = (bytes) => `sha256:${createHash3("sha256").update(bytes).digest("hex")}`;+var digest2 = (bytes) => `sha256:${createHash4("sha256").update(bytes).digest("hex")}`;function assertMaterialAllocation(records) {let bytes = 0;for (const record of records)@@ -42232,7 +42325,7 @@ class FileAssetLibrary {this.materials = materials;if (!Object.keys(roots).length)throw new Error("Configure at least one collection");- this.roots = Object.fromEntries(Object.entries(roots).map(([id, path]) => [assetIdSchema.parse(id), resolve3(path)]));+ this.roots = Object.fromEntries(Object.entries(roots).map(([id, path]) => [assetIdSchema.parse(id), resolve4(path)]));}collections() {return Object.keys(this.roots).map((id) => ({@@ -42247,21 +42340,21 @@ class FileAssetLibrary {return root;}revisionDirectory(collection, assetId, revisionId) {- return join3(this.directory(collection), assetIdSchema.parse(assetId), "revisions", assetIdSchema.parse(revisionId));+ return join4(this.directory(collection), assetIdSchema.parse(assetId), "revisions", assetIdSchema.parse(revisionId));}async path(collection, ...parts) {const root = this.directory(collection);- await mkdir2(root, { recursive: true });- const canonical = await realpath2(root);+ await mkdir3(root, { recursive: true });+ const canonical = await realpath3(root);let path = root;for (const part of parts) {assetIdSchema.parse(part);- path = join3(path, part);+ path = join4(path, part);try {- const entry = await lstat3(path);+ const entry = await lstat4(path);if (entry.isSymbolicLink())throw new Error("Collection symlinks are not supported");- const rel = relative2(canonical, await realpath2(path));+ const rel = relative2(canonical, await realpath3(path));if (rel === ".." || rel.startsWith(`..${sep2}`))throw new Error("Collection path escapes root");} catch (error) {@@ -42299,11 +42392,11 @@ class FileAssetLibrary {return records.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || a.revisionId.localeCompare(b.revisionId));}async file(dir, name, limit = ASSET_LIMIT) {- const path = join3(dir, name);- const info = await lstat3(path);+ const path = join4(dir, name);+ const info = await lstat4(path);if (!info.isFile() || info.isSymbolicLink() || info.size > limit)throw new Error("Invalid collection file");- return new Uint8Array(await readFile2(path));+ return new Uint8Array(await readFile3(path));}async read(collection, assetId, revisionId) {const dir = await this.path(collection, assetId, "revisions", revisionId);@@ -42344,7 +42437,7 @@ class FileAssetLibrary {return encodeAssetBundle(portable);}async save(collection, draft) {- const assetId = draft.assetId ?? `a_${randomUUID2().replaceAll("-", "")}`;+ const assetId = draft.assetId ?? `a_${randomUUID3().replaceAll("-", "")}`;if (draft.parentRevision)await this.read(collection, assetId, draft.parentRevision);if (draft.assetId && !draft.parentRevision && (await this.list(collection)).some((m) => m.assetId === assetId))@@ -42357,7 +42450,7 @@ class FileAssetLibrary {const manifest = assetManifestSchema.parse({version: "kiln.asset.v1",assetId,- revisionId: `r_${randomUUID2().replaceAll("-", "")}`,+ revisionId: `r_${randomUUID3().replaceAll("-", "")}`,parentRevision: draft.parentRevision,name: draft.name,tags: draft.tags ?? [],@@ -42418,16 +42511,16 @@ class FileAssetLibrary {for (const record of prepared) {const { manifest, files } = record;const dest = await this.path(collection, manifest.assetId, "revisions", manifest.revisionId);- const parent = dirname3(dest);- await mkdir2(parent, { recursive: true });- const stage = join3(parent, `.write-${randomUUID2()}`);- await mkdir2(stage);+ const parent = dirname4(dest);+ await mkdir3(parent, { recursive: true });+ const stage = join4(parent, `.write-${randomUUID3()}`);+ await mkdir3(stage);try {for (const [name, bytes] of Object.entries(files))- await writeFile2(join3(stage, name), bytes, { flag: "wx" });+ await writeFile3(join4(stage, name), bytes, { flag: "wx" });if (record.materialResources)- await writeFile2(join3(stage, ASSET_MATERIAL_FILE), JSON.stringify(record.materialResources), { flag: "wx" });- await writeFile2(join3(stage, "manifest.json"), `${JSON.stringify(manifest, null, 2)}+ await writeFile3(join4(stage, ASSET_MATERIAL_FILE), JSON.stringify(record.materialResources), { flag: "wx" });+ await writeFile3(join4(stage, "manifest.json"), `${JSON.stringify(manifest, null, 2)}`, {flag: "wx"});@@ -42441,7 +42534,7 @@ class FileAssetLibrary {throw error;if (record.materialResources && !existing.materialResources) {try {- await link(join3(stage, ASSET_MATERIAL_FILE), join3(dest, ASSET_MATERIAL_FILE));+ await link2(join4(stage, ASSET_MATERIAL_FILE), join4(dest, ASSET_MATERIAL_FILE));} catch (enrichmentError) {if (enrichmentError.code !== "EEXIST")throw enrichmentError;@@ -42459,17 +42552,17 @@ class FileAssetLibrary {}}function collectionConfigPath(env = process.env) {- return join3(localWorkspaceRoot(env), ".kiln", "collections.json");+ return join4(localWorkspaceRoot(env), ".kiln", "collections.json");}function defaultUserLibraryRoot(env = process.env, home = homedir(), operatingSystem = platform()) {const dataRoot = env.XDG_DATA_HOME?.trim();if (dataRoot)- return join3(dataRoot, "kiln", "library");+ return join4(dataRoot, "kiln", "library");if (operatingSystem === "darwin")- return join3(home, "Library", "Application Support", "Kiln", "library");+ return join4(home, "Library", "Application Support", "Kiln", "library");if (operatingSystem === "win32")- return join3(env.LOCALAPPDATA?.trim() || join3(home, "AppData", "Local"), "Kiln", "library");- return join3(home, ".local", "share", "kiln", "library");+ return join4(env.LOCALAPPDATA?.trim() || join4(home, "AppData", "Local"), "Kiln", "library");+ return join4(home, ".local", "share", "kiln", "library");}var windowsDrivePath = /^[A-Za-z]:[\\/]/;var windowsSharePath = /^[\\/]{2}[^\\/]+[\\/][^\\/]+/;@@ -42490,10 +42583,10 @@ function configuredRoots(text, source, operatingSystem) {}function localAssetLibrary(env = process.env, operatingSystem = platform()) {if (env.KILN_COLLECTIONS)- return new FileAssetLibrary(configuredRoots(env.KILN_COLLECTIONS, "KILN_COLLECTIONS", operatingSystem), new FileMaterialLibrary(join3(localWorkspaceRoot(env), ".kiln", "materials")));+ return new FileAssetLibrary(configuredRoots(env.KILN_COLLECTIONS, "KILN_COLLECTIONS", operatingSystem), new FileMaterialLibrary(join4(localWorkspaceRoot(env), ".kiln", "materials")));const config = collectionConfigPath(env);- const workspace = dirname3(dirname3(config));- const materials = new FileMaterialLibrary(join3(workspace, ".kiln", "materials"));+ const workspace = dirname4(dirname4(config));+ const materials = new FileMaterialLibrary(join4(workspace, ".kiln", "materials"));let text;try {text = readFileSync(config, "utf8");@@ -42507,7 +42600,7 @@ function localAssetLibrary(env = process.env, operatingSystem = platform()) {return new FileAssetLibrary(configuredRoots(text, config, operatingSystem), materials);}return new FileAssetLibrary({- project: join3(workspace, "assets", "kiln"),+ project: join4(workspace, "assets", "kiln"),library: defaultUserLibraryRoot(env, homedir(), operatingSystem)}, materials);}@@ -42516,29 +42609,29 @@ function localAssetLibrary(env = process.env, operatingSystem = platform()) {init_assets_resources();// src/render-service-client.ts-import { createHash as createHash6 } from "node:crypto";+import { createHash as createHash7 } from "node:crypto";import { existsSync } from "node:fs";import { fileURLToPath } from "node:url";// render-service/src/build-identity.mjs-import { createHash as createHash5 } from "node:crypto";+import { createHash as createHash6 } from "node:crypto";import { readFileSync as readFileSync3 } from "node:fs";-import { dirname as dirname4, join as join5 } from "node:path";+import { dirname as dirname5, join as join6 } from "node:path";import { createRequire } from "node:module";// render-service/src/instance.mjs-import { createHash as createHash4 } from "node:crypto";+import { createHash as createHash5 } from "node:crypto";import { readFileSync as readFileSync2, readdirSync, statSync } from "node:fs";-import { join as join4, relative as relative3 } from "node:path";+import { join as join5, relative as relative3 } from "node:path";function fingerprintSourceDir(dir) {- const hash = createHash4("sha256");+ const hash = createHash5("sha256");hash.update("kiln.render-service-source.v1");const visit = (path) => {if (statSync(path).isDirectory()) {for (const name of readdirSync(path).sort()) {if (name === "node_modules")continue;- visit(join4(path, name));+ visit(join5(path, name));}return;}@@ -42570,7 +42663,7 @@ function compatibilityFingerprint({ sourceFingerprint, dependencies }) {throw new Error(`Missing renderer dependency identity: ${name}`);return [name, dependencies[name]];}));- return `sha256:${createHash5("sha256").update(JSON.stringify({+ return `sha256:${createHash6("sha256").update(JSON.stringify({version: "kiln.render-service-build.v1",sourceFingerprint,dependencies: pins@@ -42581,20 +42674,20 @@ function resolvedRendererDependencies(anchorUrl = import.meta.url) {return Object.fromEntries(Object.entries(RENDER_SERVICE_DEPENDENCIES).map(([name, expected]) => {let dir;try {- dir = dirname4(require2.resolve(name));+ dir = dirname5(require2.resolve(name));} catch {throw new Error(`Renderer dependency ${name}@${expected} is not installed`);}let found;for (;; ) {try {- const pkg = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));+ const pkg = JSON.parse(readFileSync3(join6(dir, "package.json"), "utf8"));if (pkg.name === name) {found = pkg.version;break;}} catch {}- const parent = dirname4(dir);+ const parent = dirname5(dir);if (parent === dir)break;dir = parent;@@ -42696,7 +42789,7 @@ function makeRemoteRenderPort(url, token, sourceFingerprint) {return async (req, execution) => {const health = await verifiedHealth(url, token, sourceFingerprint, execution?.signal);execution?.signal?.throwIfAborted();- const inputGlbSha256 = `sha256:${createHash6("sha256").update(req.glb).digest("hex")}`;+ const inputGlbSha256 = `sha256:${createHash7("sha256").update(req.glb).digest("hex")}`;const body = {glb_base64: Buffer.from(req.glb).toString("base64"),input_glb_sha256: inputGlbSha256,@@ -42749,7 +42842,7 @@ import { spawn as spawn2, spawnSync } from "node:child_process";// src/render-service-windows.tsimport { spawn } from "node:child_process";-import { join as join6 } from "node:path";+import { join as join7 } from "node:path";function powerShellLiteral(value) {return `'${value.replaceAll("'", "''")}'`;}@@ -42764,7 +42857,7 @@ function launchWindowsRenderService(executable, args, directory, env) {].join(``);const systemRoot = env.SystemRoot ?? env.SYSTEMROOT;- const powerShell = systemRoot ? join6(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe") : "powershell.exe";+ const powerShell = systemRoot ? join7(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe") : "powershell.exe";const child = spawn(powerShell, ["-NoProfile","-NonInteractive",@@ -42813,7 +42906,7 @@ function launchWindowsRenderService(executable, args, directory, env) {// src/render-service-host.tsimport { existsSync as existsSync2 } from "node:fs";import { fileURLToPath as fileURLToPath2, pathToFileURL } from "node:url";-import { join as join7 } from "node:path";+import { join as join8 } from "node:path";var DEFAULT_LOCAL_RENDER_SERVICE_PORT = 8000;function localRenderServicePort(env = process.env) {const raw = Number(env["KILN_RENDER_SERVICE_PORT"]);@@ -42832,18 +42925,18 @@ function namesLocalRenderService(url, env = process.env) {function renderServiceNodeArguments(dir) {return ["--import",- pathToFileURL(join7(dir, "src/register-hooks.mjs")).href,- join7(dir, "src/server.mjs")+ pathToFileURL(join8(dir, "src/register-hooks.mjs")).href,+ join8(dir, "src/server.mjs")];}function renderServiceDir() {return process.env["KILN_RENDER_SERVICE_DIR"] || fileURLToPath2(new URL("../render-service", import.meta.url));}function localRenderServiceState(dir = renderServiceDir()) {- if (!existsSync2(join7(dir, "src/server.mjs")) || !existsSync2(join7(dir, "package.json")))+ if (!existsSync2(join8(dir, "src/server.mjs")) || !existsSync2(join8(dir, "package.json")))return "not-packaged";try {- const anchor = pathToFileURL(join7(dir, "src/server.mjs")).href;+ const anchor = pathToFileURL(join8(dir, "src/server.mjs")).href;if (process.versions.bun) {const moduleUrl = new URL("../render-service/src/build-identity.mjs", import.meta.url).href;const result = spawnSync(nodeBinary(), [@@ -42874,7 +42967,7 @@ function explainRenderServiceState(state, dir) {return "renderer dependencies are missing; reinstall the official Kiln package with optional dependencies enabled";}function renderServiceSourceFingerprint(dir) {- const source = join7(dir, "src");+ const source = join8(dir, "src");return existsSync2(source) ? fingerprintSourceDir(source) : undefined;}async function inspectLocalRenderService(url, dir = renderServiceDir(), timeoutMs = 1500) {@@ -43214,79 +43307,11 @@ async function buildRenderPort(mode, portUrl, options) {}// src/export-root-node.ts+init_cli_output();+init_export_root();import { lstat as lstat5, realpath as realpath4, stat as stat2 } from "node:fs/promises";import { isAbsolute, join as join9, relative as relative4, resolve as resolve5, sep as sep3 } from "node:path";import { platform as platform2 } from "node:os";--// src/cli-output.ts-import { createHash as createHash7, randomUUID as randomUUID3 } from "node:crypto";-import {- chmod,- lstat as lstat4,- link as link2,- mkdir as mkdir3,- open,- readFile as readFile3,- realpath as realpath3,- rename as rename2,- stat,- unlink,- writeFile as writeFile3-} from "node:fs/promises";-import { basename, dirname as dirname5, join as join8, resolve as resolve4 } from "node:path";-async function prepareDestination(path) {- await mkdir3(dirname5(path), { recursive: true });- return path;-}-async function writeNewDestinationsAtomic(outputs) {- const paths = outputs.map(({ path }) => {- const absolute = resolve4(path);- return process.platform === "win32" ? absolute.toLowerCase() : absolute;- });- if (new Set(paths).size !== paths.length)- throw new Error("Export destinations must be distinct");- const staged = [];- try {- for (const { path, data } of outputs) {- await prepareDestination(path);- const temporary = join8(dirname5(path), `.kiln-write-${randomUUID3()}.tmp`);- const file = await open(temporary, "wx");- staged.push({ path, temporary, published: false });- try {- await writeFile3(file, data);- } finally {- await file.close();- }- }- for (const output of staged) {- try {- await link2(output.temporary, output.path);- } catch (error) {- if (error.code !== "EEXIST")- throw error;- throw Object.assign(new Error(`${output.path} already exists and is never replaced; choose a new output path or remove the file.`), { code: "EEXIST" });- }- output.published = true;- }- } catch (error) {- for (const output of staged.filter((item) => item.published).reverse()) {- try {- const [destination, temporary] = await Promise.all([- lstat4(output.path),- lstat4(output.temporary)- ]);- if (destination.dev === temporary.dev && destination.ino === temporary.ino)- await unlink(output.path);- } catch {}- }- throw error;- } finally {- await Promise.all(staged.map(({ temporary }) => unlink(temporary).catch(() => {})));- }-}--// src/export-root-node.ts-init_export_root();var windowsDrivePath2 = /^[A-Za-z]:[\\/]/;var windowsSharePath2 = /^[\\/]{2}[^\\/]+[\\/][^\\/]+/;var RESTART = "Correct KILN_EXPORT_ROOT and restart the MCP session.";@@ -52185,7 +52210,7 @@ init_render();init_requirements_context();init_evaluator();init_material_resources();-import * as THREE59 from "three";+import * as THREE60 from "three";// src/render-route.tsvar GPU_SERVES = new Set([@@ -52770,8 +52795,8 @@ function collectSceneMetrics(root) {let meshes = 0;const materialSet = new Set;let lowestPart;- const box = new THREE59.Box3;- const point = new THREE59.Vector3;+ const box = new THREE60.Box3;+ const point = new THREE60.Vector3;root.updateWorldMatrix(true, true);root.traverseVisible((node) => {const n = node;@@ -52787,7 +52812,7 @@ function collectSceneMetrics(root) {const mesh = node;const position = mesh.geometry.getAttribute("position");const index = mesh.geometry.index;- const mb = new THREE59.Box3;+ const mb = new THREE60.Box3;if (position) {for (let i = 0;i < (index?.count ?? position.count); i++) {point.fromBufferAttribute(position, index ? index.getX(i) : i);@@ -52802,7 +52827,7 @@ function collectSceneMetrics(root) {});let bbox;if (!box.isEmpty()) {- const size = new THREE59.Vector3;+ const size = new THREE60.Vector3;box.getSize(size);bbox = {min: [box.min.x, box.min.y, box.min.z],