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
Measure open surfaces against the closed solids they meet (#277) (#302)
Matthew Kissingere1fd8f02b15c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9fade8c8..5519fe55 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,29 @@ does not publish a package.## Unreleased+- QA measures open surfaces against the closed solids they meet.+ `GEO_OPEN_SURFACE_PENETRATION` samples each open surface's vertices against every closed+ solid whose bounds it overlaps and reports how far inside one it reaches, naming both+ parts and the depth. A cloth, canopy or ivy card encloses no volume, so the part-volume+ observer could only ever report it unmeasured -- which meant a throw resting on a seat+ and a throw running through a wall produced the same sentence. Reproduced before fixing:+ the two cases were byte-identical `GEO_PART_SELF_INTERSECTION_UNMEASURED` findings, and a+ closed-solid overlap across two modules composed at one origin was already reported, so+ what was missing was the open-surface measurement rather than neighbour awareness.+ Distance is measured before sign: a vertex within the 0.005 m contact tolerance is+ contact, and no sign is claimed there, which is why a cloth authored exactly flush is+ silent -- that is the one position where a parity ray grazes the face it starts on. The+ tolerance is deliberately not the 0.02 m adjacency tolerance `FLOATING_EXPAND` and+ `EXTERNAL_SUPPORT_TOLERANCE` share: measured fixtures put authoring slop at 1-3 mm and+ real defects at 30-60 mm, and 2 cm would let a surface sink unreported into a cushion, a+ canopy panel or a wall cap. Synchronous, offline and deterministic: the open/closed split+ comes from edge topology, so no solid is built. Observation only, bounded, and reporting+ what it left unsampled; a clean result is not a fit audit, and a solid thinner than the+ sampled surface's facet spacing can pass between two of its vertices. A positive is a+ measurement, not a verdict: measured over the 86 shipped examples it reports 916 findings+ across 51 of them, against 3,575 from the part-volume pass across all 86, and the dominant+ real case is a fitting socketed into a structural shell -- correct geometry, reported the+ same way a bolt in a hole is ([#277](https://github.com/instruktlabs/kiln/issues/277)).- `kiln textures <files-or-folders> [--json]` reports the texture duplication a deliveredset ships: embedded image occurrences against distinct images, the bytes sharing wouldsave, and each distinct image's hash, size and the assets carrying it. The duplicationdiff --git a/dist/agent-run.mjs b/dist/agent-run.mjsindex 6995bdc8..1e68b663 100644--- a/dist/agent-run.mjs+++ b/dist/agent-run.mjs@@ -10200,6 +10200,13 @@ var init_requirements_applicability = __esm(() => {observation: true,kernel: "connectivity"},+ {+ id: "GEO_OPEN_SURFACE_PENETRATION",+ mode: "observe",+ keys: [],+ observation: true,+ kernel: "openSurface"+ },{ id: "REF_COMPARISON", mode: "observe", keys: [], observation: true },{ id: "SWEEP_SELF_INTERSECTION", mode: "observe", keys: [], observation: true, kernel: "sweep" },{ id: "HOST_VALIDATION_PROFILE", mode: "enforce", keys: ["validation"], kernel: "validation" }@@ -17017,10 +17024,745 @@ var init_part_connectivity = __esm(() => {});});-// src/sweep-analysis.ts+// src/geometry.tsimport * as THREE16 from "three";+function finiteArray(values, label, length) {+ const result = Array.from(values);+ if (length !== undefined && result.length !== length)+ throw new Error(`${label}: expected ${length} values, got ${result.length}`);+ if (!result.every((n) => Number.isFinite(Math.fround(n))))+ throw new AuthoringDiagnosticError("MESH_DATA_NONFINITE", `${label}: all values must be finite Float32 values`);+ return result;+}+function meshGeo(data) {+ const positions = finiteArray(data.positions, "meshGeo positions");+ if (positions.length < 9 || positions.length % 3)+ throw new Error("meshGeo positions: need at least three xyz vertices");+ const count = positions.length / 3;+ const geometry = new THREE16.BufferGeometry;+ geometry.setAttribute("position", new THREE16.Float32BufferAttribute(positions, 3));+ if (data.indices) {+ const indices = Array.from(data.indices);+ if (!indices.length || indices.length % 3)+ throw new Error("meshGeo indices: need complete triangles");+ if (!indices.every((i) => Number.isInteger(i) && i >= 0 && i < count))+ throw new Error("meshGeo index out of bounds or not an integer");+ geometry.setIndex(indices);+ } else if (count % 3)+ throw new Error("meshGeo: non-indexed positions must form complete triangles");+ if (data.normals) {+ const normals = finiteArray(data.normals, "meshGeo normals", count * 3);+ geometry.setAttribute("normal", new THREE16.Float32BufferAttribute(normals, 3));+ for (let i = 0;i < count; i++)+ if (Math.hypot(normals[i * 3], normals[i * 3 + 1], normals[i * 3 + 2]) === 0)+ throw new Error("meshGeo normals: zero-length normal");+ geometry.normalizeNormals();+ } else+ geometry.computeVertexNormals();+ if (data.uvs)+ geometry.setAttribute("uv", new THREE16.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 THREE16.Float32BufferAttribute(tangents, 4));+ }+ geometry.computeBoundingBox();+ geometry.computeBoundingSphere();+ return geometry;+}+function boundsScale(bounds) {+ const size = bounds.getSize(new THREE16.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 THREE16.Box3;+ const point = new THREE16.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 THREE16.Vector3 : bounds.min,+ scale: boundsScale(bounds)+ };+}+function positionTolerance(scale, supplied, relative) {+ if (supplied === undefined)+ return scale * relative;+ if (!Number.isFinite(supplied) || supplied <= 0)+ throw new Error("Geometry tolerance must be positive and finite");+ if (scale / supplied > Number.MAX_SAFE_INTEGER)+ throw new Error("Geometry tolerance is too small to resolve the position extent safely");+ return supplied;+}+function positionKey(point, origin, tolerance) {+ if (tolerance === 0)+ return point.toArray().join(",");+ return point.clone().sub(origin).toArray().map((x) => Math.round(x / tolerance)).join(",");+}+function geometryDiagnostics(geometry, tolerance) {+ const p = geometry.getAttribute("position");+ if (p?.itemSize !== 3)+ throw new Error("geometryDiagnostics requires xyz positions");+ const frame = positionFrame(p);+ const distance = positionTolerance(frame.scale, tolerance, 0.000001);+ const result = {+ tolerance: distance,+ toleranceMode: tolerance === undefined ? "relative" : "absolute",+ positionScale: frame.scale,+ vertices: p.count,+ triangles: 0,+ boundaryEdges: 0,+ nonManifoldEdges: 0,+ orientationConflicts: 0,+ degenerateTriangles: 0,+ collapsedByToleranceTriangles: 0,+ invalidIndices: 0,+ nonFiniteVertices: 0,+ solid: { closed: false, manifold: true, orientation: "mixed", signedVolume: 0 }+ };+ let signedVolume = 0;+ const pa = new THREE16.Vector3, pb = new THREE16.Vector3, pc = new THREE16.Vector3;+ const ids = [];+ const points = new Map;+ const finite = [];+ const point = new THREE16.Vector3;+ for (let i = 0;i < p.count; i++) {+ point.fromBufferAttribute(p, i);+ finite[i] = [point.x, point.y, point.z].every(Number.isFinite);+ if (!finite[i])+ result.nonFiniteVertices++;+ const key = finite[i] ? positionKey(point, frame.origin, distance) : `invalid:${i}`;+ if (!points.has(key))+ points.set(key, points.size);+ ids.push(points.get(key));+ }+ const indices = geometry.index ? Array.from(geometry.index.array) : Array.from({ length: p.count }, (_, i) => i);+ const edges = new Map;+ const a = new THREE16.Vector3, b = new THREE16.Vector3, c = new THREE16.Vector3;+ for (let i = 0;i < indices.length; i += 3) {+ result.triangles++;+ const triangle = indices.slice(i, i + 3);+ if (triangle.length !== 3 || triangle.some((n) => !Number.isInteger(n) || n < 0 || n >= p.count)) {+ result.invalidIndices++;+ continue;+ }+ const [ia, ib, ic] = triangle;+ if (!finite[ia] || !finite[ib] || !finite[ic])+ continue;+ pa.fromBufferAttribute(p, ia);+ pb.fromBufferAttribute(p, ib);+ pc.fromBufferAttribute(p, ic);+ signedVolume += pa.dot(pb.cross(pc)) / 6;+ a.fromBufferAttribute(p, ia);+ b.fromBufferAttribute(p, ib);+ c.fromBufferAttribute(p, ic);+ const scale = frame.scale || 1;+ b.sub(a).divideScalar(scale);+ c.sub(a).divideScalar(scale);+ if (b.cross(c).length() <= (distance / scale) ** 2)+ result.degenerateTriangles++;+ if (ids[ia] === ids[ib] || ids[ib] === ids[ic] || ids[ic] === ids[ia]) {+ result.collapsedByToleranceTriangles++;+ continue;+ }+ for (const [start, end] of [+ [ia, ib],+ [ib, ic],+ [ic, ia]+ ]) {+ const u = ids[start], v = ids[end];+ const key = u < v ? `${u}:${v}` : `${v}:${u}`;+ const edge = edges.get(key) ?? { count: 0, direction: 0 };+ edge.count++;+ edge.direction += u < v ? 1 : -1;+ edges.set(key, edge);+ }+ }+ for (const edge of edges.values()) {+ if (edge.count === 1)+ result.boundaryEdges++;+ else if (edge.count > 2)+ result.nonManifoldEdges++;+ else if (edge.direction !== 0)+ result.orientationConflicts++;+ }+ const volumeFloor = (frame.scale || 1) ** 3 * 0.000000000001;+ result.solid = {+ closed: result.boundaryEdges === 0 && edges.size > 0,+ manifold: result.nonManifoldEdges === 0,+ orientation: result.orientationConflicts > 0 || Math.abs(signedVolume) <= volumeFloor ? "mixed" : signedVolume > 0 ? "outward" : "inward",+ signedVolume: Object.is(signedVolume, -0) ? 0 : signedVolume+ };+ return result;+}+function parametricSurface(sample, options = {}) {+ const {+ u = [0, 1],+ v = [0, 1],+ uSegments: nu = 24,+ vSegments: nv = 24,+ periodicU = false,+ periodicV = false,+ orientation = "uv"+ } = options;+ for (const [name, n] of [+ ["uSegments", nu],+ ["vSegments", nv]+ ])+ if (!Number.isSafeInteger(n) || n < 1)+ throw new Error(`parametricSurface ${name} must be a positive integer`);+ const sampleCount = (nu + 1) * (nv + 1);+ if (!Number.isSafeInteger(sampleCount) || sampleCount > GEOMETRY_ALLOCATION_LIMITS.parametricSamples)+ throw new RangeError(`parametricSurface sample budget exceeded: requested ${sampleCount}, limit ${GEOMETRY_ALLOCATION_LIMITS.parametricSamples}. Reduce uSegments/vSegments or split the surface.`);+ for (const [name, range] of [+ ["u", u],+ ["v", v]+ ])+ if (range.length !== 2 || !range.every(Number.isFinite) || range[0] === range[1] || !Number.isFinite(range[1] - range[0]))+ throw new Error(`parametricSurface ${name} must be a finite nonzero domain`);+ if (orientation !== "uv" && orientation !== "vu")+ throw new Error("parametricSurface orientation must be uv or vu");+ const positions = [], uvs = [], indices = [];+ const sampledBounds = new THREE16.Box3;+ const sampledPoint = new THREE16.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);+ if (point.length !== 3 || !point.every(Number.isFinite))+ throw new Error(`parametricSurface: sample (${i},${j}) must return three finite coordinates`);+ positions.push(...point);+ sampledBounds.expandByPoint(sampledPoint.set(...point));+ uvs.push(i / nu, j / nv);+ }+ const groups = Array.from({ length: (nu + 1) * (nv + 1) }, (_, i) => i);+ const seamScale = boundsScale(sampledBounds);+ const find = (i) => {+ while (groups[i] !== i)+ i = groups[i];+ return i;+ };+ const join = (a, b, _label) => {+ const pa = positions.slice(a * 3, a * 3 + 3), pb = positions.slice(b * 3, b * 3 + 3);+ if (Math.hypot(...pa.map((x, k) => x - pb[k])) > seamScale * 0.000001)+ throw new AuthoringDiagnosticError("PARAMETRIC_PERIODIC_ENDPOINT");+ groups[find(b)] = find(a);+ for (let k = 0;k < 3; k++)+ positions[b * 3 + k] = positions[a * 3 + k];+ };+ if (periodicU)+ for (let j = 0;j <= nv; j++)+ join(j * (nu + 1), j * (nu + 1) + nu, "periodicU");+ if (periodicV)+ for (let i = 0;i <= nu; i++)+ join(i, nv * (nu + 1) + i, "periodicV");+ for (let j = 0;j < nv; j++)+ for (let i = 0;i < nu; i++) {+ const a = j * (nu + 1) + i, b = a + 1, c = a + nu + 1, d = c + 1;+ indices.push(...orientation === "uv" ? [a, b, c, b, d, c] : [a, c, b, b, c, d]);+ }+ const out = meshGeo({ positions, indices, uvs });+ if (periodicU || periodicV) {+ const normal = out.getAttribute("normal");+ const sums = new Map;+ for (let i = 0;i < normal.count; i++) {+ const id = find(i);+ const sum = sums.get(id) ?? new THREE16.Vector3;+ sum.add(new THREE16.Vector3().fromBufferAttribute(normal, i));+ sums.set(id, sum);+ }+ for (let i = 0;i < normal.count; i++) {+ const n = sums.get(find(i)).clone().normalize();+ normal.setXYZ(i, n.x, n.y, n.z);+ }+ }+ return out;+}+function creaseNormals(geometry, options = {}) {+ const angle = options.angle ?? 60;+ if (!Number.isFinite(angle) || angle < 0 || angle > 180)+ throw new Error("creaseNormals angle must be between 0 and 180 degrees");+ const out = geometry.index ? geometry.toNonIndexed() : geometry.clone();+ const position = out.getAttribute("position");+ if (position?.itemSize !== 3 || position.count % 3 !== 0)+ throw new Error("creaseNormals requires complete xyz triangles");+ const frame = positionFrame(position);+ const tolerance = positionTolerance(frame.scale, options.tolerance, 0.00000001);+ const scale = frame.scale || 1;+ const adjacent = new Map;+ const keys = [];+ const faces = [];+ for (let i = 0;i < position.count; i += 3) {+ const a = new THREE16.Vector3().fromBufferAttribute(position, i);+ const b = new THREE16.Vector3().fromBufferAttribute(position, i + 1);+ const c = new THREE16.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 THREE16.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);+ keys.push(key);+ const neighbors = adjacent.get(key) ?? new Set;+ neighbors.add(i / 3);+ adjacent.set(key, neighbors);+ }+ }+ const normals = new Float32Array(position.count * 3);+ const threshold = Math.cos(THREE16.MathUtils.degToRad(angle));+ for (let i = 0;i < position.count; i++) {+ const face = faces[Math.floor(i / 3)], sum = new THREE16.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 THREE16.BufferAttribute(normals, 3));+ out.deleteAttribute("tangent");+ out.computeBoundingBox();+ out.computeBoundingSphere();+ return out;+}+var init_geometry = __esm(() => {+ init_geometry_budget();+ init_authoring_diagnostic();+});++// src/qa/open-surface-penetration.ts+import * as THREE17 from "three";+function buildHierarchy(triangles) {+ const box = new THREE17.Box3;+ for (const triangle of triangles)+ box.union(triangle.box);+ if (triangles.length <= 4)+ return { box, triangles };+ const size = box.getSize(new THREE17.Vector3);+ const axis = size.x >= size.y && size.x >= size.z ? "x" : size.y >= size.z ? "y" : "z";+ const center = (triangle) => triangle.box.min[axis] / 2 + triangle.box.max[axis] / 2;+ const sorted = [...triangles].sort((a, b) => center(a) - center(b));+ const middle = Math.floor(sorted.length / 2);+ return {+ box,+ children: [buildHierarchy(sorted.slice(0, middle)), buildHierarchy(sorted.slice(middle))]+ };+}+function worldTriangles(mesh) {+ const geometry = mesh.geometry;+ const position = geometry.getAttribute("position");+ if (position?.itemSize !== 3)+ return null;+ const index = geometry.getIndex();+ const count = index ? index.count : position.count;+ if (count % 3 !== 0)+ return null;+ const triangles = [];+ const vertex = (at) => {+ const id = index ? index.getX(at) : at;+ if (!Number.isSafeInteger(id) || id < 0 || id >= position.count)+ return null;+ const point = new THREE17.Vector3().fromBufferAttribute(position, id).applyMatrix4(mesh.matrixWorld);+ return [point.x, point.y, point.z].every(Number.isFinite) ? point : null;+ };+ for (let i = 0;i < count; i += 3) {+ const a = vertex(i), b = vertex(i + 1), c = vertex(i + 2);+ if (!a || !b || !c)+ return null;+ const triangle = new THREE17.Triangle(a, b, c);+ triangles.push({ triangle, box: new THREE17.Box3().setFromPoints([a, b, c]) });+ }+ return triangles.length ? triangles : null;+}+function triangleCount(geometry) {+ const index = geometry.getIndex();+ const position = geometry.getAttribute("position");+ if (!position)+ return 0;+ return Math.floor((index ? index.count : position.count) / 3);+}+function collectParts3(root, skipped) {+ const parts = [];+ root.updateWorldMatrix(true, true);+ root.traverseVisible((node) => {+ const mesh = node;+ if (!mesh.isMesh || !mesh.geometry)+ return;+ const name = mesh.name || "(unnamed mesh)";+ if (mesh.isInstancedMesh || mesh.isSkinnedMesh || Object.values(mesh.geometry.morphAttributes).some((targets) => targets.length)) {+ skipped.push({+ part: name,+ reason: "instancing, skin or morph deformation is unsupported by surface sampling"+ });+ return;+ }+ const total = mesh.geometry.index?.count ?? mesh.geometry.getAttribute("position")?.count ?? 0;+ const range = mesh.geometry.drawRange;+ if (range.start !== 0 || range.count < total) {+ skipped.push({+ part: name,+ reason: "partial triangle draw ranges are unsupported by surface sampling"+ });+ return;+ }+ const triangles = triangleCount(mesh.geometry);+ if (triangles === 0)+ return;+ if (triangles > MAX_SURFACE_TRIANGLES) {+ skipped.push({+ part: name,+ reason: `${triangles} triangles exceeds the ${MAX_SURFACE_TRIANGLES}-triangle analysis budget`+ });+ return;+ }+ mesh.geometry.computeBoundingBox();+ const box = mesh.geometry.boundingBox.clone().applyMatrix4(mesh.matrixWorld);+ if (box.isEmpty())+ return;+ const determinant = mesh.matrixWorld.determinant();+ if (![...box.min, ...box.max].every(Number.isFinite) || !Number.isFinite(determinant)) {+ skipped.push({ part: name, reason: "non-finite transformed bounds cannot be measured" });+ return;+ }+ let diagnostics;+ try {+ diagnostics = geometryDiagnostics(mesh.geometry);+ } catch (error) {+ skipped.push({+ part: name,+ reason: `topology could not be analyzed (${error instanceof Error ? error.message : String(error)})`+ });+ return;+ }+ const closed = diagnostics.solid.closed && diagnostics.solid.manifold && diagnostics.solid.orientation !== "mixed";+ parts.push({ name, mesh, box, closed, lod: lodMembership(mesh) });+ });+ return parts;+}+function boxDistanceSquared(box, point) {+ const x = Math.max(box.min.x - point.x, 0, point.x - box.max.x);+ const y = Math.max(box.min.y - point.y, 0, point.y - box.max.y);+ const z = Math.max(box.min.z - point.z, 0, point.z - box.max.z);+ return x * x + y * y + z * z;+}+function boxOverlapRatio(a, b) {+ const extent = (box) => (box.max.x - box.min.x) * (box.max.y - box.min.y) * (box.max.z - box.min.z);+ 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(extent(a), extent(b));+ return Number.isFinite(ratio) ? ratio : 0;+}++class Budget {+ limit;+ used = 0;+ exhausted = false;+ constructor(limit) {+ this.limit = limit;+ }+ spend() {+ if (this.used >= this.limit) {+ this.exhausted = true;+ return false;+ }+ this.used++;+ return true;+ }+}+function nearestDistance(root, point, budget) {+ let best = Infinity;+ const stack = [root];+ const scratch = new THREE17.Vector3;+ while (stack.length) {+ const node = stack.pop();+ if (boxDistanceSquared(node.box, point) >= best)+ continue;+ if ("triangles" in node) {+ for (const { triangle } of node.triangles) {+ if (!budget.spend())+ return null;+ const distance = point.distanceToSquared(triangle.closestPointToPoint(point, scratch));+ if (distance < best)+ best = distance;+ }+ } else+ stack.push(node.children[0], node.children[1]);+ }+ return Number.isFinite(best) ? Math.sqrt(best) : null;+}+function parity(root, point, direction, budget) {+ const ray = new THREE17.Ray(point, direction);+ const stack = [root];+ const hit = new THREE17.Vector3;+ const barycentric = new THREE17.Vector3;+ let crossings = 0;+ while (stack.length) {+ const node = stack.pop();+ if (!ray.intersectsBox(node.box))+ continue;+ if ("triangles" in node) {+ for (const { triangle } of node.triangles) {+ if (!budget.spend())+ return null;+ if (ray.intersectTriangle(triangle.a, triangle.b, triangle.c, false, hit) === null)+ continue;+ triangle.getBarycoord(hit, barycentric);+ if ([barycentric.x, barycentric.y, barycentric.z].some((v) => Math.abs(v) < PARITY_EPSILON))+ return null;+ crossings++;+ }+ } else+ stack.push(node.children[0], node.children[1]);+ }+ return crossings % 2 === 1;+}+function inside(root, point, budget) {+ for (const direction of PARITY_DIRECTIONS) {+ const verdict = parity(root, point, direction, budget);+ if (verdict !== null)+ return verdict;+ if (budget.exhausted)+ return null;+ }+ return null;+}+function analyzeOpenSurfacePenetration(root, contactTolerance = OPEN_SURFACE_CONTACT_TOLERANCE) {+ const evidence = {+ schemaVersion: 1,+ source: "engine-scene-analysis",+ contactTolerance,+ openParts: 0,+ closedParts: 0,+ candidatePairs: 0,+ pairsTested: 0,+ pairsNotReached: 0,+ verticesUnresolved: 0,+ pairsLodAlternates: 0,+ truncated: false,+ skipped: [],+ penetrations: []+ };+ if (!(root instanceof THREE17.Object3D))+ return evidence;+ const parts = collectParts3(root, evidence.skipped);+ const open = parts.filter((part) => !part.closed);+ const closed = parts.filter((part) => part.closed);+ evidence.openParts = open.length;+ evidence.closedParts = closed.length;+ const candidates = [];+ let considered = 0;+ broadPhase:+ for (const surface of open) {+ for (const solid of closed) {+ if (considered++ === MAX_BROAD_PHASE_PAIRS) {+ evidence.broadPhaseTruncated = true;+ break broadPhase;+ }+ if (!surface.box.intersectsBox(solid.box))+ continue;+ if (surface.lod && solid.lod && surface.lod.parent === solid.lod.parent && surface.lod.stem === solid.lod.stem && surface.lod.level !== solid.lod.level) {+ evidence.pairsLodAlternates++;+ continue;+ }+ candidates.push({+ open: surface,+ solid,+ overlap: boxOverlapRatio(surface.box, solid.box),+ order: candidates.length+ });+ }+ }+ evidence.candidatePairs = candidates.length;+ evidence.truncated = evidence.broadPhaseTruncated === true;+ if (!candidates.length)+ return evidence;+ candidates.sort((x, y) => y.overlap - x.overlap || x.order - y.order);+ const budget = new Budget(MAX_WORK);+ const penetrations = [];+ for (const candidate of candidates) {+ if (budget.exhausted) {+ evidence.pairsNotReached++;+ continue;+ }+ if (!candidate.solid.hierarchy) {+ const triangles = worldTriangles(candidate.solid.mesh);+ if (!triangles) {+ evidence.skipped.push({+ part: candidate.solid.name,+ reason: "invalid or non-finite triangles cannot be indexed"+ });+ evidence.pairsNotReached++;+ continue;+ }+ candidate.solid.hierarchy = buildHierarchy(triangles);+ }+ const hierarchy = candidate.solid.hierarchy;+ const position = candidate.open.mesh.geometry.getAttribute("position");+ if (position?.itemSize !== 3) {+ evidence.skipped.push({+ part: candidate.open.name,+ reason: "open surfaces are sampled at their vertices and this part has none"+ });+ continue;+ }+ const matrix = candidate.open.mesh.matrixWorld;+ const limit = Math.min(position.count, MAX_SAMPLED_VERTICES);+ const vertex = new THREE17.Vector3;+ let depth = 0;+ let penetrating = 0;+ let tested = 0;+ let unresolved = 0;+ let partial = limit < position.count;+ for (let i = 0;i < limit; i++) {+ vertex.fromBufferAttribute(position, i).applyMatrix4(matrix);+ if (![vertex.x, vertex.y, vertex.z].every(Number.isFinite))+ continue;+ if (boxDistanceSquared(candidate.solid.box, vertex) > contactTolerance * contactTolerance) {+ tested++;+ continue;+ }+ const distance = nearestDistance(hierarchy, vertex, budget);+ if (distance === null) {+ partial = true;+ break;+ }+ tested++;+ if (distance <= contactTolerance)+ continue;+ const verdict = inside(hierarchy, vertex, budget);+ if (verdict === null) {+ if (budget.exhausted) {+ partial = true;+ break;+ }+ unresolved++;+ continue;+ }+ if (!verdict)+ continue;+ penetrating++;+ if (distance > depth)+ depth = distance;+ }+ evidence.verticesUnresolved += unresolved;+ if (partial)+ evidence.pairsNotReached++;+ else+ evidence.pairsTested++;+ if (penetrating > 0)+ penetrations.push({+ open: candidate.open.name,+ solid: candidate.solid.name,+ depth: round(depth),+ vertices: penetrating,+ tested+ });+ }+ evidence.truncated = evidence.truncated || evidence.pairsNotReached > 0;+ penetrations.sort((x, y) => y.depth - x.depth || `${x.open}:${x.solid}`.localeCompare(`${y.open}:${y.solid}`));+ evidence.penetrations = penetrations;+ return evidence;+}+function inspectOpenSurfacePenetration(evidence) {+ if (evidence?.schemaVersion !== 1)+ return [];+ const findings = evidence.penetrations.map((pair) => ({+ code: "GEO_OPEN_SURFACE_PENETRATION",+ disposition: "observe",+ dimension: "visualQuality",+ profile: "geometry.openSurfacePenetration",+ message: `Open surface ${JSON.stringify(pair.open)} reaches ${pair.depth.toFixed(4)} m inside solid ${JSON.stringify(pair.solid)}: ` + `${pair.vertices} of ${pair.tested} sampled ${pair.vertices === 1 ? "vertex lies" : "vertices lie"} deeper inside it than the ${evidence.contactTolerance} m contact tolerance.`,+ affected: { node: pair.open },+ measurement: {+ name: "openSurfacePenetrationDepth",+ actual: pair.depth,+ expected: evidence.contactTolerance,+ unit: "m",+ breakdown: { penetratingVertices: pair.vertices, sampledVertices: pair.tested }+ },+ repairText: "A positive here is not a defect. Most are intentional: a fitting set into a structural shell -- a lamp recess in a hull, a strut landing, a ridge into a cap -- puts shell vertices inside the solid by design, exactly as a bolt in a hole shares volume. Review the ones you did not intend, such as a cloth crossing a wall or a canopy pierced by a mast, and move the surface clear or cut it back to the solid. Vertices are the samples, so a solid thinner than this surface’s facet spacing can pass between two of them."+ }));+ const unresolved = evidence.verticesUnresolved ?? 0;+ if (evidence.truncated || unresolved > 0) {+ const clauses = [];+ if (evidence.truncated)+ clauses.push(`Sampled ${evidence.pairsTested} of ${evidence.broadPhaseTruncated ? "at least " : ""}${evidence.candidatePairs} overlapping open-surface and solid pairs; ` + `${evidence.pairsNotReached} were beyond the ${MAX_WORK}-test analysis budget.` + (evidence.broadPhaseTruncated ? ` Pair discovery stopped after ${MAX_BROAD_PHASE_PAIRS} box comparisons.` : "") + " Unsampled pairs were not examined; the most overlapping bounding boxes were sampled first.");+ if (unresolved > 0)+ clauses.push(`${unresolved} ${unresolved === 1 ? "vertex" : "vertices"} further than the contact tolerance from a solid could not be resolved as inside or outside it, and ${unresolved === 1 ? "is" : "are"} counted as neither.`);+ findings.push({+ code: "GEO_OPEN_SURFACE_PENETRATION_TRUNCATED",+ disposition: "observe",+ dimension: "visualQuality",+ profile: "geometry.openSurfacePenetration",+ message: clauses.join(" "),+ measurement: {+ name: "openSurfacePairsSampled",+ actual: evidence.pairsTested,+ expected: evidence.candidatePairs,+ breakdown: {+ pairsNotReached: evidence.pairsNotReached,+ verticesUnresolved: unresolved+ }+ }+ });+ }+ if (evidence.skipped.length) {+ const byReason = new Map;+ for (const { part, reason } of evidence.skipped) {+ const parts = byReason.get(reason);+ if (parts)+ parts.push(part);+ else+ byReason.set(reason, [part]);+ }+ const reasons = [...byReason].map(([reason, parts]) => `${parts.length} because ${reason}: ${namedParts(parts)}.`);+ const one = evidence.skipped.length === 1;+ findings.push({+ code: "GEO_OPEN_SURFACE_PENETRATION_UNMEASURED",+ disposition: "observe",+ dimension: "visualQuality",+ profile: "geometry.openSurfacePenetration",+ message: `${evidence.skipped.length} ${one ? "part was" : "parts were"} not sampled for open-surface penetration. ` + `${reasons.join(" ")} ${one ? "This part is" : "These parts are"} not certified clear of the solids around ${one ? "it" : "them"}.`+ });+ }+ return findings;+}+var OPEN_SURFACE_CONTACT_TOLERANCE = 0.005, MAX_SURFACE_TRIANGLES = 20000, MAX_SAMPLED_VERTICES = 20000, MAX_WORK = 250000, MAX_BROAD_PHASE_PAIRS = 250000, PARITY_DIRECTIONS, PARITY_EPSILON = 0.0000001, round = (value) => Number(value.toPrecision(9)), NAMES_SHOWN = 5, namedParts = (parts) => {+ const named = parts.slice(0, NAMES_SHOWN).map((part) => JSON.stringify(part));+ const more = parts.length > NAMES_SHOWN ? ` and ${parts.length - NAMES_SHOWN} more` : "";+ return `${named.join(", ")}${more}`;+}, OPEN_SURFACE_PENETRATION_QA_RULE;+var init_open_surface_penetration = __esm(() => {+ init_geometry();+ init_lod2();+ init_registry();+ PARITY_DIRECTIONS = Object.freeze([+ new THREE17.Vector3(1, 0, 0),+ new THREE17.Vector3(0.5773502691896258, 0.5773502691896258, 0.5773502691896258),+ new THREE17.Vector3(-0.2672612419124244, 0.5345224838248488, 0.8017837257372732)+ ]);+ OPEN_SURFACE_PENETRATION_QA_RULE = Object.freeze({+ id: "GEO_OPEN_SURFACE_PENETRATION",+ profile: "geometry.openSurfacePenetration",+ scope: { kind: "universal" },+ ruleClass: "heuristic",+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: "observe",+ evaluate(context) {+ return inspectOpenSurfacePenetration(analyzeOpenSurfacePenetration(context.scene));+ }+ });+});++// src/sweep-analysis.ts+import * as THREE18 from "three";function segmentHitsTriangle(a, b, tri, epsilon) {- const plane = new THREE16.Plane().setFromCoplanarPoints(tri.a, tri.b, tri.c);+ const plane = new THREE18.Plane().setFromCoplanarPoints(tri.a, tri.b, tri.c);if (plane.normal.lengthSq() === 0)return false;const da = plane.distanceToPoint(a), db = plane.distanceToPoint(b);@@ -17058,7 +17800,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 THREE16.Vector3).divideScalar(ring.length));+ const centers = rings.map((ring) => ring.reduce((sum, p) => sum.add(p), new THREE18.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);@@ -17072,17 +17814,17 @@ function recordSweepAnalysis(geometry, rings, profiles, closed) {const triangles = new Map;const faces = (index) => {if (!triangles.has(index))- triangles.set(index, THREE16.ShapeUtils.triangulateShape(profiles[index], []).map(([a, b, c]) => new THREE16.Triangle(rings[index][a], rings[index][b], rings[index][c])));+ triangles.set(index, THREE18.ShapeUtils.triangulateShape(profiles[index], []).map(([a, b, c]) => new THREE18.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 THREE16.Box3().setFromPoints(rings[i - 1]);- const boundsB = new THREE16.Box3().setFromPoints(rings[i]);+ const boundsA = new THREE18.Box3().setFromPoints(rings[i - 1]);+ const boundsB = new THREE18.Box3().setFromPoints(rings[i]);if (!boundsA.intersectsBox(boundsB)) {result.ringPairsChecked++;continue;}- const epsilon = Math.max(boundsA.getSize(new THREE16.Vector3).length(), boundsB.getSize(new THREE16.Vector3).length()) * 0.0000000001;+ const epsilon = Math.max(boundsA.getSize(new THREE18.Vector3).length(), boundsB.getSize(new THREE18.Vector3).length()) * 0.0000000001;let hit = false;pair:for (const [a, b] of [@@ -17114,10 +17856,10 @@ var init_sweep_analysis = __esm(() => {});// src/qa/sweep.ts-import { Object3D as Object3D6 } from "three";+import { Object3D as Object3D7 } from "three";function inspectSweepGeometry(scene) {const findings = [];- if (!(scene instanceof Object3D6))+ if (!(scene instanceof Object3D7))return findings;scene.traverseVisible((node) => {const geometry = node.geometry;@@ -17237,20 +17979,20 @@ var init_open_shell = __esm(() => {});// src/qa/self-intersection.ts-import * as THREE17 from "three";-function boxOverlapRatio(a, b) {+import * as THREE19 from "three";+function boxOverlapRatio2(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));return Number.isFinite(ratio) ? ratio : 0;}-function triangleCount(geometry) {+function triangleCount2(geometry) {const index = geometry.getIndex();const position = geometry.getAttribute("position");if (!position)return 0;return Math.floor((index ? index.count : position.count) / 3);}-function collectParts3(root, skipped) {+function collectParts4(root, skipped) {const parts = [];root.updateWorldMatrix(true, true);root.traverseVisible((node) => {@@ -17274,7 +18016,7 @@ function collectParts3(root, skipped) {});return;}- const triangles = triangleCount(mesh.geometry);+ const triangles = triangleCount2(mesh.geometry);if (triangles === 0)return;if (triangles > MAX_PART_TRIANGLES) {@@ -17288,8 +18030,8 @@ function collectParts3(root, skipped) {const box = mesh.geometry.boundingBox.clone().applyMatrix4(mesh.matrixWorld);if (box.isEmpty())return;- const center = box.getCenter(new THREE17.Vector3);- const size = box.getSize(new THREE17.Vector3);+ const center = box.getCenter(new THREE19.Vector3);+ const size = box.getSize(new THREE19.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({@@ -17321,7 +18063,7 @@ function meshToArrays(part) {matrix.elements[12] -= center.x;matrix.elements[13] -= center.y;matrix.elements[14] -= center.z;- const v = new THREE17.Vector3;+ const v = new THREE19.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);@@ -17357,7 +18099,7 @@ function meshToArrays(part) {}async function analyzePartPenetration(root) {const skipped = [];- const parts = collectParts3(root, skipped);+ const parts = collectParts4(root, skipped);const base = {schemaVersion: 1,source: "engine-scene-analysis",@@ -17378,7 +18120,7 @@ async function analyzePartPenetration(root) {broadPhase:for (let i = 0;i < parts.length; i++) {for (let j = i + 1;j < parts.length; j++) {- if (considered++ === MAX_BROAD_PHASE_PAIRS) {+ if (considered++ === MAX_BROAD_PHASE_PAIRS2) {base.broadPhaseTruncated = true;break broadPhase;}@@ -17390,7 +18132,7 @@ async function analyzePartPenetration(root) {base.pairsLodAlternates++;continue;}- candidates.push({ a: i, b: j, overlap: boxOverlapRatio(a.box, b.box) });+ candidates.push({ a: i, b: j, overlap: boxOverlapRatio2(a.box, b.box) });}}base.candidatePairs = candidates.length;@@ -17503,7 +18245,7 @@ async function analyzePartPenetration(root) {a: a.name,b: b.name,volume: roundVolume(assetVolume),- fraction: round(fraction)+ fraction: round2(fraction)});}}@@ -17561,7 +18303,7 @@ function acknowledgedFinding(acknowledged, pairs) {}const listed = [...groups.values()];const shown = listed.slice(0, ACKNOWLEDGED_REASONS_SHOWN);- const lines = shown.map(({ intent, reason, parts }) => `${parts.length} marked ${JSON.stringify(intent)}, because ${reason}: ${namedParts(parts)}.`);+ const lines = shown.map(({ intent, reason, parts }) => `${parts.length} marked ${JSON.stringify(intent)}, because ${reason}: ${namedParts2(parts)}.`);const rest = listed.slice(ACKNOWLEDGED_REASONS_SHOWN);if (rest.length) {const count = rest.reduce((sum, group) => sum + group.parts.length, 0);@@ -17610,7 +18352,7 @@ function inspectPartPenetration(evidence) {disposition: "observe",dimension: "visualQuality",profile: "geometry.selfIntersection",- message: `Tested ${evidence.pairsTested} of ${evidence.broadPhaseTruncated ? "at least " : ""}${evidence.candidatePairs} overlapping part pairs: ${pairsUnmeasurable} involve parts that could not be measured, ${pairsNotReached} were beyond the analysis budget (${MAX_NARROW_PHASE_PAIRS} booleans, ${MAX_SOLID_BUILDS} solids).` + (evidence.broadPhaseTruncated ? ` Pair discovery stopped after ${MAX_BROAD_PHASE_PAIRS} box comparisons.` : "") + " Unreached pairs were not examined; the most overlapping bounding boxes were tested first.",+ message: `Tested ${evidence.pairsTested} of ${evidence.broadPhaseTruncated ? "at least " : ""}${evidence.candidatePairs} overlapping part pairs: ${pairsUnmeasurable} involve parts that could not be measured, ${pairsNotReached} were beyond the analysis budget (${MAX_NARROW_PHASE_PAIRS} booleans, ${MAX_SOLID_BUILDS} solids).` + (evidence.broadPhaseTruncated ? ` Pair discovery stopped after ${MAX_BROAD_PHASE_PAIRS2} box comparisons.` : "") + " Unreached pairs were not examined; the most overlapping bounding boxes were tested first.",measurement: {name: "overlappingPartPairsTested",actual: evidence.pairsTested,@@ -17628,7 +18370,7 @@ function inspectPartPenetration(evidence) {elsebyReason.set(reason, [part]);}- const reasons = [...byReason].map(([reason, parts]) => `${parts.length} because ${reason}: ${namedParts(parts)}.`);+ const reasons = [...byReason].map(([reason, parts]) => `${parts.length} because ${reason}: ${namedParts2(parts)}.`);const one = evidence.skipped.length === 1;const includes = one ? "this part" : "one of these parts";const unmarked = pairsUnmeasurable - pairsAcknowledged;@@ -17645,7 +18387,7 @@ function inspectPartPenetration(evidence) {findings.push(acknowledgedFinding(acknowledged, pairsAcknowledged));return findings;}-var MAX_PART_TRIANGLES = 20000, MAX_NARROW_PHASE_PAIRS = 64, MAX_SOLID_BUILDS, MAX_SOLID_COMPONENTS = 32, MAX_BROAD_PHASE_PAIRS = 250000, CONTACT_VOLUME_FRACTION = 0.001, boxVolume = (box) => (box.max.x - box.min.x) * (box.max.y - box.min.y) * (box.max.z - box.min.z), round = (n) => Math.round(n * 1e9) / 1e9, roundVolume = (n) => Number(n.toPrecision(9)), SELF_INTERSECTION_QA_RULE, UNMEASURED_NAMES_SHOWN = 5, ACKNOWLEDGED_REASONS_SHOWN = 5, namedParts = (parts) => {+var MAX_PART_TRIANGLES = 20000, MAX_NARROW_PHASE_PAIRS = 64, MAX_SOLID_BUILDS, MAX_SOLID_COMPONENTS = 32, MAX_BROAD_PHASE_PAIRS2 = 250000, CONTACT_VOLUME_FRACTION = 0.001, boxVolume = (box) => (box.max.x - box.min.x) * (box.max.y - box.min.y) * (box.max.z - box.min.z), round2 = (n) => Math.round(n * 1e9) / 1e9, roundVolume = (n) => Number(n.toPrecision(9)), SELF_INTERSECTION_QA_RULE, UNMEASURED_NAMES_SHOWN = 5, ACKNOWLEDGED_REASONS_SHOWN = 5, namedParts2 = (parts) => {const named = parts.slice(0, UNMEASURED_NAMES_SHOWN).map((part) => JSON.stringify(part));const more = parts.length > UNMEASURED_NAMES_SHOWN ? ` and ${parts.length - UNMEASURED_NAMES_SHOWN} more` : "";return `${named.join(", ")}${more}`;@@ -17669,7 +18411,7 @@ var init_self_intersection = __esm(() => {});// src/vehicle.ts-import * as THREE18 from "three";+import * as THREE20 from "three";function assertId(value, name) {if (!ID_PATTERN.test(value))throw new TypeError(`${name} must be a stable identifier`);@@ -17704,7 +18446,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 THREE18.Object3D;+ const node = new THREE20.Object3D;node.name = `Socket_${kind}_${id}`;node.position.set(...input.position);node.quaternion.set(...rotation);@@ -17725,7 +18467,7 @@ function createTypedSocket(kind, input, parent) {return node;}function createVehicleFrame(name, options = {}) {- const root = new THREE18.Object3D;+ const root = new THREE20.Object3D;root.name = name;stampSemanticMetadataV1(root, semantic2([KILN_SEMANTIC_ROLES.vehicleFrame, KILN_SEMANTIC_ROLES.vehicleForward], {frames: [@@ -17750,7 +18492,7 @@ function createVehicleFrame(name, options = {}) {};}function cylinderZ(radius, width, segments = 16) {- const geometry = new THREE18.CylinderGeometry(radius, radius, width, segments);+ const geometry = new THREE20.CylinderGeometry(radius, radius, width, segments);geometry.rotateX(Math.PI / 2);return geometry;}@@ -17767,14 +18509,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 THREE18.TorusGeometry(radius - tube, tube, 8, 20);+ return new THREE20.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 THREE18.Box3;- const point = new THREE18.Vector3;+ const bounds = new THREE20.Box3;+ const point = new THREE20.Vector3;let actualRadius = 0;for (let i = 0;i < positions.count; i++) {point.fromBufferAttribute(positions, i);@@ -17784,7 +18526,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 THREE18.Vector3);+ const center = bounds.getCenter(new THREE20.Vector3);const tolerance = 0.00001 * Math.max(radius, width, actualRadius, actualWidth);const differences = [];if (Math.abs(actualRadius - radius) > tolerance)@@ -17829,11 +18571,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 THREE18.Object3D;+ const root = new THREE20.Object3D;root.name = `${name}_Assembly_${options.side}_${index}`;let steeringPivot;if (options.steering) {- steeringPivot = new THREE18.Object3D;+ steeringPivot = new THREE20.Object3D;steeringPivot.name = `SteeringPivot_${options.side}_${index}`;steeringPivot.position.set(...options.position ?? [0, 0, 0]);stampSemanticMetadataV1(steeringPivot, semantic2([semanticRole(ROLE.steeringPivot, key)], {@@ -17844,7 +18586,7 @@ function createWheelAssembly(name, materials, options) {}));root.add(steeringPivot);}- const spinPivot = new THREE18.Object3D;+ const spinPivot = new THREE20.Object3D;spinPivot.name = `WheelPivot_${options.side}_${index}`;if (!steeringPivot)spinPivot.position.set(...options.position ?? [0, 0, 0]);@@ -17865,9 +18607,9 @@ function createWheelAssembly(name, materials, options) {]}));(steeringPivot ?? root).add(spinPivot);- 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);+ const tire = new THREE20.Mesh(options.geometries?.tire ?? defaultTireGeometry(radius, width), materials.tire);+ const rim = new THREE20.Mesh(options.geometries?.rim ?? cylinderZ(rimRadius, rimWidth), materials.rim);+ const hub = new THREE20.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}`;@@ -17887,7 +18629,7 @@ function createWheelAssembly(name, materials, options) {]}));spinPivot.add(tire, rim, hub);- const contact = new THREE18.Object3D;+ const contact = new THREE20.Object3D;contact.name = `Contact_${options.side}_${index}`;contact.position.y = -radius;stampSemanticMetadataV1(contact, semantic2([semanticRole(ROLE.wheelContact, key), semanticRole(ROLE.contact, key)], {@@ -17945,10 +18687,10 @@ function objectBoundsInFrame(object, frame) {object.updateWorldMatrix(true, true);frame.updateWorldMatrix(true, false);const worldToFrame = frame.matrixWorld.clone().invert();- const bounds = new THREE18.Box3;+ const bounds = new THREE20.Box3;let found = false;object.traverse((node) => {- if (!(node instanceof THREE18.Mesh) || !(node.geometry instanceof THREE18.BufferGeometry))+ if (!(node instanceof THREE20.Mesh) || !(node.geometry instanceof THREE20.BufferGeometry))return;node.geometry.computeBoundingBox();const local = node.geometry.boundingBox;@@ -17958,7 +18700,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 THREE18.Vector3(x, y, z).applyMatrix4(matrix));+ bounds.expandByPoint(new THREE20.Vector3(x, y, z).applyMatrix4(matrix));found = true;}});@@ -17970,9 +18712,9 @@ function dimensions(object, frame) {const bounds = objectBoundsInFrame(object, frame);if (!bounds)return;- const size = bounds.getSize(new THREE18.Vector3);+ const size = bounds.getSize(new THREE20.Vector3);return {- center: bounds.getCenter(new THREE18.Vector3),+ center: bounds.getCenter(new THREE20.Vector3),radius: Math.max(size.x, size.y) / 2,width: size.z};@@ -17982,7 +18724,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 THREE18.Vector3;+ const centerLocal = tire?.center ?? rim?.center ?? hub?.center ?? new THREE20.Vector3;const toWorld = (value) => value.clone().applyMatrix4(pivot.matrixWorld);return {id,@@ -17997,11 +18739,11 @@ function resolved(source, id, root, pivot, parts) {...parts.hub ? { hub: parts.hub } : {},...parts.contact ? { contact: parts.contact } : {},centerWorld: toWorld(centerLocal),- pivotCenterWorld: new THREE18.Vector3().setFromMatrixPosition(pivot.matrixWorld),+ pivotCenterWorld: new THREE20.Vector3().setFromMatrixPosition(pivot.matrixWorld),...tire ? { tireCenterWorld: toWorld(tire.center) } : {},...rim ? { rimCenterWorld: toWorld(rim.center) } : {},...hub ? { hubCenterWorld: toWorld(hub.center) } : {},- spinAxisWorld: new THREE18.Vector3(0, 0, 1).transformDirection(pivot.matrixWorld),+ spinAxisWorld: new THREE20.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 } : {},@@ -18338,7 +19080,7 @@ var EPSILON = 0.0000000001, DEFAULT_TOLERANCE = 0.000001, finiteVector = (value)];// src/qa/vehicle-advisory.ts-import * as THREE19 from "three";+import * as THREE21 from "three";function advisory(context, value) {return {...value,@@ -18412,7 +19154,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 THREE19.Mesh) || isFender(node))+ if (!(node instanceof THREE21.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);}@@ -18420,10 +19162,10 @@ function objectBoundsInFrame2(object, frame) {object.updateWorldMatrix(true, true);frame.updateWorldMatrix(true, false);const worldToFrame = frame.matrixWorld.clone().invert();- const bounds = new THREE19.Box3;+ const bounds = new THREE21.Box3;let found = false;object.traverseVisible((part) => {- if (!(part instanceof THREE19.Mesh) || !(part.geometry instanceof THREE19.BufferGeometry))+ if (!(part instanceof THREE21.Mesh) || !(part.geometry instanceof THREE21.BufferGeometry))return;part.geometry.computeBoundingBox();const box = part.geometry.boundingBox;@@ -18433,7 +19175,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 THREE19.Vector3(x, y, z).applyMatrix4(matrix));+ bounds.expandByPoint(new THREE21.Vector3(x, y, z).applyMatrix4(matrix));found = true;}});@@ -18444,15 +19186,15 @@ function tuple5(value) {}function probeBox(id, root, bounds) {root.updateWorldMatrix(true, false);- 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;+ const center = bounds.getCenter(new THREE21.Vector3).applyMatrix4(root.matrixWorld);+ const size = bounds.getSize(new THREE21.Vector3);+ const position = new THREE21.Vector3;+ const quaternion = new THREE21.Quaternion;+ const scale = new THREE21.Vector3;root.matrixWorld.decompose(position, quaternion, scale);- 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();+ const xAxis = new THREE21.Vector3(1, 0, 0).applyQuaternion(quaternion).normalize();+ const yAxis = new THREE21.Vector3(0, 1, 0).applyQuaternion(quaternion).normalize();+ const zAxis = new THREE21.Vector3(0, 0, 1).applyQuaternion(quaternion).normalize();return createOrientedProbeBox3({id,frame: createProbeLocalFrame3({@@ -18521,7 +19263,7 @@ function orientationFindings(context, root, intent) {const bounds = wholeAssetBounds(root);if (!bounds)return [];- const size = bounds.getSize(new THREE19.Vector3);+ const size = bounds.getSize(new THREE21.Vector3);const ratio = size.z / Math.max(size.x, 0.000000001);if (ratio <= ORIENTATION_RATIO)return [];@@ -18565,13 +19307,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 THREE19.Mesh) || !(node.geometry instanceof THREE19.BufferGeometry))+ if (!(node instanceof THREE21.Mesh) || !(node.geometry instanceof THREE21.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 THREE19.Vector3().fromBufferAttribute(positions, index).applyMatrix4(matrix)));+ const keys = Array.from({ length: positions.count }, (_, index) => vertexKey(new THREE21.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) {@@ -18641,7 +19383,7 @@ function trackProfileFindings(context, root, intent) {const wheelBounds = objectBoundsInFrame2(roadWheel, root);if (!wheelBounds)continue;- const center = wheelBounds.getCenter(new THREE19.Vector3);+ const center = wheelBounds.getCenter(new THREE21.Vector3);if (expanded.containsPoint(center))continue;const clamped = center.clone().clamp(expanded.min, expanded.max);@@ -18667,7 +19409,7 @@ function trackProfileFindings(context, root, intent) {return findings;}function inspectMobilityAdvisory(context) {- if (!(context.scene instanceof THREE19.Object3D)) {+ if (!(context.scene instanceof THREE21.Object3D)) {return [];}const intent = context.mobility;@@ -18714,7 +19456,7 @@ var init_vehicle_advisory = __esm(() => {});// src/qa/vehicle.ts-import * as THREE20 from "three";+import * as THREE22 from "three";function finding3(context, value) {return {...value,@@ -18731,7 +19473,7 @@ function rootAxis(root, axis) {return axis.clone().transformDirection(root.matrixWorld);}function angleDegrees(a, b) {- return THREE20.MathUtils.radToDeg(Math.acos(THREE20.MathUtils.clamp(a.clone().normalize().dot(b.clone().normalize()), -1, 1)));+ return THREE22.MathUtils.radToDeg(Math.acos(THREE22.MathUtils.clamp(a.clone().normalize().dot(b.clone().normalize()), -1, 1)));}function isDescendant(node, ancestor) {let current = node;@@ -18779,7 +19521,7 @@ function wheelCountFindings(context, intent, wheels) {}function wheelGeometryFindings(context, root, wheels) {const findings = [];- const expectedAxle = rootAxis(root, new THREE20.Vector3(0, 0, 1));+ const expectedAxle = rootAxis(root, new THREE22.Vector3(0, 0, 1));for (const wheel of wheels) {const disposition = componentDisposition(wheel);const centerTolerance = Math.max(CENTER_MINIMUM, (wheel.radius ?? 0) * CENTER_RATIO);@@ -18968,7 +19710,7 @@ function contactFindings(context, root, intent, wheels) {function renderableMinYInRoot(rootInverse, node) {let minimum = Infinity;node.traverseVisible((part) => {- if (!(part instanceof THREE20.Mesh) || !(part.geometry instanceof THREE20.BufferGeometry))+ if (!(part instanceof THREE22.Mesh) || !(part.geometry instanceof THREE22.BufferGeometry))return;part.geometry.computeBoundingBox();const bounds = part.geometry.boundingBox;@@ -18978,7 +19720,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 THREE20.Vector3(x, y, z).applyMatrix4(matrix).y);+ minimum = Math.min(minimum, new THREE22.Vector3(x, y, z).applyMatrix4(matrix).y);}}}@@ -18996,7 +19738,7 @@ function supportContactFindings(context, root, intent) {if (!isWheelContact && roles.some((role) => role.startsWith("contact."))) {explicitContacts.push({node,- contactY: localPoint2(inverse, new THREE20.Vector3().setFromMatrixPosition(node.matrixWorld)).y,+ contactY: localPoint2(inverse, new THREE22.Vector3().setFromMatrixPosition(node.matrixWorld)).y,source: "contact"});}@@ -19076,7 +19818,7 @@ function steeringFindings(context, root, intent, wheels) {return [];root.updateWorldMatrix(true, false);const inverse = root.matrixWorld.clone().invert();- const expectedAxis = rootAxis(root, new THREE20.Vector3(0, 1, 0));+ const expectedAxis = rootAxis(root, new THREE22.Vector3(0, 1, 0));const localCenters = wheels.map((wheel) => ({wheel,center: localPoint2(inverse, wheel.centerWorld)@@ -19086,8 +19828,8 @@ function steeringFindings(context, root, intent, wheels) {const findings = [];for (const { wheel } of targets) {const steering = wheel.steeringPivot;- 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;+ const centerDelta = steering ? localPoint2(inverse, new THREE22.Vector3().setFromMatrixPosition(steering.matrixWorld)).distanceTo(localPoint2(inverse, wheel.centerWorld)) : Infinity;+ const axisAngle = steering ? angleDegrees(new THREE22.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, {@@ -19142,14 +19884,14 @@ function propulsionFindings(context, root, intent) {}for (const component of candidates) {const pivot = pivots.get(component.id);- 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 box = new THREE22.Box3().setFromObject(component.node);+ const center = box.isEmpty() ? undefined : box.getCenter(new THREE22.Vector3);+ const pivotCenter = pivot ? new THREE22.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 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;+ const canonicalAxis = kind === "rotor" ? new THREE22.Vector3(0, 1, 0) : new THREE22.Vector3(1, 0, 0);+ const axisAngle = pivot && axisFrame ? angleDegrees(canonicalAxis.clone().applyQuaternion(new THREE22.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",@@ -19171,7 +19913,7 @@ function propulsionFindings(context, root, intent) {return findings;}function inspectMobility(context) {- if (!(context.scene instanceof THREE20.Object3D))+ if (!(context.scene instanceof THREE22.Object3D))return [];const intent = context.mobility;if (!intent)@@ -19244,7 +19986,7 @@ var init_vehicle2 = __esm(() => {});// src/qa/vegetation.ts-import * as THREE21 from "three";+import * as THREE23 from "three";function rolesOf2(node) {return readSemanticMetadataV1(node)?.roles ?? [];}@@ -19260,22 +20002,22 @@ function pathOf(node, root) {return names.reverse().join("/");}function localPoint3(rootInverse, node) {- return node.getWorldPosition(new THREE21.Vector3).applyMatrix4(rootInverse);+ return node.getWorldPosition(new THREE23.Vector3).applyMatrix4(rootInverse);}function meshLocalBox(mesh, rootInverse) {- if (!(mesh.geometry instanceof THREE21.BufferGeometry))+ if (!(mesh.geometry instanceof THREE23.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 THREE21.Box3;- const count = mesh instanceof THREE21.InstancedMesh ? mesh.count : 1;+ const result = new THREE23.Box3;+ const count = mesh instanceof THREE23.InstancedMesh ? mesh.count : 1;for (let index = 0;index < count; index++) {const transform = base.clone();- if (mesh instanceof THREE21.InstancedMesh) {- const instance = new THREE21.Matrix4;+ if (mesh instanceof THREE23.InstancedMesh) {+ const instance = new THREE23.Matrix4;mesh.getMatrixAt(index, instance);transform.multiply(instance);}@@ -19288,7 +20030,7 @@ function collectRenderableBounds(root) {const inverse = root.matrixWorld.clone().invert();const values = [];root.traverseVisible((node) => {- if (!(node instanceof THREE21.Mesh))+ if (!(node instanceof THREE23.Mesh))return;const box = meshLocalBox(node, inverse);if (!box)@@ -19306,7 +20048,7 @@ function vegetationIntent(intent) {}function inspectFoliageContact(context) {const trusted = context.foliage;- if (!trusted?.grounded || !(context.scene instanceof THREE21.Object3D))+ if (!trusted?.grounded || !(context.scene instanceof THREE23.Object3D))return [];const planeY = context.groundPlaneY ?? 0;const root = context.scene;@@ -19344,7 +20086,7 @@ function inspectFoliageContact(context) {}const findings = [];for (const contact of contacts) {- const contactPoint = contact.frameTranslation ? new THREE21.Vector3(...contact.frameTranslation).applyMatrix4(contact.node.matrixWorld).applyMatrix4(inverse) : localPoint3(inverse, contact.node);+ const contactPoint = contact.frameTranslation ? new THREE23.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)@@ -19373,7 +20115,7 @@ function inspectFoliageContact(context) {for (const support of semanticSupports) {let minimumY = Infinity;support.traverseVisible((node) => {- if (!(node instanceof THREE21.Mesh))+ if (!(node instanceof THREE23.Mesh))return;const box = meshLocalBox(node, inverse);if (box)@@ -19401,25 +20143,25 @@ function inspectFoliageContact(context) {return findings;}function materialNames(node) {- if (!(node instanceof THREE21.Mesh))+ if (!(node instanceof THREE23.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 THREE21.Object3D))+ if (!trusted?.standalone || !(context.scene instanceof THREE23.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 THREE21.Box3);- const overallSize = overall.getSize(new THREE21.Vector3);+ const overall = renderables.reduce((box, value) => box.union(value.box), new THREE23.Box3);+ const overallSize = overall.getSize(new THREE23.Vector3);const findings = [];for (const value of renderables) {- const size = value.box.getSize(new THREE21.Vector3);- const center = value.box.getCenter(new THREE21.Vector3);+ const size = value.box.getSize(new THREE23.Vector3);+ const center = value.box.getCenter(new THREE23.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));@@ -19456,8 +20198,8 @@ function inspectFoliageScope(context) {function unionVolume(boxes) {if (boxes.length === 0)return 0;- const union = boxes.reduce((result, box) => result.union(box), new THREE21.Box3);- const size = union.getSize(new THREE21.Vector3);+ const union = boxes.reduce((result, box) => result.union(box), new THREE23.Box3);+ const size = union.getSize(new THREE23.Vector3);return size.x * size.y * size.z;}function projectedOccupancy(boxes, axes) {@@ -19527,7 +20269,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 THREE21.Vector3;+ const point = new THREE23.Vector3;for (let index = 0;index < position.count; index++) {point.fromBufferAttribute(position, index);if (Math.abs(point.getComponent(axis) - axisValue) <= tolerance)@@ -19535,7 +20277,7 @@ function endpointRadius(position, axis, axisValue, tolerance, scale) {}if (points.length === 0)return;- const center = new THREE21.Vector3;+ const center = new THREE23.Vector3;center.setComponent(axis, axisValue);for (const radialAxis of radialAxes) {center.setComponent(radialAxis, points.reduce((sum, value) => sum + value.getComponent(radialAxis), 0) / points.length);@@ -19549,7 +20291,7 @@ function endpointRadius(position, axis, axisValue, tolerance, scale) {return { center, radius };}function growthNodeMeasurement(root, candidate, allCandidates, band) {- if (!(candidate.node instanceof THREE21.Mesh))+ if (!(candidate.node instanceof THREE23.Mesh))return;const geometry = candidate.node.geometry;const position = geometry.getAttribute("position");@@ -19561,9 +20303,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 THREE21.Vector3;- relative.decompose(new THREE21.Vector3, new THREE21.Quaternion, relativeScale);- const size = geometryBox.getSize(new THREE21.Vector3);+ const relativeScale = new THREE23.Vector3;+ relative.decompose(new THREE23.Vector3, new THREE23.Quaternion, relativeScale);+ const size = geometryBox.getSize(new THREE23.Vector3);const scaledSizes = [Math.abs(size.x * relativeScale.x),Math.abs(size.y * relativeScale.y),@@ -19630,7 +20372,7 @@ function measureFoliageGrowth(foliage, root) {};}function inspectFoliageGrowth(context) {- if (!context.foliage || !(context.scene instanceof THREE21.Object3D))+ if (!context.foliage || !(context.scene instanceof THREE23.Object3D))return [];const measured = measureFoliageGrowth(context.foliage, context.scene);const findings = [];@@ -19681,7 +20423,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 THREE21.Vector3);+ const size = value.box.getSize(new THREE23.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";@@ -19704,7 +20446,7 @@ function measureVegetationFoliageAttachment(root) {};}function inspectFoliageAttachment(context) {- if (!context.foliage || !(context.scene instanceof THREE21.Object3D))+ if (!context.foliage || !(context.scene instanceof THREE23.Object3D))return [];return measureVegetationFoliageAttachment(context.scene).clusters.filter((cluster) => cluster.detached).map((cluster) => finding4(context, {code: "VEG_FOLIAGE_DETACHED",@@ -19724,9 +20466,9 @@ function inspectFoliageAttachment(context) {}function relativeTransformSignature(root, node) {const matrix = root.matrixWorld.clone().invert().multiply(node.matrixWorld);- const scale = new THREE21.Vector3;- const quaternion = new THREE21.Quaternion;- matrix.decompose(new THREE21.Vector3, quaternion, scale);+ const scale = new THREE23.Vector3;+ const quaternion = new THREE23.Quaternion;+ matrix.decompose(new THREE23.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));@@ -19747,9 +20489,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 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 centerBox = supports.reduce((box, value) => box.union(value.box), new THREE23.Box3);+ const centers = foliage.map((value) => value.box.getCenter(new THREE23.Vector3));+ const center = centerBox.isEmpty() ? centers.reduce((result, value) => result.add(value), new THREE23.Vector3).multiplyScalar(centers.length > 0 ? 1 / centers.length : 0) : centerBox.getCenter(new THREE23.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)@@ -19784,7 +20526,7 @@ function measureFoliageRepetition(requirements, root) {};}function inspectFoliageRepetition(context) {- if (!context.foliage || !(context.scene instanceof THREE21.Object3D))+ if (!context.foliage || !(context.scene instanceof THREE23.Object3D))return [];const measured = measureFoliageRepetition(context.foliage, context.scene);if (measured.suppressedForTopiary)@@ -19842,7 +20584,7 @@ function measureFoliageCanopy(profile, root) {}function inspectFoliageCanopy(context) {const trusted = context.foliage;- if (!trusted?.canopyProfile || !(context.scene instanceof THREE21.Object3D))+ if (!trusted?.canopyProfile || !(context.scene instanceof THREE23.Object3D))return [];const measurements = measureFoliageCanopy(trusted.canopyProfile, context.scene);const bands = PROFILE_BANDS[measurements.profile];@@ -19903,7 +20645,7 @@ function inspectFoliageCanopy(context) {return findings;}function materialValue(material) {- if (!(material instanceof THREE21.MeshStandardMaterial) && !(material instanceof THREE21.MeshBasicMaterial)) {+ if (!(material instanceof THREE23.MeshStandardMaterial) && !(material instanceof THREE23.MeshBasicMaterial)) {return;}const color = material.color;@@ -19913,11 +20655,11 @@ function measureFoliageMaterials(mode, root) {const values = [];let foliageNodeCount = 0;root.traverseVisible((node) => {- if (!(node instanceof THREE21.Mesh))+ if (!(node instanceof THREE23.Mesh))return;const bounds = {node,- box: new THREE21.Box3,+ box: new THREE23.Box3,roles: rolesOf2(node),source: rolesOf2(node).length > 0 ? "semantic" : "fallback"};@@ -19944,7 +20686,7 @@ function measureFoliageMaterials(mode, root) {};}function inspectFoliageMaterial(context) {- if (!context.foliage || !(context.scene instanceof THREE21.Object3D))+ if (!context.foliage || !(context.scene instanceof THREE23.Object3D))return [];if (!context.materialMode)return [];@@ -20146,7 +20888,7 @@ var init_character_repairs = __esm(() => {});// src/qa/character.ts-import * as THREE22 from "three";+import * as THREE24 from "three";function isClipLike(value) {if (typeof value !== "object" || value === null)return false;@@ -20384,7 +21126,7 @@ function contactFindings2(input, root) {const planeY = input.groundPlaneY ?? 0;const findings = [];for (const contact of contacts) {- const point = contact.node.getWorldPosition(new THREE22.Vector3).applyMatrix4(rootInverse);+ const point = contact.node.getWorldPosition(new THREE24.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.`, {@@ -20649,13 +21391,13 @@ function declaredHeldItem(nodes) {function characterJointScale(root) {root.updateMatrixWorld(true);const inverse = root.matrixWorld.clone().invert();- const bounds = new THREE22.Box3;+ const bounds = new THREE24.Box3;for (const joint of collectCharacterJointNodes(root)) {- bounds.expandByPoint(joint.node.getWorldPosition(new THREE22.Vector3).applyMatrix4(inverse));+ bounds.expandByPoint(joint.node.getWorldPosition(new THREE24.Vector3).applyMatrix4(inverse));}if (bounds.isEmpty())return 1;- const size = bounds.getSize(new THREE22.Vector3);+ const size = bounds.getSize(new THREE24.Vector3);return Math.max(size.x, size.y, size.z, 1);}function heldItemMotionFindings(input, root, clips) {@@ -20691,8 +21433,8 @@ function heldItemMotionFindings(input, root, clips) {if (!cloneItem || !cloneAttachment)continue;const inverse = clone.matrixWorld.clone().invert();- const itemPoint = cloneItem.getWorldPosition(new THREE22.Vector3).applyMatrix4(inverse);- const gripPoint = cloneAttachment.getWorldPosition(new THREE22.Vector3).applyMatrix4(inverse);+ const itemPoint = cloneItem.getWorldPosition(new THREE24.Vector3).applyMatrix4(inverse);+ const gripPoint = cloneAttachment.getWorldPosition(new THREE24.Vector3).applyMatrix4(inverse);const distance = itemPoint.distanceTo(gripPoint);baseline ??= distance;const drift = Math.abs(distance - baseline);@@ -20725,7 +21467,7 @@ function heldItemMotionFindings(input, root, clips) {function inspectRig(context) {if (!context.rig)return [];- const root = context.scene instanceof THREE22.Object3D ? context.scene : undefined;+ const root = context.scene instanceof THREE24.Object3D ? context.scene : undefined;const clips = (context.clips ?? []).filter(isClipLike);const findings = [];if (root) {@@ -20775,7 +21517,7 @@ var init_character2 = __esm(() => {});// src/qa/character-advisory.ts-import * as THREE23 from "three";+import * as THREE25 from "three";function isClipLike2(value) {if (typeof value !== "object" || value === null)return false;@@ -20798,16 +21540,16 @@ function jointPoints(root) {const inverse = rootInverse(root);return collectCharacterJointNodes(root).map((evidence) => ({evidence,- local: evidence.node.getWorldPosition(new THREE23.Vector3).applyMatrix4(inverse)+ local: evidence.node.getWorldPosition(new THREE25.Vector3).applyMatrix4(inverse)}));}function characterScale(points) {if (points.length === 0)return 1;- const bounds = new THREE23.Box3;+ const bounds = new THREE25.Box3;for (const point of points)bounds.expandByPoint(point.local);- const size = bounds.getSize(new THREE23.Vector3);+ const size = bounds.getSize(new THREE25.Vector3);return Math.max(size.x, size.y, size.z, 1);}function pairKey(descriptor) {@@ -20906,12 +21648,12 @@ function restChainFindings(context, root) {}function forwardMarkerFindings(context, root) {root.updateMatrixWorld(true);- const expected = new THREE23.Vector3(1, 0, 0).transformDirection(root.matrixWorld);+ const expected = new THREE25.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 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)));+ const quaternion = marker.node.getWorldQuaternion(new THREE25.Quaternion);+ const actual = new THREE25.Vector3(...marker.descriptor.localForwardAxis).applyQuaternion(quaternion).normalize();+ const angle = THREE25.MathUtils.radToDeg(Math.acos(THREE25.MathUtils.clamp(actual.dot(expected), -1, 1)));if (angle <= FORWARD_ANGLE_DEGREES)return [];return [@@ -20965,7 +21707,7 @@ function sampleClip(root, clip) {byRole: new Map(collectCharacterJointNodes(clone).map((evidence) => [evidence.descriptor.role,{- point: evidence.node.getWorldPosition(new THREE23.Vector3).applyMatrix4(inverse),+ point: evidence.node.getWorldPosition(new THREE25.Vector3).applyMatrix4(inverse),evidence}]))@@ -21077,12 +21819,12 @@ function phaseOppositionFindings(context, root, clips) {return findings;}function signedBendDegrees(descriptor, quaternion) {- const rest = new THREE23.Quaternion(...descriptor.rest.rotation);+ const rest = new THREE25.Quaternion(...descriptor.rest.rotation);const delta = rest.invert().multiply(quaternion).normalize();- const axis = new THREE23.Vector3(delta.x, delta.y, delta.z);- const signedMagnitude = axis.dot(new THREE23.Vector3(...descriptor.localBendAxis));+ const axis = new THREE25.Vector3(delta.x, delta.y, delta.z);+ const signedMagnitude = axis.dot(new THREE25.Vector3(...descriptor.localBendAxis));const angle = 2 * Math.atan2(signedMagnitude, delta.w);- return THREE23.MathUtils.radToDeg(THREE23.MathUtils.euclideanModulo(angle + Math.PI, Math.PI * 2) - Math.PI);+ return THREE25.MathUtils.radToDeg(THREE25.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));@@ -21096,7 +21838,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 THREE23.Quaternion().fromArray(value).normalize());+ const bend = signedBendDegrees(joint.descriptor, new THREE25.Quaternion().fromArray(value).normalize());if (Math.abs(bend) > Math.abs(maximum)) {maximum = bend;maximumFraction = fraction;@@ -21179,7 +21921,7 @@ function footSlideFindings(context, root, clips) {return findings;}function inspectRigAdvisory(context) {- if (!context.rig || !(context.scene instanceof THREE23.Object3D)) {+ if (!context.rig || !(context.scene instanceof THREE25.Object3D)) {return [];}const root = context.scene;@@ -21298,7 +22040,7 @@ var init_architecture_repairs = __esm(() => {});// src/qa/architecture.ts-import * as THREE24 from "three";+import * as THREE26 from "three";function hasRoofDimensions(value) {return value.footprint !== undefined && value.roof?.ridgeAxis !== undefined && value.roof.rise !== undefined && value.roof.overhang !== undefined;}@@ -21308,7 +22050,7 @@ function semanticMetadata(node) {function markerBounds(matrix) {const bounds = emptyBounds();for (let corner = 0;corner < 8; corner++) {- 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));+ expandBounds(bounds, new THREE26.Vector3(corner & 1 ? 0.5 : -0.5, corner & 2 ? 0.5 : -0.5, corner & 4 ? 0.5 : -0.5).applyMatrix4(matrix));}return bounds;}@@ -21317,7 +22059,7 @@ function geometryPlaneNormal(geometry, relativeMatrix) {const local = geometry.boundingBox;if (!local)return;- const size = local.getSize(new THREE24.Vector3);+ const size = local.getSize(new THREE26.Vector3);const dimensions = [["x", size.x],["y", size.y],@@ -21327,7 +22069,7 @@ function geometryPlaneNormal(geometry, relativeMatrix) {const axis = dimensions[0]?.[0];if (!axis)return;- const normal = new THREE24.Vector3(axis === "x" ? 1 : 0, axis === "y" ? 1 : 0, axis === "z" ? 1 : 0).transformDirection(relativeMatrix);+ const normal = new THREE26.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();@@ -21339,7 +22081,7 @@ function geometryEvidence(geometry, relativeMatrix) {if (position?.itemSize !== 3)return { bounds, vertices, triangles: [] };for (let index = 0;index < position.count; index++) {- const point = new THREE24.Vector3(position.getX(index), position.getY(index), position.getZ(index));+ const point = new THREE26.Vector3(position.getX(index), position.getY(index), position.getZ(index));point.applyMatrix4(relativeMatrix);vertices.push(point);expandBounds(bounds, point);@@ -21366,7 +22108,7 @@ function geometryEvidence(geometry, relativeMatrix) {return { bounds, vertices, triangles, ...planeNormal ? { planeNormal } : {} };}function collectArchitectureEvidence(scene) {- if (!(scene instanceof THREE24.Object3D))+ if (!(scene instanceof THREE26.Object3D))return;scene.updateMatrixWorld(true);const rootInverse = scene.matrixWorld.clone().invert();@@ -21386,7 +22128,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 THREE24.BufferGeometry;+ const isMesh = mesh.isMesh === true && mesh.geometry instanceof THREE26.BufferGeometry;const evidence = isMesh ? geometryEvidence(mesh.geometry, relativeMatrix) : {bounds: markerBounds(relativeMatrix),vertices: [],@@ -21445,7 +22187,7 @@ function architectureFinding(context, value) {function averageNormal(normals) {if (normals.length === 0)return;- const result = normals.reduce((sum, normal) => sum.add(normal), new THREE24.Vector3);+ const result = normals.reduce((sum, normal) => sum.add(normal), new THREE26.Vector3);return result.lengthSq() > EPSILON2 ? result.normalize() : undefined;}function intervalCoverage(min, max, expectedMin, expectedMax) {@@ -22156,8 +22898,8 @@ function evaluateArchitectureQa(context) {});}var PROFILE_RULE_ID2 = "ARCHITECTURE_PROFILE", EPSILON2 = 0.000001, ARCHITECTURE_REALISTIC_SCALE_BANDS, emptyBounds = () => ({- min: new THREE24.Vector3(Infinity, Infinity, Infinity),- max: new THREE24.Vector3(-Infinity, -Infinity, -Infinity)+ min: new THREE26.Vector3(Infinity, Infinity, Infinity),+ max: new THREE26.Vector3(-Infinity, -Infinity, -Infinity)}), expandBounds = (bounds, point) => {bounds.min.min(point);bounds.max.max(point);@@ -22201,7 +22943,7 @@ var init_architecture = __esm(() => {});// src/qa/environment.ts-import * as THREE25 from "three";+import * as THREE27 from "three";function finding5(context, value) {return { ...value, profile: context.profile ?? "asset.requirements.v1" };}@@ -22220,11 +22962,11 @@ function nodePath4(root, node) {return names.reverse().join("/");}function transformedBox2(source, transform) {- const result = new THREE25.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 THREE25.Vector3(x, y, z).applyMatrix4(transform));+ result.expandByPoint(new THREE27.Vector3(x, y, z).applyMatrix4(transform));}}}@@ -22233,16 +22975,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 THREE27.Vector3;+ const rotation = new THREE27.Quaternion;+ const scale = new THREE27.Vector3;relative.decompose(position, rotation, scale);- const recomposed = new THREE25.Matrix4().compose(position, rotation, scale);+ const recomposed = new THREE27.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 THREE27.Vector3).applyMatrix4(relative);+ const sourceHalf = source.getSize(new THREE27.Vector3).multiplyScalar(0.5);const halfExtents = [Math.abs(sourceHalf.x * scale.x),Math.abs(sourceHalf.y * scale.y),@@ -22257,30 +22999,30 @@ function orientedBoxFromLocalBounds(root, node, source, relative = root.matrixWohalfExtents});}-function collectParts4(root) {+function collectParts5(root) {root.updateWorldMatrix(true, true);const rootInverse = root.matrixWorld.clone().invert();const result = [];root.traverseVisible((node) => {const roles = rolesOf3(node);- const renderable = node instanceof THREE25.Mesh;+ const renderable = node instanceof THREE27.Mesh;let box;let orientedBox;let source;- if (renderable && node.geometry instanceof THREE25.BufferGeometry) {+ if (renderable && node.geometry instanceof THREE27.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 THREE27.Box3(new THREE27.Vector3(-0.5, -0.5, -0.5), new THREE27.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 THREE27.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 THREE27.InstancedMesh) {+ const instance = new THREE27.Matrix4;node.getMatrixAt(index, instance);transform.multiply(instance);}@@ -22311,9 +23053,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 THREE27.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);+ const rootInverseQuaternion = root.getWorldQuaternion(new THREE27.Quaternion).invert();+ const rotation = node.getWorldQuaternion(new THREE27.Quaternion).multiply(new THREE27.Quaternion(...frame.rotation)).premultiply(rootInverseQuaternion).normalize();return {id: socket.id,type: socket.type,@@ -22342,7 +23084,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 THREE27.Object3D)) {return [];}const root = context.scene;@@ -22406,8 +23148,8 @@ 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;- for (const part of collectParts4(root))+ const localBounds = new THREE27.Box3;+ for (const part of collectParts5(root))if (part.renderable && part.box)localBounds.union(part.box);if (localBounds.isEmpty())@@ -22420,30 +23162,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 THREE27.Mesh) || !(node.geometry instanceof THREE27.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 THREE27.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 THREE27.InstancedMesh) {+ const instance = new THREE27.Matrix4;node.getMatrixAt(instanceIndex, instance);transform.multiply(instance);}- const normalMatrix = new THREE25.Matrix3().getNormalMatrix(transform);+ const normalMatrix = new THREE27.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 THREE27.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 = THREE27.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 THREE27.Vector3(normals.getX(index), normals.getY(index), normals.getZ(index)).applyMatrix3(normalMatrix).normalize() : new THREE27.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 });@@ -22466,7 +23208,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]) => THREE27.MathUtils.radToDeg(Math.acos(THREE27.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`);@@ -22483,7 +23225,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 THREE27.Object3D)) {return [];}const root = context.scene;@@ -22566,11 +23308,11 @@ 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 THREE27.Object3D)) {return [];}const root = context.scene;- const parts = collectParts4(root);+ const parts = collectParts5(root);const corridors = parts.filter((part) => isCorridor(part));if (corridors.length === 0) {return [@@ -22696,11 +23438,11 @@ 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 THREE27.Object3D)) {return [];}const root = context.scene;- const parts = collectParts4(root).filter((part) => part.renderable && part.box);+ const parts = collectParts5(root).filter((part) => part.renderable && part.box);const findings = [];for (const part of parts) {const box = part.box;@@ -22743,7 +23485,7 @@ function inspectSpatialSupport(context) {}));}}- const size = box.getSize(new THREE25.Vector3);+ const size = box.getSize(new THREE27.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",@@ -23204,7 +23946,7 @@ function writtenNodeResolver(root, doc, purpose) {// src/node-visibility.tsimport { KHRNodeVisibility } from "@gltf-transform/extensions";-import * as THREE26 from "three";+import * as THREE28 from "three";function applyNodeVisibility(root, doc) {const hidden = [];root.traverse((node) => {@@ -23247,7 +23989,7 @@ function drawnSceneBounds(scene) {return;const mesh = node.getMesh();if (mesh) {- const base = new THREE26.Matrix4().fromArray(node.getWorldMatrix());+ const base = new THREE28.Matrix4().fromArray(node.getWorldMatrix());const instances = node.getExtension("EXT_mesh_gpu_instancing");const translation = instances?.getAttribute("TRANSLATION");const rotation = instances?.getAttribute("ROTATION");@@ -23258,7 +24000,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 THREE26.Matrix4().compose(new THREE26.Vector3().fromArray(t), new THREE26.Quaternion().fromArray(r), new THREE26.Vector3().fromArray(s));+ const localMatrix = new THREE28.Matrix4().compose(new THREE28.Vector3().fromArray(t), new THREE28.Quaternion().fromArray(r), new THREE28.Vector3().fromArray(s));matrices.push(base.clone().multiply(localMatrix).toArray());}const local = [0, 0, 0];@@ -23299,12 +24041,12 @@ var init_node_visibility = __esm(() => {});// src/delivery-inspect.ts-import * as THREE27 from "three";+import * as THREE29 from "three";import { PropertyType as PropertyType2 } from "@gltf-transform/core";function decompose(matrix) {- const translation = new THREE27.Vector3;- const rotation = new THREE27.Quaternion;- const scale = new THREE27.Vector3;+ const translation = new THREE29.Vector3;+ const rotation = new THREE29.Quaternion;+ const scale = new THREE29.Vector3;matrix.decompose(translation, rotation, scale);const clean = (value) => Object.is(value, -0) ? 0 : value;return {@@ -23316,7 +24058,7 @@ function decompose(matrix) {function drawnTriangles(visited) {const values = [];const local = [0, 0, 0];- const point = new THREE27.Vector3;+ const point = new THREE29.Vector3;for (const { node, roles, hidden } of visited) {const mesh = node.getMesh();if (!mesh || hidden || roles.some((role) => role.startsWith("collider.")))@@ -23329,7 +24071,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 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]));+ const instance = new THREE29.Matrix4().compose(new THREE29.Vector3().fromArray(translation?.getElement(i, []) ?? [0, 0, 0]), new THREE29.Quaternion().fromArray(rotation?.getElement(i, []) ?? [0, 0, 0, 1]), new THREE29.Vector3().fromArray(scale?.getElement(i, []) ?? [1, 1, 1]));matrices.push(base.clone().multiply(instance));}for (const primitive of mesh.listPrimitives()) {@@ -23360,20 +24102,20 @@ function triangleOverlapsBox(a, b, c, h, tolerance) {return false;}const e = [- new THREE27.Vector3().subVectors(b, a),- new THREE27.Vector3().subVectors(c, b),- new THREE27.Vector3().subVectors(a, c)+ new THREE29.Vector3().subVectors(b, a),+ new THREE29.Vector3().subVectors(c, b),+ new THREE29.Vector3().subVectors(a, c)];- const normal = new THREE27.Vector3().crossVectors(e[0], e[1]);+ const normal = new THREE29.Vector3().crossVectors(e[0], e[1]);const axes = [normal];const units = [- new THREE27.Vector3(1, 0, 0),- new THREE27.Vector3(0, 1, 0),- new THREE27.Vector3(0, 0, 1)+ new THREE29.Vector3(1, 0, 0),+ new THREE29.Vector3(0, 1, 0),+ new THREE29.Vector3(0, 0, 1)];for (const unit of units)for (const edge of e)- axes.push(new THREE27.Vector3().crossVectors(unit, edge));+ axes.push(new THREE29.Vector3().crossVectors(unit, edge));for (const axis of axes) {if (axis.lengthSq() < 0.000000000000000000000001)continue;@@ -23385,14 +24127,14 @@ function triangleOverlapsBox(a, b, c, h, tolerance) {return true;}function closestPointOnTriangle(p, a, b, c) {- 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 ab = new THREE29.Vector3().subVectors(b, a);+ const ac = new THREE29.Vector3().subVectors(c, a);+ const ap = new THREE29.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 THREE27.Vector3().subVectors(p, b);+ const bp = new THREE29.Vector3().subVectors(p, b);const d3 = ab.dot(bp);const d4 = ac.dot(bp);if (d3 >= 0 && d4 <= d3)@@ -23400,7 +24142,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 THREE27.Vector3().subVectors(p, c);+ const cp = new THREE29.Vector3().subVectors(p, c);const d5 = ab.dot(cp);const d6 = ac.dot(cp);if (d6 >= 0 && d5 <= d6)@@ -23410,14 +24152,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 THREE27.Vector3().subVectors(c, b), (d4 - d3) / (d4 - d3 + (d5 - d6)));+ return b.clone().addScaledVector(new THREE29.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 THREE27.Vector3().subVectors(q1, p1);- const d2 = new THREE27.Vector3().subVectors(q2, p2);- const r = new THREE27.Vector3().subVectors(p1, p2);+ const d1 = new THREE29.Vector3().subVectors(q1, p1);+ const d2 = new THREE29.Vector3().subVectors(q2, p2);+ const r = new THREE29.Vector3().subVectors(p1, p2);const a = d1.dot(d1);const e = d2.dot(d2);const f = d2.dot(r);@@ -23426,22 +24168,22 @@ function segmentSegmentDistanceSq(p1, q1, p2, q2) {if (a <= 0.000000000000000000000001 && e <= 0.000000000000000000000001)return r.lengthSq();if (a <= 0.000000000000000000000001)- t = THREE27.MathUtils.clamp(f / e, 0, 1);+ t = THREE29.MathUtils.clamp(f / e, 0, 1);else {const c = d1.dot(r);if (e <= 0.000000000000000000000001)- s = THREE27.MathUtils.clamp(-c / a, 0, 1);+ s = THREE29.MathUtils.clamp(-c / a, 0, 1);else {const b = d1.dot(d2);const denominator = a * e - b * b;- s = denominator !== 0 ? THREE27.MathUtils.clamp((b * f - c * e) / denominator, 0, 1) : 0;+ s = denominator !== 0 ? THREE29.MathUtils.clamp((b * f - c * e) / denominator, 0, 1) : 0;t = (b * s + f) / e;if (t < 0) {t = 0;- s = THREE27.MathUtils.clamp(-c / a, 0, 1);+ s = THREE29.MathUtils.clamp(-c / a, 0, 1);} else if (t > 1) {t = 1;- s = THREE27.MathUtils.clamp((b - c) / a, 0, 1);+ s = THREE29.MathUtils.clamp((b - c) / a, 0, 1);}}}@@ -23450,8 +24192,8 @@ function segmentSegmentDistanceSq(p1, q1, p2, q2) {return c1.distanceToSquared(c2);}function segmentCrossesTriangle(p, q, a, b, c) {- const hit = new THREE27.Vector3;- const ray = new THREE27.Ray(p, new THREE27.Vector3().subVectors(q, p));+ const hit = new THREE29.Vector3;+ const ray = new THREE29.Ray(p, new THREE29.Vector3().subVectors(q, p));const length = ray.direction.length();if (length === 0)return false;@@ -23568,9 +24310,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 THREE27.Box3(new THREE27.Vector3(...min), new THREE27.Vector3(...max));+ const bounds = new THREE29.Box3(new THREE29.Vector3(...min), new THREE29.Vector3(...max));const finiteBounds = [...min, ...max].every(Number.isFinite);- const diagonal = finiteBounds ? bounds.getSize(new THREE27.Vector3).length() : 0;+ const diagonal = finiteBounds ? bounds.getSize(new THREE29.Vector3).length() : 0;const tolerance = Math.max(0.0001, diagonal * 0.0001);const colliderNodes = [];for (const entry of visited) {@@ -23649,23 +24391,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 THREE27.Vector3;- const b = new THREE27.Vector3;- const c = new THREE27.Vector3;+ const a = new THREE29.Vector3;+ const b = new THREE29.Vector3;+ const c = new THREE29.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 THREE27.Box3;+ const proxyBounds = new THREE29.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 THREE27.Vector3().fromArray(position.getElement(i, local)).applyMatrix4(matrix));+ proxyBounds.expandByPoint(new THREE29.Vector3().fromArray(position.getElement(i, local)).applyMatrix4(matrix));}if (proxyBounds.isEmpty())- proxyBounds.expandByPoint(new THREE27.Vector3().setFromMatrixPosition(matrix));+ proxyBounds.expandByPoint(new THREE29.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.");@@ -23676,11 +24418,11 @@ function inspectDelivery(doc) {continue;}overlapTests += triangleCount;- const toLocal = new THREE27.Matrix4;+ const toLocal = new THREE29.Matrix4;let touches = false;if (record.shape.kind === "box") {toLocal.copy(matrix).invert();- const half = new THREE27.Vector3(0.5, 0.5, 0.5);+ const half = new THREE29.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);@@ -23690,10 +24432,10 @@ function inspectDelivery(doc) {}} else {const { translation, rotation } = record.transform;- toLocal.compose(new THREE27.Vector3(...translation), new THREE27.Quaternion(...rotation), new THREE27.Vector3(1, 1, 1)).invert();+ toLocal.compose(new THREE29.Vector3(...translation), new THREE29.Quaternion(...rotation), new THREE29.Vector3(1, 1, 1)).invert();const { radius, height } = record.shape;- const p = new THREE27.Vector3(0, -height / 2 + radius, 0);- const q = new THREE27.Vector3(0, height / 2 - radius, 0);+ const p = new THREE29.Vector3(0, -height / 2 + radius, 0);+ const q = new THREE29.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);@@ -23712,7 +24454,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 THREE27.Vector3(...record.transform.translation).applyMatrix4(worldMatrix(moduleEntry.node).invert());+ const point = new THREE29.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);@@ -23726,7 +24468,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 THREE27.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 THREE29.Matrix4().fromArray(node.getWorldMatrix());var init_delivery_inspect = __esm(() => {init_gltf_io();init_semantic();@@ -23868,16 +24610,16 @@ function evaluateValidationProfileDocument(profile, doc, options = {}) {measurement: { actual: null }}, "observe");} else if (outcome.failures.length > 0)- report("HOST_VALIDATION_ATTRIBUTE_GRADIENT", "gradient", `${where} ${check.gradient.attribute}[${check.gradient.component}] fails the ${outcome.failures.join(" and ")} test along local ${check.gradient.axis}: ${round2(outcome.fromMean)} to ${round2(outcome.toMean)}, expected ${check.gradient.from} to ${check.gradient.to} within ${check.gradient.tolerance}.`, {+ report("HOST_VALIDATION_ATTRIBUTE_GRADIENT", "gradient", `${where} ${check.gradient.attribute}[${check.gradient.component}] fails the ${outcome.failures.join(" and ")} test along local ${check.gradient.axis}: ${round3(outcome.fromMean)} to ${round3(outcome.toMean)}, expected ${check.gradient.from} to ${check.gradient.to} within ${check.gradient.tolerance}.`, {affected: { ...affected, attribute: check.gradient.attribute },measurement: {- actual: `${round2(outcome.fromMean)}..${round2(outcome.toMean)}`,+ actual: `${round3(outcome.fromMean)}..${round3(outcome.toMean)}`,expected: `${check.gradient.from}..${check.gradient.to}`,threshold: check.gradient.tolerance,breakdown: {- fromMean: round2(outcome.fromMean),- toMean: round2(outcome.toMean),- worstRegression: round2(outcome.worstRegression)+ fromMean: round3(outcome.fromMean),+ toMean: round3(outcome.toMean),+ worstRegression: round3(outcome.worstRegression)}}});@@ -23902,10 +24644,10 @@ function evaluateValidationProfileDocument(profile, doc, options = {}) {}const { tolerance } = check.range;if (accessor.getCount() > 0 && (min < check.range.min - tolerance || max > check.range.max + tolerance))- report("HOST_VALIDATION_ATTRIBUTE_RANGE", "range", `${where} ${check.range.attribute}[${check.range.component}] spans ${round2(min)}..${round2(max)}; the host allows ${check.range.min}..${check.range.max} within ${tolerance}.`, {+ report("HOST_VALIDATION_ATTRIBUTE_RANGE", "range", `${where} ${check.range.attribute}[${check.range.component}] spans ${round3(min)}..${round3(max)}; the host allows ${check.range.min}..${check.range.max} within ${tolerance}.`, {affected: { ...affected, attribute: check.range.attribute },measurement: {- actual: `${round2(min)}..${round2(max)}`,+ actual: `${round3(min)}..${round3(max)}`,expected: `${check.range.min}..${check.range.max}`,threshold: tolerance}@@ -24069,7 +24811,7 @@ async function evaluateValidationProfileGlb(profile, bytes, options = {}) {}return evaluateValidationProfileDocument(profile, doc, options);}-var HOST_VALIDATION_RULE_ID = "HOST_VALIDATION_PROFILE", MAX_VALIDATION_ATTRIBUTE_READS = 4000000, MAX_VALIDATION_FINDINGS_PER_CODE = 32, ENDPOINT_BAND = 0.05, GRADIENT_BINS = 16, MIN_AXIS_EXTENT = 0.000001, HOST_VALIDATION_QA_RULE, round2 = (value) => Math.round(value * 1e6) / 1e6, AXIS_INDEX;+var HOST_VALIDATION_RULE_ID = "HOST_VALIDATION_PROFILE", MAX_VALIDATION_ATTRIBUTE_READS = 4000000, MAX_VALIDATION_FINDINGS_PER_CODE = 32, ENDPOINT_BAND = 0.05, GRADIENT_BINS = 16, MIN_AXIS_EXTENT = 0.000001, HOST_VALIDATION_QA_RULE, round3 = (value) => Math.round(value * 1e6) / 1e6, AXIS_INDEX;var init_validation_profile2 = __esm(() => {init_gltf_io();init_delivery_inspect();@@ -24202,6 +24944,7 @@ var init_run = __esm(() => {init_part_connectivity();init_reference_comparison();init_self_intersection();+ init_open_surface_penetration();init_sweep();init_environment2();init_breadth2();@@ -24222,6 +24965,7 @@ var init_run = __esm(() => {...ENVIRONMENT_QA_RULES,...W7_BREADTH_QA_RULES,SELF_INTERSECTION_QA_RULE,+ OPEN_SURFACE_PENETRATION_QA_RULE,SWEEP_QA_RULE,PART_CONNECTIVITY_QA_RULE,REFERENCE_COMPARISON_QA_RULE,@@ -24245,13 +24989,13 @@ var init_run = __esm(() => {});// src/qa/requirements-run.ts-import { Object3D as Object3D15 } from "three";+import { Object3D as Object3D16 } 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"))+ if (!(scene instanceof Object3D16) || !sceneDecisions(context, policy).some((d) => d.ruleId === SELF_INTERSECTION_QA_RULE.id && d.mode !== "off"))return {};try {return { partPenetration: await analyzePartPenetration(scene) };@@ -24292,12 +25036,12 @@ function runRequirementsSceneQa(context, scene, clips, policy = {}, evidence = {};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 scopeObservation = scope?.state === "requested" && scene instanceof Object3D16 && 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) } : {}+ ...effects && scene instanceof Object3D16 && decisions.some((d) => d.ruleId.startsWith("VFX_") && d.mode !== "off") ? { vfxArtifact: analyzeVfxArtifactEvidenceV1(effects, scene, clips) } : {}}};const spatialInput = {@@ -24357,11 +25101,32 @@ function runRequirementsSceneQa(context, scene, clips, policy = {}, evidence = {}continue;}+ if (decision.ruleId === OPEN_SURFACE_PENETRATION_QA_RULE.id) {+ if (!(scene instanceof Object3D16))+ continue;+ const surfaces = analyzeOpenSurfacePenetration(scene);+ executedRules.push(decision.ruleId);+ findings.push(...inspectOpenSurfacePenetration(surfaces));+ Object.assign(geometryMetrics, {+ openSurfaceCoverage: surfaces.truncated || surfaces.skipped.length > 0 ? "partial" : "complete-surface-pairs",+ openSurfaceScope: "Visible static open surfaces sampled at their vertices against visible static closed solids, except alternates on different LOD levels; excludes open-vs-open pairs, motion, and any solid thinner than the sampled surface's facet spacing. Penetration within the contact tolerance is treated as intended contact, and penetration beyond it may still be intentional, as a fitting socketed into a shell is.",+ openSurfaceContactTolerance: surfaces.contactTolerance,+ openSurfaceOpenParts: surfaces.openParts,+ openSurfaceClosedParts: surfaces.closedParts,+ openSurfaceCandidatePairs: surfaces.candidatePairs,+ openSurfacePairsSampled: surfaces.pairsTested,+ openSurfacePairsNotReached: surfaces.pairsNotReached,+ openSurfaceVerticesUnresolved: surfaces.verticesUnresolved,+ openSurfaceLodAlternatePairs: surfaces.pairsLodAlternates,+ openSurfaceSkipped: surfaces.skipped.length+ });+ continue;+ }if (decision.ruleId === ASSET_SCOPE_QA_RULE.id && !scopeObservation)continue;if (decision.ruleId === HOST_VALIDATION_QA_RULE.id)continue;- if (decision.ruleId === PART_CONNECTIVITY_QA_RULE.id && !(scene instanceof Object3D15))+ if (decision.ruleId === PART_CONNECTIVITY_QA_RULE.id && !(scene instanceof Object3D16))continue;executedRules.push(decision.ruleId);if (decision.ruleId === PROP_EXACT_QA_RULE.id) {@@ -24507,6 +25272,7 @@ var init_requirements_run = __esm(() => {init_material();init_prop();init_part_connectivity();+ init_open_surface_penetration();init_sweep();init_self_intersection();init_vehicle2();@@ -24527,6 +25293,7 @@ var init_requirements_run = __esm(() => {PROP_ADVISORY_QA_RULE,PART_CONNECTIVITY_QA_RULE,SELF_INTERSECTION_QA_RULE,+ OPEN_SURFACE_PENETRATION_QA_RULE,SWEEP_QA_RULE,...VEHICLE_QA_RULES,...ARCHITECTURE_QA_RULES,@@ -24542,7 +25309,7 @@ var init_requirements_run = __esm(() => {});// src/qa/skin-integrity.ts-import * as THREE28 from "three";+import * as THREE30 from "three";function validAttribute(a, count, size) {if (!a || a.itemSize !== size || a.count !== count || !Number.isSafeInteger(count) || count < 1)return false;@@ -24589,9 +25356,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 THREE30.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 THREE30.Matrix4().multiplyMatrices(parent, local) : local;worlds.set(n, value);}return worlds.get(node);@@ -24641,7 +25408,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 || ![THREE30.AttachedBindMode, THREE30.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;@@ -24690,7 +25457,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 === THREE30.AttachedBindMode ? meshWorld.clone().invert() : mesh.bindMatrix.clone().invert();const matrices = [];for (let joint = 0;joint < bones.length; joint++) {const boneWorld = world(bones[joint]);@@ -24698,13 +25465,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 THREE30.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 THREE30.Vector3, posed = new THREE30.Vector3, temp = new THREE30.Vector3, box = new THREE30.Box3;for (let vertex = 0;vertex < count; vertex++) {- THREE28.Mesh.prototype.getVertexPosition.call(mesh, vertex, base);+ THREE30.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);@@ -24901,7 +25668,7 @@ var init_material_export = __esm(() => {});// src/community-exporter.ts-import * as THREE29 from "three";+import * as THREE31 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) {@@ -24931,7 +25698,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 THREE31.TextureSource(source.image);textures.set(source, copy);const bytes = source.userData["encoded"];if (bytes?.bytes) {@@ -24940,8 +25707,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 = THREE31.RGBAFormat;+ copy.type = THREE31.UnsignedByteType;})());}return copy;@@ -24958,7 +25725,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 THREE31.Texture)copy[key] = texture(value);}materials.set(source, copy);@@ -24974,15 +25741,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 THREE31.Group;copy.copy(shadow, false);}if (source.isSprite) {const sprite = source;- const geometry = new THREE29.PlaneGeometry(1, 1);+ const geometry = new THREE31.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 THREE31.MeshBasicMaterial({name: sprite.material.name,color: sprite.material.color,opacity: sprite.material.opacity,@@ -24993,8 +25760,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 THREE31.Mesh(geometry, spriteMaterial);+ THREE31.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];@@ -25058,8 +25825,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 THREE31.Texture().copy(map);+ adapted.source = new THREE31.TextureSource(canvas);canvasInputs.set(map, adapted);const direct = directImages.get(map);if (direct)@@ -25068,7 +25835,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 THREE31.Texture && value.flipY && value.image?.data)material[key] = canvasInput(value);}const standard = material;@@ -25090,8 +25857,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 = THREE31.PropertyBinding.parseTrackName(track.name);+ return ["position", "quaternion", "scale", "morphTargetInfluences"].includes(binding.propertyName) && THREE31.PropertyBinding.findNode(copy, binding.nodeName) !== null;} catch {return false;}@@ -25286,7 +26053,7 @@ function applyIndexPolicy(doc, policy) {var init_index_policy = () => {};// src/surface-bake.ts-import * as THREE30 from "three";+import * as THREE32 from "three";function settings(value, label) {if (value === false)return;@@ -25328,13 +26095,13 @@ function drawnMeshes(root) {function weld(mesh) {const position = mesh.geometry.getAttribute("position");const world = [];- const box = new THREE30.Box3;+ const box = new THREE32.Box3;for (let i = 0;i < position.count; i++) {- const point = new THREE30.Vector3().fromBufferAttribute(position, i).applyMatrix4(mesh.matrixWorld);+ const point = new THREE32.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 THREE32.Vector3).length();const tolerance = size > 0 ? size * 0.000001 : 0.000000001;const keys = new Map;const ids = new Int32Array(position.count);@@ -25368,7 +26135,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 THREE32.Vector3().subVectors(b, a).cross(new THREE32.Vector3().subVectors(c, a)).normalize());}const edges = new Map;const neighbours = points.map(() => new Set);@@ -25387,7 +26154,7 @@ function bakeEdge(topology, thresholdDegrees, smoothing) {edges.set(key, list);}}- const threshold = THREE30.MathUtils.degToRad(thresholdDegrees);+ const threshold = THREE32.MathUtils.degToRad(thresholdDegrees);const weights = new Float64Array(points.length);for (const [key, incidences] of edges) {let weight;@@ -25397,10 +26164,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(THREE32.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 THREE32.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))@@ -25562,12 +26329,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 THREE32.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 THREE32.Vector3;for (const mesh of drawnMeshes(occluders)) {if (!drawn(mesh, null))continue;@@ -25631,12 +26398,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 THREE32.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 THREE32.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 THREE32.Vector3).length()};bvhs.set(key, entry);}@@ -25653,27 +26420,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] = THREE32.MathUtils.clamp(welded[topology.ids[i]], 0, 1);+ geometry.setAttribute("_edge", new THREE32.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 THREE32.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 THREE32.Vector3().subVectors(points[triangles[t + 1]], a).cross(new THREE32.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 THREE32.Vector3;+ const bitangent = new THREE32.Vector3;+ const origin = new THREE32.Vector3;+ const direction = new THREE32.Vector3;points.forEach((point, id) => {const normal = normals[id];if (normal.lengthSq() === 0) {@@ -25695,8 +26462,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] = THREE32.MathUtils.clamp(exposure[topology.ids[i]], 0, 1);+ geometry.setAttribute("_cavity", new THREE32.BufferAttribute(values, 1));record._CAVITY = { rays, radius };}geometry.userData = { ...geometry.userData, [SURFACE_BAKE_KEY]: record };@@ -25716,7 +26483,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 = THREE32.MathUtils.clamp((x - edge0) / (edge1 - edge0), 0, 1);return t * t * (3 - 2 * t);};var init_surface_bake = __esm(() => {@@ -25729,318 +26496,6 @@ var init_surface_bake = __esm(() => {});});-// src/geometry.ts-import * as THREE31 from "three";-function finiteArray(values, label, length) {- const result = Array.from(values);- if (length !== undefined && result.length !== length)- throw new Error(`${label}: expected ${length} values, got ${result.length}`);- if (!result.every((n) => Number.isFinite(Math.fround(n))))- throw new AuthoringDiagnosticError("MESH_DATA_NONFINITE", `${label}: all values must be finite Float32 values`);- return result;-}-function meshGeo(data) {- const positions = finiteArray(data.positions, "meshGeo positions");- if (positions.length < 9 || positions.length % 3)- throw new Error("meshGeo positions: need at least three xyz vertices");- const count = positions.length / 3;- const geometry = new 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)- throw new Error("meshGeo indices: need complete triangles");- if (!indices.every((i) => Number.isInteger(i) && i >= 0 && i < count))- throw new Error("meshGeo index out of bounds or not an integer");- geometry.setIndex(indices);- } else if (count % 3)- throw new Error("meshGeo: non-indexed positions must form complete triangles");- if (data.normals) {- const normals = finiteArray(data.normals, "meshGeo normals", count * 3);- geometry.setAttribute("normal", new 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");- geometry.normalizeNormals();- } else- geometry.computeVertexNormals();- if (data.uvs)- 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 THREE31.Float32BufferAttribute(tangents, 4));- }- geometry.computeBoundingBox();- geometry.computeBoundingSphere();- return geometry;-}-function boundsScale(bounds) {- 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 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 THREE31.Vector3 : bounds.min,- scale: boundsScale(bounds)- };-}-function positionTolerance(scale, supplied, relative) {- if (supplied === undefined)- return scale * relative;- if (!Number.isFinite(supplied) || supplied <= 0)- throw new Error("Geometry tolerance must be positive and finite");- if (scale / supplied > Number.MAX_SAFE_INTEGER)- throw new Error("Geometry tolerance is too small to resolve the position extent safely");- return supplied;-}-function positionKey(point, origin, tolerance) {- if (tolerance === 0)- return point.toArray().join(",");- return point.clone().sub(origin).toArray().map((x) => Math.round(x / tolerance)).join(",");-}-function geometryDiagnostics(geometry, tolerance) {- const p = geometry.getAttribute("position");- if (p?.itemSize !== 3)- throw new Error("geometryDiagnostics requires xyz positions");- const frame = positionFrame(p);- const distance = positionTolerance(frame.scale, tolerance, 0.000001);- const result = {- tolerance: distance,- toleranceMode: tolerance === undefined ? "relative" : "absolute",- positionScale: frame.scale,- vertices: p.count,- triangles: 0,- boundaryEdges: 0,- nonManifoldEdges: 0,- orientationConflicts: 0,- degenerateTriangles: 0,- collapsedByToleranceTriangles: 0,- invalidIndices: 0,- nonFiniteVertices: 0,- 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 ids = [];- const points = new Map;- const finite = [];- 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);- if (!finite[i])- result.nonFiniteVertices++;- const key = finite[i] ? positionKey(point, frame.origin, distance) : `invalid:${i}`;- if (!points.has(key))- points.set(key, points.size);- ids.push(points.get(key));- }- const indices = geometry.index ? Array.from(geometry.index.array) : Array.from({ length: p.count }, (_, i) => i);- const edges = new Map;- const a = new 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);- if (triangle.length !== 3 || triangle.some((n) => !Number.isInteger(n) || n < 0 || n >= p.count)) {- result.invalidIndices++;- continue;- }- const [ia, ib, ic] = triangle;- if (!finite[ia] || !finite[ib] || !finite[ic])- continue;- pa.fromBufferAttribute(p, ia);- pb.fromBufferAttribute(p, ib);- pc.fromBufferAttribute(p, ic);- signedVolume += pa.dot(pb.cross(pc)) / 6;- a.fromBufferAttribute(p, ia);- b.fromBufferAttribute(p, ib);- c.fromBufferAttribute(p, ic);- const scale = frame.scale || 1;- b.sub(a).divideScalar(scale);- c.sub(a).divideScalar(scale);- if (b.cross(c).length() <= (distance / scale) ** 2)- result.degenerateTriangles++;- if (ids[ia] === ids[ib] || ids[ib] === ids[ic] || ids[ic] === ids[ia]) {- result.collapsedByToleranceTriangles++;- continue;- }- for (const [start, end] of [- [ia, ib],- [ib, ic],- [ic, ia]- ]) {- const u = ids[start], v = ids[end];- const key = u < v ? `${u}:${v}` : `${v}:${u}`;- const edge = edges.get(key) ?? { count: 0, direction: 0 };- edge.count++;- edge.direction += u < v ? 1 : -1;- edges.set(key, edge);- }- }- for (const edge of edges.values()) {- if (edge.count === 1)- result.boundaryEdges++;- else if (edge.count > 2)- result.nonManifoldEdges++;- else if (edge.direction !== 0)- result.orientationConflicts++;- }- const volumeFloor = (frame.scale || 1) ** 3 * 0.000000000001;- result.solid = {- closed: result.boundaryEdges === 0 && edges.size > 0,- manifold: result.nonManifoldEdges === 0,- orientation: result.orientationConflicts > 0 || Math.abs(signedVolume) <= volumeFloor ? "mixed" : signedVolume > 0 ? "outward" : "inward",- signedVolume: Object.is(signedVolume, -0) ? 0 : signedVolume- };- return result;-}-function parametricSurface(sample, options = {}) {- const {- u = [0, 1],- v = [0, 1],- uSegments: nu = 24,- vSegments: nv = 24,- periodicU = false,- periodicV = false,- orientation = "uv"- } = options;- for (const [name, n] of [- ["uSegments", nu],- ["vSegments", nv]- ])- if (!Number.isSafeInteger(n) || n < 1)- throw new Error(`parametricSurface ${name} must be a positive integer`);- const sampleCount = (nu + 1) * (nv + 1);- if (!Number.isSafeInteger(sampleCount) || sampleCount > GEOMETRY_ALLOCATION_LIMITS.parametricSamples)- throw new RangeError(`parametricSurface sample budget exceeded: requested ${sampleCount}, limit ${GEOMETRY_ALLOCATION_LIMITS.parametricSamples}. Reduce uSegments/vSegments or split the surface.`);- for (const [name, range] of [- ["u", u],- ["v", v]- ])- if (range.length !== 2 || !range.every(Number.isFinite) || range[0] === range[1] || !Number.isFinite(range[1] - range[0]))- throw new Error(`parametricSurface ${name} must be a finite nonzero domain`);- if (orientation !== "uv" && orientation !== "vu")- throw new Error("parametricSurface orientation must be uv or vu");- const positions = [], uvs = [], indices = [];- 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);- if (point.length !== 3 || !point.every(Number.isFinite))- throw new Error(`parametricSurface: sample (${i},${j}) must return three finite coordinates`);- positions.push(...point);- sampledBounds.expandByPoint(sampledPoint.set(...point));- uvs.push(i / nu, j / nv);- }- const groups = Array.from({ length: (nu + 1) * (nv + 1) }, (_, i) => i);- const seamScale = boundsScale(sampledBounds);- const find = (i) => {- while (groups[i] !== i)- i = groups[i];- return i;- };- const join = (a, b, _label) => {- const pa = positions.slice(a * 3, a * 3 + 3), pb = positions.slice(b * 3, b * 3 + 3);- if (Math.hypot(...pa.map((x, k) => x - pb[k])) > seamScale * 0.000001)- throw new AuthoringDiagnosticError("PARAMETRIC_PERIODIC_ENDPOINT");- groups[find(b)] = find(a);- for (let k = 0;k < 3; k++)- positions[b * 3 + k] = positions[a * 3 + k];- };- if (periodicU)- for (let j = 0;j <= nv; j++)- join(j * (nu + 1), j * (nu + 1) + nu, "periodicU");- if (periodicV)- for (let i = 0;i <= nu; i++)- join(i, nv * (nu + 1) + i, "periodicV");- for (let j = 0;j < nv; j++)- for (let i = 0;i < nu; i++) {- const a = j * (nu + 1) + i, b = a + 1, c = a + nu + 1, d = c + 1;- indices.push(...orientation === "uv" ? [a, b, c, b, d, c] : [a, c, b, b, c, d]);- }- const out = meshGeo({ positions, indices, uvs });- if (periodicU || periodicV) {- const normal = out.getAttribute("normal");- const sums = new Map;- for (let i = 0;i < normal.count; i++) {- const id = find(i);- const sum = sums.get(id) ?? new THREE31.Vector3;- sum.add(new THREE31.Vector3().fromBufferAttribute(normal, i));- sums.set(id, sum);- }- for (let i = 0;i < normal.count; i++) {- const n = sums.get(find(i)).clone().normalize();- normal.setXYZ(i, n.x, n.y, n.z);- }- }- return out;-}-function creaseNormals(geometry, options = {}) {- const angle = options.angle ?? 60;- if (!Number.isFinite(angle) || angle < 0 || angle > 180)- throw new Error("creaseNormals angle must be between 0 and 180 degrees");- const out = geometry.index ? geometry.toNonIndexed() : geometry.clone();- const position = out.getAttribute("position");- if (position?.itemSize !== 3 || position.count % 3 !== 0)- throw new Error("creaseNormals requires complete xyz triangles");- const frame = positionFrame(position);- const tolerance = positionTolerance(frame.scale, options.tolerance, 0.00000001);- const scale = frame.scale || 1;- const adjacent = new Map;- 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 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);- 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);- keys.push(key);- const neighbors = adjacent.get(key) ?? new Set;- neighbors.add(i / 3);- adjacent.set(key, neighbors);- }- }- const normals = new Float32Array(position.count * 3);- const threshold = Math.cos(THREE31.MathUtils.degToRad(angle));- for (let i = 0;i < position.count; i++) {- 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 THREE31.BufferAttribute(normals, 3));- out.deleteAttribute("tangent");- out.computeBoundingBox();- out.computeBoundingSphere();- return out;-}-var init_geometry = __esm(() => {- init_geometry_budget();- init_authoring_diagnostic();-});-// src/require-solid.tsfunction requireSolid(part) {if (part?.isObject3D !== true)@@ -26628,16 +27083,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 };@@ -26645,7 +27100,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;@@ -26692,7 +27147,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;@@ -26702,7 +27157,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;@@ -26718,7 +27173,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.");@@ -26734,21 +27189,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 (!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 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);@@ -26789,11 +27244,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);@@ -26815,7 +27270,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,@@ -26825,7 +27280,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 });@@ -26860,7 +27315,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: {@@ -26899,7 +27354,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))@@ -26932,16 +27387,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.");}}@@ -27029,9 +27484,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")@@ -27058,7 +27513,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));@@ -27099,7 +27554,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 = [];@@ -27112,7 +27567,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());@@ -27177,7 +27632,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@@ -27718,7 +28173,7 @@ var init_budget = __esm(() => {});// src/animation-cubic.ts-import * as THREE34 from "three";+import * as THREE35 from "three";function useCubicSpline(track) {track.createInterpolant = cubicSplineFactory;return track;@@ -27726,7 +28181,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;@@ -27754,7 +28209,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`);@@ -27819,17 +28274,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,@@ -27839,13 +28294,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);@@ -27863,17 +28318,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)], [@@ -27943,7 +28398,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);@@ -27962,7 +28417,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);@@ -27970,7 +28425,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@@ -27979,7 +28434,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"),@@ -27995,7 +28450,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);@@ -28015,7 +28470,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}`], [@@ -28027,8 +28482,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);@@ -28045,7 +28500,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);@@ -28068,7 +28523,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 = {@@ -28086,7 +28541,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}`))));@@ -28201,13 +28656,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;@@ -28224,7 +28679,7 @@ var init_architecture2 = __esm(() => {});// src/gears.ts-import * as THREE36 from "three";+import * as THREE37 from "three";function gearGeo(opts = {}) {const {teeth = 12,@@ -28323,8 +28778,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();@@ -28409,8 +28864,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();@@ -28422,7 +28877,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) {@@ -28456,9 +28911,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 = {}) {@@ -28471,12 +28926,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);}@@ -28515,7 +28970,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();@@ -28554,13 +29009,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();@@ -28568,17 +29023,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 });@@ -28610,9 +29065,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";@@ -28636,13 +29091,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) {@@ -28650,7 +29105,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();@@ -28659,15 +29114,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.`);}@@ -28683,13 +29138,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);}@@ -28724,8 +29179,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))@@ -28755,13 +29210,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++) {@@ -28770,7 +29225,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;@@ -28784,7 +29239,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);@@ -28849,9 +29304,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");@@ -28882,15 +29337,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;@@ -28906,9 +29361,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();@@ -28926,12 +29381,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}`);}@@ -28944,20 +29399,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(",");@@ -28980,7 +29435,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;@@ -29001,17 +29456,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");@@ -29038,7 +29493,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;@@ -29061,7 +29516,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");@@ -29095,31 +29550,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(() => {@@ -29127,7 +29582,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.`);@@ -29135,9 +29590,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));@@ -29160,7 +29615,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)@@ -29174,11 +29629,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]));@@ -29238,13 +29693,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@@ -29257,7 +29712,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);};@@ -29295,8 +29750,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 ? [] : [{@@ -29319,8 +29774,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;@@ -29361,7 +29816,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");@@ -29378,7 +29833,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]));}@@ -29388,7 +29843,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]));});@@ -29413,7 +29868,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;@@ -29435,7 +29890,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;}@@ -29720,14 +30175,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@@ -29736,7 +30191,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();@@ -29791,7 +30246,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;@@ -29821,10 +30276,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;@@ -29841,11 +30296,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))@@ -29925,7 +30380,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))))@@ -30068,11 +30523,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) {@@ -30103,7 +30558,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);@@ -30162,7 +30617,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;@@ -30571,7 +31026,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.`);@@ -30603,8 +31058,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();@@ -30658,8 +31113,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();@@ -30667,7 +31122,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;@@ -30781,7 +31236,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.");@@ -30810,7 +31265,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;@@ -30827,13 +31282,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 = {@@ -30891,7 +31346,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))@@ -31116,7 +31571,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)@@ -31151,7 +31606,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))@@ -31263,7 +31718,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 () => {@@ -31295,7 +31750,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;@@ -31305,8 +31760,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);@@ -31341,11 +31796,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)))@@ -31381,7 +31836,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.");@@ -31422,15 +31877,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);@@ -31445,8 +31900,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();@@ -31502,7 +31957,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;@@ -31523,17 +31978,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)@@ -31565,16 +32020,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);@@ -31597,7 +32052,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);@@ -31616,7 +32071,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);@@ -31631,20 +32086,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);@@ -31661,7 +32116,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(",")}]).`);@@ -31669,7 +32124,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;@@ -31691,7 +32146,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);@@ -31699,14 +32154,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);@@ -31720,7 +32175,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;@@ -31736,12 +32191,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);@@ -31768,9 +32223,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;@@ -31785,7 +32240,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;@@ -31881,8 +32336,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;@@ -31913,17 +32368,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;@@ -31932,11 +32387,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];@@ -31952,7 +32407,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());@@ -31987,8 +32442,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)@@ -31996,7 +32451,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.");@@ -32006,19 +32461,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: [@@ -32058,7 +32513,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;@@ -32089,7 +32544,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, {@@ -32143,7 +32598,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;@@ -32173,7 +32628,7 @@ function requireColor(color, fn) {}function gameMaterial(color, options = {}) {requireColor(color, "gameMaterial");- const material = new THREE49.MeshStandardMaterial({+ const material = new THREE50.MeshStandardMaterial({color,metalness: options.metalness ?? 0,roughness: options.roughness ?? 0.8,@@ -32187,7 +32642,7 @@ function gameMaterial(color, options = {}) {}function basicMaterial(color, options = {}) {requireColor(color, "basicMaterial");- const material = new THREE49.MeshBasicMaterial({+ const material = new THREE50.MeshBasicMaterial({color,transparent: options.transparent ?? false,opacity: options.opacity ?? 1@@ -32198,13 +32653,13 @@ function basicMaterial(color, options = {}) {}function glassMaterial(color, options = {}) {requireColor(color, "glassMaterial");- const material = new THREE49.MeshStandardMaterial({+ const material = 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});if (options.name !== undefined)material.name = assertMaterialName(options.name, "glassMaterial");@@ -32212,7 +32667,7 @@ function glassMaterial(color, options = {}) {}function lambertMaterial(color, options = {}) {requireColor(color, "lambertMaterial");- const material = new THREE49.MeshLambertMaterial({+ const material = new THREE50.MeshLambertMaterial({color,flatShading: options.flatShading ?? true,emissive: options.emissive ?? 0@@ -32225,12 +32680,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) {@@ -32284,15 +32739,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);@@ -32302,7 +32757,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);@@ -32312,7 +32767,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())@@ -32325,7 +32780,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.");@@ -32339,12 +32794,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);@@ -32367,7 +32822,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;@@ -32444,12 +32899,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)@@ -32742,7 +33197,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};@@ -32871,7 +33326,7 @@ import {PropertyType as PropertyType4} 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]);@@ -32989,10 +33444,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 = [];@@ -33016,7 +33471,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;@@ -33030,9 +33485,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;@@ -33353,7 +33808,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 === 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 THREE51.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);@@ -34703,7 +35158,7 @@ var init_kit = __esm(() => {// src/texture-bake.tsimport { createHash as createHash8 } from "node:crypto";-import * as THREE51 from "three";+import * as THREE52 from "three";function readPixels(texture) {const image = texture.image;if (!image)@@ -34830,7 +35285,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)@@ -34913,10 +35368,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]);@@ -34936,7 +35391,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;@@ -35174,7 +35629,7 @@ import {KHRTextureBasisu as KHRTextureBasisu2} from "@gltf-transform/extensions";import { cloneDocument, dedup, prune, quantize, reorder } from "@gltf-transform/functions";-import * as THREE52 from "three";+import * as THREE53 from "three";function meshSignature(mesh, ids) {const id = (property) => {if (!property)@@ -35322,8 +35777,8 @@ function isCoreMaterialUse(parent) {return parent.propertyType === PropertyType5.MATERIAL;}function decomposeDelta(before, after) {- 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;+ const delta = new THREE53.Matrix4().fromArray(before).invert().multiply(new THREE53.Matrix4().fromArray(after));+ const position = new THREE53.Vector3, quaternion = new THREE53.Quaternion, scale = new THREE53.Vector3;delta.decompose(position, quaternion, scale);return {scale: scale.x,@@ -35351,12 +35806,12 @@ function positionGridSteps(doc, bits) {if (level.propertyType === PropertyType5.NODE)lodBase.set(level, node);const world = (node) => {- const matrix = new THREE52.Matrix4().fromArray(node.getWorldMatrix());+ const matrix = new THREE53.Matrix4().fromArray(node.getWorldMatrix());let top = node;while (top.getParentNode())top = top.getParentNode();const placed = lodBase.get(top)?.getParentNode();- return placed ? new THREE52.Matrix4().fromArray(placed.getWorldMatrix()).multiply(matrix) : matrix;+ return placed ? new THREE53.Matrix4().fromArray(placed.getWorldMatrix()).multiply(matrix) : matrix;};const halfExtent = (mesh) => {const min = [Infinity, Infinity, Infinity];@@ -35504,7 +35959,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 THREE52.Matrix4().identity().toArray() : original;+ const reference = moved ? new THREE53.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))@@ -35700,7 +36155,7 @@ var init_exporter_node = __esm(() => {});// src/views/character.ts-import * as THREE53 from "three";+import * as THREE54 from "three";function rounded(value) {const result = Math.round(value * 1e9) / 1e9;return Object.is(result, -0) ? 0 : result;@@ -35742,9 +36197,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 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 position = new THREE54.Vector3().setFromMatrixPosition(relative);+ const forward = new THREE54.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);+ const bend = new THREE54.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);const chainId = chainIdFor(joint.descriptor, descriptorByRole);return {role: joint.descriptor.role,@@ -36726,7 +37181,7 @@ import {PropertyBinding as PropertyBinding3,VectorKeyframeTrack as VectorKeyframeTrack2,Quaternion as Quaternion20,- Vector3 as Vector340,+ Vector3 as Vector341,InterpolateDiscrete as InterpolateDiscrete2,InterpolateLinear as InterpolateLinear2} from "three";@@ -36910,7 +37365,7 @@ function instanceMatrices(node) {translations?.getElement(index, translation);rotations?.getElement(index, rotation);scales?.getElement(index, scale);- const local = new Matrix418().compose(new Vector340(translations ? translation[0] : 0, translations ? translation[1] : 0, translations ? translation[2] : 0), new Quaternion20(rotations ? rotation[0] : 0, rotations ? rotation[1] : 0, rotations ? rotation[2] : 0, rotations ? rotation[3] : 1).normalize(), new Vector340(scales ? scale[0] : 1, scales ? scale[1] : 1, scales ? scale[2] : 1));+ const local = new Matrix418().compose(new Vector341(translations ? translation[0] : 0, translations ? translation[1] : 0, translations ? translation[2] : 0), new Quaternion20(rotations ? rotation[0] : 0, rotations ? rotation[1] : 0, rotations ? rotation[2] : 0, rotations ? rotation[3] : 1).normalize(), new Vector341(scales ? scale[0] : 1, scales ? scale[1] : 1, scales ? scale[2] : 1));matrices.push(world.clone().multiply(local));}return { matrices, count };@@ -37017,7 +37472,7 @@ function localInstanceMatrices(node) {translations?.getElement(index, translation);rotations?.getElement(index, rotation);scales?.getElement(index, scale);- return new Matrix418().compose(new Vector340(...translations ? translation.slice(0, 3) : [0, 0, 0]), new Quaternion20(...rotations ? rotation.slice(0, 4) : [0, 0, 0, 1]).normalize(), new Vector340(...scales ? scale.slice(0, 3) : [1, 1, 1]));+ return new Matrix418().compose(new Vector341(...translations ? translation.slice(0, 3) : [0, 0, 0]), new Quaternion20(...rotations ? rotation.slice(0, 4) : [0, 0, 0, 1]).normalize(), new Vector341(...scales ? scale.slice(0, 3) : [1, 1, 1]));});}async function loadGlbReviewScene(bytes) {@@ -37391,7 +37846,7 @@ var init_renderer_id = __esm(() => {});// src/views/scene-raster.ts-import * as THREE54 from "three";+import * as THREE55 from "three";var DEG2;var init_scene_raster = __esm(() => {init_evaluator();@@ -37403,18 +37858,18 @@ var init_scene_raster = __esm(() => {});// src/views/vehicle.ts-import * as THREE55 from "three";+import * as THREE56 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 THREE55.Box3;+ const bounds = new THREE56.Box3;let found = false;root.traverse((node) => {if (!hasRole2(node, "chassis"))return;node.traverse((part) => {- if (!(part instanceof THREE55.Mesh) || !(part.geometry instanceof THREE55.BufferGeometry))+ if (!(part instanceof THREE56.Mesh) || !(part.geometry instanceof THREE56.BufferGeometry))return;part.geometry.computeBoundingBox();const box = part.geometry.boundingBox;@@ -37424,7 +37879,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 THREE55.Vector3(x, y, z).applyMatrix4(matrix));+ bounds.expandByPoint(new THREE56.Vector3(x, y, z).applyMatrix4(matrix));found = true;}});@@ -37492,33 +37947,33 @@ function tagDiagnostic(node, role) {stampSemanticMetadataV1(node, { roles: [role] });}function rod(name, start, end, radius, color, role) {- const from = new THREE55.Vector3(...start);- const to = new THREE55.Vector3(...end);+ const from = new THREE56.Vector3(...start);+ const to = new THREE56.Vector3(...end);const direction = to.clone().sub(from);const length = direction.length();- 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 }));+ const geometry = length > 0.000000001 ? new THREE56.CylinderGeometry(radius, radius, length, 8) : new THREE56.SphereGeometry(radius, 8, 6);+ const result = new THREE56.Mesh(geometry, new THREE56.MeshBasicMaterial({ color }));result.name = name;result.position.copy(from).add(to).multiplyScalar(0.5);if (length > 0.000000001) {- result.quaternion.setFromUnitVectors(new THREE55.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));+ result.quaternion.setFromUnitVectors(new THREE56.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));}tagDiagnostic(result, role);return result;}function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnostics(root)) {- const overlay = new THREE55.Group;+ const overlay = new THREE56.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 THREE55.Group;+ const arrow = new THREE56.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 THREE55.Mesh(new THREE55.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE55.MeshBasicMaterial({ color: 16724804 }));+ const arrowHead = new THREE56.Mesh(new THREE56.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE56.MeshBasicMaterial({ color: 16724804 }));arrowHead.name = "Diagnostic_Forward_Head";arrowHead.position.set(descriptor.forwardArrow.end[0] - 0.12, 0, 0);- arrowHead.quaternion.setFromUnitVectors(new THREE55.Vector3(0, 1, 0), new THREE55.Vector3(1, 0, 0));+ arrowHead.quaternion.setFromUnitVectors(new THREE56.Vector3(0, 1, 0), new THREE56.Vector3(1, 0, 0));tagDiagnostic(arrowHead, "diagnostic.vehicle.forward");arrow.add(arrowHead);overlay.add(arrow);@@ -37526,18 +37981,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 THREE55.Mesh(new THREE55.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE55.MeshBasicMaterial({ color: 16763955 }));+ const ring = new THREE56.Mesh(new THREE56.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE56.MeshBasicMaterial({ color: 16763955 }));ring.name = `Diagnostic_Wheel_${wheel.id}`;ring.position.set(...wheel.center);- const axle = new THREE55.Vector3(...wheel.axle);+ const axle = new THREE56.Vector3(...wheel.axle);if (axle.lengthSq() > 0.000000000001) {- ring.quaternion.setFromUnitVectors(new THREE55.Vector3(0, 0, 1), axle.normalize());+ ring.quaternion.setFromUnitVectors(new THREE56.Vector3(0, 0, 1), axle.normalize());}tagDiagnostic(ring, `diagnostic.vehicle.wheel.${wheel.id}`);overlay.add(ring);}if (descriptor.chassisBox) {- const chassis = new THREE55.Group;+ const chassis = new THREE56.Group;chassis.name = "Diagnostic_ChassisBox";tagDiagnostic(chassis, "diagnostic.vehicle.chassis");const { min, max } = descriptor.chassisBox;@@ -37571,7 +38026,7 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnooverlay.add(chassis);}if (descriptor.supportPlaneY !== undefined) {- const plane = new THREE55.Group;+ const plane = new THREE56.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;@@ -38169,7 +38624,7 @@ var init_views = __esm(() => {});// src/views/character-capture.ts-import * as THREE56 from "three";+import * as THREE57 from "three";function drawLine2(rgb, width, height, from, to, color) {let x0 = Math.round(from[0]);let y0 = Math.round(from[1]);@@ -38206,22 +38661,22 @@ function drawCross(rgb, width, height, point, color, radius = 3) {}function projector(root, cameraId, size) {root.updateMatrixWorld(true);- const bounds = new THREE56.Box3().setFromObject(root);+ const bounds = new THREE57.Box3().setFromObject(root);if (bounds.isEmpty())- 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();+ bounds.set(new THREE57.Vector3(-0.5, 0, -0.5), new THREE57.Vector3(0.5, 1, 0.5));+ const center = bounds.getCenter(new THREE57.Vector3);+ const camera = cameraId === "front" ? new THREE57.Vector3(1, 0, 0) : new THREE57.Vector3(0, 0, 1);+ const upHint = new THREE57.Vector3(0, 1, 0);+ const xAxis = new THREE57.Vector3().crossVectors(upHint, camera).normalize();+ const yAxis = new THREE57.Vector3().crossVectors(camera, xAxis).normalize();let extent = 0.000001;for (let corner = 0;corner < 8; corner++) {- 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);+ const point = new THREE57.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 THREE56.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);+ const world = new THREE57.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);return [size / 2 + world.dot(xAxis) * scale, size / 2 - world.dot(yAxis) * scale];};}@@ -38347,7 +38802,7 @@ var init_character_capture = __esm(() => {});// src/render.ts-import * as THREE57 from "three";+import * as THREE58 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";@@ -38577,7 +39032,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache, authorExtras, atlas)} else if (stdMat.transparent) {mat.setAlphaMode("BLEND");}- if (stdMat.side === THREE57.DoubleSide) {+ if (stdMat.side === THREE58.DoubleSide) {mat.setDoubleSided(true);}if (stdMat.map) {@@ -38654,7 +39109,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache, authorExtras, atlas)} else if (common.transparent || (common.opacity ?? 1) < 1) {mat.setAlphaMode("BLEND");}- if (threeMat.side === THREE57.DoubleSide)+ if (threeMat.side === THREE58.DoubleSide)mat.setDoubleSided(true);if (common.map && !mat.getBaseColorTexture()) {const texture = bridgeTexture(doc, common.map, textureCache);@@ -38817,7 +39272,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 THREE57.PlaneGeometry(1, 1);+ const geometry = new THREE58.PlaneGeometry(1, 1);if (centerX !== 0.5 || centerY !== 0.5) {geometry.translate(0.5 - centerX, 0.5 - centerY, 0);}@@ -38841,9 +39296,9 @@ function animationInterpolation(track) {if (isCubicSplineTrack(track))return "CUBICSPLINE";const mode = track.getInterpolation();- if (mode === THREE57.InterpolateDiscrete)+ if (mode === THREE58.InterpolateDiscrete)return "STEP";- if (mode === THREE57.InterpolateLinear)+ if (mode === THREE58.InterpolateLinear)return "LINEAR";throw new Error(`Unsupported animation interpolation on ${track.name}; use LINEAR, STEP or CUBICSPLINE.`);}@@ -39407,8 +39862,8 @@ function collectMeshStats(root) {if (!Number.isFinite(box.min.x) || !Number.isFinite(box.max.x)) {return;}- const center = new THREE57.Vector3;- const size = new THREE57.Vector3;+ const center = new THREE58.Vector3;+ const size = new THREE58.Vector3;box.getCenter(center);box.getSize(size);out.push({@@ -39424,7 +39879,7 @@ function collectMeshStats(root) {return out;}function minimalGapVector(a, b) {- const v = new THREE57.Vector3;+ const v = new THREE58.Vector3;for (const axis of ["x", "y", "z"]) {if (a.min[axis] > b.max[axis])v[axis] = b.max[axis] - a.min[axis];@@ -39442,10 +39897,10 @@ function inspectSceneStructure(root, opts = {}) {return warnings;const cat = opts.category?.toLowerCase();if (cat === "vehicle" || cat === "weapon" || cat === "boat" || cat === "aircraft") {- const all = new THREE57.Box3;+ const all = new THREE58.Box3;for (const m of meshes)all.union(m.box);- const size = new THREE57.Vector3;+ const size = new THREE58.Vector3;all.getSize(size);if (cat === "aircraft") {if (size.y > size.x * 1.2) {@@ -39570,18 +40025,18 @@ var init_render = __esm(() => {engineIO = createGltfIO;ACCESSOR_TYPES = [TYPE_SCALAR, TYPE_VEC2, TYPE_VEC3, TYPE_VEC4];GLTF_MIN_FILTER = {- [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 };+ [THREE58.NearestFilter]: 9728,+ [THREE58.LinearFilter]: 9729,+ [THREE58.NearestMipmapNearestFilter]: 9984,+ [THREE58.LinearMipmapNearestFilter]: 9985,+ [THREE58.NearestMipmapLinearFilter]: 9986,+ [THREE58.LinearMipmapLinearFilter]: 9987+ };+ GLTF_MAG_FILTER = { [THREE58.NearestFilter]: 9728, [THREE58.LinearFilter]: 9729 };GLTF_WRAP = {- [THREE57.ClampToEdgeWrapping]: 33071,- [THREE57.MirroredRepeatWrapping]: 33648,- [THREE57.RepeatWrapping]: 10497+ [THREE58.ClampToEdgeWrapping]: 33071,+ [THREE58.MirroredRepeatWrapping]: 33648,+ [THREE58.RepeatWrapping]: 10497};REVIEW_CLIP_LIMITS2 = {clips: 32,@@ -40163,12 +40618,12 @@ var exports_part_placement = {};__export(exports_part_placement, {createPartPlacementReader: () => createPartPlacementReader});-import * as THREE58 from "three";+import * as THREE59 from "three";function createPartPlacementReader(root) {const bounds = createPartBoundsReader(root);- const position = new THREE58.Vector3;- const quaternion = new THREE58.Quaternion;- const scale = new THREE58.Vector3;+ const position = new THREE59.Vector3;+ const quaternion = new THREE59.Quaternion;+ const scale = new THREE59.Vector3;return (node) => {node.matrixWorld.decompose(position, quaternion, scale);const box = bounds(node);@@ -40181,10 +40636,10 @@ function createPartPlacementReader(root) {};};}-var round3 = (value) => {+var round4 = (value) => {const rounded = Math.round(value * 1e6) / 1e6;return rounded === 0 ? 0 : rounded;-}, rounded2 = (values) => values.map(round3);+}, rounded2 = (values) => values.map(round4);var init_part_placement = __esm(() => {init_raster();});@@ -40319,13 +40774,13 @@ var init_inspect = __esm(() => {});// src/views/measurement.ts-import { Box3 as Box326, Vector3 as Vector345 } from "three";+import { Box3 as Box327, Vector3 as Vector346 } from "three";function describeSubjectFrame(root, subject) {const selected = selectCameraSubject(root, subject);selected.node.updateWorldMatrix(true, true);const matrix = selected.node.matrixWorld;- const bounds = new Box326().setFromObject(selected.node);- const local = new Box326;+ const bounds = new Box327().setFromObject(selected.node);+ const local = new Box327;const invertible = matrix.determinant() !== 0;const inverse = matrix.clone().invert();selected.node.traverse((node) => {@@ -40336,10 +40791,10 @@ function describeSubjectFrame(root, subject) {if (!attr)return;for (let i = 0;i < attr.count; i++)- local.expandByPoint(new Vector345().fromBufferAttribute(attr, i).applyMatrix4(mesh.matrixWorld).applyMatrix4(inverse));+ local.expandByPoint(new Vector346().fromBufferAttribute(attr, i).applyMatrix4(mesh.matrixWorld).applyMatrix4(inverse));});const box = (b) => b.isEmpty() ? null : { min: b.min.toArray(), max: b.max.toArray() };- const axis = (i) => new Vector345().setFromMatrixColumn(matrix, i).normalize().toArray();+ const axis = (i) => new Vector346().setFromMatrixColumn(matrix, i).normalize().toArray();return {path: selected.path,name: selected.name,@@ -40349,7 +40804,7 @@ function describeSubjectFrame(root, subject) {invertible,worldMatrix: matrix.toArray(),axes: { frame: "world", x: axis(0), y: axis(1), z: axis(2) },- origin: new Vector345().setFromMatrixPosition(matrix).toArray()+ origin: new Vector346().setFromMatrixPosition(matrix).toArray()};}function measureAttachment(root, input) {@@ -40362,7 +40817,7 @@ function measureAttachment(root, input) {return {path: selected.path,local: [...local],- world: new Vector345(...local).applyMatrix4(selected.node.matrixWorld).toArray()+ world: new Vector346(...local).applyMatrix4(selected.node.matrixWorld).toArray()};};const from = endpoint(input.from), to = endpoint(input.to);@@ -40372,7 +40827,7 @@ function measureAttachment(root, input) {method: "straight-line anchor distance",from,to,- distance: new Vector345(...from.world).distanceTo(new Vector345(...to.world))+ distance: new Vector346(...from.world).distanceTo(new Vector346(...to.world))};}var init_measurement = __esm(() => {@@ -40384,7 +40839,7 @@ import {PropertyType as PropertyType6} from "@gltf-transform/core";import { ALL_EXTENSIONS as ALL_EXTENSIONS2 } from "@gltf-transform/extensions";-import { Box3 as Box327, Matrix4 as Matrix419, Quaternion as Quaternion23, Vector3 as Vector346 } from "three";+import { Box3 as Box328, Matrix4 as Matrix419, Quaternion as Quaternion23, Vector3 as Vector347 } from "three";async function accessorFingerprint(accessor) {const array = accessor?.getArray();if (!accessor || !array)@@ -40403,7 +40858,7 @@ function bounds(box) {return box.isEmpty() ? null : {min: box.min.toArray(),max: box.max.toArray(),- size: box.getSize(new Vector346).toArray()+ size: box.getSize(new Vector347).toArray()};}async function digest3(bytes) {@@ -40419,7 +40874,7 @@ function placements(node) {const rotation = instances.getAttribute("ROTATION");const scale = instances.getAttribute("SCALE");const count = translation?.getCount() ?? rotation?.getCount() ?? scale?.getCount() ?? 1;- return Array.from({ length: count }, (_, i) => world.clone().multiply(new Matrix419().compose(new Vector346().fromArray(translation?.getElement(i, []) ?? [0, 0, 0]), new Quaternion23().fromArray(rotation?.getElement(i, []) ?? [0, 0, 0, 1]), new Vector346().fromArray(scale?.getElement(i, []) ?? [1, 1, 1]))));+ return Array.from({ length: count }, (_, i) => world.clone().multiply(new Matrix419().compose(new Vector347().fromArray(translation?.getElement(i, []) ?? [0, 0, 0]), new Quaternion23().fromArray(rotation?.getElement(i, []) ?? [0, 0, 0, 1]), new Vector347().fromArray(scale?.getElement(i, []) ?? [1, 1, 1]))));}function triangleCorners(mode, count) {const corners = [];@@ -40486,7 +40941,7 @@ async function drawnGeometryDigests(doc) {}const data = new Float32Array(triangles * RECORD);const others = [];- const point = new Vector346;+ const point = new Vector347;const element = [0, 0, 0];const texcoord = [0, 0];const corner = new Float32Array(15);@@ -40569,7 +41024,7 @@ async function revisionTotals(doc) {const { vertices, geometry, uv } = await drawnGeometryDigests(doc);const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];const drawnBounds = scene ? drawnSceneBounds(scene) : null;- const box = drawnBounds && [...drawnBounds.min, ...drawnBounds.max].every(Number.isFinite) ? new Box327(new Vector346(...drawnBounds.min), new Vector346(...drawnBounds.max)) : new Box327;+ const box = drawnBounds && [...drawnBounds.min, ...drawnBounds.max].every(Number.isFinite) ? new Box328(new Vector347(...drawnBounds.min), new Vector347(...drawnBounds.max)) : new Box328;return {triangles: metrics.triangles,vertices,@@ -40644,7 +41099,7 @@ async function snapshot3(bytes) {if (depth > 128)throw new Error("Revision comparison hierarchy exceeds 128 levels.");const names = new Set;- const combined = new Box327;+ const combined = new Box328;const placed = siblings.flatMap((node) => [{ node, drawn: true },...lowerLevels(node).map((level) => ({ node: level, drawn: false }))@@ -40661,7 +41116,7 @@ async function snapshot3(bytes) {if (node.listExtensions().some((extension) => extension.extensionName !== MSFT_LOD && extension.extensionName !== "KHR_node_visibility") || mesh?.listExtensions().length)throw new Error("Revision comparison does not support node/mesh extensions (including instancing).");const primitives = mesh?.listPrimitives() ?? [];- const own = new Box327;+ const own = new Box328;const matrix = parentWorld.clone().multiply(new Matrix419().fromArray(node.getMatrix()));if (matrix.elements.some((value) => !Number.isFinite(value)))throw new Error("Revision comparison requires finite transforms.");@@ -40682,7 +41137,7 @@ async function snapshot3(bytes) {if (!Number.isInteger(vertex) || vertex < 0 || vertex >= position.getCount())throw new Error("Revision comparison found an invalid vertex index.");position.getElement(vertex, element);- const point = new Vector346(...element).applyMatrix4(matrix);+ const point = new Vector347(...element).applyMatrix4(matrix);if (point.toArray().some((value) => !Number.isFinite(value)))throw new Error("Revision comparison requires finite positions.");own.expandByPoint(point);@@ -40882,20 +41337,20 @@ var init_revision_comparison = __esm(() => {// src/views/surface-distance.tsimport {- Box3 as Box328,+ Box3 as Box329,Matrix4 as Matrix420,- Ray as Ray2,- Triangle as Triangle2,- Vector3 as Vector347+ Ray as Ray3,+ Triangle as Triangle3,+ Vector3 as Vector348} from "three";function hierarchy(triangles) {- const box = new Box328;+ const box = new Box329;for (const triangle of triangles)box.union(triangle.box);const count = triangles.length;if (count <= 4)return { box, count, triangles };- const size = box.getSize(new Vector347);+ const size = box.getSize(new Vector348);const axis = size.x >= size.y && size.x >= size.z ? "x" : size.y >= size.z ? "y" : "z";const center = (triangle) => triangle.box.min[axis] / 2 + triangle.box.max[axis] / 2;triangles.sort((a, b) => center(a) - center(b));@@ -40906,7 +41361,7 @@ function hierarchy(triangles) {children: [hierarchy(triangles.slice(0, middle)), hierarchy(triangles.slice(middle))]};}-function boxDistanceSquared(a, b) {+function boxDistanceSquared2(a, b) {const x = Math.max(0, a.min.x - b.max.x, b.min.x - a.max.x);const y = Math.max(0, a.min.y - b.max.y, b.min.y - a.max.y);const z = Math.max(0, a.min.z - b.max.z, b.min.z - a.max.z);@@ -40914,7 +41369,7 @@ function boxDistanceSquared(a, b) {}function collect(node, paths) {const triangles = [];- const bounds = new Box328;+ const bounds = new Box329;node.updateWorldMatrix(true, true);node.traverseVisible((child) => {const mesh = child;@@ -40947,13 +41402,13 @@ function collect(node, paths) {const id = index ? index.getX(i + offset) : i + offset;if (!Number.isSafeInteger(id) || id < 0 || id >= position.count)throw new Error("Surface distance encountered an invalid triangle index.");- const point = new Vector347().fromBufferAttribute(position, id).applyMatrix4(matrix);+ const point = new Vector348().fromBufferAttribute(position, id).applyMatrix4(matrix);if (![point.x, point.y, point.z].every(Number.isFinite))throw new Error("Surface distance encountered a non-finite world position.");return point;};- const triangle = new Triangle2(vertex(0), vertex(1), vertex(2));- const box = new Box328().setFromPoints([triangle.a, triangle.b, triangle.c]);+ const triangle = new Triangle3(vertex(0), vertex(1), vertex(2));+ const box = new Box329().setFromPoints([triangle.a, triangle.b, triangle.c]);bounds.union(box);triangles.push({triangle,@@ -41006,10 +41461,10 @@ function trianglePair(a, b) {const av = [a.a, a.b, a.c], bv = [b.a, b.b, b.c];if (b.getArea() > 0)for (const p of av)- record(p, b.closestPointToPoint(p, new Vector347));+ record(p, b.closestPointToPoint(p, new Vector348));if (a.getArea() > 0)for (const q of bv)- record(a.closestPointToPoint(q, new Vector347), q);+ record(a.closestPointToPoint(q, new Vector348), q);for (let i = 0;i < 3; i++) {const p = av[i], q = av[(i + 1) % 3];for (let j = 0;j < 3; j++)@@ -41022,9 +41477,9 @@ function trianglePair(a, b) {const length = delta.length();if (length === 0)continue;- const hit = new Ray2(origin, delta.divideScalar(length)).intersectTriangle(target.a, target.b, target.c, false, new Vector347);+ const hit = new Ray3(origin, delta.divideScalar(length)).intersectTriangle(target.a, target.b, target.c, false, new Vector348);if (hit && origin.distanceTo(hit) <= length) {- const onFace = target.closestPointToPoint(hit, new Vector347);+ const onFace = target.closestPointToPoint(hit, new Vector348);if (vertices === av)record(hit, onFace);else@@ -41058,7 +41513,7 @@ function measureSurfaceDistance(root, input) {});const finish = (complete) => {const upper = Number.isFinite(best) ? Math.sqrt(best) : null;- const lower = complete ? upper : Math.sqrt(boxDistanceSquared(a.bounds, b.bounds));+ const lower = complete ? upper : Math.sqrt(boxDistanceSquared2(a.bounds, b.bounds));if (!Number.isFinite(lower))throw new Error("Surface distance exceeds the finite numeric range.");return {@@ -41072,7 +41527,7 @@ function measureSurfaceDistance(root, input) {bounds: { lower, upper },closest,pairsVisited: visited,- reason: complete ? null : `Search budget ${MAX_WORK} reached (hierarchy and triangle pairs); select smaller parts. Upper bound is the closest pair found, not a completed minimum.`,+ reason: complete ? null : `Search budget ${MAX_WORK2} reached (hierarchy and triangle pairs); select smaller parts. Upper bound is the closest pair found, not a completed minimum.`,limitations: LIMITATIONS};};@@ -41080,25 +41535,25 @@ function measureSurfaceDistance(root, input) {{a: hierarchy(a.triangles),b: hierarchy(b.triangles),- lower: boxDistanceSquared(a.bounds, b.bounds)+ lower: boxDistanceSquared2(a.bounds, b.bounds)}];while (pending.length) {const current = pending.pop();if (current.lower >= best)continue;- if (work === MAX_WORK)+ if (work === MAX_WORK2)return finish(false);work++;const { a: x, b: y } = current;if ("triangles" in x && "triangles" in y) {for (const left of x.triangles)for (const right of y.triangles) {- if (work === MAX_WORK)+ if (work === MAX_WORK2)return finish(false);work++;visited++;- if (boxDistanceSquared(left.box, right.box) >= best)+ if (boxDistanceSquared2(left.box, right.box) >= best)continue;const candidate = trianglePair(left.triangle, right.triangle);if (candidate.squared < best) {@@ -41115,7 +41570,7 @@ function measureSurfaceDistance(root, input) {}));const next = pairs.map((pair) => ({...pair,- lower: boxDistanceSquared(pair.a.box, pair.b.box)+ lower: boxDistanceSquared2(pair.a.box, pair.b.box)}));if (next[0].lower <= next[1].lower)pending.push(next[1], next[0]);@@ -41178,7 +41633,7 @@ function measureSurfacePairs(root, pairs) {results};}-var MAX_TRIANGLES = 20000, MAX_WORK = 250000, LIMITATIONS = "Unsigned distance between tessellated surfaces in the exported rest pose. Zero means touching or crossing surfaces; positive distance does not exclude containment. Does not establish solid clearance, attachment strength, motion, or alpha/displacement appearance.";+var MAX_TRIANGLES = 20000, MAX_WORK2 = 250000, LIMITATIONS = "Unsigned distance between tessellated surfaces in the exported rest pose. Zero means touching or crossing surfaces; positive distance does not exclude containment. Does not establish solid clearance, attachment strength, motion, or alpha/displacement appearance.";var init_surface_distance = __esm(() => {init_camera();});@@ -41190,7 +41645,7 @@ __export(exports_draw_diagnostics, {});import { Primitive as Primitive3 } from "@gltf-transform/core";import { cloneDocument as cloneDocument2 } from "@gltf-transform/functions";-import * as THREE59 from "three";+import * as THREE60 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)@@ -41243,7 +41698,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 THREE59.Vector3).length(), b.bounds.getSize(new THREE59.Vector3).length(), 0.000000000001) * 0.000001;+ const tolerance = Math.max(a.bounds.getSize(new THREE60.Vector3).length(), b.bounds.getSize(new THREE60.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);@@ -41285,7 +41740,7 @@ function observe(uses) {unexaminedPrimitiveUses++;continue;}- const matrix = new THREE59.Matrix4().fromArray(node.getWorldMatrix());+ const matrix = new THREE60.Matrix4().fromArray(node.getWorldMatrix());if (primitive.getAttribute("TANGENT") && matrix.determinant() < 0)mirrored.set(part.id, part);const position = primitive.getAttribute("POSITION");@@ -41299,14 +41754,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 THREE59.Vector3().fromArray(position.getElement(indices ? indices.getScalar(start + j) : start + j, [])).applyMatrix4(matrix));+ const points = [0, 1, 2].map((j) => new THREE60.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 THREE59.Box3().setFromPoints(points),+ bounds: new THREE60.Box3().setFromPoints(points),part});}@@ -43542,6 +43997,7 @@ define2("markOpenShell", {semantics: ["QA reports a marked part that cannot be built as a closed solid as GEO_PART_SELF_INTERSECTION_ACKNOWLEDGED with the reason, instead of GEO_PART_SELF_INTERSECTION_UNMEASURED.","Overlapping pairs with the marked part stay unmeasured and are counted; overlap there is not ruled out. Overlap between other parts is still measured and reported.",+ "Volume stays unmeasured, but GEO_OPEN_SURFACE_PENETRATION separately samples an open surface against the closed solids it meets and reports how far inside one it reaches.","A marked part that builds as a closed solid is measured like any other part. A part skipped for its size, draw range, instancing or invalid indices is still reported as unmeasured.","Both exporters write the mark as the node extras kilnOpenShell: { schemaVersion: 1, reason }; import restores it to userData.","Invalid arguments, or a kilnOpenShell value this helper did not write, are an OPEN_SHELL build error."@@ -48316,7 +48772,7 @@ function createCachedEvaluatorPort(evaluator, options) {// src/tools/registry.tsinit_validation();-import * as THREE60 from "three";+import * as THREE61 from "three";// src/evaluator/source-check.tsinit_validation();@@ -48945,8 +49401,8 @@ function collectSceneMetrics(root) {let meshes = 0;const materialSet = new Set;let lowestPart;- const box = new THREE60.Box3;- const point = new THREE60.Vector3;+ const box = new THREE61.Box3;+ const point = new THREE61.Vector3;root.updateWorldMatrix(true, true);root.traverseVisible((node) => {const n = node;@@ -48962,7 +49418,7 @@ function collectSceneMetrics(root) {const mesh = node;const position = mesh.geometry.getAttribute("position");const index = mesh.geometry.index;- const mb = new THREE60.Box3;+ const mb = new THREE61.Box3;if (position) {for (let i = 0;i < (index?.count ?? position.count); i++) {point.fromBufferAttribute(position, index ? index.getX(i) : i);@@ -48977,7 +49433,7 @@ function collectSceneMetrics(root) {});let bbox;if (!box.isEmpty()) {- const size = new THREE60.Vector3;+ const size = new THREE61.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 19f593a4..b833a5fb 100644--- a/dist/build.json+++ b/dist/build.json@@ -2,10 +2,10 @@"schemaVersion": 1,"entries": {"worker": {- "identity": "sha256:2bff9c95fd0652f2d244d339f2c82b1dd34766198236933cada9ae382e8a3a5f",+ "identity": "sha256:29191bc644016fb83842b601665ed047d44eef915334c876176d2939c12475be","engineVersion": "1.5.0","toolchain": "[email protected]",- "sourceHash": "63773ab08b47dc0156580336a7143d5327d44c5d18ac9b23ff21326cb9f49b3b",+ "sourceHash": "62f95d7fb2ba8984dfdb211aaeb3aa69f935c3db07f108697f338f8ce9cbe0c2","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -37,13 +37,13 @@},"target": "node","file": "evaluator-worker.mjs",- "bundleHash": "sha256:4c5521b27238d6848a39c552d2844507d7bd2f92df3ce5e4e2b91d15ca521706"+ "bundleHash": "sha256:395bac1322db31159ac553f054496245315a1473099fd4c6bd0e1e7b339aed66"},"agent-run": {- "identity": "sha256:2bff9c95fd0652f2d244d339f2c82b1dd34766198236933cada9ae382e8a3a5f",+ "identity": "sha256:29191bc644016fb83842b601665ed047d44eef915334c876176d2939c12475be","engineVersion": "1.5.0","toolchain": "[email protected]",- "sourceHash": "63773ab08b47dc0156580336a7143d5327d44c5d18ac9b23ff21326cb9f49b3b",+ "sourceHash": "62f95d7fb2ba8984dfdb211aaeb3aa69f935c3db07f108697f338f8ce9cbe0c2","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -75,13 +75,13 @@},"target": "node","file": "agent-run.mjs",- "bundleHash": "sha256:33747e032418f3bf976da377d5335ff7edc10db2bd8f8dc11fb4a65af2443273"+ "bundleHash": "sha256:36dec36a18ce6d33f049180709c53e4b464475f78842fd3a4e0798e841bc6295"},"agent-providers": {- "identity": "sha256:2bff9c95fd0652f2d244d339f2c82b1dd34766198236933cada9ae382e8a3a5f",+ "identity": "sha256:29191bc644016fb83842b601665ed047d44eef915334c876176d2939c12475be","engineVersion": "1.5.0","toolchain": "[email protected]",- "sourceHash": "63773ab08b47dc0156580336a7143d5327d44c5d18ac9b23ff21326cb9f49b3b",+ "sourceHash": "62f95d7fb2ba8984dfdb211aaeb3aa69f935c3db07f108697f338f8ce9cbe0c2","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -116,10 +116,10 @@"bundleHash": "sha256:9d6faf03d307321bc2e3bd5ce5bdee0bbbf61e0ebed8bfebfa1fb072287b83fa"},"mcp": {- "identity": "sha256:2bff9c95fd0652f2d244d339f2c82b1dd34766198236933cada9ae382e8a3a5f",+ "identity": "sha256:29191bc644016fb83842b601665ed047d44eef915334c876176d2939c12475be","engineVersion": "1.5.0","toolchain": "[email protected]",- "sourceHash": "63773ab08b47dc0156580336a7143d5327d44c5d18ac9b23ff21326cb9f49b3b",+ "sourceHash": "62f95d7fb2ba8984dfdb211aaeb3aa69f935c3db07f108697f338f8ce9cbe0c2","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -154,10 +154,10 @@"bundleHash": "sha256:deeb947091b693e92337a2081678ed06cd0a2d23f813a375001c31dbf529a815"},"cli": {- "identity": "sha256:2bff9c95fd0652f2d244d339f2c82b1dd34766198236933cada9ae382e8a3a5f",+ "identity": "sha256:29191bc644016fb83842b601665ed047d44eef915334c876176d2939c12475be","engineVersion": "1.5.0","toolchain": "[email protected]",- "sourceHash": "63773ab08b47dc0156580336a7143d5327d44c5d18ac9b23ff21326cb9f49b3b",+ "sourceHash": "62f95d7fb2ba8984dfdb211aaeb3aa69f935c3db07f108697f338f8ce9cbe0c2","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -189,13 +189,13 @@},"target": "node","file": "cli.mjs",- "bundleHash": "sha256:6399e324ae81df586ab6ec6cca3c9a03e60fcc879d23a0bfe9ccbfb76f934e9e"+ "bundleHash": "sha256:769aacd03ca587946da398590ae2417a0a01484fbd185a9eea8c30d146105617"},"engine": {- "identity": "sha256:2bff9c95fd0652f2d244d339f2c82b1dd34766198236933cada9ae382e8a3a5f",+ "identity": "sha256:29191bc644016fb83842b601665ed047d44eef915334c876176d2939c12475be","engineVersion": "1.5.0","toolchain": "[email protected]",- "sourceHash": "63773ab08b47dc0156580336a7143d5327d44c5d18ac9b23ff21326cb9f49b3b",+ "sourceHash": "62f95d7fb2ba8984dfdb211aaeb3aa69f935c3db07f108697f338f8ce9cbe0c2","rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a","dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10","dependencies": {@@ -227,7 +227,7 @@},"target": "node","file": "mcp-engine.mjs",- "bundleHash": "sha256:e84cf4c11c00d00d83252bad2c7e0ea2de14a84fef2507015670dbcf619cc3ab"+ "bundleHash": "sha256:e5a7160d3ba3d72d478ae3e7d1c0e230028fbe9f9c01b07aa46c94d8ff0c36c4"}}}diff --git a/dist/cli.mjs b/dist/cli.mjsindex 9e4f2171..e0c169e0 100644--- a/dist/cli.mjs+++ b/dist/cli.mjs@@ -12194,10 +12194,745 @@ var init_self_intersection = __esm(() => {});});-// src/sweep-analysis.ts+// src/geometry.tsimport * as THREE18 from "three";+function finiteArray(values, label, length) {+ const result = Array.from(values);+ if (length !== undefined && result.length !== length)+ throw new Error(`${label}: expected ${length} values, got ${result.length}`);+ if (!result.every((n) => Number.isFinite(Math.fround(n))))+ throw new AuthoringDiagnosticError("MESH_DATA_NONFINITE", `${label}: all values must be finite Float32 values`);+ return result;+}+function meshGeo(data) {+ const positions = finiteArray(data.positions, "meshGeo positions");+ if (positions.length < 9 || positions.length % 3)+ throw new Error("meshGeo positions: need at least three xyz vertices");+ const count = positions.length / 3;+ const geometry = new THREE18.BufferGeometry;+ geometry.setAttribute("position", new THREE18.Float32BufferAttribute(positions, 3));+ if (data.indices) {+ const indices = Array.from(data.indices);+ if (!indices.length || indices.length % 3)+ throw new Error("meshGeo indices: need complete triangles");+ if (!indices.every((i) => Number.isInteger(i) && i >= 0 && i < count))+ throw new Error("meshGeo index out of bounds or not an integer");+ geometry.setIndex(indices);+ } else if (count % 3)+ throw new Error("meshGeo: non-indexed positions must form complete triangles");+ if (data.normals) {+ const normals = finiteArray(data.normals, "meshGeo normals", count * 3);+ geometry.setAttribute("normal", new THREE18.Float32BufferAttribute(normals, 3));+ for (let i = 0;i < count; i++)+ if (Math.hypot(normals[i * 3], normals[i * 3 + 1], normals[i * 3 + 2]) === 0)+ throw new Error("meshGeo normals: zero-length normal");+ geometry.normalizeNormals();+ } else+ geometry.computeVertexNormals();+ if (data.uvs)+ geometry.setAttribute("uv", new THREE18.Float32BufferAttribute(finiteArray(data.uvs, "meshGeo uvs", count * 2), 2));+ if (data.tangents) {+ const tangents = finiteArray(data.tangents, "meshGeo tangents", count * 4);+ for (let i = 0;i < count; i++) {+ if (Math.abs(Math.hypot(tangents[i * 4], tangents[i * 4 + 1], tangents[i * 4 + 2]) - 1) > 0.0001 || Math.abs(tangents[i * 4 + 3]) !== 1)+ throw new Error("meshGeo tangents: expected unit xyz and handedness +1 or -1");+ }+ geometry.setAttribute("tangent", new THREE18.Float32BufferAttribute(tangents, 4));+ }+ geometry.computeBoundingBox();+ geometry.computeBoundingSphere();+ return geometry;+}+function boundsScale(bounds) {+ const size = bounds.getSize(new THREE18.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 THREE18.Box3;+ const point = new THREE18.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 THREE18.Vector3 : bounds.min,+ scale: boundsScale(bounds)+ };+}+function positionTolerance(scale, supplied, relative) {+ if (supplied === undefined)+ return scale * relative;+ if (!Number.isFinite(supplied) || supplied <= 0)+ throw new Error("Geometry tolerance must be positive and finite");+ if (scale / supplied > Number.MAX_SAFE_INTEGER)+ throw new Error("Geometry tolerance is too small to resolve the position extent safely");+ return supplied;+}+function positionKey(point, origin, tolerance) {+ if (tolerance === 0)+ return point.toArray().join(",");+ return point.clone().sub(origin).toArray().map((x) => Math.round(x / tolerance)).join(",");+}+function geometryDiagnostics(geometry, tolerance) {+ const p = geometry.getAttribute("position");+ if (p?.itemSize !== 3)+ throw new Error("geometryDiagnostics requires xyz positions");+ const frame = positionFrame(p);+ const distance = positionTolerance(frame.scale, tolerance, 0.000001);+ const result = {+ tolerance: distance,+ toleranceMode: tolerance === undefined ? "relative" : "absolute",+ positionScale: frame.scale,+ vertices: p.count,+ triangles: 0,+ boundaryEdges: 0,+ nonManifoldEdges: 0,+ orientationConflicts: 0,+ degenerateTriangles: 0,+ collapsedByToleranceTriangles: 0,+ invalidIndices: 0,+ nonFiniteVertices: 0,+ solid: { closed: false, manifold: true, orientation: "mixed", signedVolume: 0 }+ };+ let signedVolume = 0;+ const pa = new THREE18.Vector3, pb = new THREE18.Vector3, pc = new THREE18.Vector3;+ const ids = [];+ const points = new Map;+ const finite = [];+ const point = new THREE18.Vector3;+ for (let i = 0;i < p.count; i++) {+ point.fromBufferAttribute(p, i);+ finite[i] = [point.x, point.y, point.z].every(Number.isFinite);+ if (!finite[i])+ result.nonFiniteVertices++;+ const key = finite[i] ? positionKey(point, frame.origin, distance) : `invalid:${i}`;+ if (!points.has(key))+ points.set(key, points.size);+ ids.push(points.get(key));+ }+ const indices = geometry.index ? Array.from(geometry.index.array) : Array.from({ length: p.count }, (_, i) => i);+ const edges = new Map;+ const a = new THREE18.Vector3, b = new THREE18.Vector3, c = new THREE18.Vector3;+ for (let i = 0;i < indices.length; i += 3) {+ result.triangles++;+ const triangle = indices.slice(i, i + 3);+ if (triangle.length !== 3 || triangle.some((n) => !Number.isInteger(n) || n < 0 || n >= p.count)) {+ result.invalidIndices++;+ continue;+ }+ const [ia, ib, ic] = triangle;+ if (!finite[ia] || !finite[ib] || !finite[ic])+ continue;+ pa.fromBufferAttribute(p, ia);+ pb.fromBufferAttribute(p, ib);+ pc.fromBufferAttribute(p, ic);+ signedVolume += pa.dot(pb.cross(pc)) / 6;+ a.fromBufferAttribute(p, ia);+ b.fromBufferAttribute(p, ib);+ c.fromBufferAttribute(p, ic);+ const scale = frame.scale || 1;+ b.sub(a).divideScalar(scale);+ c.sub(a).divideScalar(scale);+ if (b.cross(c).length() <= (distance / scale) ** 2)+ result.degenerateTriangles++;+ if (ids[ia] === ids[ib] || ids[ib] === ids[ic] || ids[ic] === ids[ia]) {+ result.collapsedByToleranceTriangles++;+ continue;+ }+ for (const [start, end] of [+ [ia, ib],+ [ib, ic],+ [ic, ia]+ ]) {+ const u = ids[start], v = ids[end];+ const key = u < v ? `${u}:${v}` : `${v}:${u}`;+ const edge = edges.get(key) ?? { count: 0, direction: 0 };+ edge.count++;+ edge.direction += u < v ? 1 : -1;+ edges.set(key, edge);+ }+ }+ for (const edge of edges.values()) {+ if (edge.count === 1)+ result.boundaryEdges++;+ else if (edge.count > 2)+ result.nonManifoldEdges++;+ else if (edge.direction !== 0)+ result.orientationConflicts++;+ }+ const volumeFloor = (frame.scale || 1) ** 3 * 0.000000000001;+ result.solid = {+ closed: result.boundaryEdges === 0 && edges.size > 0,+ manifold: result.nonManifoldEdges === 0,+ orientation: result.orientationConflicts > 0 || Math.abs(signedVolume) <= volumeFloor ? "mixed" : signedVolume > 0 ? "outward" : "inward",+ signedVolume: Object.is(signedVolume, -0) ? 0 : signedVolume+ };+ return result;+}+function parametricSurface(sample, options = {}) {+ const {+ u = [0, 1],+ v = [0, 1],+ uSegments: nu = 24,+ vSegments: nv = 24,+ periodicU = false,+ periodicV = false,+ orientation = "uv"+ } = options;+ for (const [name, n] of [+ ["uSegments", nu],+ ["vSegments", nv]+ ])+ if (!Number.isSafeInteger(n) || n < 1)+ throw new Error(`parametricSurface ${name} must be a positive integer`);+ const sampleCount = (nu + 1) * (nv + 1);+ if (!Number.isSafeInteger(sampleCount) || sampleCount > GEOMETRY_ALLOCATION_LIMITS.parametricSamples)+ throw new RangeError(`parametricSurface sample budget exceeded: requested ${sampleCount}, limit ${GEOMETRY_ALLOCATION_LIMITS.parametricSamples}. Reduce uSegments/vSegments or split the surface.`);+ for (const [name, range] of [+ ["u", u],+ ["v", v]+ ])+ if (range.length !== 2 || !range.every(Number.isFinite) || range[0] === range[1] || !Number.isFinite(range[1] - range[0]))+ throw new Error(`parametricSurface ${name} must be a finite nonzero domain`);+ if (orientation !== "uv" && orientation !== "vu")+ throw new Error("parametricSurface orientation must be uv or vu");+ const positions = [], uvs = [], indices = [];+ const sampledBounds = new THREE18.Box3;+ const sampledPoint = new THREE18.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);+ if (point.length !== 3 || !point.every(Number.isFinite))+ throw new Error(`parametricSurface: sample (${i},${j}) must return three finite coordinates`);+ positions.push(...point);+ sampledBounds.expandByPoint(sampledPoint.set(...point));+ uvs.push(i / nu, j / nv);+ }+ const groups = Array.from({ length: (nu + 1) * (nv + 1) }, (_, i) => i);+ const seamScale = boundsScale(sampledBounds);+ const find = (i) => {+ while (groups[i] !== i)+ i = groups[i];+ return i;+ };+ const join = (a, b, _label) => {+ const pa = positions.slice(a * 3, a * 3 + 3), pb = positions.slice(b * 3, b * 3 + 3);+ if (Math.hypot(...pa.map((x, k) => x - pb[k])) > seamScale * 0.000001)+ throw new AuthoringDiagnosticError("PARAMETRIC_PERIODIC_ENDPOINT");+ groups[find(b)] = find(a);+ for (let k = 0;k < 3; k++)+ positions[b * 3 + k] = positions[a * 3 + k];+ };+ if (periodicU)+ for (let j = 0;j <= nv; j++)+ join(j * (nu + 1), j * (nu + 1) + nu, "periodicU");+ if (periodicV)+ for (let i = 0;i <= nu; i++)+ join(i, nv * (nu + 1) + i, "periodicV");+ for (let j = 0;j < nv; j++)+ for (let i = 0;i < nu; i++) {+ const a = j * (nu + 1) + i, b = a + 1, c = a + nu + 1, d = c + 1;+ indices.push(...orientation === "uv" ? [a, b, c, b, d, c] : [a, c, b, b, c, d]);+ }+ const out = meshGeo({ positions, indices, uvs });+ if (periodicU || periodicV) {+ const normal = out.getAttribute("normal");+ const sums = new Map;+ for (let i = 0;i < normal.count; i++) {+ const id = find(i);+ const sum = sums.get(id) ?? new THREE18.Vector3;+ sum.add(new THREE18.Vector3().fromBufferAttribute(normal, i));+ sums.set(id, sum);+ }+ for (let i = 0;i < normal.count; i++) {+ const n = sums.get(find(i)).clone().normalize();+ normal.setXYZ(i, n.x, n.y, n.z);+ }+ }+ return out;+}+function creaseNormals(geometry, options = {}) {+ const angle = options.angle ?? 60;+ if (!Number.isFinite(angle) || angle < 0 || angle > 180)+ throw new Error("creaseNormals angle must be between 0 and 180 degrees");+ const out = geometry.index ? geometry.toNonIndexed() : geometry.clone();+ const position = out.getAttribute("position");+ if (position?.itemSize !== 3 || position.count % 3 !== 0)+ throw new Error("creaseNormals requires complete xyz triangles");+ const frame = positionFrame(position);+ const tolerance = positionTolerance(frame.scale, options.tolerance, 0.00000001);+ const scale = frame.scale || 1;+ const adjacent = new Map;+ const keys = [];+ const faces = [];+ for (let i = 0;i < position.count; i += 3) {+ const a = new THREE18.Vector3().fromBufferAttribute(position, i);+ const b = new THREE18.Vector3().fromBufferAttribute(position, i + 1);+ const c = new THREE18.Vector3().fromBufferAttribute(position, i + 2);+ const face = b.sub(a).divideScalar(scale).cross(c.sub(a).divideScalar(scale)).normalize();+ faces.push(face);+ for (let j = i;j < i + 3; j++) {+ const point = new THREE18.Vector3().fromBufferAttribute(position, j);+ if (![point.x, point.y, point.z].every(Number.isFinite))+ throw new Error("creaseNormals positions must be finite");+ const key = positionKey(point, frame.origin, tolerance);+ keys.push(key);+ const neighbors = adjacent.get(key) ?? new Set;+ neighbors.add(i / 3);+ adjacent.set(key, neighbors);+ }+ }+ const normals = new Float32Array(position.count * 3);+ const threshold = Math.cos(THREE18.MathUtils.degToRad(angle));+ for (let i = 0;i < position.count; i++) {+ const face = faces[Math.floor(i / 3)], sum = new THREE18.Vector3;+ for (const other of adjacent.get(keys[i]))+ if (face.dot(faces[other]) >= threshold - 0.000000000001)+ sum.add(faces[other]);+ sum.normalize().toArray(normals, i * 3);+ }+ out.setAttribute("normal", new THREE18.BufferAttribute(normals, 3));+ out.deleteAttribute("tangent");+ out.computeBoundingBox();+ out.computeBoundingSphere();+ return out;+}+var init_geometry = __esm(() => {+ init_geometry_budget();+ init_authoring_diagnostic();+});++// src/qa/open-surface-penetration.ts+import * as THREE19 from "three";+function buildHierarchy(triangles) {+ const box = new THREE19.Box3;+ for (const triangle of triangles)+ box.union(triangle.box);+ if (triangles.length <= 4)+ return { box, triangles };+ const size = box.getSize(new THREE19.Vector3);+ const axis = size.x >= size.y && size.x >= size.z ? "x" : size.y >= size.z ? "y" : "z";+ const center = (triangle) => triangle.box.min[axis] / 2 + triangle.box.max[axis] / 2;+ const sorted = [...triangles].sort((a, b) => center(a) - center(b));+ const middle = Math.floor(sorted.length / 2);+ return {+ box,+ children: [buildHierarchy(sorted.slice(0, middle)), buildHierarchy(sorted.slice(middle))]+ };+}+function worldTriangles(mesh) {+ const geometry = mesh.geometry;+ const position = geometry.getAttribute("position");+ if (position?.itemSize !== 3)+ return null;+ const index = geometry.getIndex();+ const count = index ? index.count : position.count;+ if (count % 3 !== 0)+ return null;+ const triangles = [];+ const vertex = (at) => {+ const id = index ? index.getX(at) : at;+ if (!Number.isSafeInteger(id) || id < 0 || id >= position.count)+ return null;+ const point = new THREE19.Vector3().fromBufferAttribute(position, id).applyMatrix4(mesh.matrixWorld);+ return [point.x, point.y, point.z].every(Number.isFinite) ? point : null;+ };+ for (let i = 0;i < count; i += 3) {+ const a = vertex(i), b = vertex(i + 1), c = vertex(i + 2);+ if (!a || !b || !c)+ return null;+ const triangle = new THREE19.Triangle(a, b, c);+ triangles.push({ triangle, box: new THREE19.Box3().setFromPoints([a, b, c]) });+ }+ return triangles.length ? triangles : null;+}+function triangleCount2(geometry) {+ const index = geometry.getIndex();+ const position = geometry.getAttribute("position");+ if (!position)+ return 0;+ return Math.floor((index ? index.count : position.count) / 3);+}+function collectParts4(root, skipped) {+ const parts = [];+ root.updateWorldMatrix(true, true);+ root.traverseVisible((node) => {+ const mesh = node;+ if (!mesh.isMesh || !mesh.geometry)+ return;+ const name = mesh.name || "(unnamed mesh)";+ if (mesh.isInstancedMesh || mesh.isSkinnedMesh || Object.values(mesh.geometry.morphAttributes).some((targets) => targets.length)) {+ skipped.push({+ part: name,+ reason: "instancing, skin or morph deformation is unsupported by surface sampling"+ });+ return;+ }+ const total = mesh.geometry.index?.count ?? mesh.geometry.getAttribute("position")?.count ?? 0;+ const range = mesh.geometry.drawRange;+ if (range.start !== 0 || range.count < total) {+ skipped.push({+ part: name,+ reason: "partial triangle draw ranges are unsupported by surface sampling"+ });+ return;+ }+ const triangles = triangleCount2(mesh.geometry);+ if (triangles === 0)+ return;+ if (triangles > MAX_SURFACE_TRIANGLES) {+ skipped.push({+ part: name,+ reason: `${triangles} triangles exceeds the ${MAX_SURFACE_TRIANGLES}-triangle analysis budget`+ });+ return;+ }+ mesh.geometry.computeBoundingBox();+ const box = mesh.geometry.boundingBox.clone().applyMatrix4(mesh.matrixWorld);+ if (box.isEmpty())+ return;+ const determinant = mesh.matrixWorld.determinant();+ if (![...box.min, ...box.max].every(Number.isFinite) || !Number.isFinite(determinant)) {+ skipped.push({ part: name, reason: "non-finite transformed bounds cannot be measured" });+ return;+ }+ let diagnostics;+ try {+ diagnostics = geometryDiagnostics(mesh.geometry);+ } catch (error) {+ skipped.push({+ part: name,+ reason: `topology could not be analyzed (${error instanceof Error ? error.message : String(error)})`+ });+ return;+ }+ const closed = diagnostics.solid.closed && diagnostics.solid.manifold && diagnostics.solid.orientation !== "mixed";+ parts.push({ name, mesh, box, closed, lod: lodMembership(mesh) });+ });+ return parts;+}+function boxDistanceSquared(box, point) {+ const x = Math.max(box.min.x - point.x, 0, point.x - box.max.x);+ const y = Math.max(box.min.y - point.y, 0, point.y - box.max.y);+ const z = Math.max(box.min.z - point.z, 0, point.z - box.max.z);+ return x * x + y * y + z * z;+}+function boxOverlapRatio2(a, b) {+ const extent = (box) => (box.max.x - box.min.x) * (box.max.y - box.min.y) * (box.max.z - box.min.z);+ 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(extent(a), extent(b));+ return Number.isFinite(ratio) ? ratio : 0;+}++class Budget {+ limit;+ used = 0;+ exhausted = false;+ constructor(limit) {+ this.limit = limit;+ }+ spend() {+ if (this.used >= this.limit) {+ this.exhausted = true;+ return false;+ }+ this.used++;+ return true;+ }+}+function nearestDistance(root, point, budget) {+ let best = Infinity;+ const stack = [root];+ const scratch = new THREE19.Vector3;+ while (stack.length) {+ const node = stack.pop();+ if (boxDistanceSquared(node.box, point) >= best)+ continue;+ if ("triangles" in node) {+ for (const { triangle } of node.triangles) {+ if (!budget.spend())+ return null;+ const distance = point.distanceToSquared(triangle.closestPointToPoint(point, scratch));+ if (distance < best)+ best = distance;+ }+ } else+ stack.push(node.children[0], node.children[1]);+ }+ return Number.isFinite(best) ? Math.sqrt(best) : null;+}+function parity(root, point, direction, budget) {+ const ray = new THREE19.Ray(point, direction);+ const stack = [root];+ const hit = new THREE19.Vector3;+ const barycentric = new THREE19.Vector3;+ let crossings = 0;+ while (stack.length) {+ const node = stack.pop();+ if (!ray.intersectsBox(node.box))+ continue;+ if ("triangles" in node) {+ for (const { triangle } of node.triangles) {+ if (!budget.spend())+ return null;+ if (ray.intersectTriangle(triangle.a, triangle.b, triangle.c, false, hit) === null)+ continue;+ triangle.getBarycoord(hit, barycentric);+ if ([barycentric.x, barycentric.y, barycentric.z].some((v) => Math.abs(v) < PARITY_EPSILON))+ return null;+ crossings++;+ }+ } else+ stack.push(node.children[0], node.children[1]);+ }+ return crossings % 2 === 1;+}+function inside(root, point, budget) {+ for (const direction of PARITY_DIRECTIONS) {+ const verdict = parity(root, point, direction, budget);+ if (verdict !== null)+ return verdict;+ if (budget.exhausted)+ return null;+ }+ return null;+}+function analyzeOpenSurfacePenetration(root, contactTolerance = OPEN_SURFACE_CONTACT_TOLERANCE) {+ const evidence = {+ schemaVersion: 1,+ source: "engine-scene-analysis",+ contactTolerance,+ openParts: 0,+ closedParts: 0,+ candidatePairs: 0,+ pairsTested: 0,+ pairsNotReached: 0,+ verticesUnresolved: 0,+ pairsLodAlternates: 0,+ truncated: false,+ skipped: [],+ penetrations: []+ };+ if (!(root instanceof THREE19.Object3D))+ return evidence;+ const parts = collectParts4(root, evidence.skipped);+ const open = parts.filter((part) => !part.closed);+ const closed = parts.filter((part) => part.closed);+ evidence.openParts = open.length;+ evidence.closedParts = closed.length;+ const candidates = [];+ let considered = 0;+ broadPhase:+ for (const surface of open) {+ for (const solid of closed) {+ if (considered++ === MAX_BROAD_PHASE_PAIRS2) {+ evidence.broadPhaseTruncated = true;+ break broadPhase;+ }+ if (!surface.box.intersectsBox(solid.box))+ continue;+ if (surface.lod && solid.lod && surface.lod.parent === solid.lod.parent && surface.lod.stem === solid.lod.stem && surface.lod.level !== solid.lod.level) {+ evidence.pairsLodAlternates++;+ continue;+ }+ candidates.push({+ open: surface,+ solid,+ overlap: boxOverlapRatio2(surface.box, solid.box),+ order: candidates.length+ });+ }+ }+ evidence.candidatePairs = candidates.length;+ evidence.truncated = evidence.broadPhaseTruncated === true;+ if (!candidates.length)+ return evidence;+ candidates.sort((x, y) => y.overlap - x.overlap || x.order - y.order);+ const budget = new Budget(MAX_WORK);+ const penetrations = [];+ for (const candidate of candidates) {+ if (budget.exhausted) {+ evidence.pairsNotReached++;+ continue;+ }+ if (!candidate.solid.hierarchy) {+ const triangles = worldTriangles(candidate.solid.mesh);+ if (!triangles) {+ evidence.skipped.push({+ part: candidate.solid.name,+ reason: "invalid or non-finite triangles cannot be indexed"+ });+ evidence.pairsNotReached++;+ continue;+ }+ candidate.solid.hierarchy = buildHierarchy(triangles);+ }+ const hierarchy = candidate.solid.hierarchy;+ const position = candidate.open.mesh.geometry.getAttribute("position");+ if (position?.itemSize !== 3) {+ evidence.skipped.push({+ part: candidate.open.name,+ reason: "open surfaces are sampled at their vertices and this part has none"+ });+ continue;+ }+ const matrix = candidate.open.mesh.matrixWorld;+ const limit = Math.min(position.count, MAX_SAMPLED_VERTICES);+ const vertex = new THREE19.Vector3;+ let depth = 0;+ let penetrating = 0;+ let tested = 0;+ let unresolved = 0;+ let partial = limit < position.count;+ for (let i = 0;i < limit; i++) {+ vertex.fromBufferAttribute(position, i).applyMatrix4(matrix);+ if (![vertex.x, vertex.y, vertex.z].every(Number.isFinite))+ continue;+ if (boxDistanceSquared(candidate.solid.box, vertex) > contactTolerance * contactTolerance) {+ tested++;+ continue;+ }+ const distance = nearestDistance(hierarchy, vertex, budget);+ if (distance === null) {+ partial = true;+ break;+ }+ tested++;+ if (distance <= contactTolerance)+ continue;+ const verdict = inside(hierarchy, vertex, budget);+ if (verdict === null) {+ if (budget.exhausted) {+ partial = true;+ break;+ }+ unresolved++;+ continue;+ }+ if (!verdict)+ continue;+ penetrating++;+ if (distance > depth)+ depth = distance;+ }+ evidence.verticesUnresolved += unresolved;+ if (partial)+ evidence.pairsNotReached++;+ else+ evidence.pairsTested++;+ if (penetrating > 0)+ penetrations.push({+ open: candidate.open.name,+ solid: candidate.solid.name,+ depth: round2(depth),+ vertices: penetrating,+ tested+ });+ }+ evidence.truncated = evidence.truncated || evidence.pairsNotReached > 0;+ penetrations.sort((x, y) => y.depth - x.depth || `${x.open}:${x.solid}`.localeCompare(`${y.open}:${y.solid}`));+ evidence.penetrations = penetrations;+ return evidence;+}+function inspectOpenSurfacePenetration(evidence) {+ if (evidence?.schemaVersion !== 1)+ return [];+ const findings = evidence.penetrations.map((pair) => ({+ code: "GEO_OPEN_SURFACE_PENETRATION",+ disposition: "observe",+ dimension: "visualQuality",+ profile: "geometry.openSurfacePenetration",+ message: `Open surface ${JSON.stringify(pair.open)} reaches ${pair.depth.toFixed(4)} m inside solid ${JSON.stringify(pair.solid)}: ` + `${pair.vertices} of ${pair.tested} sampled ${pair.vertices === 1 ? "vertex lies" : "vertices lie"} deeper inside it than the ${evidence.contactTolerance} m contact tolerance.`,+ affected: { node: pair.open },+ measurement: {+ name: "openSurfacePenetrationDepth",+ actual: pair.depth,+ expected: evidence.contactTolerance,+ unit: "m",+ breakdown: { penetratingVertices: pair.vertices, sampledVertices: pair.tested }+ },+ repairText: "A positive here is not a defect. Most are intentional: a fitting set into a structural shell -- a lamp recess in a hull, a strut landing, a ridge into a cap -- puts shell vertices inside the solid by design, exactly as a bolt in a hole shares volume. Review the ones you did not intend, such as a cloth crossing a wall or a canopy pierced by a mast, and move the surface clear or cut it back to the solid. Vertices are the samples, so a solid thinner than this surface’s facet spacing can pass between two of them."+ }));+ const unresolved = evidence.verticesUnresolved ?? 0;+ if (evidence.truncated || unresolved > 0) {+ const clauses = [];+ if (evidence.truncated)+ clauses.push(`Sampled ${evidence.pairsTested} of ${evidence.broadPhaseTruncated ? "at least " : ""}${evidence.candidatePairs} overlapping open-surface and solid pairs; ` + `${evidence.pairsNotReached} were beyond the ${MAX_WORK}-test analysis budget.` + (evidence.broadPhaseTruncated ? ` Pair discovery stopped after ${MAX_BROAD_PHASE_PAIRS2} box comparisons.` : "") + " Unsampled pairs were not examined; the most overlapping bounding boxes were sampled first.");+ if (unresolved > 0)+ clauses.push(`${unresolved} ${unresolved === 1 ? "vertex" : "vertices"} further than the contact tolerance from a solid could not be resolved as inside or outside it, and ${unresolved === 1 ? "is" : "are"} counted as neither.`);+ findings.push({+ code: "GEO_OPEN_SURFACE_PENETRATION_TRUNCATED",+ disposition: "observe",+ dimension: "visualQuality",+ profile: "geometry.openSurfacePenetration",+ message: clauses.join(" "),+ measurement: {+ name: "openSurfacePairsSampled",+ actual: evidence.pairsTested,+ expected: evidence.candidatePairs,+ breakdown: {+ pairsNotReached: evidence.pairsNotReached,+ verticesUnresolved: unresolved+ }+ }+ });+ }+ if (evidence.skipped.length) {+ const byReason = new Map;+ for (const { part, reason } of evidence.skipped) {+ const parts = byReason.get(reason);+ if (parts)+ parts.push(part);+ else+ byReason.set(reason, [part]);+ }+ const reasons = [...byReason].map(([reason, parts]) => `${parts.length} because ${reason}: ${namedParts2(parts)}.`);+ const one = evidence.skipped.length === 1;+ findings.push({+ code: "GEO_OPEN_SURFACE_PENETRATION_UNMEASURED",+ disposition: "observe",+ dimension: "visualQuality",+ profile: "geometry.openSurfacePenetration",+ message: `${evidence.skipped.length} ${one ? "part was" : "parts were"} not sampled for open-surface penetration. ` + `${reasons.join(" ")} ${one ? "This part is" : "These parts are"} not certified clear of the solids around ${one ? "it" : "them"}.`+ });+ }+ return findings;+}+var OPEN_SURFACE_CONTACT_TOLERANCE = 0.005, MAX_SURFACE_TRIANGLES = 20000, MAX_SAMPLED_VERTICES = 20000, MAX_WORK = 250000, MAX_BROAD_PHASE_PAIRS2 = 250000, PARITY_DIRECTIONS, PARITY_EPSILON = 0.0000001, round2 = (value) => Number(value.toPrecision(9)), NAMES_SHOWN = 5, namedParts2 = (parts) => {+ const named = parts.slice(0, NAMES_SHOWN).map((part) => JSON.stringify(part));+ const more = parts.length > NAMES_SHOWN ? ` and ${parts.length - NAMES_SHOWN} more` : "";+ return `${named.join(", ")}${more}`;+}, OPEN_SURFACE_PENETRATION_QA_RULE;+var init_open_surface_penetration = __esm(() => {+ init_geometry();+ init_lod2();+ init_registry();+ PARITY_DIRECTIONS = Object.freeze([+ new THREE19.Vector3(1, 0, 0),+ new THREE19.Vector3(0.5773502691896258, 0.5773502691896258, 0.5773502691896258),+ new THREE19.Vector3(-0.2672612419124244, 0.5345224838248488, 0.8017837257372732)+ ]);+ OPEN_SURFACE_PENETRATION_QA_RULE = Object.freeze({+ id: "GEO_OPEN_SURFACE_PENETRATION",+ profile: "geometry.openSurfacePenetration",+ scope: { kind: "universal" },+ ruleClass: "heuristic",+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: "observe",+ evaluate(context) {+ return inspectOpenSurfacePenetration(analyzeOpenSurfacePenetration(context.scene));+ }+ });+});++// src/sweep-analysis.ts+import * as THREE20 from "three";function segmentHitsTriangle(a, b, tri, epsilon) {- const plane = new THREE18.Plane().setFromCoplanarPoints(tri.a, tri.b, tri.c);+ const plane = new THREE20.Plane().setFromCoplanarPoints(tri.a, tri.b, tri.c);if (plane.normal.lengthSq() === 0)return false;const da = plane.distanceToPoint(a), db = plane.distanceToPoint(b);@@ -12235,7 +12970,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 THREE18.Vector3).divideScalar(ring.length));+ const centers = rings.map((ring) => ring.reduce((sum, p) => sum.add(p), new THREE20.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);@@ -12249,17 +12984,17 @@ function recordSweepAnalysis(geometry, rings, profiles, closed) {const triangles = new Map;const faces = (index) => {if (!triangles.has(index))- triangles.set(index, THREE18.ShapeUtils.triangulateShape(profiles[index], []).map(([a, b, c]) => new THREE18.Triangle(rings[index][a], rings[index][b], rings[index][c])));+ triangles.set(index, THREE20.ShapeUtils.triangulateShape(profiles[index], []).map(([a, b, c]) => new THREE20.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 THREE18.Box3().setFromPoints(rings[i - 1]);- const boundsB = new THREE18.Box3().setFromPoints(rings[i]);+ const boundsA = new THREE20.Box3().setFromPoints(rings[i - 1]);+ const boundsB = new THREE20.Box3().setFromPoints(rings[i]);if (!boundsA.intersectsBox(boundsB)) {result.ringPairsChecked++;continue;}- const epsilon = Math.max(boundsA.getSize(new THREE18.Vector3).length(), boundsB.getSize(new THREE18.Vector3).length()) * 0.0000000001;+ const epsilon = Math.max(boundsA.getSize(new THREE20.Vector3).length(), boundsB.getSize(new THREE20.Vector3).length()) * 0.0000000001;let hit = false;pair:for (const [a, b] of [@@ -12291,10 +13026,10 @@ var init_sweep_analysis = __esm(() => {});// src/qa/sweep.ts-import { Object3D as Object3D13 } from "three";+import { Object3D as Object3D14 } from "three";function inspectSweepGeometry(scene) {const findings = [];- if (!(scene instanceof Object3D13))+ if (!(scene instanceof Object3D14))return findings;scene.traverseVisible((node) => {const geometry = node.geometry;@@ -12359,7 +13094,7 @@ var init_sweep = __esm(() => {});// src/qa/environment.ts-import * as THREE19 from "three";+import * as THREE21 from "three";function finding4(context, value) {return { ...value, profile: context.profile ?? "asset.requirements.v1" };}@@ -12378,11 +13113,11 @@ function nodePath3(root, node) {return names.reverse().join("/");}function transformedBox2(source, transform) {- const result = new THREE19.Box3;+ const result = new THREE21.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 THREE19.Vector3(x, y, z).applyMatrix4(transform));+ result.expandByPoint(new THREE21.Vector3(x, y, z).applyMatrix4(transform));}}}@@ -12391,16 +13126,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 THREE19.Vector3;- const rotation = new THREE19.Quaternion;- const scale = new THREE19.Vector3;+ const position = new THREE21.Vector3;+ const rotation = new THREE21.Quaternion;+ const scale = new THREE21.Vector3;relative.decompose(position, rotation, scale);- const recomposed = new THREE19.Matrix4().compose(position, rotation, scale);+ const recomposed = new THREE21.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 THREE19.Vector3).applyMatrix4(relative);- const sourceHalf = source.getSize(new THREE19.Vector3).multiplyScalar(0.5);+ const center = source.getCenter(new THREE21.Vector3).applyMatrix4(relative);+ const sourceHalf = source.getSize(new THREE21.Vector3).multiplyScalar(0.5);const halfExtents = [Math.abs(sourceHalf.x * scale.x),Math.abs(sourceHalf.y * scale.y),@@ -12415,30 +13150,30 @@ function orientedBoxFromLocalBounds(root, node, source, relative = root.matrixWohalfExtents});}-function collectParts4(root) {+function collectParts5(root) {root.updateWorldMatrix(true, true);const rootInverse = root.matrixWorld.clone().invert();const result = [];root.traverseVisible((node) => {const roles = rolesOf3(node);- const renderable = node instanceof THREE19.Mesh;+ const renderable = node instanceof THREE21.Mesh;let box;let orientedBox;let source;- if (renderable && node.geometry instanceof THREE19.BufferGeometry) {+ if (renderable && node.geometry instanceof THREE21.BufferGeometry) {node.geometry.computeBoundingBox();if (node.geometry.boundingBox) {source = node.geometry.boundingBox;}} else if (roles.length > 0) {- source = new THREE19.Box3(new THREE19.Vector3(-0.5, -0.5, -0.5), new THREE19.Vector3(0.5, 0.5, 0.5));+ source = new THREE21.Box3(new THREE21.Vector3(-0.5, -0.5, -0.5), new THREE21.Vector3(0.5, 0.5, 0.5));}const relative = rootInverse.clone().multiply(node.matrixWorld);- const count = node instanceof THREE19.InstancedMesh ? node.count : 1;+ const count = node instanceof THREE21.InstancedMesh ? node.count : 1;for (let index = 0;index < count; index++) {const transform = relative.clone();- if (node instanceof THREE19.InstancedMesh) {- const instance = new THREE19.Matrix4;+ if (node instanceof THREE21.InstancedMesh) {+ const instance = new THREE21.Matrix4;node.getMatrixAt(index, instance);transform.multiply(instance);}@@ -12469,9 +13204,9 @@ function resolveSocket(root, node, socket) {return;root.updateWorldMatrix(true, true);const rootInverse = root.matrixWorld.clone().invert();- const point = new THREE19.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);- const rootInverseQuaternion = root.getWorldQuaternion(new THREE19.Quaternion).invert();- const rotation = node.getWorldQuaternion(new THREE19.Quaternion).multiply(new THREE19.Quaternion(...frame.rotation)).premultiply(rootInverseQuaternion).normalize();+ const point = new THREE21.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);+ const rootInverseQuaternion = root.getWorldQuaternion(new THREE21.Quaternion).invert();+ const rotation = node.getWorldQuaternion(new THREE21.Quaternion).multiply(new THREE21.Quaternion(...frame.rotation)).premultiply(rootInverseQuaternion).normalize();return {id: socket.id,type: socket.type,@@ -12500,7 +13235,7 @@ function socketByType(sockets, type) {return sockets.find((socket) => socket.type === type);}function inspectPlacementSockets(context) {- if (!(context.scene instanceof THREE19.Object3D)) {+ if (!(context.scene instanceof THREE21.Object3D)) {return [];}const root = context.scene;@@ -12564,8 +13299,8 @@ function materialSignature(material) {function boundarySamples(root, axis, side, bins = 12) {root.updateWorldMatrix(true, true);const inverse = root.matrixWorld.clone().invert();- const localBounds = new THREE19.Box3;- for (const part of collectParts4(root))+ const localBounds = new THREE21.Box3;+ for (const part of collectParts5(root))if (part.renderable && part.box)localBounds.union(part.box);if (localBounds.isEmpty())@@ -12578,30 +13313,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 THREE19.Mesh) || !(node.geometry instanceof THREE19.BufferGeometry))+ if (!(node instanceof THREE21.Mesh) || !(node.geometry instanceof THREE21.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 THREE19.InstancedMesh ? node.count : 1;+ const count = node instanceof THREE21.InstancedMesh ? node.count : 1;for (let instanceIndex = 0;instanceIndex < count; instanceIndex++) {const transform = relative.clone();- if (node instanceof THREE19.InstancedMesh) {- const instance = new THREE19.Matrix4;+ if (node instanceof THREE21.InstancedMesh) {+ const instance = new THREE21.Matrix4;node.getMatrixAt(instanceIndex, instance);transform.multiply(instance);}- const normalMatrix = new THREE19.Matrix3().getNormalMatrix(transform);+ const normalMatrix = new THREE21.Matrix3().getNormalMatrix(transform);const material = materialSignature(node.material);for (let index = 0;index < positions.count; index++) {- const point = new THREE19.Vector3(positions.getX(index), positions.getY(index), positions.getZ(index)).applyMatrix4(transform);+ const point = new THREE21.Vector3(positions.getX(index), positions.getY(index), positions.getZ(index)).applyMatrix4(transform);if (Math.abs(point[axis] - edge) > band)continue;- const t = THREE19.MathUtils.clamp((point[crossAxis] - crossMin) / crossExtent, 0, 1);+ const t = THREE21.MathUtils.clamp((point[crossAxis] - crossMin) / crossExtent, 0, 1);const bin = Math.min(bins - 1, Math.floor(t * bins));- const normal = normals ? new THREE19.Vector3(normals.getX(index), normals.getY(index), normals.getZ(index)).applyMatrix3(normalMatrix).normalize() : new THREE19.Vector3(0, 1, 0);+ const normal = normals ? new THREE21.Vector3(normals.getX(index), normals.getY(index), normals.getZ(index)).applyMatrix3(normalMatrix).normalize() : new THREE21.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 });@@ -12624,7 +13359,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]) => THREE19.MathUtils.radToDeg(Math.acos(THREE19.MathUtils.clamp(a.normal.dot(b.normal), -1, 1))))) : 180;+ const maximumNormalDeltaDegrees = pairs.length ? Math.max(...pairs.map(([a, b]) => THREE21.MathUtils.radToDeg(Math.acos(THREE21.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`);@@ -12641,7 +13376,7 @@ function edgePairMeasurements(root, axis, sockets) {};}function inspectTileEdges(context) {- if (context.tileable !== true || !(context.scene instanceof THREE19.Object3D)) {+ if (context.tileable !== true || !(context.scene instanceof THREE21.Object3D)) {return [];}const root = context.scene;@@ -12724,11 +13459,11 @@ function isCorridor(part) {return part.roles.some((role) => /^environment\.(?:navigation\.)?corridor(?:\.|$)/.test(role));}function inspectNavigationClearance(context) {- if (context.navigable !== true || !(context.scene instanceof THREE19.Object3D)) {+ if (context.navigable !== true || !(context.scene instanceof THREE21.Object3D)) {return [];}const root = context.scene;- const parts = collectParts4(root);+ const parts = collectParts5(root);const corridors = parts.filter((part) => isCorridor(part));if (corridors.length === 0) {return [@@ -12854,11 +13589,11 @@ 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 THREE19.Object3D)) {+ if (context.groundPlaneY === undefined || !(context.scene instanceof THREE21.Object3D)) {return [];}const root = context.scene;- const parts = collectParts4(root).filter((part) => part.renderable && part.box);+ const parts = collectParts5(root).filter((part) => part.renderable && part.box);const findings = [];for (const part of parts) {const box = part.box;@@ -12901,7 +13636,7 @@ function inspectSpatialSupport(context) {}));}}- const size = box.getSize(new THREE19.Vector3);+ const size = box.getSize(new THREE21.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",@@ -13513,7 +14248,7 @@ var init_breadth2 = __esm(() => {});// src/qa/breadth-evidence.ts-import * as THREE20 from "three";+import * as THREE22 from "three";function record6(value) {return typeof value === "object" && value !== null && !Array.isArray(value);}@@ -13532,7 +14267,7 @@ function isAnimationClip(value) {function localRenderableBox(rootInverse, node) {if (isSpriteNode(node)) {const transform = rootInverse.clone().multiply(node.matrixWorld);- return new THREE20.Box3(new THREE20.Vector3(-0.5, -0.5, -0.0005), new THREE20.Vector3(0.5, 0.5, 0.0005)).applyMatrix4(transform);+ return new THREE22.Box3(new THREE22.Vector3(-0.5, -0.5, -0.0005), new THREE22.Vector3(0.5, 0.5, 0.0005)).applyMatrix4(transform);}if (!isMeshNode(node) || !node.geometry?.isBufferGeometry)return;@@ -13541,11 +14276,11 @@ function localRenderableBox(rootInverse, node) {if (!source || source.isEmpty())return;const transform = rootInverse.clone().multiply(node.matrixWorld);- const result = new THREE20.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 THREE20.Vector3(x, y, z).applyMatrix4(transform));+ result.expandByPoint(new THREE22.Vector3(x, y, z).applyMatrix4(transform));}}}@@ -13633,10 +14368,10 @@ function isEffectSurface(nodes) {function coverageRatio(boxes, overall) {if (boxes.length === 0 || overall.isEmpty())return 0;- const overallSize = overall.getSize(new THREE20.Vector3);+ const overallSize = overall.getSize(new THREE22.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 THREE20.Vector3);+ const size = box.getSize(new THREE22.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));@@ -13645,7 +14380,7 @@ function collectMaterialEvidence(root, intent) {root.updateWorldMatrix(true, true);const inverse = root.matrixWorld.clone().invert();const byMaterial = new Map;- const overall = new THREE20.Box3;+ const overall = new THREE22.Box3;root.traverseVisible((node) => {const box = localRenderableBox(inverse, node);if (!box || !isMeshNode(node) && !isSpriteNode(node))@@ -13670,7 +14405,7 @@ function collectMaterialEvidence(root, intent) {effectSurface: isEffectSurface(value.nodes),alphaMode: mode,alphaData: alphaData(material),- doubleSided: material.side === THREE20.DoubleSide,+ doubleSided: material.side === THREE22.DoubleSide,...mode === "mask" ? { alphaCutoff: standard.alphaTest ?? 0 } : {},screenAreaRatio: coverageRatio(value.boxes, overall),transparentLayers: mode === "blend" ? value.nodes.length : 0,@@ -13698,23 +14433,23 @@ function dominantGeometryAxis(root, mode) {const bounds = node.geometry.boundingBox;if (!bounds || bounds.isEmpty())return;- const size = bounds.getSize(new THREE20.Vector3);+ const size = bounds.getSize(new THREE22.Vector3);const axes = [- { score: size.x, direction: new THREE20.Vector3(1, 0, 0) },- { score: size.y, direction: new THREE20.Vector3(0, 1, 0) },- { score: size.z, direction: new THREE20.Vector3(0, 0, 1) }+ { score: size.x, direction: new THREE22.Vector3(1, 0, 0) },+ { score: size.y, direction: new THREE22.Vector3(0, 1, 0) },+ { score: size.z, direction: new THREE22.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 THREE20.Vector3).length();+ const score = selected.score * node.getWorldScale(new THREE22.Vector3).length();if (!best || (mode === "length" ? score > best.score : score < best.score)) {best = { score, direction };}});if (best)return signedAxis(best.direction);- const overall = new THREE20.Box3;+ const overall = new THREE22.Box3;root.traverseVisible((node) => {const box = localRenderableBox(inverse, node);if (box)@@ -13722,8 +14457,8 @@ function dominantGeometryAxis(root, mode) {});if (overall.isEmpty())return "+X";- const size = overall.getSize(new THREE20.Vector3);- const vector = mode === "length" ? size.x >= size.y && size.x >= size.z ? new THREE20.Vector3(1, 0, 0) : size.y >= size.z ? new THREE20.Vector3(0, 1, 0) : new THREE20.Vector3(0, 0, 1) : size.x <= size.y && size.x <= size.z ? new THREE20.Vector3(1, 0, 0) : size.y <= size.z ? new THREE20.Vector3(0, 1, 0) : new THREE20.Vector3(0, 0, 1);+ const size = overall.getSize(new THREE22.Vector3);+ const vector = mode === "length" ? size.x >= size.y && size.x >= size.z ? new THREE22.Vector3(1, 0, 0) : size.y >= size.z ? new THREE22.Vector3(0, 1, 0) : new THREE22.Vector3(0, 0, 1) : size.x <= size.y && size.x <= size.z ? new THREE22.Vector3(1, 0, 0) : size.y <= size.z ? new THREE22.Vector3(0, 1, 0) : new THREE22.Vector3(0, 0, 1);return signedAxis(vector);}function analyzedFacing(root, intent) {@@ -13757,8 +14492,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 THREE20.Quaternion().fromArray(first);- const b = new THREE20.Quaternion().fromArray(last);+ const a = new THREE22.Quaternion().fromArray(first);+ const b = new THREE22.Quaternion().fromArray(last);if (a.lengthSq() === 0 || b.lengthSq() === 0)return false;return 1 - Math.abs(a.normalize().dot(b.normalize())) <= 0.000001;@@ -14673,7 +15408,7 @@ function writtenNodeResolver(root, doc, purpose) {// src/node-visibility.tsimport { KHRNodeVisibility } from "@gltf-transform/extensions";-import * as THREE21 from "three";+import * as THREE23 from "three";function applyNodeVisibility(root, doc) {const hidden = [];root.traverse((node) => {@@ -14716,7 +15451,7 @@ function drawnSceneBounds(scene) {return;const mesh = node.getMesh();if (mesh) {- const base = new THREE21.Matrix4().fromArray(node.getWorldMatrix());+ const base = new THREE23.Matrix4().fromArray(node.getWorldMatrix());const instances = node.getExtension("EXT_mesh_gpu_instancing");const translation = instances?.getAttribute("TRANSLATION");const rotation = instances?.getAttribute("ROTATION");@@ -14727,7 +15462,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 THREE21.Matrix4().compose(new THREE21.Vector3().fromArray(t), new THREE21.Quaternion().fromArray(r), new THREE21.Vector3().fromArray(s));+ const localMatrix = new THREE23.Matrix4().compose(new THREE23.Vector3().fromArray(t), new THREE23.Quaternion().fromArray(r), new THREE23.Vector3().fromArray(s));matrices.push(base.clone().multiply(localMatrix).toArray());}const local = [0, 0, 0];@@ -14768,12 +15503,12 @@ var init_node_visibility = __esm(() => {});// src/delivery-inspect.ts-import * as THREE22 from "three";+import * as THREE24 from "three";import { PropertyType as PropertyType2 } from "@gltf-transform/core";function decompose(matrix) {- const translation = new THREE22.Vector3;- const rotation = new THREE22.Quaternion;- const scale = new THREE22.Vector3;+ const translation = new THREE24.Vector3;+ const rotation = new THREE24.Quaternion;+ const scale = new THREE24.Vector3;matrix.decompose(translation, rotation, scale);const clean = (value) => Object.is(value, -0) ? 0 : value;return {@@ -14785,7 +15520,7 @@ function decompose(matrix) {function drawnTriangles(visited) {const values = [];const local = [0, 0, 0];- const point = new THREE22.Vector3;+ const point = new THREE24.Vector3;for (const { node, roles, hidden } of visited) {const mesh = node.getMesh();if (!mesh || hidden || roles.some((role) => role.startsWith("collider.")))@@ -14798,7 +15533,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 THREE22.Matrix4().compose(new THREE22.Vector3().fromArray(translation?.getElement(i, []) ?? [0, 0, 0]), new THREE22.Quaternion().fromArray(rotation?.getElement(i, []) ?? [0, 0, 0, 1]), new THREE22.Vector3().fromArray(scale?.getElement(i, []) ?? [1, 1, 1]));+ const instance = new THREE24.Matrix4().compose(new THREE24.Vector3().fromArray(translation?.getElement(i, []) ?? [0, 0, 0]), new THREE24.Quaternion().fromArray(rotation?.getElement(i, []) ?? [0, 0, 0, 1]), new THREE24.Vector3().fromArray(scale?.getElement(i, []) ?? [1, 1, 1]));matrices.push(base.clone().multiply(instance));}for (const primitive of mesh.listPrimitives()) {@@ -14829,20 +15564,20 @@ function triangleOverlapsBox(a, b, c, h, tolerance) {return false;}const e = [- new THREE22.Vector3().subVectors(b, a),- new THREE22.Vector3().subVectors(c, b),- new THREE22.Vector3().subVectors(a, c)+ new THREE24.Vector3().subVectors(b, a),+ new THREE24.Vector3().subVectors(c, b),+ new THREE24.Vector3().subVectors(a, c)];- const normal = new THREE22.Vector3().crossVectors(e[0], e[1]);+ const normal = new THREE24.Vector3().crossVectors(e[0], e[1]);const axes = [normal];const units = [- new THREE22.Vector3(1, 0, 0),- new THREE22.Vector3(0, 1, 0),- new THREE22.Vector3(0, 0, 1)+ new THREE24.Vector3(1, 0, 0),+ new THREE24.Vector3(0, 1, 0),+ new THREE24.Vector3(0, 0, 1)];for (const unit of units)for (const edge of e)- axes.push(new THREE22.Vector3().crossVectors(unit, edge));+ axes.push(new THREE24.Vector3().crossVectors(unit, edge));for (const axis of axes) {if (axis.lengthSq() < 0.000000000000000000000001)continue;@@ -14854,14 +15589,14 @@ function triangleOverlapsBox(a, b, c, h, tolerance) {return true;}function closestPointOnTriangle(p, a, b, c) {- const ab = new THREE22.Vector3().subVectors(b, a);- const ac = new THREE22.Vector3().subVectors(c, a);- const ap = new THREE22.Vector3().subVectors(p, a);+ const ab = new THREE24.Vector3().subVectors(b, a);+ const ac = new THREE24.Vector3().subVectors(c, a);+ const ap = new THREE24.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 THREE22.Vector3().subVectors(p, b);+ const bp = new THREE24.Vector3().subVectors(p, b);const d3 = ab.dot(bp);const d4 = ac.dot(bp);if (d3 >= 0 && d4 <= d3)@@ -14869,7 +15604,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 THREE22.Vector3().subVectors(p, c);+ const cp = new THREE24.Vector3().subVectors(p, c);const d5 = ab.dot(cp);const d6 = ac.dot(cp);if (d6 >= 0 && d5 <= d6)@@ -14879,14 +15614,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 THREE22.Vector3().subVectors(c, b), (d4 - d3) / (d4 - d3 + (d5 - d6)));+ return b.clone().addScaledVector(new THREE24.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 THREE22.Vector3().subVectors(q1, p1);- const d2 = new THREE22.Vector3().subVectors(q2, p2);- const r = new THREE22.Vector3().subVectors(p1, p2);+ const d1 = new THREE24.Vector3().subVectors(q1, p1);+ const d2 = new THREE24.Vector3().subVectors(q2, p2);+ const r = new THREE24.Vector3().subVectors(p1, p2);const a = d1.dot(d1);const e = d2.dot(d2);const f = d2.dot(r);@@ -14895,22 +15630,22 @@ function segmentSegmentDistanceSq(p1, q1, p2, q2) {if (a <= 0.000000000000000000000001 && e <= 0.000000000000000000000001)return r.lengthSq();if (a <= 0.000000000000000000000001)- t = THREE22.MathUtils.clamp(f / e, 0, 1);+ t = THREE24.MathUtils.clamp(f / e, 0, 1);else {const c = d1.dot(r);if (e <= 0.000000000000000000000001)- s = THREE22.MathUtils.clamp(-c / a, 0, 1);+ s = THREE24.MathUtils.clamp(-c / a, 0, 1);else {const b = d1.dot(d2);const denominator = a * e - b * b;- s = denominator !== 0 ? THREE22.MathUtils.clamp((b * f - c * e) / denominator, 0, 1) : 0;+ s = denominator !== 0 ? THREE24.MathUtils.clamp((b * f - c * e) / denominator, 0, 1) : 0;t = (b * s + f) / e;if (t < 0) {t = 0;- s = THREE22.MathUtils.clamp(-c / a, 0, 1);+ s = THREE24.MathUtils.clamp(-c / a, 0, 1);} else if (t > 1) {t = 1;- s = THREE22.MathUtils.clamp((b - c) / a, 0, 1);+ s = THREE24.MathUtils.clamp((b - c) / a, 0, 1);}}}@@ -14919,8 +15654,8 @@ function segmentSegmentDistanceSq(p1, q1, p2, q2) {return c1.distanceToSquared(c2);}function segmentCrossesTriangle(p, q, a, b, c) {- const hit = new THREE22.Vector3;- const ray = new THREE22.Ray(p, new THREE22.Vector3().subVectors(q, p));+ const hit = new THREE24.Vector3;+ const ray = new THREE24.Ray(p, new THREE24.Vector3().subVectors(q, p));const length = ray.direction.length();if (length === 0)return false;@@ -15037,9 +15772,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 THREE22.Box3(new THREE22.Vector3(...min), new THREE22.Vector3(...max));+ const bounds = new THREE24.Box3(new THREE24.Vector3(...min), new THREE24.Vector3(...max));const finiteBounds = [...min, ...max].every(Number.isFinite);- const diagonal = finiteBounds ? bounds.getSize(new THREE22.Vector3).length() : 0;+ const diagonal = finiteBounds ? bounds.getSize(new THREE24.Vector3).length() : 0;const tolerance = Math.max(0.0001, diagonal * 0.0001);const colliderNodes = [];for (const entry of visited) {@@ -15118,23 +15853,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 THREE22.Vector3;- const b = new THREE22.Vector3;- const c = new THREE22.Vector3;+ const a = new THREE24.Vector3;+ const b = new THREE24.Vector3;+ const c = new THREE24.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 THREE22.Box3;+ const proxyBounds = new THREE24.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 THREE22.Vector3().fromArray(position.getElement(i, local)).applyMatrix4(matrix));+ proxyBounds.expandByPoint(new THREE24.Vector3().fromArray(position.getElement(i, local)).applyMatrix4(matrix));}if (proxyBounds.isEmpty())- proxyBounds.expandByPoint(new THREE22.Vector3().setFromMatrixPosition(matrix));+ proxyBounds.expandByPoint(new THREE24.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.");@@ -15145,11 +15880,11 @@ function inspectDelivery(doc) {continue;}overlapTests += triangleCount;- const toLocal = new THREE22.Matrix4;+ const toLocal = new THREE24.Matrix4;let touches = false;if (record.shape.kind === "box") {toLocal.copy(matrix).invert();- const half = new THREE22.Vector3(0.5, 0.5, 0.5);+ const half = new THREE24.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);@@ -15159,10 +15894,10 @@ function inspectDelivery(doc) {}} else {const { translation, rotation } = record.transform;- toLocal.compose(new THREE22.Vector3(...translation), new THREE22.Quaternion(...rotation), new THREE22.Vector3(1, 1, 1)).invert();+ toLocal.compose(new THREE24.Vector3(...translation), new THREE24.Quaternion(...rotation), new THREE24.Vector3(1, 1, 1)).invert();const { radius, height } = record.shape;- const p = new THREE22.Vector3(0, -height / 2 + radius, 0);- const q = new THREE22.Vector3(0, height / 2 - radius, 0);+ const p = new THREE24.Vector3(0, -height / 2 + radius, 0);+ const q = new THREE24.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);@@ -15181,7 +15916,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 THREE22.Vector3(...record.transform.translation).applyMatrix4(worldMatrix(moduleEntry.node).invert());+ const point = new THREE24.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);@@ -15195,7 +15930,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 THREE22.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 THREE24.Matrix4().fromArray(node.getWorldMatrix());var init_delivery_inspect = __esm(() => {init_gltf_io();init_semantic();@@ -15438,16 +16173,16 @@ function evaluateValidationProfileDocument(profile, doc, options = {}) {measurement: { actual: null }}, "observe");} else if (outcome.failures.length > 0)- report("HOST_VALIDATION_ATTRIBUTE_GRADIENT", "gradient", `${where} ${check.gradient.attribute}[${check.gradient.component}] fails the ${outcome.failures.join(" and ")} test along local ${check.gradient.axis}: ${round2(outcome.fromMean)} to ${round2(outcome.toMean)}, expected ${check.gradient.from} to ${check.gradient.to} within ${check.gradient.tolerance}.`, {+ report("HOST_VALIDATION_ATTRIBUTE_GRADIENT", "gradient", `${where} ${check.gradient.attribute}[${check.gradient.component}] fails the ${outcome.failures.join(" and ")} test along local ${check.gradient.axis}: ${round3(outcome.fromMean)} to ${round3(outcome.toMean)}, expected ${check.gradient.from} to ${check.gradient.to} within ${check.gradient.tolerance}.`, {affected: { ...affected, attribute: check.gradient.attribute },measurement: {- actual: `${round2(outcome.fromMean)}..${round2(outcome.toMean)}`,+ actual: `${round3(outcome.fromMean)}..${round3(outcome.toMean)}`,expected: `${check.gradient.from}..${check.gradient.to}`,threshold: check.gradient.tolerance,breakdown: {- fromMean: round2(outcome.fromMean),- toMean: round2(outcome.toMean),- worstRegression: round2(outcome.worstRegression)+ fromMean: round3(outcome.fromMean),+ toMean: round3(outcome.toMean),+ worstRegression: round3(outcome.worstRegression)}}});@@ -15472,10 +16207,10 @@ function evaluateValidationProfileDocument(profile, doc, options = {}) {}const { tolerance } = check.range;if (accessor.getCount() > 0 && (min < check.range.min - tolerance || max > check.range.max + tolerance))- report("HOST_VALIDATION_ATTRIBUTE_RANGE", "range", `${where} ${check.range.attribute}[${check.range.component}] spans ${round2(min)}..${round2(max)}; the host allows ${check.range.min}..${check.range.max} within ${tolerance}.`, {+ report("HOST_VALIDATION_ATTRIBUTE_RANGE", "range", `${where} ${check.range.attribute}[${check.range.component}] spans ${round3(min)}..${round3(max)}; the host allows ${check.range.min}..${check.range.max} within ${tolerance}.`, {affected: { ...affected, attribute: check.range.attribute },measurement: {- actual: `${round2(min)}..${round2(max)}`,+ actual: `${round3(min)}..${round3(max)}`,expected: `${check.range.min}..${check.range.max}`,threshold: tolerance}@@ -15639,7 +16374,7 @@ async function evaluateValidationProfileGlb(profile, bytes, options = {}) {}return evaluateValidationProfileDocument(profile, doc, options);}-var HOST_VALIDATION_RULE_ID = "HOST_VALIDATION_PROFILE", MAX_VALIDATION_ATTRIBUTE_READS = 4000000, MAX_VALIDATION_FINDINGS_PER_CODE = 32, ENDPOINT_BAND = 0.05, GRADIENT_BINS = 16, MIN_AXIS_EXTENT = 0.000001, HOST_VALIDATION_QA_RULE, round2 = (value) => Math.round(value * 1e6) / 1e6, AXIS_INDEX;+var HOST_VALIDATION_RULE_ID = "HOST_VALIDATION_PROFILE", MAX_VALIDATION_ATTRIBUTE_READS = 4000000, MAX_VALIDATION_FINDINGS_PER_CODE = 32, ENDPOINT_BAND = 0.05, GRADIENT_BINS = 16, MIN_AXIS_EXTENT = 0.000001, HOST_VALIDATION_QA_RULE, round3 = (value) => Math.round(value * 1e6) / 1e6, AXIS_INDEX;var init_validation_profile2 = __esm(() => {init_gltf_io();init_delivery_inspect();@@ -15710,6 +16445,7 @@ var init_run = __esm(() => {init_part_connectivity();init_reference_comparison();init_self_intersection();+ init_open_surface_penetration();init_sweep();init_environment2();init_breadth2();@@ -15730,6 +16466,7 @@ var init_run = __esm(() => {...ENVIRONMENT_QA_RULES,...W7_BREADTH_QA_RULES,SELF_INTERSECTION_QA_RULE,+ OPEN_SURFACE_PENETRATION_QA_RULE,SWEEP_QA_RULE,PART_CONNECTIVITY_QA_RULE,REFERENCE_COMPARISON_QA_RULE,@@ -17567,7 +18304,7 @@ var init_texture_atlas_pixels = __esm(() => {});// src/procedural-texture.ts-import * as THREE23 from "three";+import * as THREE25 from "three";function proceduralTextureSchemaVersion(input) {if (!input || typeof input !== "object" || Array.isArray(input))throw new ProceduralTextureError("proceduralTexture requires a plain JSON object.", "PROCEDURAL_TEXTURE_V3_CONTRACT");@@ -17588,14 +18325,14 @@ function proceduralTexture(spec) {if (proceduralTextureSchemaVersion(spec) === 3) {const compiled = compileProceduralTextureSpecV3(spec);const { width, height, usage, name } = compiled.spec;- const tex = new THREE23.DataTexture(compiled.pixels, width, height, THREE23.RGBAFormat, THREE23.UnsignedByteType);+ const tex = new THREE25.DataTexture(compiled.pixels, width, height, THREE25.RGBAFormat, THREE25.UnsignedByteType);if (name)tex.name = name;- tex.colorSpace = usage === "albedo" || usage === "emissive" ? THREE23.SRGBColorSpace : THREE23.NoColorSpace;- tex.wrapS = THREE23.RepeatWrapping;- tex.wrapT = THREE23.RepeatWrapping;- tex.minFilter = THREE23.LinearMipmapLinearFilter;- tex.magFilter = THREE23.LinearFilter;+ tex.colorSpace = usage === "albedo" || usage === "emissive" ? THREE25.SRGBColorSpace : THREE25.NoColorSpace;+ tex.wrapS = THREE25.RepeatWrapping;+ tex.wrapT = THREE25.RepeatWrapping;+ tex.minFilter = THREE25.LinearMipmapLinearFilter;+ tex.magFilter = THREE25.LinearFilter;tex.generateMipmaps = true;tex.needsUpdate = true;tex.userData["kilnProcedural"] = {@@ -17608,14 +18345,14 @@ function proceduralTexture(spec) {}const compiled = compileProceduralTextureSpecV2(spec);const { size, usage, name, layers } = compiled.spec;- const tex = new THREE23.DataTexture(compiled.pixels, size, size, THREE23.RGBAFormat, THREE23.UnsignedByteType);+ const tex = new THREE25.DataTexture(compiled.pixels, size, size, THREE25.RGBAFormat, THREE25.UnsignedByteType);if (name)tex.name = name;- tex.colorSpace = usage === "albedo" || usage === "emissive" ? THREE23.SRGBColorSpace : THREE23.NoColorSpace;- tex.wrapS = THREE23.RepeatWrapping;- tex.wrapT = THREE23.RepeatWrapping;- tex.minFilter = THREE23.LinearMipmapLinearFilter;- tex.magFilter = THREE23.LinearFilter;+ tex.colorSpace = usage === "albedo" || usage === "emissive" ? THREE25.SRGBColorSpace : THREE25.NoColorSpace;+ tex.wrapS = THREE25.RepeatWrapping;+ tex.wrapT = THREE25.RepeatWrapping;+ tex.minFilter = THREE25.LinearMipmapLinearFilter;+ tex.magFilter = THREE25.LinearFilter;tex.generateMipmaps = true;tex.needsUpdate = true;tex.userData["kilnProcedural"] = {@@ -17669,13 +18406,13 @@ function normalMapFromHeight(source, opts = {}) {out[o + 3] = 255;}}- const tex = new THREE23.DataTexture(out, width, height, THREE23.RGBAFormat, THREE23.UnsignedByteType);+ const tex = new THREE25.DataTexture(out, width, height, THREE25.RGBAFormat, THREE25.UnsignedByteType);tex.name = opts.name ?? (source.name ? `${source.name}_Normal` : "");- tex.colorSpace = THREE23.NoColorSpace;- tex.wrapS = THREE23.RepeatWrapping;- tex.wrapT = THREE23.RepeatWrapping;- tex.minFilter = THREE23.LinearMipmapLinearFilter;- tex.magFilter = THREE23.LinearFilter;+ tex.colorSpace = THREE25.NoColorSpace;+ tex.wrapS = THREE25.RepeatWrapping;+ tex.wrapT = THREE25.RepeatWrapping;+ tex.minFilter = THREE25.LinearMipmapLinearFilter;+ tex.magFilter = THREE25.LinearFilter;tex.generateMipmaps = true;tex.needsUpdate = true;return tex;@@ -17690,7 +18427,7 @@ var init_procedural_texture = __esm(() => {});// src/textures.ts-import * as THREE24 from "three";+import * as THREE26 from "three";async function loadTexture(source, opts = {}) {let bytes;if (typeof source === "string") {@@ -17711,7 +18448,7 @@ async function loadTexture(source, opts = {}) {if (!meta.width || !meta.height) {throw new Error("loadTexture: could not read image dimensions");}- const tex = new THREE24.DataTexture(new Uint8Array(data), meta.width, meta.height, THREE24.RGBAFormat, THREE24.UnsignedByteType);+ const tex = new THREE26.DataTexture(new Uint8Array(data), meta.width, meta.height, THREE26.RGBAFormat, THREE26.UnsignedByteType);const usage = opts.usage ?? "albedo";const colorSpace = usage === "albedo" || usage === "emissive" ? "srgb" : "linear";let hasAlpha = false;@@ -17721,14 +18458,14 @@ async function loadTexture(source, opts = {}) {break;}}- tex.colorSpace = colorSpace === "srgb" ? THREE24.SRGBColorSpace : THREE24.NoColorSpace;+ tex.colorSpace = colorSpace === "srgb" ? THREE26.SRGBColorSpace : THREE26.NoColorSpace;if (opts.name)tex.name = opts.name;tex.needsUpdate = true;- tex.wrapS = THREE24.RepeatWrapping;- tex.wrapT = THREE24.RepeatWrapping;- tex.minFilter = THREE24.LinearMipmapLinearFilter;- tex.magFilter = THREE24.LinearFilter;+ tex.wrapS = THREE26.RepeatWrapping;+ tex.wrapT = THREE26.RepeatWrapping;+ tex.minFilter = THREE26.LinearMipmapLinearFilter;+ tex.magFilter = THREE26.LinearFilter;tex.generateMipmaps = true;tex.userData["encoded"] = {mime,@@ -17763,17 +18500,17 @@ function requireTextureUsage(texture, usage) {if (meta && meta.usage !== usage) {throw new TypeError(`Texture ${JSON.stringify(texture.name || "(unnamed)")} was loaded for ${meta.usage}, not ${usage}.`);}- texture.colorSpace = usage === "albedo" || usage === "emissive" ? THREE24.SRGBColorSpace : THREE24.NoColorSpace;+ texture.colorSpace = usage === "albedo" || usage === "emissive" ? THREE26.SRGBColorSpace : THREE26.NoColorSpace;}function pbrMaterial(opts = {}) {- const mat = new THREE24.MeshStandardMaterial;+ const mat = new THREE26.MeshStandardMaterial;const isTex = (v) => !!v?.isTexture;if (isTex(opts.albedo)) {requireTextureUsage(opts.albedo, "albedo");mat.map = opts.albedo;- mat.color = new THREE24.Color(16777215);+ mat.color = new THREE26.Color(16777215);} else if (opts.albedo !== undefined) {- mat.color = new THREE24.Color(opts.albedo);+ mat.color = new THREE26.Color(opts.albedo);}if (opts.normal) {requireTextureUsage(opts.normal, "normal");@@ -17811,9 +18548,9 @@ function pbrMaterial(opts = {}) {if (isTex(opts.emissive)) {requireTextureUsage(opts.emissive, "emissive");mat.emissiveMap = opts.emissive;- mat.emissive = new THREE24.Color(16777215);+ mat.emissive = new THREE26.Color(16777215);} else if (opts.emissive !== undefined) {- mat.emissive = new THREE24.Color(opts.emissive);+ mat.emissive = new THREE26.Color(opts.emissive);}if (opts.emissiveIntensity !== undefined) {mat.emissiveIntensity = opts.emissiveIntensity;@@ -17845,7 +18582,7 @@ function pbrMaterial(opts = {}) {mat.transparent = true;}if (opts.doubleSided)- mat.side = THREE24.DoubleSide;+ mat.side = THREE26.DoubleSide;mat.userData["kilnMaterial"] = {alphaMode,...alphaMode === "mask" ? { alphaCutoff: mat.alphaTest } : {},@@ -20022,7 +20759,7 @@ var init_material_resources = __esm(() => {});// src/material-recipe-runtime.ts-import * as THREE25 from "three";+import * as THREE27 from "three";async function applyMaterialRecipeV1(request, options = {}) {const resolved = resolveMaterialRecipeV1(request);const cache = options.cache ?? DEFAULT_APPROVED_TEXTURE_CACHE;@@ -20045,9 +20782,9 @@ async function applyMaterialRecipeV1(request, options = {}) {};const material = pbrMaterial(materialOptions);material.name = options.name ?? request.id;- material.color.setRGB(resolved.baseColorFactor[0], resolved.baseColorFactor[1], resolved.baseColorFactor[2], THREE25.LinearSRGBColorSpace);+ material.color.setRGB(resolved.baseColorFactor[0], resolved.baseColorFactor[1], resolved.baseColorFactor[2], THREE27.LinearSRGBColorSpace);material.opacity = resolved.baseColorFactor[3];- material.emissive.setRGB(resolved.emissiveFactor[0], resolved.emissiveFactor[1], resolved.emissiveFactor[2], THREE25.LinearSRGBColorSpace);+ material.emissive.setRGB(resolved.emissiveFactor[0], resolved.emissiveFactor[1], resolved.emissiveFactor[2], THREE27.LinearSRGBColorSpace);const resources = [...loaded.values()].map((entry) => entry.provenance).sort((a, b) => `${a.resourceId}:${a.usage}`.localeCompare(`${b.resourceId}:${b.usage}`));const provenance = {schemaVersion: 1,@@ -20305,7 +21042,7 @@ var init_procedural_material_v3 = __esm(() => {});// src/qa/breadth-final.ts-import * as THREE26 from "three";+import * as THREE28 from "three";function bytesContainAscii(bytes, value) {const needle = new TextEncoder().encode(value);outer:@@ -20364,7 +21101,7 @@ function finalEffectAxis(nodes, mode) {if (!(semantic?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {continue;}- const matrix = new THREE26.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() ?? []) {@@ -20374,9 +21111,9 @@ function finalEffectAxis(nodes, mode) {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) }+ { 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 = {@@ -20793,6 +21530,13 @@ var init_requirements_applicability = __esm(() => {observation: true,kernel: "connectivity"},+ {+ id: "GEO_OPEN_SURFACE_PENETRATION",+ mode: "observe",+ keys: [],+ observation: true,+ kernel: "openSurface"+ },{ id: "REF_COMPARISON", mode: "observe", keys: [], observation: true },{ id: "SWEEP_SELF_INTERSECTION", mode: "observe", keys: [], observation: true, kernel: "sweep" },{ id: "HOST_VALIDATION_PROFILE", mode: "enforce", keys: ["validation"], kernel: "validation" }@@ -20937,13 +21681,13 @@ var init_requirements_report = __esm(() => {});// src/qa/requirements-run.ts-import { Object3D as Object3D15 } from "three";+import { Object3D as Object3D16 } 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"))+ if (!(scene instanceof Object3D16) || !sceneDecisions(context, policy).some((d) => d.ruleId === SELF_INTERSECTION_QA_RULE.id && d.mode !== "off"))return {};try {return { partPenetration: await analyzePartPenetration(scene) };@@ -20984,12 +21728,12 @@ function runRequirementsSceneQa(context, scene, clips, policy = {}, evidence = {};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 scopeObservation = scope?.state === "requested" && scene instanceof Object3D16 && 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) } : {}+ ...effects && scene instanceof Object3D16 && decisions.some((d) => d.ruleId.startsWith("VFX_") && d.mode !== "off") ? { vfxArtifact: analyzeVfxArtifactEvidenceV1(effects, scene, clips) } : {}}};const spatialInput = {@@ -21049,11 +21793,32 @@ function runRequirementsSceneQa(context, scene, clips, policy = {}, evidence = {}continue;}+ if (decision.ruleId === OPEN_SURFACE_PENETRATION_QA_RULE.id) {+ if (!(scene instanceof Object3D16))+ continue;+ const surfaces = analyzeOpenSurfacePenetration(scene);+ executedRules.push(decision.ruleId);+ findings.push(...inspectOpenSurfacePenetration(surfaces));+ Object.assign(geometryMetrics, {+ openSurfaceCoverage: surfaces.truncated || surfaces.skipped.length > 0 ? "partial" : "complete-surface-pairs",+ openSurfaceScope: "Visible static open surfaces sampled at their vertices against visible static closed solids, except alternates on different LOD levels; excludes open-vs-open pairs, motion, and any solid thinner than the sampled surface's facet spacing. Penetration within the contact tolerance is treated as intended contact, and penetration beyond it may still be intentional, as a fitting socketed into a shell is.",+ openSurfaceContactTolerance: surfaces.contactTolerance,+ openSurfaceOpenParts: surfaces.openParts,+ openSurfaceClosedParts: surfaces.closedParts,+ openSurfaceCandidatePairs: surfaces.candidatePairs,+ openSurfacePairsSampled: surfaces.pairsTested,+ openSurfacePairsNotReached: surfaces.pairsNotReached,+ openSurfaceVerticesUnresolved: surfaces.verticesUnresolved,+ openSurfaceLodAlternatePairs: surfaces.pairsLodAlternates,+ openSurfaceSkipped: surfaces.skipped.length+ });+ continue;+ }if (decision.ruleId === ASSET_SCOPE_QA_RULE.id && !scopeObservation)continue;if (decision.ruleId === HOST_VALIDATION_QA_RULE.id)continue;- if (decision.ruleId === PART_CONNECTIVITY_QA_RULE.id && !(scene instanceof Object3D15))+ if (decision.ruleId === PART_CONNECTIVITY_QA_RULE.id && !(scene instanceof Object3D16))continue;executedRules.push(decision.ruleId);if (decision.ruleId === PROP_EXACT_QA_RULE.id) {@@ -21199,6 +21964,7 @@ var init_requirements_run = __esm(() => {init_material();init_prop();init_part_connectivity();+ init_open_surface_penetration();init_sweep();init_self_intersection();init_vehicle2();@@ -21219,6 +21985,7 @@ var init_requirements_run = __esm(() => {PROP_ADVISORY_QA_RULE,PART_CONNECTIVITY_QA_RULE,SELF_INTERSECTION_QA_RULE,+ OPEN_SURFACE_PENETRATION_QA_RULE,SWEEP_QA_RULE,...VEHICLE_QA_RULES,...ARCHITECTURE_QA_RULES,@@ -21234,7 +22001,7 @@ var init_requirements_run = __esm(() => {});// src/qa/skin-integrity.ts-import * as THREE27 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;@@ -21281,9 +22048,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 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 THREE27.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);@@ -21333,7 +22100,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 || ![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;@@ -21382,7 +22149,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 === THREE29.AttachedBindMode ? meshWorld.clone().invert() : mesh.bindMatrix.clone().invert();const matrices = [];for (let joint = 0;joint < bones.length; joint++) {const boneWorld = world(bones[joint]);@@ -21390,13 +22157,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 THREE29.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 THREE29.Vector3, posed = new THREE29.Vector3, temp = new THREE29.Vector3, box = new THREE29.Box3;for (let vertex = 0;vertex < count; vertex++) {- THREE27.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);@@ -21593,7 +22360,7 @@ var init_material_export = __esm(() => {});// src/community-exporter.ts-import * as THREE28 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) {@@ -21623,7 +22390,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 THREE30.TextureSource(source.image);textures.set(source, copy);const bytes = source.userData["encoded"];if (bytes?.bytes) {@@ -21632,8 +22399,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 = THREE30.RGBAFormat;+ copy.type = THREE30.UnsignedByteType;})());}return copy;@@ -21650,7 +22417,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 THREE30.Texture)copy[key] = texture(value);}materials.set(source, copy);@@ -21666,15 +22433,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 THREE30.Group;copy.copy(shadow, false);}if (source.isSprite) {const sprite = source;- const geometry = new THREE28.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 THREE28.MeshBasicMaterial({+ const spriteMaterial = new THREE30.MeshBasicMaterial({name: sprite.material.name,color: sprite.material.color,opacity: sprite.material.opacity,@@ -21685,8 +22452,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 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];@@ -21750,8 +22517,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 THREE30.Texture().copy(map);+ adapted.source = new THREE30.TextureSource(canvas);canvasInputs.set(map, adapted);const direct = directImages.get(map);if (direct)@@ -21760,7 +22527,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 THREE30.Texture && value.flipY && value.image?.data)material[key] = canvasInput(value);}const standard = material;@@ -21782,8 +22549,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 = THREE30.PropertyBinding.parseTrackName(track.name);+ return ["position", "quaternion", "scale", "morphTargetInfluences"].includes(binding.propertyName) && THREE30.PropertyBinding.findNode(copy, binding.nodeName) !== null;} catch {return false;}@@ -21978,7 +22745,7 @@ function applyIndexPolicy(doc, policy) {var init_index_policy = () => {};// src/surface-bake.ts-import * as THREE29 from "three";+import * as THREE31 from "three";function settings(value, label) {if (value === false)return;@@ -22020,13 +22787,13 @@ function drawnMeshes(root) {function weld(mesh) {const position = mesh.geometry.getAttribute("position");const world = [];- const box = new THREE29.Box3;+ const box = new THREE31.Box3;for (let i = 0;i < position.count; i++) {- const point = new THREE29.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 THREE29.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);@@ -22060,7 +22827,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 THREE31.Vector3().subVectors(b, a).cross(new THREE31.Vector3().subVectors(c, a)).normalize());}const edges = new Map;const neighbours = points.map(() => new Set);@@ -22079,7 +22846,7 @@ function bakeEdge(topology, thresholdDegrees, smoothing) {edges.set(key, list);}}- const threshold = THREE29.MathUtils.degToRad(thresholdDegrees);+ const threshold = THREE31.MathUtils.degToRad(thresholdDegrees);const weights = new Float64Array(points.length);for (const [key, incidences] of edges) {let weight;@@ -22089,10 +22856,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(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 THREE29.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))@@ -22254,12 +23021,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 THREE31.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 THREE31.Vector3;for (const mesh of drawnMeshes(occluders)) {if (!drawn(mesh, null))continue;@@ -22323,12 +23090,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 THREE31.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 THREE31.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 THREE31.Vector3).length()};bvhs.set(key, entry);}@@ -22345,27 +23112,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] = 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 THREE29.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 THREE29.Vector3().subVectors(points[triangles[t + 1]], a).cross(new THREE29.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 THREE29.Vector3;- const bitangent = new THREE29.Vector3;- const origin = new THREE29.Vector3;- const direction = new THREE29.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) {@@ -22387,8 +23154,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] = 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 };@@ -22408,7 +23175,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 = THREE31.MathUtils.clamp((x - edge0) / (edge1 - edge0), 0, 1);return t * t * (3 - 2 * t);};var init_surface_bake = __esm(() => {@@ -22421,318 +23188,6 @@ var init_surface_bake = __esm(() => {});});-// src/geometry.ts-import * as THREE30 from "three";-function finiteArray(values, label, length) {- const result = Array.from(values);- if (length !== undefined && result.length !== length)- throw new Error(`${label}: expected ${length} values, got ${result.length}`);- if (!result.every((n) => Number.isFinite(Math.fround(n))))- throw new AuthoringDiagnosticError("MESH_DATA_NONFINITE", `${label}: all values must be finite Float32 values`);- return result;-}-function meshGeo(data) {- const positions = finiteArray(data.positions, "meshGeo positions");- if (positions.length < 9 || positions.length % 3)- throw new Error("meshGeo positions: need at least three xyz vertices");- const count = positions.length / 3;- const geometry = new THREE30.BufferGeometry;- geometry.setAttribute("position", new THREE30.Float32BufferAttribute(positions, 3));- if (data.indices) {- const indices = Array.from(data.indices);- if (!indices.length || indices.length % 3)- throw new Error("meshGeo indices: need complete triangles");- if (!indices.every((i) => Number.isInteger(i) && i >= 0 && i < count))- throw new Error("meshGeo index out of bounds or not an integer");- geometry.setIndex(indices);- } else if (count % 3)- throw new Error("meshGeo: non-indexed positions must form complete triangles");- if (data.normals) {- const normals = finiteArray(data.normals, "meshGeo normals", count * 3);- geometry.setAttribute("normal", new THREE30.Float32BufferAttribute(normals, 3));- for (let i = 0;i < count; i++)- if (Math.hypot(normals[i * 3], normals[i * 3 + 1], normals[i * 3 + 2]) === 0)- throw new Error("meshGeo normals: zero-length normal");- geometry.normalizeNormals();- } else- geometry.computeVertexNormals();- if (data.uvs)- geometry.setAttribute("uv", new THREE30.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.computeBoundingBox();- geometry.computeBoundingSphere();- return geometry;-}-function boundsScale(bounds) {- const size = bounds.getSize(new THREE30.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;- 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,- scale: boundsScale(bounds)- };-}-function positionTolerance(scale, supplied, relative) {- if (supplied === undefined)- return scale * relative;- if (!Number.isFinite(supplied) || supplied <= 0)- throw new Error("Geometry tolerance must be positive and finite");- if (scale / supplied > Number.MAX_SAFE_INTEGER)- throw new Error("Geometry tolerance is too small to resolve the position extent safely");- return supplied;-}-function positionKey(point, origin, tolerance) {- if (tolerance === 0)- return point.toArray().join(",");- return point.clone().sub(origin).toArray().map((x) => Math.round(x / tolerance)).join(",");-}-function geometryDiagnostics(geometry, tolerance) {- const p = geometry.getAttribute("position");- if (p?.itemSize !== 3)- throw new Error("geometryDiagnostics requires xyz positions");- const frame = positionFrame(p);- const distance = positionTolerance(frame.scale, tolerance, 0.000001);- const result = {- tolerance: distance,- toleranceMode: tolerance === undefined ? "relative" : "absolute",- positionScale: frame.scale,- vertices: p.count,- triangles: 0,- boundaryEdges: 0,- nonManifoldEdges: 0,- orientationConflicts: 0,- degenerateTriangles: 0,- collapsedByToleranceTriangles: 0,- invalidIndices: 0,- nonFiniteVertices: 0,- 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 ids = [];- const points = new Map;- const finite = [];- const point = new THREE30.Vector3;- for (let i = 0;i < p.count; i++) {- point.fromBufferAttribute(p, i);- finite[i] = [point.x, point.y, point.z].every(Number.isFinite);- if (!finite[i])- result.nonFiniteVertices++;- const key = finite[i] ? positionKey(point, frame.origin, distance) : `invalid:${i}`;- if (!points.has(key))- points.set(key, points.size);- ids.push(points.get(key));- }- const indices = geometry.index ? Array.from(geometry.index.array) : Array.from({ length: p.count }, (_, i) => i);- const edges = new Map;- const a = new THREE30.Vector3, b = new THREE30.Vector3, c = new THREE30.Vector3;- for (let i = 0;i < indices.length; i += 3) {- result.triangles++;- const triangle = indices.slice(i, i + 3);- if (triangle.length !== 3 || triangle.some((n) => !Number.isInteger(n) || n < 0 || n >= p.count)) {- result.invalidIndices++;- continue;- }- const [ia, ib, ic] = triangle;- if (!finite[ia] || !finite[ib] || !finite[ic])- continue;- pa.fromBufferAttribute(p, ia);- pb.fromBufferAttribute(p, ib);- pc.fromBufferAttribute(p, ic);- signedVolume += pa.dot(pb.cross(pc)) / 6;- a.fromBufferAttribute(p, ia);- b.fromBufferAttribute(p, ib);- c.fromBufferAttribute(p, ic);- const scale = frame.scale || 1;- b.sub(a).divideScalar(scale);- c.sub(a).divideScalar(scale);- if (b.cross(c).length() <= (distance / scale) ** 2)- result.degenerateTriangles++;- if (ids[ia] === ids[ib] || ids[ib] === ids[ic] || ids[ic] === ids[ia]) {- result.collapsedByToleranceTriangles++;- continue;- }- for (const [start, end] of [- [ia, ib],- [ib, ic],- [ic, ia]- ]) {- const u = ids[start], v = ids[end];- const key = u < v ? `${u}:${v}` : `${v}:${u}`;- const edge = edges.get(key) ?? { count: 0, direction: 0 };- edge.count++;- edge.direction += u < v ? 1 : -1;- edges.set(key, edge);- }- }- for (const edge of edges.values()) {- if (edge.count === 1)- result.boundaryEdges++;- else if (edge.count > 2)- result.nonManifoldEdges++;- else if (edge.direction !== 0)- result.orientationConflicts++;- }- const volumeFloor = (frame.scale || 1) ** 3 * 0.000000000001;- result.solid = {- closed: result.boundaryEdges === 0 && edges.size > 0,- manifold: result.nonManifoldEdges === 0,- orientation: result.orientationConflicts > 0 || Math.abs(signedVolume) <= volumeFloor ? "mixed" : signedVolume > 0 ? "outward" : "inward",- signedVolume: Object.is(signedVolume, -0) ? 0 : signedVolume- };- return result;-}-function parametricSurface(sample, options = {}) {- const {- u = [0, 1],- v = [0, 1],- uSegments: nu = 24,- vSegments: nv = 24,- periodicU = false,- periodicV = false,- orientation = "uv"- } = options;- for (const [name, n] of [- ["uSegments", nu],- ["vSegments", nv]- ])- if (!Number.isSafeInteger(n) || n < 1)- throw new Error(`parametricSurface ${name} must be a positive integer`);- const sampleCount = (nu + 1) * (nv + 1);- if (!Number.isSafeInteger(sampleCount) || sampleCount > GEOMETRY_ALLOCATION_LIMITS.parametricSamples)- throw new RangeError(`parametricSurface sample budget exceeded: requested ${sampleCount}, limit ${GEOMETRY_ALLOCATION_LIMITS.parametricSamples}. Reduce uSegments/vSegments or split the surface.`);- for (const [name, range] of [- ["u", u],- ["v", v]- ])- if (range.length !== 2 || !range.every(Number.isFinite) || range[0] === range[1] || !Number.isFinite(range[1] - range[0]))- throw new Error(`parametricSurface ${name} must be a finite nonzero domain`);- if (orientation !== "uv" && orientation !== "vu")- throw new Error("parametricSurface orientation must be uv or vu");- const positions = [], uvs = [], indices = [];- const sampledBounds = new THREE30.Box3;- const sampledPoint = new THREE30.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);- if (point.length !== 3 || !point.every(Number.isFinite))- throw new Error(`parametricSurface: sample (${i},${j}) must return three finite coordinates`);- positions.push(...point);- sampledBounds.expandByPoint(sampledPoint.set(...point));- uvs.push(i / nu, j / nv);- }- const groups = Array.from({ length: (nu + 1) * (nv + 1) }, (_, i) => i);- const seamScale = boundsScale(sampledBounds);- const find = (i) => {- while (groups[i] !== i)- i = groups[i];- return i;- };- const join = (a, b, _label) => {- const pa = positions.slice(a * 3, a * 3 + 3), pb = positions.slice(b * 3, b * 3 + 3);- if (Math.hypot(...pa.map((x, k) => x - pb[k])) > seamScale * 0.000001)- throw new AuthoringDiagnosticError("PARAMETRIC_PERIODIC_ENDPOINT");- groups[find(b)] = find(a);- for (let k = 0;k < 3; k++)- positions[b * 3 + k] = positions[a * 3 + k];- };- if (periodicU)- for (let j = 0;j <= nv; j++)- join(j * (nu + 1), j * (nu + 1) + nu, "periodicU");- if (periodicV)- for (let i = 0;i <= nu; i++)- join(i, nv * (nu + 1) + i, "periodicV");- for (let j = 0;j < nv; j++)- for (let i = 0;i < nu; i++) {- const a = j * (nu + 1) + i, b = a + 1, c = a + nu + 1, d = c + 1;- indices.push(...orientation === "uv" ? [a, b, c, b, d, c] : [a, c, b, b, c, d]);- }- const out = meshGeo({ positions, indices, uvs });- if (periodicU || periodicV) {- const normal = out.getAttribute("normal");- const sums = new Map;- for (let i = 0;i < normal.count; i++) {- const id = find(i);- const sum = sums.get(id) ?? new THREE30.Vector3;- sum.add(new THREE30.Vector3().fromBufferAttribute(normal, i));- sums.set(id, sum);- }- for (let i = 0;i < normal.count; i++) {- const n = sums.get(find(i)).clone().normalize();- normal.setXYZ(i, n.x, n.y, n.z);- }- }- return out;-}-function creaseNormals(geometry, options = {}) {- const angle = options.angle ?? 60;- if (!Number.isFinite(angle) || angle < 0 || angle > 180)- throw new Error("creaseNormals angle must be between 0 and 180 degrees");- const out = geometry.index ? geometry.toNonIndexed() : geometry.clone();- const position = out.getAttribute("position");- if (position?.itemSize !== 3 || position.count % 3 !== 0)- throw new Error("creaseNormals requires complete xyz triangles");- const frame = positionFrame(position);- const tolerance = positionTolerance(frame.scale, options.tolerance, 0.00000001);- const scale = frame.scale || 1;- const adjacent = new Map;- 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 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);- 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);- keys.push(key);- const neighbors = adjacent.get(key) ?? new Set;- neighbors.add(i / 3);- adjacent.set(key, neighbors);- }- }- const normals = new Float32Array(position.count * 3);- const threshold = Math.cos(THREE30.MathUtils.degToRad(angle));- for (let i = 0;i < position.count; i++) {- const face = faces[Math.floor(i / 3)], sum = new THREE30.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.deleteAttribute("tangent");- out.computeBoundingBox();- out.computeBoundingSphere();- return out;-}-var init_geometry = __esm(() => {- init_geometry_budget();- init_authoring_diagnostic();-});-// src/require-solid.tsfunction requireSolid(part) {if (part?.isObject3D !== true)@@ -23320,16 +23775,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 };@@ -23337,7 +23792,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;@@ -23384,7 +23839,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;@@ -23394,7 +23849,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;@@ -23410,7 +23865,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.");@@ -23426,21 +23881,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);@@ -23481,11 +23936,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);@@ -23507,7 +23962,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,@@ -23517,7 +23972,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 });@@ -23552,7 +24007,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: {@@ -23591,7 +24046,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))@@ -23624,16 +24079,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.");}}@@ -23721,9 +24176,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")@@ -23750,7 +24205,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));@@ -23791,7 +24246,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 = [];@@ -23804,7 +24259,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());@@ -23869,7 +24324,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@@ -24410,7 +24865,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;@@ -24418,7 +24873,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;@@ -24446,7 +24901,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`);@@ -24511,17 +24966,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,@@ -24531,13 +24986,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);@@ -24555,17 +25010,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)], [@@ -24635,7 +25090,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);@@ -24654,7 +25109,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);@@ -24662,7 +25117,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@@ -24671,7 +25126,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"),@@ -24687,7 +25142,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);@@ -24707,7 +25162,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}`], [@@ -24719,8 +25174,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);@@ -24737,7 +25192,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);@@ -24760,7 +25215,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 = {@@ -24778,7 +25233,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}`))));@@ -24893,13 +25348,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;@@ -24916,7 +25371,7 @@ var init_architecture2 = __esm(() => {});// src/gears.ts-import * as THREE35 from "three";+import * as THREE36 from "three";function gearGeo(opts = {}) {const {teeth = 12,@@ -25015,8 +25470,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();@@ -25101,8 +25556,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();@@ -25114,7 +25569,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) {@@ -25148,9 +25603,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 = {}) {@@ -25163,12 +25618,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);}@@ -25207,7 +25662,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();@@ -25246,13 +25701,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();@@ -25260,17 +25715,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 });@@ -25302,9 +25757,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";@@ -25328,13 +25783,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) {@@ -25342,7 +25797,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();@@ -25351,15 +25806,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.`);}@@ -25375,13 +25830,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);}@@ -25416,8 +25871,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))@@ -25447,13 +25902,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++) {@@ -25462,7 +25917,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;@@ -25476,7 +25931,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);@@ -25541,9 +25996,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");@@ -25574,15 +26029,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;@@ -25598,9 +26053,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();@@ -25618,12 +26073,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}`);}@@ -25636,20 +26091,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(",");@@ -25672,7 +26127,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;@@ -25693,17 +26148,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");@@ -25730,7 +26185,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;@@ -25753,7 +26208,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");@@ -25787,31 +26242,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(() => {@@ -25819,7 +26274,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.`);@@ -25827,9 +26282,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));@@ -25852,7 +26307,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)@@ -25866,11 +26321,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]));@@ -25930,13 +26385,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@@ -25949,7 +26404,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);};@@ -25987,8 +26442,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 ? [] : [{@@ -26011,8 +26466,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;@@ -26053,7 +26508,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");@@ -26070,7 +26525,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]));}@@ -26080,7 +26535,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]));});@@ -26105,7 +26560,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;@@ -26127,7 +26582,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;}@@ -26412,14 +26867,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@@ -26428,7 +26883,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();@@ -26483,7 +26938,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;@@ -26513,10 +26968,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;@@ -26533,11 +26988,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))@@ -26617,7 +27072,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))))@@ -26760,11 +27215,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) {@@ -26795,7 +27250,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);@@ -26854,7 +27309,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;@@ -27263,7 +27718,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.`);@@ -27295,8 +27750,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();@@ -27350,8 +27805,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();@@ -27359,7 +27814,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;@@ -27473,7 +27928,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.");@@ -27502,7 +27957,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;@@ -27519,13 +27974,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 = {@@ -27583,7 +28038,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))@@ -27808,7 +28263,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)@@ -27843,7 +28298,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))@@ -27955,7 +28410,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 () => {@@ -27987,7 +28442,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;@@ -27997,8 +28452,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);@@ -28033,11 +28488,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)))@@ -28073,7 +28528,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.");@@ -28114,15 +28569,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);@@ -28137,8 +28592,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();@@ -28194,7 +28649,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;@@ -28215,17 +28670,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)@@ -28257,16 +28712,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);@@ -28289,7 +28744,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);@@ -28308,7 +28763,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);@@ -28323,20 +28778,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);@@ -28353,7 +28808,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(",")}]).`);@@ -28361,7 +28816,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;@@ -28383,7 +28838,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);@@ -28391,14 +28846,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);@@ -28412,7 +28867,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;@@ -28428,12 +28883,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);@@ -28460,9 +28915,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;@@ -28477,7 +28932,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;@@ -28573,8 +29028,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;@@ -28605,17 +29060,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;@@ -28624,11 +29079,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];@@ -28644,7 +29099,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());@@ -28679,8 +29134,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)@@ -28688,7 +29143,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.");@@ -28698,19 +29153,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: [@@ -28750,7 +29205,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;@@ -28781,7 +29236,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, {@@ -28835,7 +29290,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;@@ -28865,7 +29320,7 @@ function requireColor(color, fn) {}function gameMaterial(color, options = {}) {requireColor(color, "gameMaterial");- const material = new THREE48.MeshStandardMaterial({+ const material = new THREE49.MeshStandardMaterial({color,metalness: options.metalness ?? 0,roughness: options.roughness ?? 0.8,@@ -28879,7 +29334,7 @@ function gameMaterial(color, options = {}) {}function basicMaterial(color, options = {}) {requireColor(color, "basicMaterial");- const material = new THREE48.MeshBasicMaterial({+ const material = new THREE49.MeshBasicMaterial({color,transparent: options.transparent ?? false,opacity: options.opacity ?? 1@@ -28890,13 +29345,13 @@ function basicMaterial(color, options = {}) {}function glassMaterial(color, options = {}) {requireColor(color, "glassMaterial");- const material = new THREE48.MeshStandardMaterial({+ const material = 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});if (options.name !== undefined)material.name = assertMaterialName(options.name, "glassMaterial");@@ -28904,7 +29359,7 @@ function glassMaterial(color, options = {}) {}function lambertMaterial(color, options = {}) {requireColor(color, "lambertMaterial");- const material = new THREE48.MeshLambertMaterial({+ const material = new THREE49.MeshLambertMaterial({color,flatShading: options.flatShading ?? true,emissive: options.emissive ?? 0@@ -28917,12 +29372,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) {@@ -28976,15 +29431,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);@@ -28994,7 +29449,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);@@ -29004,7 +29459,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())@@ -29017,7 +29472,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.");@@ -29031,12 +29486,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);@@ -29059,7 +29514,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;@@ -29136,12 +29591,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)@@ -29434,7 +29889,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};@@ -29577,7 +30032,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]);@@ -29695,10 +30150,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 = [];@@ -29722,7 +30177,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;@@ -29736,9 +30191,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;@@ -30059,7 +30514,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);@@ -32599,7 +33054,7 @@ var init_kit = __esm(() => {// src/texture-bake.tsimport { createHash as createHash6 } from "node:crypto";-import * as THREE50 from "three";+import * as THREE51 from "three";function readPixels(texture) {const image = texture.image;if (!image)@@ -32726,7 +33181,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)@@ -32809,10 +33264,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]);@@ -32832,7 +33287,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;@@ -33070,7 +33525,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)@@ -33218,8 +33673,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,@@ -33247,12 +33702,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];@@ -33400,7 +33855,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))@@ -33596,7 +34051,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;@@ -33638,9 +34093,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,@@ -35052,7 +35507,7 @@ function prepareTriangleCoverage(ax, ay, bx, by, cx, cy, size) {}// src/views/raster.ts-import { Vector3 as Vector338 } from "three";+import { Vector3 as Vector339 } from "three";function orbitDir(azimuthDeg, elevationDeg) {const el = Math.min(MAX_ELEVATION_DEG, Math.max(MIN_ELEVATION_DEG, elevationDeg)) * Math.PI / 180;const az = azimuthDeg * Math.PI / 180;@@ -35087,7 +35542,7 @@ function updateSurfaceMatrices(root) {function surfaceVertexReader(mesh, position) {for (const bone of mesh.skeleton?.bones ?? [])bone.updateWorldMatrix?.(true, false);- const vertex = new Vector338;+ const vertex = new Vector339;if (mesh.getVertexPosition)return (index) => mesh.getVertexPosition(index, vertex);if (position.getX && position.getY && position.getZ)@@ -35497,7 +35952,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 Vector340, Matrix4 as Matrix417, Euler as Euler5, Group as Group4 } from "three";function strict(value, keys, label) {for (const key of Object.keys(value))if (!keys.includes(key)) {@@ -35591,14 +36046,14 @@ function cameraFromBounds(bounds, dir, padding = 1, up, sceneBounds = bounds) {const z = vec(dir).normalize();if (!z.length())throw new Error("camera direction must be non-zero");- const hint = up ? vec(up) : Math.abs(z.y) > 0.99 ? new Vector339(0, 0, -1) : new Vector339(0, 1, 0);+ const hint = up ? vec(up) : Math.abs(z.y) > 0.99 ? new Vector340(0, 0, -1) : new Vector340(0, 1, 0);const x = hint.clone().cross(z).normalize();if (x.length() < 0.000000001)throw new Error("camera up must not be collinear with view");const y = z.clone().cross(x);let extent = 0.000001;for (let i = 0;i < 8; i++) {- const p = new Vector339((i & 1 ? bounds.max : bounds.min)[0], (i & 2 ? bounds.max : bounds.min)[1], (i & 4 ? bounds.max : bounds.min)[2]).sub(target);+ const p = new Vector340((i & 1 ? bounds.max : bounds.min)[0], (i & 2 ? bounds.max : bounds.min)[1], (i & 4 ? bounds.max : bounds.min)[2]).sub(target);extent = Math.max(extent, Math.abs(p.dot(x)), Math.abs(p.dot(y)));}const depthMin = bounds.min.map((v, i) => Math.min(v, sceneBounds.min[i]));@@ -35679,7 +36134,7 @@ function resolveAssetCamera(root, shot = {}) {if (relative !== "world") {const node = relative === "part" ? selected.node : rootNode;dir.transformDirection(node.matrixWorld);- up = tuple6(new Vector339(0, 1, 0).transformDirection(node.matrixWorld));+ up = tuple6(new Vector340(0, 1, 0).transformDirection(node.matrixWorld));}camera = cameraFromBounds(bounds, tuple6(dir), request.padding ?? 1.2, up, measureBounds(root));} else if (request.type === "explicit") {@@ -35726,7 +36181,7 @@ function resolveAssetCamera(root, shot = {}) {const position = vec(triple2(request.position, "position")).applyMatrix4(matrix);const target = request.target ? vec(triple2(request.target, "target")).applyMatrix4(matrix) : vec(bounds.min).add(vec(bounds.max)).multiplyScalar(0.5);const up = vec(triple2(request.up ?? [0, 1, 0], "up")).transformDirection(matrix);- const offset = vec(triple2(request.targetOffset ?? [0, 0, 0], "targetOffset")).applyMatrix4(matrix).sub(new Vector339().setFromMatrixPosition(matrix));+ const offset = vec(triple2(request.targetOffset ?? [0, 0, 0], "targetOffset")).applyMatrix4(matrix).sub(new Vector340().setFromMatrixPosition(matrix));const radius = vec(bounds.max).sub(vec(bounds.min)).length();camera = {version: "kiln.camera.v1",@@ -35855,11 +36310,11 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true, backdrop)}return result;};- const key = new Vector339(1.5, 2, 1).normalize();+ const key = new Vector340(1.5, 2, 1).normalize();const srgb = (n) => n <= 0.0031308 ? n * 12.92 : 1.055 * n ** (1 / 2.4) - 0.055;const ordered = compositingOrder(collectTriangles(root).tris, (px, py, pz) => camera.projection === "perspective" ? Math.hypot(px - position.x, py - position.y, pz - position.z) : (position.x - px) * z.x + (position.y - py) * z.y + (position.z - pz) * z.z);for (const tri of ordered) {- const world = [0, 1, 2].map((i) => new Vector339(tri.v[i * 3], tri.v[i * 3 + 1], tri.v[i * 3 + 2]));+ const world = [0, 1, 2].map((i) => new Vector340(tri.v[i * 3], tri.v[i * 3 + 1], tri.v[i * 3 + 2]));const normal = world[1].clone().sub(world[0]).cross(world[2].clone().sub(world[0])).normalize().multiplyScalar(tri.windingParity);const normalSign = visibleNormalSign(normal.dot(camera.projection === "perspective" ? position.clone().sub(world[0]) : z), tri.side, backfaceCull);if (normalSign === 0)@@ -35870,7 +36325,7 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true, backdrop)const color = tri.color.map((c) => Math.round(srgb(c * light) * 255));let polygon = world.map((p) => {const d = p.clone().sub(position);- return new Vector339(d.dot(x), d.dot(y), -d.dot(z));+ return new Vector340(d.dot(x), d.dot(y), -d.dot(z));});polygon = clip(clip(polygon, camera.near, true), camera.far, false);for (let t = 1;t < polygon.length - 1; t++) {@@ -35902,7 +36357,7 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true, backdrop)}return out;}-var vec = (a) => new Vector339(...a), tuple6 = (v) => [v.x || 0, v.y || 0, v.z || 0], KEY_HINTS;+var vec = (a) => new Vector340(...a), tuple6 = (v) => [v.x || 0, v.y || 0, v.z || 0], KEY_HINTS;var init_camera = __esm(() => {init_raster();init_background();@@ -36673,7 +37128,7 @@ import {PropertyBinding as PropertyBinding3,VectorKeyframeTrack as VectorKeyframeTrack2,Quaternion as Quaternion20,- Vector3 as Vector340,+ Vector3 as Vector341,InterpolateDiscrete as InterpolateDiscrete2,InterpolateLinear as InterpolateLinear2} from "three";@@ -36857,7 +37312,7 @@ function instanceMatrices(node) {translations?.getElement(index, translation);rotations?.getElement(index, rotation);scales?.getElement(index, scale);- const local = new Matrix418().compose(new Vector340(translations ? translation[0] : 0, translations ? translation[1] : 0, translations ? translation[2] : 0), new Quaternion20(rotations ? rotation[0] : 0, rotations ? rotation[1] : 0, rotations ? rotation[2] : 0, rotations ? rotation[3] : 1).normalize(), new Vector340(scales ? scale[0] : 1, scales ? scale[1] : 1, scales ? scale[2] : 1));+ const local = new Matrix418().compose(new Vector341(translations ? translation[0] : 0, translations ? translation[1] : 0, translations ? translation[2] : 0), new Quaternion20(rotations ? rotation[0] : 0, rotations ? rotation[1] : 0, rotations ? rotation[2] : 0, rotations ? rotation[3] : 1).normalize(), new Vector341(scales ? scale[0] : 1, scales ? scale[1] : 1, scales ? scale[2] : 1));matrices.push(world.clone().multiply(local));}return { matrices, count };@@ -36964,7 +37419,7 @@ function localInstanceMatrices(node) {translations?.getElement(index, translation);rotations?.getElement(index, rotation);scales?.getElement(index, scale);- return new Matrix418().compose(new Vector340(...translations ? translation.slice(0, 3) : [0, 0, 0]), new Quaternion20(...rotations ? rotation.slice(0, 4) : [0, 0, 0, 1]).normalize(), new Vector340(...scales ? scale.slice(0, 3) : [1, 1, 1]));+ return new Matrix418().compose(new Vector341(...translations ? translation.slice(0, 3) : [0, 0, 0]), new Quaternion20(...rotations ? rotation.slice(0, 4) : [0, 0, 0, 1]).normalize(), new Vector341(...scales ? scale.slice(0, 3) : [1, 1, 1]));});}async function loadGlbReviewScene(bytes) {@@ -37813,7 +38268,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();@@ -37825,18 +38280,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;@@ -37846,7 +38301,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;}});@@ -37914,33 +38369,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);@@ -37948,18 +38403,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;@@ -37993,7 +38448,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;@@ -38591,7 +39046,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]);@@ -38628,22 +39083,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];};}@@ -38769,7 +39224,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";@@ -38999,7 +39454,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) {@@ -39076,7 +39531,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);@@ -39239,7 +39694,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);}@@ -39263,9 +39718,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.`);}@@ -39839,8 +40294,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({@@ -39856,7 +40311,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];@@ -39874,10 +40329,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) {@@ -40002,18 +40457,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,@@ -40235,7 +40690,7 @@ var init_port = __esm(() => {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";+import * as THREE58 from "three";async function decodePng2(bytes) {const { data, info } = await sharp(bytes, {limitInputPixels: MATERIAL_LIBRARY_LIMITS.maxRecordPixels,@@ -40444,14 +40899,14 @@ async function previewGlb(manifest, maps, tiles, planeMeters) {material.color.setHex(p.baseColor);if (textures.has("emissive") && p.emissive !== undefined)material.emissive.setHex(p.emissive);- const geometry = new THREE57.PlaneGeometry(planeMeters, planeMeters);+ const geometry = new THREE58.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;+ const root = new THREE58.Group;root.name = `${manifest.materialId}-preview`;- const mesh = new THREE57.Mesh(geometry, material);+ const mesh = new THREE58.Mesh(geometry, material);mesh.name = "tiles";root.add(mesh);await Promise.resolve().then(() => init_render());@@ -47474,6 +47929,7 @@ var init_helper_contracts = __esm(() => {semantics: ["QA reports a marked part that cannot be built as a closed solid as GEO_PART_SELF_INTERSECTION_ACKNOWLEDGED with the reason, instead of GEO_PART_SELF_INTERSECTION_UNMEASURED.","Overlapping pairs with the marked part stay unmeasured and are counted; overlap there is not ruled out. Overlap between other parts is still measured and reported.",+ "Volume stays unmeasured, but GEO_OPEN_SURFACE_PENETRATION separately samples an open surface against the closed solids it meets and reports how far inside one it reaches.","A marked part that builds as a closed solid is measured like any other part. A part skipped for its size, draw range, instancing or invalid indices is still reported as unmeasured.","Both exporters write the mark as the node extras kilnOpenShell: { schemaVersion: 1, reason }; import restores it to userData.","Invalid arguments, or a kilnOpenShell value this helper did not write, are an OPEN_SHELL build error."@@ -52361,12 +52817,12 @@ var exports_part_placement = {};__export(exports_part_placement, {createPartPlacementReader: () => createPartPlacementReader});-import * as THREE58 from "three";+import * as THREE59 from "three";function createPartPlacementReader(root) {const bounds = createPartBoundsReader(root);- const position = new THREE58.Vector3;- const quaternion = new THREE58.Quaternion;- const scale = new THREE58.Vector3;+ const position = new THREE59.Vector3;+ const quaternion = new THREE59.Quaternion;+ const scale = new THREE59.Vector3;return (node) => {node.matrixWorld.decompose(position, quaternion, scale);const box = bounds(node);@@ -52379,10 +52835,10 @@ function createPartPlacementReader(root) {};};}-var round3 = (value) => {+var round4 = (value) => {const rounded = Math.round(value * 1e6) / 1e6;return rounded === 0 ? 0 : rounded;-}, rounded2 = (values) => values.map(round3);+}, rounded2 = (values) => values.map(round4);var init_part_placement = __esm(() => {init_raster();});@@ -52517,13 +52973,13 @@ var init_inspect = __esm(() => {});// src/views/measurement.ts-import { Box3 as Box326, Vector3 as Vector345 } from "three";+import { Box3 as Box327, Vector3 as Vector346 } from "three";function describeSubjectFrame(root, subject) {const selected = selectCameraSubject(root, subject);selected.node.updateWorldMatrix(true, true);const matrix = selected.node.matrixWorld;- const bounds = new Box326().setFromObject(selected.node);- const local = new Box326;+ const bounds = new Box327().setFromObject(selected.node);+ const local = new Box327;const invertible = matrix.determinant() !== 0;const inverse = matrix.clone().invert();selected.node.traverse((node) => {@@ -52534,10 +52990,10 @@ function describeSubjectFrame(root, subject) {if (!attr)return;for (let i = 0;i < attr.count; i++)- local.expandByPoint(new Vector345().fromBufferAttribute(attr, i).applyMatrix4(mesh.matrixWorld).applyMatrix4(inverse));+ local.expandByPoint(new Vector346().fromBufferAttribute(attr, i).applyMatrix4(mesh.matrixWorld).applyMatrix4(inverse));});const box = (b) => b.isEmpty() ? null : { min: b.min.toArray(), max: b.max.toArray() };- const axis = (i) => new Vector345().setFromMatrixColumn(matrix, i).normalize().toArray();+ const axis = (i) => new Vector346().setFromMatrixColumn(matrix, i).normalize().toArray();return {path: selected.path,name: selected.name,@@ -52547,7 +53003,7 @@ function describeSubjectFrame(root, subject) {invertible,worldMatrix: matrix.toArray(),axes: { frame: "world", x: axis(0), y: axis(1), z: axis(2) },- origin: new Vector345().setFromMatrixPosition(matrix).toArray()+ origin: new Vector346().setFromMatrixPosition(matrix).toArray()};}function measureAttachment(root, input) {@@ -52560,7 +53016,7 @@ function measureAttachment(root, input) {return {path: selected.path,local: [...local],- world: new Vector345(...local).applyMatrix4(selected.node.matrixWorld).toArray()+ world: new Vector346(...local).applyMatrix4(selected.node.matrixWorld).toArray()};};const from = endpoint(input.from), to = endpoint(input.to);@@ -52570,7 +53026,7 @@ function measureAttachment(root, input) {method: "straight-line anchor distance",from,to,- distance: new Vector345(...from.world).distanceTo(new Vector345(...to.world))+ distance: new Vector346(...from.world).distanceTo(new Vector346(...to.world))};}var init_measurement = __esm(() => {@@ -52582,7 +53038,7 @@ import {PropertyType as PropertyType6} from "@gltf-transform/core";import { ALL_EXTENSIONS as ALL_EXTENSIONS2 } from "@gltf-transform/extensions";-import { Box3 as Box327, Matrix4 as Matrix419, Quaternion as Quaternion23, Vector3 as Vector346 } from "three";+import { Box3 as Box328, Matrix4 as Matrix419, Quaternion as Quaternion23, Vector3 as Vector347 } from "three";async function accessorFingerprint(accessor) {const array = accessor?.getArray();if (!accessor || !array)@@ -52601,7 +53057,7 @@ function bounds(box) {return box.isEmpty() ? null : {min: box.min.toArray(),max: box.max.toArray(),- size: box.getSize(new Vector346).toArray()+ size: box.getSize(new Vector347).toArray()};}async function digest8(bytes) {@@ -52617,7 +53073,7 @@ function placements(node) {const rotation = instances.getAttribute("ROTATION");const scale = instances.getAttribute("SCALE");const count = translation?.getCount() ?? rotation?.getCount() ?? scale?.getCount() ?? 1;- return Array.from({ length: count }, (_, i) => world.clone().multiply(new Matrix419().compose(new Vector346().fromArray(translation?.getElement(i, []) ?? [0, 0, 0]), new Quaternion23().fromArray(rotation?.getElement(i, []) ?? [0, 0, 0, 1]), new Vector346().fromArray(scale?.getElement(i, []) ?? [1, 1, 1]))));+ return Array.from({ length: count }, (_, i) => world.clone().multiply(new Matrix419().compose(new Vector347().fromArray(translation?.getElement(i, []) ?? [0, 0, 0]), new Quaternion23().fromArray(rotation?.getElement(i, []) ?? [0, 0, 0, 1]), new Vector347().fromArray(scale?.getElement(i, []) ?? [1, 1, 1]))));}function triangleCorners(mode, count) {const corners = [];@@ -52684,7 +53140,7 @@ async function drawnGeometryDigests(doc) {}const data = new Float32Array(triangles * RECORD);const others = [];- const point = new Vector346;+ const point = new Vector347;const element = [0, 0, 0];const texcoord = [0, 0];const corner = new Float32Array(15);@@ -52767,7 +53223,7 @@ async function revisionTotals(doc) {const { vertices, geometry, uv } = await drawnGeometryDigests(doc);const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];const drawnBounds = scene ? drawnSceneBounds(scene) : null;- const box = drawnBounds && [...drawnBounds.min, ...drawnBounds.max].every(Number.isFinite) ? new Box327(new Vector346(...drawnBounds.min), new Vector346(...drawnBounds.max)) : new Box327;+ const box = drawnBounds && [...drawnBounds.min, ...drawnBounds.max].every(Number.isFinite) ? new Box328(new Vector347(...drawnBounds.min), new Vector347(...drawnBounds.max)) : new Box328;return {triangles: metrics.triangles,vertices,@@ -52842,7 +53298,7 @@ async function snapshot3(bytes) {if (depth > 128)throw new Error("Revision comparison hierarchy exceeds 128 levels.");const names = new Set;- const combined = new Box327;+ const combined = new Box328;const placed = siblings.flatMap((node) => [{ node, drawn: true },...lowerLevels(node).map((level) => ({ node: level, drawn: false }))@@ -52859,7 +53315,7 @@ async function snapshot3(bytes) {if (node.listExtensions().some((extension) => extension.extensionName !== MSFT_LOD && extension.extensionName !== "KHR_node_visibility") || mesh?.listExtensions().length)throw new Error("Revision comparison does not support node/mesh extensions (including instancing).");const primitives = mesh?.listPrimitives() ?? [];- const own = new Box327;+ const own = new Box328;const matrix = parentWorld.clone().multiply(new Matrix419().fromArray(node.getMatrix()));if (matrix.elements.some((value) => !Number.isFinite(value)))throw new Error("Revision comparison requires finite transforms.");@@ -52880,7 +53336,7 @@ async function snapshot3(bytes) {if (!Number.isInteger(vertex) || vertex < 0 || vertex >= position.getCount())throw new Error("Revision comparison found an invalid vertex index.");position.getElement(vertex, element);- const point = new Vector346(...element).applyMatrix4(matrix);+ const point = new Vector347(...element).applyMatrix4(matrix);if (point.toArray().some((value) => !Number.isFinite(value)))throw new Error("Revision comparison requires finite positions.");own.expandByPoint(point);@@ -53080,20 +53536,20 @@ var init_revision_comparison = __esm(() => {// src/views/surface-distance.tsimport {- Box3 as Box328,+ Box3 as Box329,Matrix4 as Matrix420,- Ray as Ray2,- Triangle as Triangle2,- Vector3 as Vector347+ Ray as Ray3,+ Triangle as Triangle3,+ Vector3 as Vector348} from "three";function hierarchy(triangles) {- const box = new Box328;+ const box = new Box329;for (const triangle of triangles)box.union(triangle.box);const count = triangles.length;if (count <= 4)return { box, count, triangles };- const size = box.getSize(new Vector347);+ const size = box.getSize(new Vector348);const axis = size.x >= size.y && size.x >= size.z ? "x" : size.y >= size.z ? "y" : "z";const center = (triangle) => triangle.box.min[axis] / 2 + triangle.box.max[axis] / 2;triangles.sort((a, b) => center(a) - center(b));@@ -53104,7 +53560,7 @@ function hierarchy(triangles) {children: [hierarchy(triangles.slice(0, middle)), hierarchy(triangles.slice(middle))]};}-function boxDistanceSquared(a, b) {+function boxDistanceSquared2(a, b) {const x = Math.max(0, a.min.x - b.max.x, b.min.x - a.max.x);const y = Math.max(0, a.min.y - b.max.y, b.min.y - a.max.y);const z = Math.max(0, a.min.z - b.max.z, b.min.z - a.max.z);@@ -53112,7 +53568,7 @@ function boxDistanceSquared(a, b) {}function collect(node, paths) {const triangles = [];- const bounds = new Box328;+ const bounds = new Box329;node.updateWorldMatrix(true, true);node.traverseVisible((child) => {const mesh = child;@@ -53145,13 +53601,13 @@ function collect(node, paths) {const id = index ? index.getX(i + offset) : i + offset;if (!Number.isSafeInteger(id) || id < 0 || id >= position.count)throw new Error("Surface distance encountered an invalid triangle index.");- const point = new Vector347().fromBufferAttribute(position, id).applyMatrix4(matrix);+ const point = new Vector348().fromBufferAttribute(position, id).applyMatrix4(matrix);if (![point.x, point.y, point.z].every(Number.isFinite))throw new Error("Surface distance encountered a non-finite world position.");return point;};- const triangle = new Triangle2(vertex(0), vertex(1), vertex(2));- const box = new Box328().setFromPoints([triangle.a, triangle.b, triangle.c]);+ const triangle = new Triangle3(vertex(0), vertex(1), vertex(2));+ const box = new Box329().setFromPoints([triangle.a, triangle.b, triangle.c]);bounds.union(box);triangles.push({triangle,@@ -53204,10 +53660,10 @@ function trianglePair(a, b) {const av = [a.a, a.b, a.c], bv = [b.a, b.b, b.c];if (b.getArea() > 0)for (const p of av)- record(p, b.closestPointToPoint(p, new Vector347));+ record(p, b.closestPointToPoint(p, new Vector348));if (a.getArea() > 0)for (const q of bv)- record(a.closestPointToPoint(q, new Vector347), q);+ record(a.closestPointToPoint(q, new Vector348), q);for (let i = 0;i < 3; i++) {const p = av[i], q = av[(i + 1) % 3];for (let j = 0;j < 3; j++)@@ -53220,9 +53676,9 @@ function trianglePair(a, b) {const length = delta.length();if (length === 0)continue;- const hit = new Ray2(origin, delta.divideScalar(length)).intersectTriangle(target.a, target.b, target.c, false, new Vector347);+ const hit = new Ray3(origin, delta.divideScalar(length)).intersectTriangle(target.a, target.b, target.c, false, new Vector348);if (hit && origin.distanceTo(hit) <= length) {- const onFace = target.closestPointToPoint(hit, new Vector347);+ const onFace = target.closestPointToPoint(hit, new Vector348);if (vertices === av)record(hit, onFace);else@@ -53256,7 +53712,7 @@ function measureSurfaceDistance(root, input) {});const finish = (complete) => {const upper = Number.isFinite(best) ? Math.sqrt(best) : null;- const lower = complete ? upper : Math.sqrt(boxDistanceSquared(a.bounds, b.bounds));+ const lower = complete ? upper : Math.sqrt(boxDistanceSquared2(a.bounds, b.bounds));if (!Number.isFinite(lower))throw new Error("Surface distance exceeds the finite numeric range.");return {@@ -53270,7 +53726,7 @@ function measureSurfaceDistance(root, input) {bounds: { lower, upper },closest,pairsVisited: visited,- reason: complete ? null : `Search budget ${MAX_WORK} reached (hierarchy and triangle pairs); select smaller parts. Upper bound is the closest pair found, not a completed minimum.`,+ reason: complete ? null : `Search budget ${MAX_WORK2} reached (hierarchy and triangle pairs); select smaller parts. Upper bound is the closest pair found, not a completed minimum.`,limitations: LIMITATIONS};};@@ -53278,25 +53734,25 @@ function measureSurfaceDistance(root, input) {{a: hierarchy(a.triangles),b: hierarchy(b.triangles),- lower: boxDistanceSquared(a.bounds, b.bounds)+ lower: boxDistanceSquared2(a.bounds, b.bounds)}];while (pending.length) {const current = pending.pop();if (current.lower >= best)continue;- if (work === MAX_WORK)+ if (work === MAX_WORK2)return finish(false);work++;const { a: x, b: y } = current;if ("triangles" in x && "triangles" in y) {for (const left of x.triangles)for (const right of y.triangles) {- if (work === MAX_WORK)+ if (work === MAX_WORK2)return finish(false);work++;visited++;- if (boxDistanceSquared(left.box, right.box) >= best)+ if (boxDistanceSquared2(left.box, right.box) >= best)continue;const candidate = trianglePair(left.triangle, right.triangle);if (candidate.squared < best) {@@ -53313,7 +53769,7 @@ function measureSurfaceDistance(root, input) {}));const next = pairs.map((pair) => ({...pair,- lower: boxDistanceSquared(pair.a.box, pair.b.box)+ lower: boxDistanceSquared2(pair.a.box, pair.b.box)}));if (next[0].lower <= next[1].lower)pending.push(next[1], next[0]);@@ -53376,7 +53832,7 @@ function measureSurfacePairs(root, pairs) {results};}-var MAX_TRIANGLES = 20000, MAX_WORK = 250000, LIMITATIONS = "Unsigned distance between tessellated surfaces in the exported rest pose. Zero means touching or crossing surfaces; positive distance does not exclude containment. Does not establish solid clearance, attachment strength, motion, or alpha/displacement appearance.";+var MAX_TRIANGLES = 20000, MAX_WORK2 = 250000, LIMITATIONS = "Unsigned distance between tessellated surfaces in the exported rest pose. Zero means touching or crossing surfaces; positive distance does not exclude containment. Does not establish solid clearance, attachment strength, motion, or alpha/displacement appearance.";var init_surface_distance = __esm(() => {init_camera();});@@ -53388,7 +53844,7 @@ __export(exports_draw_diagnostics, {});import { Primitive as Primitive3 } from "@gltf-transform/core";import { cloneDocument as cloneDocument2 } from "@gltf-transform/functions";-import * as THREE59 from "three";+import * as THREE60 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)@@ -53441,7 +53897,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 THREE59.Vector3).length(), b.bounds.getSize(new THREE59.Vector3).length(), 0.000000000001) * 0.000001;+ const tolerance = Math.max(a.bounds.getSize(new THREE60.Vector3).length(), b.bounds.getSize(new THREE60.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);@@ -53483,7 +53939,7 @@ function observe(uses) {unexaminedPrimitiveUses++;continue;}- const matrix = new THREE59.Matrix4().fromArray(node.getWorldMatrix());+ const matrix = new THREE60.Matrix4().fromArray(node.getWorldMatrix());if (primitive.getAttribute("TANGENT") && matrix.determinant() < 0)mirrored.set(part.id, part);const position = primitive.getAttribute("POSITION");@@ -53497,14 +53953,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 THREE59.Vector3().fromArray(position.getElement(indices ? indices.getScalar(start + j) : start + j, [])).applyMatrix4(matrix));+ const points = [0, 1, 2].map((j) => new THREE60.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 THREE59.Box3().setFromPoints(points),+ bounds: new THREE60.Box3().setFromPoints(points),part});}@@ -53795,7 +54251,7 @@ var init_export_root = __esm(() => {// src/tools/registry.tsimport { z as z25 } from "zod";-import * as THREE60 from "three";+import * as THREE61 from "three";function proceduralTextureMaterialContract(rendered, context) {const required = [...new Set(context.requiredProceduralTextureUsages ?? [])];if (required.length === 0)@@ -54076,8 +54532,8 @@ function collectSceneMetrics(root) {let meshes = 0;const materialSet = new Set;let lowestPart;- const box = new THREE60.Box3;- const point = new THREE60.Vector3;+ const box = new THREE61.Box3;+ const point = new THREE61.Vector3;root.updateWorldMatrix(true, true);root.traverseVisible((node) => {const n = node;@@ -54093,7 +54549,7 @@ function collectSceneMetrics(root) {const mesh = node;const position = mesh.geometry.getAttribute("position");const index = mesh.geometry.index;- const mb = new THREE60.Box3;+ const mb = new THREE61.Box3;if (position) {for (let i = 0;i < (index?.count ?? position.count); i++) {point.fromBufferAttribute(position, index ? index.getX(i) : i);@@ -54108,7 +54564,7 @@ function collectSceneMetrics(root) {});let bbox;if (!box.isEmpty()) {- const size = new THREE60.Vector3;+ const size = new THREE61.Vector3;box.getSize(size);bbox = {min: [box.min.x, box.min.y, box.min.z],diff --git a/dist/evaluator-worker.mjs b/dist/evaluator-worker.mjsindex 60ef3a42..df5f56af 100644--- a/dist/evaluator-worker.mjs+++ b/dist/evaluator-worker.mjs@@ -7261,231 +7261,361 @@ var init_part_connectivity = __esm(() => {});});-// src/sweep-analysis.ts+// src/geometry.tsimport * as THREE10 from "three";-function segmentHitsTriangle(a, b, tri, epsilon) {- const plane = new THREE10.Plane().setFromCoplanarPoints(tri.a, tri.b, tri.c);- if (plane.normal.lengthSq() === 0)- return false;- const da = plane.distanceToPoint(a), db = plane.distanceToPoint(b);- if (Math.abs(da) <= epsilon && Math.abs(db) <= epsilon) {- if (tri.containsPoint(a) || tri.containsPoint(b))- return true;- const n = plane.normal;- const drop = Math.abs(n.x) >= Math.abs(n.y) && Math.abs(n.x) >= Math.abs(n.z) ? 0 : Math.abs(n.y) >= Math.abs(n.z) ? 1 : 2;- const axes = [0, 1, 2].filter((axis) => axis !== drop);- const point = (p) => [p.getComponent(axes[0]), p.getComponent(axes[1])];- const cross = (p, q, r) => (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]);- const p = point(a), q = point(b);- const vertices = [tri.a, tri.b, tri.c];- return vertices.some((v, i) => {- const r = point(v), s = point(vertices[(i + 1) % 3]);- return cross(p, q, r) * cross(p, q, s) <= 0 && cross(r, s, p) * cross(r, s, q) <= 0 && axes.every((_, axis) => Math.max(Math.min(p[axis], q[axis]), Math.min(r[axis], s[axis])) <= Math.min(Math.max(p[axis], q[axis]), Math.max(r[axis], s[axis])) + epsilon);- });+function finiteArray(values, label, length) {+ const result = Array.from(values);+ if (length !== undefined && result.length !== length)+ throw new Error(`${label}: expected ${length} values, got ${result.length}`);+ if (!result.every((n) => Number.isFinite(Math.fround(n))))+ throw new AuthoringDiagnosticError("MESH_DATA_NONFINITE", `${label}: all values must be finite Float32 values`);+ return result;+}+function meshGeo(data) {+ const positions = finiteArray(data.positions, "meshGeo positions");+ if (positions.length < 9 || positions.length % 3)+ throw new Error("meshGeo positions: need at least three xyz vertices");+ const count = positions.length / 3;+ const geometry = new THREE10.BufferGeometry;+ geometry.setAttribute("position", new THREE10.Float32BufferAttribute(positions, 3));+ if (data.indices) {+ const indices = Array.from(data.indices);+ if (!indices.length || indices.length % 3)+ throw new Error("meshGeo indices: need complete triangles");+ if (!indices.every((i) => Number.isInteger(i) && i >= 0 && i < count))+ throw new Error("meshGeo index out of bounds or not an integer");+ geometry.setIndex(indices);+ } else if (count % 3)+ throw new Error("meshGeo: non-indexed positions must form complete triangles");+ if (data.normals) {+ const normals = finiteArray(data.normals, "meshGeo normals", count * 3);+ geometry.setAttribute("normal", new THREE10.Float32BufferAttribute(normals, 3));+ for (let i = 0;i < count; i++)+ if (Math.hypot(normals[i * 3], normals[i * 3 + 1], normals[i * 3 + 2]) === 0)+ throw new Error("meshGeo normals: zero-length normal");+ geometry.normalizeNormals();+ } else+ geometry.computeVertexNormals();+ if (data.uvs)+ geometry.setAttribute("uv", new THREE10.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 THREE10.Float32BufferAttribute(tangents, 4));}- if (da > epsilon && db > epsilon || da < -epsilon && db < -epsilon)- return false;- const t = da / (da - db);- return t >= 0 && t <= 1 && tri.containsPoint(a.clone().lerp(b, t));+ geometry.computeBoundingBox();+ geometry.computeBoundingSphere();+ return geometry;}-function recordSweepAnalysis(geometry, rings, profiles, closed) {+function boundsScale(bounds) {+ const size = bounds.getSize(new THREE10.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 THREE10.Box3;+ const point = new THREE10.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 THREE10.Vector3 : bounds.min,+ scale: boundsScale(bounds)+ };+}+function positionTolerance(scale, supplied, relative) {+ if (supplied === undefined)+ return scale * relative;+ if (!Number.isFinite(supplied) || supplied <= 0)+ throw new Error("Geometry tolerance must be positive and finite");+ if (scale / supplied > Number.MAX_SAFE_INTEGER)+ throw new Error("Geometry tolerance is too small to resolve the position extent safely");+ return supplied;+}+function positionKey(point, origin, tolerance) {+ if (tolerance === 0)+ return point.toArray().join(",");+ return point.clone().sub(origin).toArray().map((x) => Math.round(x / tolerance)).join(",");+}+function geometryDiagnostics(geometry, tolerance) {+ const p = geometry.getAttribute("position");+ if (p?.itemSize !== 3)+ throw new Error("geometryDiagnostics requires xyz positions");+ const frame = positionFrame(p);+ const distance = positionTolerance(frame.scale, tolerance, 0.000001);const result = {- complete: true,- stationsChecked: 0,- ringPairsChecked: 0,- tests: 0,- findings: []+ tolerance: distance,+ toleranceMode: tolerance === undefined ? "relative" : "absolute",+ positionScale: frame.scale,+ vertices: p.count,+ triangles: 0,+ boundaryEdges: 0,+ nonManifoldEdges: 0,+ orientationConflicts: 0,+ degenerateTriangles: 0,+ collapsedByToleranceTriangles: 0,+ invalidIndices: 0,+ nonFiniteVertices: 0,+ solid: { closed: false, manifold: true, orientation: "mixed", signedVolume: 0 }};- analyses.set(geometry, result);- if (rings.length > SWEEP_ANALYSIS_MAX_STATIONS || rings.some((ring) => ring.length > SWEEP_ANALYSIS_MAX_RING_POINTS)) {- result.complete = false;- return result;- }- const unique = closed ? rings.length - 1 : rings.length;- const centers = rings.map((ring) => ring.reduce((sum, p) => sum.add(p), new THREE10.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);- const cross = u.clone().cross(v).length();- const radius = cross > 0 ? u.length() * v.length() * a.distanceTo(c) / (2 * cross) : u.dot(v) < 0 ? 0 : Infinity;- const halfExtent = Math.max(...rings[i].map((p) => p.distanceTo(b)));- result.stationsChecked++;- if (radius < halfExtent)- result.findings.push({ station: i, kind: "curvature", radius, halfExtent });+ let signedVolume = 0;+ const pa = new THREE10.Vector3, pb = new THREE10.Vector3, pc = new THREE10.Vector3;+ const ids = [];+ const points = new Map;+ const finite = [];+ const point = new THREE10.Vector3;+ for (let i = 0;i < p.count; i++) {+ point.fromBufferAttribute(p, i);+ finite[i] = [point.x, point.y, point.z].every(Number.isFinite);+ if (!finite[i])+ result.nonFiniteVertices++;+ const key = finite[i] ? positionKey(point, frame.origin, distance) : `invalid:${i}`;+ if (!points.has(key))+ points.set(key, points.size);+ ids.push(points.get(key));}- const triangles = new Map;- const faces = (index) => {- if (!triangles.has(index))- triangles.set(index, THREE10.ShapeUtils.triangulateShape(profiles[index], []).map(([a, b, c]) => new THREE10.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 THREE10.Box3().setFromPoints(rings[i - 1]);- const boundsB = new THREE10.Box3().setFromPoints(rings[i]);- if (!boundsA.intersectsBox(boundsB)) {- result.ringPairsChecked++;+ const indices = geometry.index ? Array.from(geometry.index.array) : Array.from({ length: p.count }, (_, i) => i);+ const edges = new Map;+ const a = new THREE10.Vector3, b = new THREE10.Vector3, c = new THREE10.Vector3;+ for (let i = 0;i < indices.length; i += 3) {+ result.triangles++;+ const triangle = indices.slice(i, i + 3);+ if (triangle.length !== 3 || triangle.some((n) => !Number.isInteger(n) || n < 0 || n >= p.count)) {+ result.invalidIndices++;continue;}- const epsilon = Math.max(boundsA.getSize(new THREE10.Vector3).length(), boundsB.getSize(new THREE10.Vector3).length()) * 0.0000000001;- let hit = false;- pair:- for (const [a, b] of [- [i - 1, i],- [i, i - 1]- ]) {- for (let edge = 0;edge < rings[a].length; edge++)- for (const triangle of faces(b)) {- if (result.tests === SWEEP_ANALYSIS_MAX_TESTS) {- result.complete = false;- return result;- }- result.tests++;- if (segmentHitsTriangle(rings[a][edge], rings[a][(edge + 1) % rings[a].length], triangle, epsilon)) {- hit = true;- break pair;- }- }- }- result.ringPairsChecked++;- if (hit)- result.findings.push({ station: i, otherStation: i - 1, kind: "rings" });+ const [ia, ib, ic] = triangle;+ if (!finite[ia] || !finite[ib] || !finite[ic])+ continue;+ pa.fromBufferAttribute(p, ia);+ pb.fromBufferAttribute(p, ib);+ pc.fromBufferAttribute(p, ic);+ signedVolume += pa.dot(pb.cross(pc)) / 6;+ a.fromBufferAttribute(p, ia);+ b.fromBufferAttribute(p, ib);+ c.fromBufferAttribute(p, ic);+ const scale = frame.scale || 1;+ b.sub(a).divideScalar(scale);+ c.sub(a).divideScalar(scale);+ if (b.cross(c).length() <= (distance / scale) ** 2)+ result.degenerateTriangles++;+ if (ids[ia] === ids[ib] || ids[ib] === ids[ic] || ids[ic] === ids[ia]) {+ result.collapsedByToleranceTriangles++;+ continue;+ }+ for (const [start, end] of [+ [ia, ib],+ [ib, ic],+ [ic, ia]+ ]) {+ const u = ids[start], v = ids[end];+ const key = u < v ? `${u}:${v}` : `${v}:${u}`;+ const edge = edges.get(key) ?? { count: 0, direction: 0 };+ edge.count++;+ edge.direction += u < v ? 1 : -1;+ edges.set(key, edge);+ }+ }+ for (const edge of edges.values()) {+ if (edge.count === 1)+ result.boundaryEdges++;+ else if (edge.count > 2)+ result.nonManifoldEdges++;+ else if (edge.direction !== 0)+ result.orientationConflicts++;}+ const volumeFloor = (frame.scale || 1) ** 3 * 0.000000000001;+ result.solid = {+ closed: result.boundaryEdges === 0 && edges.size > 0,+ manifold: result.nonManifoldEdges === 0,+ orientation: result.orientationConflicts > 0 || Math.abs(signedVolume) <= volumeFloor ? "mixed" : signedVolume > 0 ? "outward" : "inward",+ signedVolume: Object.is(signedVolume, -0) ? 0 : signedVolume+ };return result;}-var SWEEP_ANALYSIS_MAX_STATIONS = 4096, SWEEP_ANALYSIS_MAX_RING_POINTS = 512, SWEEP_ANALYSIS_MAX_TESTS = 65536, analyses, readSweepAnalysis = (geometry) => analyses.get(geometry);-var init_sweep_analysis = __esm(() => {- analyses = new WeakMap;-});--// src/qa/sweep.ts-import { Object3D as Object3D5 } from "three";-function inspectSweepGeometry(scene) {- const findings = [];- if (!(scene instanceof Object3D5))- return findings;- scene.traverseVisible((node) => {- const geometry = node.geometry;- if (!geometry)- return;- const evidence = readSweepAnalysis(geometry);- if (!evidence)- return;- for (const finding of evidence.findings.slice(0, 16))- findings.push({- code: "SWEEP_SELF_INTERSECTION",- disposition: "observe",- dimension: "exportIntegrity",- profile: "geometry.sweep",- affected: { node: node.name },- message: finding.kind === "curvature" ? `Station ${finding.station}: curvature radius ${finding.radius} is below profile half-extent ${finding.halfExtent}.` : `Station ${finding.station}: its ring intersects ring ${finding.otherStation}.`,- measurement: {- name: finding.kind === "curvature" ? "curvatureRadius" : "intersectingRings",- actual: finding.radius ?? 1,- ...finding.halfExtent !== undefined ? { threshold: finding.halfExtent, unit: "m" } : {},- breakdown: {- station: finding.station,- ...finding.otherStation !== undefined ? { otherStation: finding.otherStation } : {}- }- },- repairText: "Inspect the named station; widen its turn, reduce the profile, or separate intersecting rings. This local check does not certify distant segments."- });- if (!evidence.complete || evidence.findings.length > 16)- findings.push({- code: "SWEEP_SELF_INTERSECTION_PARTIAL",- disposition: "observe",- dimension: "exportIntegrity",- profile: "geometry.sweep",- affected: { node: node.name },- message: "Sweep/loft analysis or its finding list reached the bounded budget; unchecked geometry remains.",- measurement: {- name: "ringPairsChecked",- actual: evidence.ringPairsChecked,- breakdown: {- stationsChecked: evidence.stationsChecked,- tests: evidence.tests,- omittedFindings: Math.max(0, evidence.findings.length - 16)- }- }- });- });- return findings;-}-var SWEEP_QA_RULE;-var init_sweep = __esm(() => {- init_sweep_analysis();- init_registry();- SWEEP_QA_RULE = Object.freeze({- id: "SWEEP_SELF_INTERSECTION",- profile: "geometry.sweep",- scope: { kind: "universal" },- ruleClass: "heuristic",- defaultMode: "observe",- owner: KILN_ENGINE_QA_OWNER,- evaluate: (context) => inspectSweepGeometry(context.scene)- });-});--// src/open-shell.ts-function markOpenShell(part, reason) {- const node = part;- if (!node || typeof node !== "object" || node.isObject3D !== true)- fail5("part must be a scene node, such as the mesh createPart returned or a group.");- const kept = validReason(reason);- if (kept === undefined)- fail5(`reason must be a non-empty string of at most ${MAX_OPEN_SHELL_REASON} characters saying why the shell is open.`);- const target = node;- if (!target.userData || typeof target.userData !== "object")- target.userData = {};- target.userData[OPEN_SHELL_KEY] = { schemaVersion: 1, reason: kept };- return part;-}-function markReason(value) {- if (!value || typeof value !== "object" || Array.isArray(value))- return;- const mark = value;- if (mark.schemaVersion !== 1)- return;- if (Object.keys(mark).some((key) => key !== "schemaVersion" && key !== "reason"))- return;- const reason = validReason(mark.reason);- return reason === mark.reason ? reason : undefined;-}-function openShellIntent(node) {- for (let at = node;at; at = at.parent) {- const value = at.userData?.[OPEN_SHELL_KEY];- if (value !== undefined)- return markReason(value);+function parametricSurface(sample, options = {}) {+ const {+ u = [0, 1],+ v = [0, 1],+ uSegments: nu = 24,+ vSegments: nv = 24,+ periodicU = false,+ periodicV = false,+ orientation = "uv"+ } = options;+ for (const [name, n] of [+ ["uSegments", nu],+ ["vSegments", nv]+ ])+ if (!Number.isSafeInteger(n) || n < 1)+ throw new Error(`parametricSurface ${name} must be a positive integer`);+ const sampleCount = (nu + 1) * (nv + 1);+ if (!Number.isSafeInteger(sampleCount) || sampleCount > GEOMETRY_ALLOCATION_LIMITS.parametricSamples)+ throw new RangeError(`parametricSurface sample budget exceeded: requested ${sampleCount}, limit ${GEOMETRY_ALLOCATION_LIMITS.parametricSamples}. Reduce uSegments/vSegments or split the surface.`);+ for (const [name, range] of [+ ["u", u],+ ["v", v]+ ])+ if (range.length !== 2 || !range.every(Number.isFinite) || range[0] === range[1] || !Number.isFinite(range[1] - range[0]))+ throw new Error(`parametricSurface ${name} must be a finite nonzero domain`);+ if (orientation !== "uv" && orientation !== "vu")+ throw new Error("parametricSurface orientation must be uv or vu");+ const positions = [], uvs = [], indices = [];+ const sampledBounds = new THREE10.Box3;+ const sampledPoint = new THREE10.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);+ if (point.length !== 3 || !point.every(Number.isFinite))+ throw new Error(`parametricSurface: sample (${i},${j}) must return three finite coordinates`);+ positions.push(...point);+ sampledBounds.expandByPoint(sampledPoint.set(...point));+ uvs.push(i / nu, j / nv);+ }+ const groups = Array.from({ length: (nu + 1) * (nv + 1) }, (_, i) => i);+ const seamScale = boundsScale(sampledBounds);+ const find = (i) => {+ while (groups[i] !== i)+ i = groups[i];+ return i;+ };+ const join = (a, b, _label) => {+ const pa = positions.slice(a * 3, a * 3 + 3), pb = positions.slice(b * 3, b * 3 + 3);+ if (Math.hypot(...pa.map((x, k) => x - pb[k])) > seamScale * 0.000001)+ throw new AuthoringDiagnosticError("PARAMETRIC_PERIODIC_ENDPOINT");+ groups[find(b)] = find(a);+ for (let k = 0;k < 3; k++)+ positions[b * 3 + k] = positions[a * 3 + k];+ };+ if (periodicU)+ for (let j = 0;j <= nv; j++)+ join(j * (nu + 1), j * (nu + 1) + nu, "periodicU");+ if (periodicV)+ for (let i = 0;i <= nu; i++)+ join(i, nv * (nu + 1) + i, "periodicV");+ for (let j = 0;j < nv; j++)+ for (let i = 0;i < nu; i++) {+ const a = j * (nu + 1) + i, b = a + 1, c = a + nu + 1, d = c + 1;+ indices.push(...orientation === "uv" ? [a, b, c, b, d, c] : [a, c, b, b, c, d]);+ }+ const out = meshGeo({ positions, indices, uvs });+ if (periodicU || periodicV) {+ const normal = out.getAttribute("normal");+ const sums = new Map;+ for (let i = 0;i < normal.count; i++) {+ const id = find(i);+ const sum = sums.get(id) ?? new THREE10.Vector3;+ sum.add(new THREE10.Vector3().fromBufferAttribute(normal, i));+ sums.set(id, sum);+ }+ for (let i = 0;i < normal.count; i++) {+ const n = sums.get(find(i)).clone().normalize();+ normal.setXYZ(i, n.x, n.y, n.z);+ }}- return;+ return out;}-function openShellExtras(node) {- const target = node;- const value = target?.userData?.[OPEN_SHELL_KEY];- if (value === undefined)- return {};- const reason = markReason(value);- if (reason === undefined)- fail5(`userData.${OPEN_SHELL_KEY} on ${JSON.stringify(target?.name || "(unnamed node)")} is not a mark this helper wrote; the engine owns that key, so set it only through markOpenShell.`);- return { [OPEN_SHELL_KEY]: { schemaVersion: 1, reason } };+function creaseNormals(geometry, options = {}) {+ const angle = options.angle ?? 60;+ if (!Number.isFinite(angle) || angle < 0 || angle > 180)+ throw new Error("creaseNormals angle must be between 0 and 180 degrees");+ const out = geometry.index ? geometry.toNonIndexed() : geometry.clone();+ const position = out.getAttribute("position");+ if (position?.itemSize !== 3 || position.count % 3 !== 0)+ throw new Error("creaseNormals requires complete xyz triangles");+ const frame = positionFrame(position);+ const tolerance = positionTolerance(frame.scale, options.tolerance, 0.00000001);+ const scale = frame.scale || 1;+ const adjacent = new Map;+ const keys = [];+ const faces = [];+ for (let i = 0;i < position.count; i += 3) {+ const a = new THREE10.Vector3().fromBufferAttribute(position, i);+ const b = new THREE10.Vector3().fromBufferAttribute(position, i + 1);+ const c = new THREE10.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 THREE10.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);+ keys.push(key);+ const neighbors = adjacent.get(key) ?? new Set;+ neighbors.add(i / 3);+ adjacent.set(key, neighbors);+ }+ }+ const normals = new Float32Array(position.count * 3);+ const threshold = Math.cos(THREE10.MathUtils.degToRad(angle));+ for (let i = 0;i < position.count; i++) {+ const face = faces[Math.floor(i / 3)], sum = new THREE10.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 THREE10.BufferAttribute(normals, 3));+ out.deleteAttribute("tangent");+ out.computeBoundingBox();+ out.computeBoundingSphere();+ return out;}-var OPEN_SHELL_KEY = "kilnOpenShell", MAX_OPEN_SHELL_REASON = 200, EXAMPLE2 = 'markOpenShell(rail, "C-channel closed by the end plates")', fail5 = (detail) => {- throw new AuthoringDiagnosticError("OPEN_SHELL", `markOpenShell(part, reason): ${detail} For example ${EXAMPLE2}.`);-}, validReason = (reason) => {- if (typeof reason !== "string")- return;- const trimmed = reason.trim();- return trimmed.length > 0 && trimmed.length <= MAX_OPEN_SHELL_REASON ? trimmed : undefined;-};-var init_open_shell = __esm(() => {+var init_geometry = __esm(() => {+ init_geometry_budget();init_authoring_diagnostic();});-// src/qa/self-intersection.ts+// src/qa/open-surface-penetration.tsimport * as THREE11 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));- return Number.isFinite(ratio) ? ratio : 0;+function buildHierarchy(triangles) {+ const box = new THREE11.Box3;+ for (const triangle of triangles)+ box.union(triangle.box);+ if (triangles.length <= 4)+ return { box, triangles };+ const size = box.getSize(new THREE11.Vector3);+ const axis = size.x >= size.y && size.x >= size.z ? "x" : size.y >= size.z ? "y" : "z";+ const center = (triangle) => triangle.box.min[axis] / 2 + triangle.box.max[axis] / 2;+ const sorted = [...triangles].sort((a, b) => center(a) - center(b));+ const middle = Math.floor(sorted.length / 2);+ return {+ box,+ children: [buildHierarchy(sorted.slice(0, middle)), buildHierarchy(sorted.slice(middle))]+ };+}+function worldTriangles(mesh) {+ const geometry = mesh.geometry;+ const position = geometry.getAttribute("position");+ if (position?.itemSize !== 3)+ return null;+ const index = geometry.getIndex();+ const count = index ? index.count : position.count;+ if (count % 3 !== 0)+ return null;+ const triangles = [];+ const vertex = (at) => {+ const id = index ? index.getX(at) : at;+ if (!Number.isSafeInteger(id) || id < 0 || id >= position.count)+ return null;+ const point = new THREE11.Vector3().fromBufferAttribute(position, id).applyMatrix4(mesh.matrixWorld);+ return [point.x, point.y, point.z].every(Number.isFinite) ? point : null;+ };+ for (let i = 0;i < count; i += 3) {+ const a = vertex(i), b = vertex(i + 1), c = vertex(i + 2);+ if (!a || !b || !c)+ return null;+ const triangle = new THREE11.Triangle(a, b, c);+ triangles.push({ triangle, box: new THREE11.Box3().setFromPoints([a, b, c]) });+ }+ return triangles.length ? triangles : null;}function triangleCount(geometry) {const index = geometry.getIndex();@@ -7505,7 +7635,7 @@ function collectParts3(root, skipped) {if (mesh.isInstancedMesh || mesh.isSkinnedMesh || Object.values(mesh.geometry.morphAttributes).some((targets) => targets.length)) {skipped.push({part: name,- reason: "instancing, skin or morph deformation is unsupported by part-volume analysis"+ reason: "instancing, skin or morph deformation is unsupported by surface sampling"});return;}@@ -7514,17 +7644,17 @@ function collectParts3(root, skipped) {if (range.start !== 0 || range.count < total) {skipped.push({part: name,- reason: "partial triangle draw ranges are unsupported by part-volume analysis"+ reason: "partial triangle draw ranges are unsupported by surface sampling"});return;}const triangles = triangleCount(mesh.geometry);if (triangles === 0)return;- if (triangles > MAX_PART_TRIANGLES) {+ if (triangles > MAX_SURFACE_TRIANGLES) {skipped.push({part: name,- reason: `${triangles} triangles exceeds the ${MAX_PART_TRIANGLES}-triangle analysis budget`+ reason: `${triangles} triangles exceeds the ${MAX_SURFACE_TRIANGLES}-triangle analysis budget`});return;}@@ -7532,334 +7662,289 @@ function collectParts3(root, skipped) {const box = mesh.geometry.boundingBox.clone().applyMatrix4(mesh.matrixWorld);if (box.isEmpty())return;- const center = box.getCenter(new THREE11.Vector3);- const size = box.getSize(new THREE11.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) {+ const determinant = mesh.matrixWorld.determinant();+ if (![...box.min, ...box.max].every(Number.isFinite) || !Number.isFinite(determinant)) {+ skipped.push({ part: name, reason: "non-finite transformed bounds cannot be measured" });+ return;+ }+ let diagnostics;+ try {+ diagnostics = geometryDiagnostics(mesh.geometry);+ } catch (error) {skipped.push({part: name,- reason: "non-finite or collapsed transformed bounds cannot be measured"+ reason: `topology could not be analyzed (${error instanceof Error ? error.message : String(error)})`});return;}- parts.push({- name,- mesh,- box,- triangles,- center,- scale,- lod: lodMembership(mesh),- intent: openShellIntent(mesh)- });+ const closed = diagnostics.solid.closed && diagnostics.solid.manifold && diagnostics.solid.orientation !== "mixed";+ parts.push({ name, mesh, box, closed, lod: lodMembership(mesh) });});return parts;}-function meshToArrays(part) {- const { mesh, center, scale } = part;- const geometry = mesh.geometry;- const position = geometry.getAttribute("position");- if (position?.itemSize !== 3)- return null;- const matrix = mesh.matrixWorld.clone();- matrix.elements[12] -= center.x;- matrix.elements[13] -= center.y;- matrix.elements[14] -= center.z;- const v = new THREE11.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);- if (![v.x, v.y, v.z].every((n) => Number.isFinite(Math.fround(n))))- return null;- verts[i * 3] = v.x;- verts[i * 3 + 1] = v.y;- verts[i * 3 + 2] = v.z;- }- const index = geometry.getIndex();- let tris;- if (index) {- if (index.count % 3 !== 0)- return null;- tris = new Uint32Array(index.count);- for (let i = 0;i < index.count; i++) {- const id = index.getX(i);- if (!Number.isSafeInteger(id) || id < 0 || id >= position.count)- return null;- tris[i] = id;+function boxDistanceSquared(box, point) {+ const x = Math.max(box.min.x - point.x, 0, point.x - box.max.x);+ const y = Math.max(box.min.y - point.y, 0, point.y - box.max.y);+ const z = Math.max(box.min.z - point.z, 0, point.z - box.max.z);+ return x * x + y * y + z * z;+}+function boxOverlapRatio(a, b) {+ const extent = (box) => (box.max.x - box.min.x) * (box.max.y - box.min.y) * (box.max.z - box.min.z);+ 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(extent(a), extent(b));+ return Number.isFinite(ratio) ? ratio : 0;+}++class Budget {+ limit;+ used = 0;+ exhausted = false;+ constructor(limit) {+ this.limit = limit;+ }+ spend() {+ if (this.used >= this.limit) {+ this.exhausted = true;+ return false;}- } else {- if (position.count % 3 !== 0)+ this.used++;+ return true;+ }+}+function nearestDistance(root, point, budget) {+ let best = Infinity;+ const stack = [root];+ const scratch = new THREE11.Vector3;+ while (stack.length) {+ const node = stack.pop();+ if (boxDistanceSquared(node.box, point) >= best)+ continue;+ if ("triangles" in node) {+ for (const { triangle } of node.triangles) {+ if (!budget.spend())+ return null;+ const distance = point.distanceToSquared(triangle.closestPointToPoint(point, scratch));+ if (distance < best)+ best = distance;+ }+ } else+ stack.push(node.children[0], node.children[1]);+ }+ return Number.isFinite(best) ? Math.sqrt(best) : null;+}+function parity(root, point, direction, budget) {+ const ray = new THREE11.Ray(point, direction);+ const stack = [root];+ const hit = new THREE11.Vector3;+ const barycentric = new THREE11.Vector3;+ let crossings = 0;+ while (stack.length) {+ const node = stack.pop();+ if (!ray.intersectsBox(node.box))+ continue;+ if ("triangles" in node) {+ for (const { triangle } of node.triangles) {+ if (!budget.spend())+ return null;+ if (ray.intersectTriangle(triangle.a, triangle.b, triangle.c, false, hit) === null)+ continue;+ triangle.getBarycoord(hit, barycentric);+ if ([barycentric.x, barycentric.y, barycentric.z].some((v) => Math.abs(v) < PARITY_EPSILON))+ return null;+ crossings++;+ }+ } else+ stack.push(node.children[0], node.children[1]);+ }+ return crossings % 2 === 1;+}+function inside(root, point, budget) {+ for (const direction of PARITY_DIRECTIONS) {+ const verdict = parity(root, point, direction, budget);+ if (verdict !== null)+ return verdict;+ if (budget.exhausted)return null;- tris = new Uint32Array(position.count);- for (let i = 0;i < position.count; i++)- tris[i] = i;}- if (mesh.matrixWorld.determinant() < 0)- for (let i = 0;i < tris.length; i += 3)- [tris[i + 1], tris[i + 2]] = [tris[i + 2], tris[i + 1]];- return { vertProperties: verts, triVerts: tris };+ return null;}-async function analyzePartPenetration(root) {- const skipped = [];- const parts = collectParts3(root, skipped);- const base = {+function analyzeOpenSurfacePenetration(root, contactTolerance = OPEN_SURFACE_CONTACT_TOLERANCE) {+ const evidence = {schemaVersion: 1,source: "engine-scene-analysis",- partsAnalyzed: parts.length,+ contactTolerance,+ openParts: 0,+ closedParts: 0,candidatePairs: 0,pairsTested: 0,- pairsUnmeasurable: 0,pairsNotReached: 0,+ verticesUnresolved: 0,pairsLodAlternates: 0,truncated: false,- skipped,+ skipped: [],penetrations: []};- if (parts.length < 2)- return base;+ if (!(root instanceof THREE11.Object3D))+ return evidence;+ const parts = collectParts3(root, evidence.skipped);+ const open = parts.filter((part) => !part.closed);+ const closed = parts.filter((part) => part.closed);+ evidence.openParts = open.length;+ evidence.closedParts = closed.length;const candidates = [];let considered = 0;broadPhase:- for (let i = 0;i < parts.length; i++) {- for (let j = i + 1;j < parts.length; j++) {+ for (const surface of open) {+ for (const solid of closed) {if (considered++ === MAX_BROAD_PHASE_PAIRS) {- base.broadPhaseTruncated = true;+ evidence.broadPhaseTruncated = true;break broadPhase;}- const a = parts[i];- const b = parts[j];- if (!a.box.intersectsBox(b.box))+ if (!surface.box.intersectsBox(solid.box))continue;- if (a.lod && b.lod && a.lod.parent === b.lod.parent && a.lod.stem === b.lod.stem && a.lod.level !== b.lod.level) {- base.pairsLodAlternates++;+ if (surface.lod && solid.lod && surface.lod.parent === solid.lod.parent && surface.lod.stem === solid.lod.stem && surface.lod.level !== solid.lod.level) {+ evidence.pairsLodAlternates++;continue;}- candidates.push({ a: i, b: j, overlap: boxOverlapRatio(a.box, b.box) });+ candidates.push({+ open: surface,+ solid,+ overlap: boxOverlapRatio(surface.box, solid.box),+ order: candidates.length+ });}}- base.candidatePairs = candidates.length;- base.truncated = !!base.broadPhaseTruncated;- if (candidates.length === 0)- return base;- candidates.sort((x, y) => y.overlap - x.overlap || x.a - y.a || x.b - y.b);- const Module = await import("manifold-3d");- const wasm = await Module.default();- wasm.setup();- const { Manifold, Mesh } = wasm;- const solids = new Map;- const unbuildable = [];- const build = (index) => {- if (solids.has(index))- return solids.get(index);- if (solids.size === MAX_SOLID_BUILDS)- return;- const part = parts[index];- let solid = null;- try {- const arrays = meshToArrays(part);- if (arrays) {- const mesh = new Mesh({ numProp: 3, ...arrays });- mesh.merge();- solid = new Manifold(mesh);- const components = solid.decompose();- try {- if (components.length > MAX_SOLID_COMPONENTS || components.some((part) => part.volume() <= 0)) {- unbuildable.push({- index,- reason: "compound solid exceeds the component budget or contains an unsupported inward shell",- open: false- });- solid.delete();- solid = null;- } else if (components.length > 1) {- const union = Manifold.union(components);- solid.delete();- solid = union;- }- } finally {- for (const component of components)- component.delete();- }- } else {- unbuildable.push({- index,- reason: "its triangle positions or indices are invalid",- open: false+ evidence.candidatePairs = candidates.length;+ evidence.truncated = evidence.broadPhaseTruncated === true;+ if (!candidates.length)+ return evidence;+ candidates.sort((x, y) => y.overlap - x.overlap || x.order - y.order);+ const budget = new Budget(MAX_WORK);+ const penetrations = [];+ for (const candidate of candidates) {+ if (budget.exhausted) {+ evidence.pairsNotReached++;+ continue;+ }+ if (!candidate.solid.hierarchy) {+ const triangles = worldTriangles(candidate.solid.mesh);+ if (!triangles) {+ evidence.skipped.push({+ part: candidate.solid.name,+ reason: "invalid or non-finite triangles cannot be indexed"});+ evidence.pairsNotReached++;+ continue;}- } catch (err) {- unbuildable.push({- index,- reason: `a valid closed solid could not be measured (${err instanceof Error ? err.message : String(err)})`,- open: true+ candidate.solid.hierarchy = buildHierarchy(triangles);+ }+ const hierarchy = candidate.solid.hierarchy;+ const position = candidate.open.mesh.geometry.getAttribute("position");+ if (position?.itemSize !== 3) {+ evidence.skipped.push({+ part: candidate.open.name,+ reason: "open surfaces are sampled at their vertices and this part has none"});- solid?.delete();- solid = null;+ continue;}- solids.set(index, solid);- return solid;- };- const penetrations = [];- const rangeSkips = [];- const unmeasured = [];- try {- for (const pair of candidates) {- if (solids.get(pair.a) === null || solids.get(pair.b) === null) {- base.pairsUnmeasurable++;- unmeasured.push(pair);+ const matrix = candidate.open.mesh.matrixWorld;+ const limit = Math.min(position.count, MAX_SAMPLED_VERTICES);+ const vertex = new THREE11.Vector3;+ let depth = 0;+ let penetrating = 0;+ let tested = 0;+ let unresolved = 0;+ let partial = limit < position.count;+ for (let i = 0;i < limit; i++) {+ vertex.fromBufferAttribute(position, i).applyMatrix4(matrix);+ if (![vertex.x, vertex.y, vertex.z].every(Number.isFinite))continue;- }- const sa = build(pair.a);- const sb = sa === null ? null : build(pair.b);- if (sa === null || sb === null) {- base.pairsUnmeasurable++;- unmeasured.push(pair);+ if (boxDistanceSquared(candidate.solid.box, vertex) > contactTolerance * contactTolerance) {+ tested++;continue;}- if (!sa || !sb || base.pairsTested === MAX_NARROW_PHASE_PAIRS) {- base.pairsNotReached++;- continue;+ const distance = nearestDistance(hierarchy, vertex, budget);+ if (distance === null) {+ partial = true;+ break;}- base.pairsTested++;- const a = parts[pair.a];- const b = parts[pair.b];- let overlap = null;- const scale = Math.max(a.scale, b.scale);- const pa = sa.scale(a.scale / scale);- const scaledB = sb.scale(b.scale / scale);- const pb = scaledB.translate(b.center.clone().sub(a.center).divideScalar(scale).toArray());- try {- overlap = Manifold.intersection(pa, pb);- const volume = overlap.volume();- if (volume > 0) {- const smaller = Math.min(Math.abs(pa.volume()), Math.abs(pb.volume()));- const fraction = smaller > 0 ? volume / smaller : 0;- if (fraction > CONTACT_VOLUME_FRACTION) {- const assetVolume = volume * scale ** 3;- if (!Number.isFinite(assetVolume) || !(assetVolume > 0)) {- rangeSkips.push({- part: a.name,- reason: `intersection with ${JSON.stringify(b.name)} is outside representable volume range`- });- continue;- }- penetrations.push({- a: a.name,- b: b.name,- volume: roundVolume(assetVolume),- fraction: round(fraction)- });- }+ tested++;+ if (distance <= contactTolerance)+ continue;+ const verdict = inside(hierarchy, vertex, budget);+ if (verdict === null) {+ if (budget.exhausted) {+ partial = true;+ break;}- } finally {- overlap?.delete();- pa.delete();- pb.delete();- scaledB.delete();+ unresolved++;+ continue;}+ if (!verdict)+ continue;+ penetrating++;+ if (distance > depth)+ depth = distance;}- for (const pair of candidates) {- if (solids.get(pair.a) === null)- build(pair.b);- else if (solids.get(pair.b) === null)- build(pair.a);- }- } finally {- for (const solid of solids.values())- solid?.delete();- }- base.truncated = !!base.broadPhaseTruncated || base.pairsNotReached > 0;- unbuildable.sort((x, y) => x.index - y.index);- const acknowledged = [];- const acknowledgedIndices = new Set;- for (const { index, reason, open } of unbuildable) {- const part = parts[index];- if (open && part.intent !== undefined) {- acknowledged.push({ part: part.name, reason, intent: part.intent });- acknowledgedIndices.add(index);- } else- skipped.push({ part: part.name, reason });- }- skipped.push(...rangeSkips);- if (acknowledged.length) {- base.acknowledged = acknowledged;- base.pairsUnmeasurableAcknowledged = unmeasured.filter((pair) => [pair.a, pair.b].filter((index) => solids.get(index) === null).every((index) => acknowledgedIndices.has(index))).length;- }- penetrations.sort((x, y) => y.fraction - x.fraction || `${x.a}:${x.b}`.localeCompare(`${y.a}:${y.b}`));- base.penetrations = penetrations;- return base;-}-function readEvidence(context) {- const evidence = context.derivedEvidence?.["partPenetration"];- return evidence?.schemaVersion === 1 ? evidence : undefined;-}-function acknowledgedFinding(acknowledged, pairs) {- const groups = new Map;- for (const { part, reason, intent } of acknowledged) {- const key = JSON.stringify([intent, reason]);- const group = groups.get(key);- if (group)- group.parts.push(part);+ evidence.verticesUnresolved += unresolved;+ if (partial)+ evidence.pairsNotReached++;else- groups.set(key, { intent, reason, parts: [part] });- }- const listed = [...groups.values()];- const shown = listed.slice(0, ACKNOWLEDGED_REASONS_SHOWN);- const lines = shown.map(({ intent, reason, parts }) => `${parts.length} marked ${JSON.stringify(intent)}, because ${reason}: ${namedParts(parts)}.`);- const rest = listed.slice(ACKNOWLEDGED_REASONS_SHOWN);- if (rest.length) {- const count = rest.reduce((sum, group) => sum + group.parts.length, 0);- lines.push(`${count} more ${count === 1 ? "part" : "parts"} marked with ${rest.length} other ${rest.length === 1 ? "reason" : "reasons"}.`);+ evidence.pairsTested++;+ if (penetrating > 0)+ penetrations.push({+ open: candidate.open.name,+ solid: candidate.solid.name,+ depth: round(depth),+ vertices: penetrating,+ tested+ });}- const one = acknowledged.length === 1;- const which = one ? "this part" : "these parts";- const pairText = pairs === 1 ? ` 1 overlapping part pair was not measured because of ${which} alone; overlap there is not ruled out.` : pairs > 1 ? ` ${pairs} overlapping part pairs were not measured because of ${which} alone; overlap there is not ruled out.` : "";- return {- code: "GEO_PART_SELF_INTERSECTION_ACKNOWLEDGED",- disposition: "observe",- dimension: "visualQuality",- profile: "geometry.selfIntersection",- message: `${acknowledged.length} ${one ? "part" : "parts"} marked intentionally open (markOpenShell) ${one ? "was" : "were"} not measured as ${one ? "a closed solid" : "closed solids"}. ${lines.join(" ")}${pairText}`,- measurement: {- name: "acknowledgedOpenShells",- actual: acknowledged.length,- breakdown: { pairsUnmeasurable: pairs }- }- };+ evidence.truncated = evidence.truncated || evidence.pairsNotReached > 0;+ penetrations.sort((x, y) => y.depth - x.depth || `${x.open}:${x.solid}`.localeCompare(`${y.open}:${y.solid}`));+ evidence.penetrations = penetrations;+ return evidence;}-function inspectPartPenetration(evidence) {- if (!evidence)+function inspectOpenSurfacePenetration(evidence) {+ if (evidence?.schemaVersion !== 1)return [];const findings = evidence.penetrations.map((pair) => ({- code: "GEO_PART_SELF_INTERSECTION",+ code: "GEO_OPEN_SURFACE_PENETRATION",disposition: "observe",dimension: "visualQuality",- profile: "geometry.selfIntersection",- message: `Parts ${JSON.stringify(pair.a)} and ${JSON.stringify(pair.b)} occupy the same space: they share ${pair.volume.toPrecision(3)} m³, which is ${(pair.fraction * 100).toFixed(1)}% of the smaller part.`,- affected: { node: pair.a },+ profile: "geometry.openSurfacePenetration",+ message: `Open surface ${JSON.stringify(pair.open)} reaches ${pair.depth.toFixed(4)} m inside solid ${JSON.stringify(pair.solid)}: ` + `${pair.vertices} of ${pair.tested} sampled ${pair.vertices === 1 ? "vertex lies" : "vertices lie"} deeper inside it than the ${evidence.contactTolerance} m contact tolerance.`,+ affected: { node: pair.open },measurement: {- name: "intersectionVolumeFraction",- actual: pair.fraction,- expected: CONTACT_VOLUME_FRACTION+ name: "openSurfacePenetrationDepth",+ actual: pair.depth,+ expected: evidence.contactTolerance,+ unit: "m",+ breakdown: { penetratingVertices: pair.vertices, sampledVertices: pair.tested }},- repairText: "Check whether this overlap is intentional, such as a joined beam or embedded detail. For unintended solid overlap, move a part or use boolDiff to cut clearance. This observation does not test intersections within a single mesh, open surfaces, empty passage space or motion."+ repairText: "A positive here is not a defect. Most are intentional: a fitting set into a structural shell -- a lamp recess in a hull, a strut landing, a ridge into a cap -- puts shell vertices inside the solid by design, exactly as a bolt in a hole shares volume. Review the ones you did not intend, such as a cloth crossing a wall or a canopy pierced by a mast, and move the surface clear or cut it back to the solid. Vertices are the samples, so a solid thinner than this surface’s facet spacing can pass between two of them."}));- const pairsUnmeasurable = evidence.pairsUnmeasurable ?? 0;- const acknowledged = evidence.acknowledged ?? [];- const pairsAcknowledged = acknowledged.length ? Math.min(evidence.pairsUnmeasurableAcknowledged ?? 0, pairsUnmeasurable) : 0;- if (evidence.truncated) {- const pairsNotReached = evidence.pairsNotReached ?? 0;+ const unresolved = evidence.verticesUnresolved ?? 0;+ if (evidence.truncated || unresolved > 0) {+ const clauses = [];+ if (evidence.truncated)+ clauses.push(`Sampled ${evidence.pairsTested} of ${evidence.broadPhaseTruncated ? "at least " : ""}${evidence.candidatePairs} overlapping open-surface and solid pairs; ` + `${evidence.pairsNotReached} were beyond the ${MAX_WORK}-test analysis budget.` + (evidence.broadPhaseTruncated ? ` Pair discovery stopped after ${MAX_BROAD_PHASE_PAIRS} box comparisons.` : "") + " Unsampled pairs were not examined; the most overlapping bounding boxes were sampled first.");+ if (unresolved > 0)+ clauses.push(`${unresolved} ${unresolved === 1 ? "vertex" : "vertices"} further than the contact tolerance from a solid could not be resolved as inside or outside it, and ${unresolved === 1 ? "is" : "are"} counted as neither.`);findings.push({- code: "GEO_PART_SELF_INTERSECTION_TRUNCATED",+ code: "GEO_OPEN_SURFACE_PENETRATION_TRUNCATED",disposition: "observe",dimension: "visualQuality",- profile: "geometry.selfIntersection",- message: `Tested ${evidence.pairsTested} of ${evidence.broadPhaseTruncated ? "at least " : ""}${evidence.candidatePairs} overlapping part pairs: ${pairsUnmeasurable} involve parts that could not be measured, ${pairsNotReached} were beyond the analysis budget (${MAX_NARROW_PHASE_PAIRS} booleans, ${MAX_SOLID_BUILDS} solids).` + (evidence.broadPhaseTruncated ? ` Pair discovery stopped after ${MAX_BROAD_PHASE_PAIRS} box comparisons.` : "") + " Unreached pairs were not examined; the most overlapping bounding boxes were tested first.",+ profile: "geometry.openSurfacePenetration",+ message: clauses.join(" "),measurement: {- name: "overlappingPartPairsTested",+ name: "openSurfacePairsSampled",actual: evidence.pairsTested,expected: evidence.candidatePairs,- breakdown: { pairsUnmeasurable, pairsNotReached }+ breakdown: {+ pairsNotReached: evidence.pairsNotReached,+ verticesUnresolved: unresolved+ }}});}@@ -7874,1239 +7959,1378 @@ function inspectPartPenetration(evidence) {}const reasons = [...byReason].map(([reason, parts]) => `${parts.length} because ${reason}: ${namedParts(parts)}.`);const one = evidence.skipped.length === 1;- const includes = one ? "this part" : "one of these parts";- const unmarked = pairsUnmeasurable - pairsAcknowledged;- const pairs = unmarked === 1 ? ` 1 overlapping part pair includes ${includes} and was not measured.` : unmarked > 1 ? ` ${unmarked} overlapping part pairs include ${includes} and were not measured.` : "";findings.push({- code: "GEO_PART_SELF_INTERSECTION_UNMEASURED",+ code: "GEO_OPEN_SURFACE_PENETRATION_UNMEASURED",disposition: "observe",dimension: "visualQuality",- profile: "geometry.selfIntersection",- message: `${evidence.skipped.length} part-volume ${one ? "measurement was" : "measurements were"} unavailable. ${reasons.join(" ")}${pairs} ${one ? "This part is" : "These parts are"} not certified clear.`+ profile: "geometry.openSurfacePenetration",+ message: `${evidence.skipped.length} ${one ? "part was" : "parts were"} not sampled for open-surface penetration. ` + `${reasons.join(" ")} ${one ? "This part is" : "These parts are"} not certified clear of the solids around ${one ? "it" : "them"}.`});}- if (acknowledged.length)- findings.push(acknowledgedFinding(acknowledged, pairsAcknowledged));return findings;}-var MAX_PART_TRIANGLES = 20000, MAX_NARROW_PHASE_PAIRS = 64, MAX_SOLID_BUILDS, MAX_SOLID_COMPONENTS = 32, MAX_BROAD_PHASE_PAIRS = 250000, CONTACT_VOLUME_FRACTION = 0.001, boxVolume = (box) => (box.max.x - box.min.x) * (box.max.y - box.min.y) * (box.max.z - box.min.z), round = (n) => Math.round(n * 1e9) / 1e9, roundVolume = (n) => Number(n.toPrecision(9)), SELF_INTERSECTION_QA_RULE, UNMEASURED_NAMES_SHOWN = 5, ACKNOWLEDGED_REASONS_SHOWN = 5, namedParts = (parts) => {- const named = parts.slice(0, UNMEASURED_NAMES_SHOWN).map((part) => JSON.stringify(part));- const more = parts.length > UNMEASURED_NAMES_SHOWN ? ` and ${parts.length - UNMEASURED_NAMES_SHOWN} more` : "";+var OPEN_SURFACE_CONTACT_TOLERANCE = 0.005, MAX_SURFACE_TRIANGLES = 20000, MAX_SAMPLED_VERTICES = 20000, MAX_WORK = 250000, MAX_BROAD_PHASE_PAIRS = 250000, PARITY_DIRECTIONS, PARITY_EPSILON = 0.0000001, round = (value) => Number(value.toPrecision(9)), NAMES_SHOWN = 5, namedParts = (parts) => {+ const named = parts.slice(0, NAMES_SHOWN).map((part) => JSON.stringify(part));+ const more = parts.length > NAMES_SHOWN ? ` and ${parts.length - NAMES_SHOWN} more` : "";return `${named.join(", ")}${more}`;-};-var init_self_intersection = __esm(() => {- init_open_shell();+}, OPEN_SURFACE_PENETRATION_QA_RULE;+var init_open_surface_penetration = __esm(() => {+ init_geometry();init_lod2();init_registry();- MAX_SOLID_BUILDS = 2 * MAX_NARROW_PHASE_PAIRS;- SELF_INTERSECTION_QA_RULE = Object.freeze({- id: "GEO_PART_SELF_INTERSECTION",- profile: "geometry.selfIntersection",+ PARITY_DIRECTIONS = Object.freeze([+ new THREE11.Vector3(1, 0, 0),+ new THREE11.Vector3(0.5773502691896258, 0.5773502691896258, 0.5773502691896258),+ new THREE11.Vector3(-0.2672612419124244, 0.5345224838248488, 0.8017837257372732)+ ]);+ OPEN_SURFACE_PENETRATION_QA_RULE = Object.freeze({+ id: "GEO_OPEN_SURFACE_PENETRATION",+ profile: "geometry.openSurfacePenetration",scope: { kind: "universal" },ruleClass: "heuristic",owner: KILN_ENGINE_QA_OWNER,defaultMode: "observe",evaluate(context) {- return inspectPartPenetration(readEvidence(context));+ return inspectOpenSurfacePenetration(analyzeOpenSurfacePenetration(context.scene));}});});-// src/vehicle.ts+// src/sweep-analysis.tsimport * as THREE12 from "three";-function assertId(value, name) {- if (!ID_PATTERN.test(value))- throw new TypeError(`${name} must be a stable identifier`);- return value;-}-function positive2(value, name) {- assertDimension(name, value);- return value;-}-function normalizedQuaternion(value) {- const source = value ?? [0, 0, 0, 1];- const length = Math.hypot(source[0], source[1], source[2], source[3]);- if (!Number.isFinite(length) || length <= 0.000000001)- throw new TypeError("socket rotation must be a finite quaternion");- return [source[0] / length, source[1] / length, source[2] / length, source[3] / length];-}-function semantic2(roles, options = {}) {- return {- roles,- relationships: options.relationships ?? [],- frames: options.frames ?? [],- sockets: options.sockets ?? []- };-}-function socketRole(kind, id) {- if (kind === "chassis")- return KILN_SEMANTIC_ROLES.chassisMain;- return semanticRole(SOCKET_ROLE_BASE[kind], id);-}-function createTypedSocket(kind, input, parent) {- const id = assertId(input.id, `${kind} socket id`);- if (!input.position.every(Number.isFinite))- throw new TypeError(`${kind}.${id} position must be finite`);- const rotation = normalizedQuaternion(input.rotation);- const node = new THREE12.Object3D;- node.name = `Socket_${kind}_${id}`;- node.position.set(...input.position);- node.quaternion.set(...rotation);- const socket = {- id,- type: `vehicle.${kind}`,- frame: "socket",- compatibleTypes: [...input.compatibleTypes ?? [`vehicle.${kind}`]]- };- stampSemanticMetadataV1(node, semantic2([semanticRole(KILN_SEMANTIC_ROLES.socket, kind, id), socketRole(kind, id)], {- frames: [{ id: "socket", translation: [0, 0, 0], rotation: [0, 0, 0, 1] }],- sockets: [socket],- relationships: [- { kind: "owned-by", target: KILN_SEMANTIC_ROLES.vehicleFrame, targetType: "role" }- ]- }));- parent.add(node);- return node;-}-function createVehicleFrame(name, options = {}) {- const root = new THREE12.Object3D;- root.name = name;- stampSemanticMetadataV1(root, semantic2([KILN_SEMANTIC_ROLES.vehicleFrame, KILN_SEMANTIC_ROLES.vehicleForward], {- frames: [- { id: "origin", translation: [0, 0, 0], rotation: [0, 0, 0, 1] },- { id: "forward.+x", translation: [0, 0, 0], rotation: [0, 0, 0, 1] },- { id: "up.+y", translation: [0, 0, 0], rotation: [0, 0, 0, 1] },- { id: "right.+z", translation: [0, 0, 0], rotation: [0, 0, 0, 1] }- ]- }));- if (options.parent)- options.parent.add(root);- const chassis = createTypedSocket("chassis", options.chassis ?? { id: "main", position: [0, 0, 0] }, root);- const build = (kind, values) => (values ?? []).map((value) => createTypedSocket(kind, value, root));- return {- root,- chassis,- axles: build("axle", options.axles),- seats: build("seat", options.seats),- contacts: build("contact", options.contacts),- steering: build("steering", options.steering),- propulsion: build("propulsion", options.propulsion)- };-}-function cylinderZ(radius, width, segments = 16) {- const geometry = new THREE12.CylinderGeometry(radius, radius, width, segments);- geometry.rotateX(Math.PI / 2);- return geometry;+function segmentHitsTriangle(a, b, tri, epsilon) {+ const plane = new THREE12.Plane().setFromCoplanarPoints(tri.a, tri.b, tri.c);+ if (plane.normal.lengthSq() === 0)+ return false;+ const da = plane.distanceToPoint(a), db = plane.distanceToPoint(b);+ if (Math.abs(da) <= epsilon && Math.abs(db) <= epsilon) {+ if (tri.containsPoint(a) || tri.containsPoint(b))+ return true;+ const n = plane.normal;+ const drop = Math.abs(n.x) >= Math.abs(n.y) && Math.abs(n.x) >= Math.abs(n.z) ? 0 : Math.abs(n.y) >= Math.abs(n.z) ? 1 : 2;+ const axes = [0, 1, 2].filter((axis) => axis !== drop);+ const point = (p) => [p.getComponent(axes[0]), p.getComponent(axes[1])];+ const cross = (p, q, r) => (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]);+ const p = point(a), q = point(b);+ const vertices = [tri.a, tri.b, tri.c];+ return vertices.some((v, i) => {+ const r = point(v), s = point(vertices[(i + 1) % 3]);+ return cross(p, q, r) * cross(p, q, s) <= 0 && cross(r, s, p) * cross(r, s, q) <= 0 && axes.every((_, axis) => Math.max(Math.min(p[axis], q[axis]), Math.min(r[axis], s[axis])) <= Math.min(Math.max(p[axis], q[axis]), Math.max(r[axis], s[axis])) + epsilon);+ });+ }+ if (da > epsilon && db > epsilon || da < -epsilon && db < -epsilon)+ return false;+ const t = da / (da - db);+ return t >= 0 && t <= 1 && tri.containsPoint(a.clone().lerp(b, t));}-function createWheelGeometrySet(radius, width) {- positive2(radius, "radius");- positive2(width, "width");- return {- tire: defaultTireGeometry(radius, width),- rim: cylinderZ(radius * 0.68, width * 0.8),- hub: cylinderZ(radius * 0.34, width * 0.94)+function recordSweepAnalysis(geometry, rings, profiles, closed) {+ const result = {+ complete: true,+ stationsChecked: 0,+ ringPairsChecked: 0,+ tests: 0,+ findings: []};-}-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 THREE12.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 THREE12.Box3;- const point = new THREE12.Vector3;- let actualRadius = 0;- for (let i = 0;i < positions.count; i++) {- point.fromBufferAttribute(positions, i);- if (![point.x, point.y, point.z].every(Number.isFinite))- throw new RangeError(`wheel ${part} position coordinates must be finite.`);- bounds.expandByPoint(point);- actualRadius = Math.max(actualRadius, Math.hypot(point.x, point.y));+ analyses.set(geometry, result);+ if (rings.length > SWEEP_ANALYSIS_MAX_STATIONS || rings.some((ring) => ring.length > SWEEP_ANALYSIS_MAX_RING_POINTS)) {+ result.complete = false;+ return result;}- const actualWidth = bounds.max.z - bounds.min.z;- const center = bounds.getCenter(new THREE12.Vector3);- const tolerance = 0.00001 * Math.max(radius, width, actualRadius, actualWidth);- const differences = [];- if (Math.abs(actualRadius - radius) > tolerance)- differences.push("radius");- if (Math.abs(actualWidth - width) > tolerance)- differences.push("width");- if (Math.max(Math.abs(center.x), Math.abs(center.y), Math.abs(center.z)) > tolerance)- differences.push("center");- return {- part,- status: differences.length ? "mismatch" : "match",- declared: { radius, width },- observed: { radius: actualRadius, width: actualWidth, boundsCenter: center.toArray() },- differences+ const unique = closed ? rings.length - 1 : rings.length;+ const centers = rings.map((ring) => ring.reduce((sum, p) => sum.add(p), new THREE12.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);+ const cross = u.clone().cross(v).length();+ const radius = cross > 0 ? u.length() * v.length() * a.distanceTo(c) / (2 * cross) : u.dot(v) < 0 ? 0 : Infinity;+ const halfExtent = Math.max(...rings[i].map((p) => p.distanceTo(b)));+ result.stationsChecked++;+ if (radius < halfExtent)+ result.findings.push({ station: i, kind: "curvature", radius, halfExtent });+ }+ const triangles = new Map;+ const faces = (index) => {+ if (!triangles.has(index))+ triangles.set(index, THREE12.ShapeUtils.triangulateShape(profiles[index], []).map(([a, b, c]) => new THREE12.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 THREE12.Box3().setFromPoints(rings[i - 1]);+ const boundsB = new THREE12.Box3().setFromPoints(rings[i]);+ if (!boundsA.intersectsBox(boundsB)) {+ result.ringPairsChecked++;+ continue;+ }+ const epsilon = Math.max(boundsA.getSize(new THREE12.Vector3).length(), boundsB.getSize(new THREE12.Vector3).length()) * 0.0000000001;+ let hit = false;+ pair:+ for (const [a, b] of [+ [i - 1, i],+ [i, i - 1]+ ]) {+ for (let edge = 0;edge < rings[a].length; edge++)+ for (const triangle of faces(b)) {+ if (result.tests === SWEEP_ANALYSIS_MAX_TESTS) {+ result.complete = false;+ return result;+ }+ result.tests++;+ if (segmentHitsTriangle(rings[a][edge], rings[a][(edge + 1) % rings[a].length], triangle, epsilon)) {+ hit = true;+ break pair;+ }+ }+ }+ result.ringPairsChecked++;+ if (hit)+ result.findings.push({ station: i, otherStation: i - 1, kind: "rings" });+ }+ return result;}-function createWheelAssembly(name, materials, options) {- const radius = positive2(options.radius, "radius");- const width = positive2(options.width, "width");- const rimRadius = positive2(options.rimRadius ?? radius * 0.68, "rimRadius");- const hubRadius = positive2(options.hubRadius ?? radius * 0.34, "hubRadius");- const rimWidth = positive2(options.rimWidth ?? width * 0.8, "rimWidth");- const hubWidth = positive2(options.hubWidth ?? width * 0.94, "hubWidth");- if (rimRadius >= radius || hubRadius >= rimRadius)- throw new RangeError("wheel radii must satisfy hub < rim < tire");- if (rimWidth > width || hubWidth > width)- throw new RangeError("rim/hub width must not exceed tire width");- if (options.side !== "left" && options.side !== "right" && options.side !== "center")- throw new RangeError("wheel side must be left, right or center");- if (options.position !== undefined)- assertFiniteTriple("wheel position", options.position);- const geometryChecks = [];- for (const [part, declaredRadius, declaredWidth] of [- ["tire", radius, width],- ["rim", rimRadius, rimWidth],- ["hub", hubRadius, hubWidth]- ]) {- const geometry = options.geometries?.[part];- if (geometry)- geometryChecks.push(checkWheelGeometry(part, geometry, declaredRadius, declaredWidth));- }- const index = assertId(String(options.index), "wheel index");- const key = `${options.side}.${index}`;- const parent = options.parent;- const root = new THREE12.Object3D;- root.name = `${name}_Assembly_${options.side}_${index}`;- let steeringPivot;- if (options.steering) {- steeringPivot = new THREE12.Object3D;- steeringPivot.name = `SteeringPivot_${options.side}_${index}`;- steeringPivot.position.set(...options.position ?? [0, 0, 0]);- stampSemanticMetadataV1(steeringPivot, semantic2([semanticRole(ROLE.steeringPivot, key)], {- frames: [{ id: "steering-axis.+y", translation: [0, 0, 0], rotation: [0, 0, 0, 1] }],- relationships: [- { kind: "steers", target: semanticRole(ROLE.wheelAssembly, key), targetType: "role" }- ]- }));- root.add(steeringPivot);- }- const spinPivot = new THREE12.Object3D;- spinPivot.name = `WheelPivot_${options.side}_${index}`;- if (!steeringPivot)- spinPivot.position.set(...options.position ?? [0, 0, 0]);- stampSemanticMetadataV1(spinPivot, semantic2([- semanticRole(ROLE.wheelAssembly, key),- semanticRole(ROLE.wheelPivot, key),- ...options.loadBearing === false ? [] : [semanticRole(ROLE.wheelLoadBearing, key)]- ], {- frames: [- { id: "axle-center", translation: [0, 0, 0], rotation: [0, 0, 0, 1] },- { id: "spin-axis.+z", translation: [0, 0, 0], rotation: [0, 0, 0, 1] }- ],- relationships: [- { kind: "mounted-on", target: semanticRole(ROLE.axle, index), targetType: "role" },- { kind: "contains", target: semanticRole(ROLE.wheelTire, key), targetType: "role" },- { kind: "contains", target: semanticRole(ROLE.wheelRim, key), targetType: "role" },- { kind: "contains", target: semanticRole(ROLE.wheelHub, key), targetType: "role" }- ]- }));- (steeringPivot ?? root).add(spinPivot);- const tire = new THREE12.Mesh(options.geometries?.tire ?? defaultTireGeometry(radius, width), materials.tire);- const rim = new THREE12.Mesh(options.geometries?.rim ?? cylinderZ(rimRadius, rimWidth), materials.rim);- const hub = new THREE12.Mesh(options.geometries?.hub ?? cylinderZ(hubRadius, hubWidth), materials.hub ?? materials.rim);- tire.name = `Tire_${options.side}_${index}`;- rim.name = `Rim_${options.side}_${index}`;- hub.name = `Hub_${options.side}_${index}`;- stampSemanticMetadataV1(tire, semantic2([semanticRole(ROLE.wheelTire, key)], {- relationships: [- { kind: "descends-from", target: semanticRole(ROLE.wheelPivot, key), targetType: "role" }- ]- }));- stampSemanticMetadataV1(rim, semantic2([semanticRole(ROLE.wheelRim, key)], {- relationships: [- { kind: "contained-by", target: semanticRole(ROLE.wheelTire, key), targetType: "role" }- ]- }));- stampSemanticMetadataV1(hub, semantic2([semanticRole(ROLE.wheelHub, key)], {- relationships: [- { kind: "contained-by", target: semanticRole(ROLE.wheelRim, key), targetType: "role" }- ]- }));- spinPivot.add(tire, rim, hub);- const contact = new THREE12.Object3D;- contact.name = `Contact_${options.side}_${index}`;- contact.position.y = -radius;- stampSemanticMetadataV1(contact, semantic2([semanticRole(ROLE.wheelContact, key), semanticRole(ROLE.contact, key)], {- frames: [{ id: "contact", translation: [0, 0, 0], rotation: [0, 0, 0, 1] }],- relationships: [{ kind: "supports", target: ROLE.vehicleFrame, targetType: "role" }]- }));- spinPivot.add(contact);- if (parent)- parent.add(root);- return {- root,- ...steeringPivot ? { steeringPivot } : {},- spinPivot,- tire,- rim,- hub,- contact,- radius,- width,- side: options.side,- index,- spinAxis: VEHICLE_AXES.wheelAxle,- geometryChecks- };-}-function roles(node) {- return readSemanticMetadataV1(node)?.roles ?? [];-}-function descendantWithRole(root, prefix) {- let found;- root.traverse((node) => {- if (!found && roles(node).some((role) => role.startsWith(prefix)))- found = node;- });- return found;-}-function ancestorWithRole(node, prefix) {- let current = node.parent;- while (current) {- if (roles(current).some((role) => role.startsWith(prefix)))- return current;- current = current.parent;- }- return;-}-function parseWheelRole(role) {- const parts = role.split(".");- const side = parts.at(-2);- return {- ...side === "left" || side === "right" || side === "center" ? { side } : {},- ...parts.at(-1) ? { index: parts.at(-1) } : {}- };-}-function objectBoundsInFrame(object, frame) {- object.updateWorldMatrix(true, true);- frame.updateWorldMatrix(true, false);- const worldToFrame = frame.matrixWorld.clone().invert();- const bounds = new THREE12.Box3;- let found = false;- object.traverse((node) => {- if (!(node instanceof THREE12.Mesh) || !(node.geometry instanceof THREE12.BufferGeometry))+var SWEEP_ANALYSIS_MAX_STATIONS = 4096, SWEEP_ANALYSIS_MAX_RING_POINTS = 512, SWEEP_ANALYSIS_MAX_TESTS = 65536, analyses, readSweepAnalysis = (geometry) => analyses.get(geometry);+var init_sweep_analysis = __esm(() => {+ analyses = new WeakMap;+});++// src/qa/sweep.ts+import { Object3D as Object3D6 } from "three";+function inspectSweepGeometry(scene) {+ const findings = [];+ if (!(scene instanceof Object3D6))+ return findings;+ scene.traverseVisible((node) => {+ const geometry = node.geometry;+ if (!geometry)return;- node.geometry.computeBoundingBox();- const local = node.geometry.boundingBox;- if (!local)+ const evidence = readSweepAnalysis(geometry);+ if (!evidence)return;- const matrix = worldToFrame.clone().multiply(node.matrixWorld);- for (const x of [local.min.x, local.max.x])- for (const y of [local.min.y, local.max.y])- for (const z of [local.min.z, local.max.z]) {- bounds.expandByPoint(new THREE12.Vector3(x, y, z).applyMatrix4(matrix));- found = true;+ for (const finding of evidence.findings.slice(0, 16))+ findings.push({+ code: "SWEEP_SELF_INTERSECTION",+ disposition: "observe",+ dimension: "exportIntegrity",+ profile: "geometry.sweep",+ affected: { node: node.name },+ message: finding.kind === "curvature" ? `Station ${finding.station}: curvature radius ${finding.radius} is below profile half-extent ${finding.halfExtent}.` : `Station ${finding.station}: its ring intersects ring ${finding.otherStation}.`,+ measurement: {+ name: finding.kind === "curvature" ? "curvatureRadius" : "intersectingRings",+ actual: finding.radius ?? 1,+ ...finding.halfExtent !== undefined ? { threshold: finding.halfExtent, unit: "m" } : {},+ breakdown: {+ station: finding.station,+ ...finding.otherStation !== undefined ? { otherStation: finding.otherStation } : {}+ }+ },+ repairText: "Inspect the named station; widen its turn, reduce the profile, or separate intersecting rings. This local check does not certify distant segments."+ });+ if (!evidence.complete || evidence.findings.length > 16)+ findings.push({+ code: "SWEEP_SELF_INTERSECTION_PARTIAL",+ disposition: "observe",+ dimension: "exportIntegrity",+ profile: "geometry.sweep",+ affected: { node: node.name },+ message: "Sweep/loft analysis or its finding list reached the bounded budget; unchecked geometry remains.",+ measurement: {+ name: "ringPairsChecked",+ actual: evidence.ringPairsChecked,+ breakdown: {+ stationsChecked: evidence.stationsChecked,+ tests: evidence.tests,+ omittedFindings: Math.max(0, evidence.findings.length - 16)+ }}+ });});- return found ? bounds : undefined;+ return findings;}-function dimensions(object, frame) {- if (!object)+var SWEEP_QA_RULE;+var init_sweep = __esm(() => {+ init_sweep_analysis();+ init_registry();+ SWEEP_QA_RULE = Object.freeze({+ id: "SWEEP_SELF_INTERSECTION",+ profile: "geometry.sweep",+ scope: { kind: "universal" },+ ruleClass: "heuristic",+ defaultMode: "observe",+ owner: KILN_ENGINE_QA_OWNER,+ evaluate: (context) => inspectSweepGeometry(context.scene)+ });+});++// src/open-shell.ts+function markOpenShell(part, reason) {+ const node = part;+ if (!node || typeof node !== "object" || node.isObject3D !== true)+ fail5("part must be a scene node, such as the mesh createPart returned or a group.");+ const kept = validReason(reason);+ if (kept === undefined)+ fail5(`reason must be a non-empty string of at most ${MAX_OPEN_SHELL_REASON} characters saying why the shell is open.`);+ const target = node;+ if (!target.userData || typeof target.userData !== "object")+ target.userData = {};+ target.userData[OPEN_SHELL_KEY] = { schemaVersion: 1, reason: kept };+ return part;+}+function markReason(value) {+ if (!value || typeof value !== "object" || Array.isArray(value))return;- const bounds = objectBoundsInFrame(object, frame);- if (!bounds)+ const mark = value;+ if (mark.schemaVersion !== 1)return;- const size = bounds.getSize(new THREE12.Vector3);- return {- center: bounds.getCenter(new THREE12.Vector3),- radius: Math.max(size.x, size.y) / 2,- width: size.z- };+ if (Object.keys(mark).some((key) => key !== "schemaVersion" && key !== "reason"))+ return;+ const reason = validReason(mark.reason);+ return reason === mark.reason ? reason : undefined;}-function resolved(source, id, root, pivot, parts) {- pivot.updateWorldMatrix(true, false);- const tire = dimensions(parts.tire, pivot);- const rim = dimensions(parts.rim, pivot);- const hub = dimensions(parts.hub, pivot);- const centerLocal = tire?.center ?? rim?.center ?? hub?.center ?? new THREE12.Vector3;- const toWorld = (value) => value.clone().applyMatrix4(pivot.matrixWorld);- return {- id,- source,- ...parts.side ? { side: parts.side } : {},- ...parts.index ? { index: parts.index } : {},- root,- pivot,- ...parts.steeringPivot ? { steeringPivot: parts.steeringPivot } : {},- ...parts.tire ? { tire: parts.tire } : {},- ...parts.rim ? { rim: parts.rim } : {},- ...parts.hub ? { hub: parts.hub } : {},- ...parts.contact ? { contact: parts.contact } : {},- centerWorld: toWorld(centerLocal),- pivotCenterWorld: new THREE12.Vector3().setFromMatrixPosition(pivot.matrixWorld),- ...tire ? { tireCenterWorld: toWorld(tire.center) } : {},- ...rim ? { rimCenterWorld: toWorld(rim.center) } : {},- ...hub ? { hubCenterWorld: toWorld(hub.center) } : {},- spinAxisWorld: new THREE12.Vector3(0, 0, 1).transformDirection(pivot.matrixWorld),- ...tire ? { radius: tire.radius, width: tire.width } : {},- ...rim ? { rimRadius: rim.radius, rimWidth: rim.width } : {},- ...hub ? { hubRadius: hub.radius, hubWidth: hub.width } : {},- loadBearing: hasSemanticRole(roles(pivot), ROLE.wheelLoadBearing)- };+function openShellIntent(node) {+ for (let at = node;at; at = at.parent) {+ const value = at.userData?.[OPEN_SHELL_KEY];+ if (value !== undefined)+ return markReason(value);+ }+ return;}-function semanticAssemblies(root) {- const result = [];- root.traverse((node) => {- const assemblyRole = roles(node).find((role) => semanticRoleMatches(role, ROLE.wheelAssembly));- if (!assemblyRole)- return;- const parsed = parseWheelRole(assemblyRole);- result.push(resolved("semantic", assemblyRole, node, node, {- ...parsed,- tire: descendantWithRole(node, `${ROLE.wheelTire}.`),- rim: descendantWithRole(node, `${ROLE.wheelRim}.`),- hub: descendantWithRole(node, `${ROLE.wheelHub}.`),- contact: descendantWithRole(node, `${ROLE.wheelContact}.`),- steeringPivot: ancestorWithRole(node, `${ROLE.steeringPivot}.`)- }));- });- return result;+function openShellExtras(node) {+ const target = node;+ const value = target?.userData?.[OPEN_SHELL_KEY];+ if (value === undefined)+ return {};+ const reason = markReason(value);+ if (reason === undefined)+ fail5(`userData.${OPEN_SHELL_KEY} on ${JSON.stringify(target?.name || "(unnamed node)")} is not a mark this helper wrote; the engine owns that key, so set it only through markOpenShell.`);+ return { [OPEN_SHELL_KEY]: { schemaVersion: 1, reason } };}-function legacyCorner(name) {- const value = name.toLowerCase().replace(/[^a-z0-9]+/g, "-");- if (!/(wheel|tire|rim|hub)/.test(value))+var OPEN_SHELL_KEY = "kilnOpenShell", MAX_OPEN_SHELL_REASON = 200, EXAMPLE2 = 'markOpenShell(rail, "C-channel closed by the end plates")', fail5 = (detail) => {+ throw new AuthoringDiagnosticError("OPEN_SHELL", `markOpenShell(part, reason): ${detail} For example ${EXAMPLE2}.`);+}, validReason = (reason) => {+ if (typeof reason !== "string")return;- const side = /(?:left|(^|-)l($|-)|fl|rl)/.test(value) ? "left" : /(?:right|(^|-)r($|-)|fr|rr)/.test(value) ? "right" : undefined;- const index = /(?:front|(^|-)f($|-)|fl|fr)/.test(value) ? "front" : /(?:rear|back|(^|-)r[lr]($|-)|rl|rr)/.test(value) ? "rear" : value.match(/\d+/)?.[0];- return {- key: `${side ?? "unknown"}.${index ?? value}`,- ...side ? { side } : {},- ...index ? { index } : {}- };-}-function legacyAssemblies(root) {- const groups = new Map;- root.traverse((node) => {- const corner = legacyCorner(node.name);- if (!corner)- return;- const entry = groups.get(corner.key) ?? {- ...corner.side ? { side: corner.side } : {},- ...corner.index ? { index: corner.index } : {}- };- const lower = node.name.toLowerCase();- if (lower.includes("pivot"))- entry.pivot = node;- else if (lower.includes("rim"))- entry.rim = node;- else if (lower.includes("hub"))- entry.hub = node;- else- entry.tire = node;- groups.set(corner.key, entry);- });- return [...groups.entries()].map(([key, parts]) => {- const pivot = parts.pivot ?? parts.tire?.parent ?? parts.rim?.parent ?? parts.hub?.parent ?? root;- return resolved("legacy", key, pivot, pivot, parts);- });+ const trimmed = reason.trim();+ return trimmed.length > 0 && trimmed.length <= MAX_OPEN_SHELL_REASON ? trimmed : undefined;+};+var init_open_shell = __esm(() => {+ init_authoring_diagnostic();+});++// src/qa/self-intersection.ts+import * as THREE13 from "three";+function boxOverlapRatio2(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));+ return Number.isFinite(ratio) ? ratio : 0;}-function resolveVehicleWheelAssemblies(root) {- const semantic = semanticAssemblies(root);- return semantic.length > 0 ? semantic : legacyAssemblies(root);+function triangleCount2(geometry) {+ const index = geometry.getIndex();+ const position = geometry.getAttribute("position");+ if (!position)+ return 0;+ return Math.floor((index ? index.count : position.count) / 3);}-function hasCanonicalVehicleFront(root) {- let found = false;- root.traverse((node) => {- const metadata = readSemanticMetadataV1(node);- if (metadata?.roles.includes(ROLE.vehicleFrame) && metadata.roles.includes(ROLE.vehicleForward) && metadata.frames.some((frame) => frame.id === "forward.+x")) {- found = true;+function collectParts4(root, skipped) {+ const parts = [];+ root.updateWorldMatrix(true, true);+ root.traverseVisible((node) => {+ const mesh = node;+ if (!mesh.isMesh || !mesh.geometry)+ return;+ const name = mesh.name || "(unnamed mesh)";+ if (mesh.isInstancedMesh || mesh.isSkinnedMesh || Object.values(mesh.geometry.morphAttributes).some((targets) => targets.length)) {+ skipped.push({+ part: name,+ reason: "instancing, skin or morph deformation is unsupported by part-volume analysis"+ });+ return;+ }+ const total = mesh.geometry.index?.count ?? mesh.geometry.getAttribute("position")?.count ?? 0;+ const range = mesh.geometry.drawRange;+ if (range.start !== 0 || range.count < total) {+ skipped.push({+ part: name,+ reason: "partial triangle draw ranges are unsupported by part-volume analysis"+ });+ return;+ }+ const triangles = triangleCount2(mesh.geometry);+ if (triangles === 0)+ return;+ if (triangles > MAX_PART_TRIANGLES) {+ skipped.push({+ part: name,+ reason: `${triangles} triangles exceeds the ${MAX_PART_TRIANGLES}-triangle analysis budget`+ });+ return;+ }+ mesh.geometry.computeBoundingBox();+ const box = mesh.geometry.boundingBox.clone().applyMatrix4(mesh.matrixWorld);+ if (box.isEmpty())+ return;+ const center = box.getCenter(new THREE13.Vector3);+ const size = box.getSize(new THREE13.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({+ part: name,+ reason: "non-finite or collapsed transformed bounds cannot be measured"+ });+ return;}+ parts.push({+ name,+ mesh,+ box,+ triangles,+ center,+ scale,+ lod: lodMembership(mesh),+ intent: openShellIntent(mesh)+ });});- return found;+ return parts;}-var ROLE, VEHICLE_AXES, ID_PATTERN, SOCKET_ROLE_BASE;-var init_vehicle = __esm(() => {- init_geometry_budget();- init_contracts();- ROLE = KILN_SEMANTIC_ROLES;- VEHICLE_AXES = Object.freeze({- forward: Object.freeze([1, 0, 0]),- up: Object.freeze([0, 1, 0]),- right: Object.freeze([0, 0, 1]),- wheelAxle: Object.freeze([0, 0, 1])- });- ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;- SOCKET_ROLE_BASE = Object.freeze({- chassis: KILN_SEMANTIC_ROLES.chassis,- axle: KILN_SEMANTIC_ROLES.axle,- seat: KILN_SEMANTIC_ROLES.seat,- contact: KILN_SEMANTIC_ROLES.contact,- steering: KILN_SEMANTIC_ROLES.steering,- propulsion: KILN_SEMANTIC_ROLES.propulsion- });-});--// src/qa/geometry-relations.ts-function createProbeLocalFrame3(input) {- if (!input.id.trim())- throw new TypeError("Probe frame ID must be non-empty.");- if (!finiteVector(input.origin))- throw new TypeError("Probe frame origin must be finite.");- const basis = [input.xAxis, input.yAxis, input.zAxis];- for (const [index, value] of basis.entries()) {- if (!finiteVector(value) || Math.abs(length2(value) - 1) > 0.000001) {- throw new TypeError(`Probe frame axis ${index} must be finite and normalized within 1e-6.`);- }+function meshToArrays(part) {+ const { mesh, center, scale } = part;+ const geometry = mesh.geometry;+ const position = geometry.getAttribute("position");+ if (position?.itemSize !== 3)+ return null;+ const matrix = mesh.matrixWorld.clone();+ matrix.elements[12] -= center.x;+ matrix.elements[13] -= center.y;+ matrix.elements[14] -= center.z;+ const v = new THREE13.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);+ if (![v.x, v.y, v.z].every((n) => Number.isFinite(Math.fround(n))))+ return null;+ verts[i * 3] = v.x;+ verts[i * 3 + 1] = v.y;+ verts[i * 3 + 2] = v.z;}- if (Math.abs(dot2(input.xAxis, input.yAxis)) > 0.000001 || Math.abs(dot2(input.xAxis, input.zAxis)) > 0.000001 || Math.abs(dot2(input.yAxis, input.zAxis)) > 0.000001 || dot2(cross(input.xAxis, input.yAxis), input.zAxis) < 1 - 0.000001) {- throw new TypeError("Probe frame axes must be orthonormal and right-handed.");+ const index = geometry.getIndex();+ let tris;+ if (index) {+ if (index.count % 3 !== 0)+ return null;+ tris = new Uint32Array(index.count);+ for (let i = 0;i < index.count; i++) {+ const id = index.getX(i);+ if (!Number.isSafeInteger(id) || id < 0 || id >= position.count)+ return null;+ tris[i] = id;+ }+ } else {+ if (position.count % 3 !== 0)+ return null;+ tris = new Uint32Array(position.count);+ for (let i = 0;i < position.count; i++)+ tris[i] = i;}- return {- id: input.id,- origin: stableVector(input.origin),- xAxis: stableVector(input.xAxis),- yAxis: stableVector(input.yAxis),- zAxis: stableVector(input.zAxis)- };+ if (mesh.matrixWorld.determinant() < 0)+ for (let i = 0;i < tris.length; i += 3)+ [tris[i + 1], tris[i + 2]] = [tris[i + 2], tris[i + 1]];+ return { vertProperties: verts, triVerts: tris };}-function probeLocalFrameFromQuaternion(id, origin, quaternion) {- if (!quaternion.every((component) => Number.isFinite(component))) {- throw new TypeError("Probe frame quaternion must be finite.");- }- const quaternionLength = Math.hypot(...quaternion);- if (Math.abs(quaternionLength - 1) > 0.000001) {- throw new TypeError("Probe frame quaternion must be normalized within 1e-6.");- }- const [x, y, z, w] = quaternion;- const xx = x * x;- const yy = y * y;- const zz = z * z;- const xy = x * y;- const xz = x * z;- const yz = y * z;- const wx = w * x;- const wy = w * y;- const wz = w * z;- return createProbeLocalFrame3({- id,- origin,- xAxis: [1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy)],- yAxis: [2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx)],- zAxis: [2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy)]- });-}-function createOrientedProbeBox3(input) {- if (!input.id.trim())- throw new TypeError("Oriented probe box ID must be non-empty.");- if (!finiteVector(input.halfExtents) || input.halfExtents.some((extent) => extent <= 0)) {- throw new TypeError("Oriented probe box half-extents must be finite and greater than zero.");- }- return {- id: input.id,- frame: createProbeLocalFrame3(input.frame),- halfExtents: stableVector(input.halfExtents)+async function analyzePartPenetration(root) {+ const skipped = [];+ const parts = collectParts4(root, skipped);+ const base = {+ schemaVersion: 1,+ source: "engine-scene-analysis",+ partsAnalyzed: parts.length,+ candidatePairs: 0,+ pairsTested: 0,+ pairsUnmeasurable: 0,+ pairsNotReached: 0,+ pairsLodAlternates: 0,+ truncated: false,+ skipped,+ penetrations: []};-}-function worldPointToProbeLocal(frame, worldPoint) {- const offset = subtract2(worldPoint, frame.origin);- return stableVector([- dot2(offset, frame.xAxis),- dot2(offset, frame.yAxis),- dot2(offset, frame.zAxis)- ]);-}-function worldVectorToProbeLocal(frame, worldVector) {- return stableVector([- dot2(worldVector, frame.xAxis),- dot2(worldVector, frame.yAxis),- dot2(worldVector, frame.zAxis)- ]);-}-function projection(box, axisWorld) {- const center = dot2(box.frame.origin, axisWorld);- const radius = axes(box.frame).reduce((total, boxAxis, index) => total + Math.abs(dot2(boxAxis, axisWorld)) * box.halfExtents[index], 0);- return { min: center - radius, max: center + radius };-}-function orientFromReferenceToSubject(axisWorld, subject, reference) {- return dot2(subtract2(subject.frame.origin, reference.frame.origin), axisWorld) < 0 ? scale(axisWorld, -1) : axisWorld;-}-function candidateSatAxes(subject, reference) {- const subjectAxes = axes(subject.frame);- const referenceAxes = axes(reference.frame);+ if (parts.length < 2)+ return base;const candidates = [];- const pushUnique = (rawAxis, label) => {- if (length2(rawAxis) <= EPSILON)- return;- const axis = normalize2(rawAxis);- if (candidates.some((candidate) => Math.abs(dot2(candidate.axis, axis)) > 1 - 0.000000001))+ let considered = 0;+ broadPhase:+ for (let i = 0;i < parts.length; i++) {+ for (let j = i + 1;j < parts.length; j++) {+ if (considered++ === MAX_BROAD_PHASE_PAIRS2) {+ base.broadPhaseTruncated = true;+ break broadPhase;+ }+ const a = parts[i];+ const b = parts[j];+ if (!a.box.intersectsBox(b.box))+ continue;+ if (a.lod && b.lod && a.lod.parent === b.lod.parent && a.lod.stem === b.lod.stem && a.lod.level !== b.lod.level) {+ base.pairsLodAlternates++;+ continue;+ }+ candidates.push({ a: i, b: j, overlap: boxOverlapRatio2(a.box, b.box) });+ }+ }+ base.candidatePairs = candidates.length;+ base.truncated = !!base.broadPhaseTruncated;+ if (candidates.length === 0)+ return base;+ candidates.sort((x, y) => y.overlap - x.overlap || x.a - y.a || x.b - y.b);+ const Module = await import("manifold-3d");+ const wasm = await Module.default();+ wasm.setup();+ const { Manifold, Mesh } = wasm;+ const solids = new Map;+ const unbuildable = [];+ const build = (index) => {+ if (solids.has(index))+ return solids.get(index);+ if (solids.size === MAX_SOLID_BUILDS)return;- candidates.push({ axis, label });+ const part = parts[index];+ let solid = null;+ try {+ const arrays = meshToArrays(part);+ if (arrays) {+ const mesh = new Mesh({ numProp: 3, ...arrays });+ mesh.merge();+ solid = new Manifold(mesh);+ const components = solid.decompose();+ try {+ if (components.length > MAX_SOLID_COMPONENTS || components.some((part) => part.volume() <= 0)) {+ unbuildable.push({+ index,+ reason: "compound solid exceeds the component budget or contains an unsupported inward shell",+ open: false+ });+ solid.delete();+ solid = null;+ } else if (components.length > 1) {+ const union = Manifold.union(components);+ solid.delete();+ solid = union;+ }+ } finally {+ for (const component of components)+ component.delete();+ }+ } else {+ unbuildable.push({+ index,+ reason: "its triangle positions or indices are invalid",+ open: false+ });+ }+ } catch (err) {+ unbuildable.push({+ index,+ reason: `a valid closed solid could not be measured (${err instanceof Error ? err.message : String(err)})`,+ open: true+ });+ solid?.delete();+ solid = null;+ }+ solids.set(index, solid);+ return solid;};- for (let index = 0;index < 3; index++) {- pushUnique(referenceAxes[index], `reference.${["x", "y", "z"][index]}`);+ const penetrations = [];+ const rangeSkips = [];+ const unmeasured = [];+ try {+ for (const pair of candidates) {+ if (solids.get(pair.a) === null || solids.get(pair.b) === null) {+ base.pairsUnmeasurable++;+ unmeasured.push(pair);+ continue;+ }+ const sa = build(pair.a);+ const sb = sa === null ? null : build(pair.b);+ if (sa === null || sb === null) {+ base.pairsUnmeasurable++;+ unmeasured.push(pair);+ continue;+ }+ if (!sa || !sb || base.pairsTested === MAX_NARROW_PHASE_PAIRS) {+ base.pairsNotReached++;+ continue;+ }+ base.pairsTested++;+ const a = parts[pair.a];+ const b = parts[pair.b];+ let overlap = null;+ const scale = Math.max(a.scale, b.scale);+ const pa = sa.scale(a.scale / scale);+ const scaledB = sb.scale(b.scale / scale);+ const pb = scaledB.translate(b.center.clone().sub(a.center).divideScalar(scale).toArray());+ try {+ overlap = Manifold.intersection(pa, pb);+ const volume = overlap.volume();+ if (volume > 0) {+ const smaller = Math.min(Math.abs(pa.volume()), Math.abs(pb.volume()));+ const fraction = smaller > 0 ? volume / smaller : 0;+ if (fraction > CONTACT_VOLUME_FRACTION) {+ const assetVolume = volume * scale ** 3;+ if (!Number.isFinite(assetVolume) || !(assetVolume > 0)) {+ rangeSkips.push({+ part: a.name,+ reason: `intersection with ${JSON.stringify(b.name)} is outside representable volume range`+ });+ continue;+ }+ penetrations.push({+ a: a.name,+ b: b.name,+ volume: roundVolume(assetVolume),+ fraction: round2(fraction)+ });+ }+ }+ } finally {+ overlap?.delete();+ pa.delete();+ pb.delete();+ scaledB.delete();+ }+ }+ for (const pair of candidates) {+ if (solids.get(pair.a) === null)+ build(pair.b);+ else if (solids.get(pair.b) === null)+ build(pair.a);+ }+ } finally {+ for (const solid of solids.values())+ solid?.delete();}- for (let index = 0;index < 3; index++) {- pushUnique(subjectAxes[index], `subject.${["x", "y", "z"][index]}`);+ base.truncated = !!base.broadPhaseTruncated || base.pairsNotReached > 0;+ unbuildable.sort((x, y) => x.index - y.index);+ const acknowledged = [];+ const acknowledgedIndices = new Set;+ for (const { index, reason, open } of unbuildable) {+ const part = parts[index];+ if (open && part.intent !== undefined) {+ acknowledged.push({ part: part.name, reason, intent: part.intent });+ acknowledgedIndices.add(index);+ } else+ skipped.push({ part: part.name, reason });}- for (let subjectIndex = 0;subjectIndex < 3; subjectIndex++) {- for (let referenceIndex = 0;referenceIndex < 3; referenceIndex++) {- pushUnique(cross(subjectAxes[subjectIndex], referenceAxes[referenceIndex]), `cross.subject.${["x", "y", "z"][subjectIndex]}.reference.${["x", "y", "z"][referenceIndex]}`);- }+ skipped.push(...rangeSkips);+ if (acknowledged.length) {+ base.acknowledged = acknowledged;+ base.pairsUnmeasurableAcknowledged = unmeasured.filter((pair) => [pair.a, pair.b].filter((index) => solids.get(index) === null).every((index) => acknowledgedIndices.has(index))).length;}- return candidates;+ penetrations.sort((x, y) => y.fraction - x.fraction || `${x.a}:${x.b}`.localeCompare(`${y.a}:${y.b}`));+ base.penetrations = penetrations;+ return base;}-function sat(subject, reference) {- let maximumSeparation = -Infinity;- let separatingAxis = reference.frame.xAxis;- let separatingLabel = "reference.x";- let minimumOverlap = Infinity;- let overlapAxis = reference.frame.xAxis;- let overlapLabel = "reference.x";- for (const candidate of candidateSatAxes(subject, reference)) {- const subjectProjection = projection(subject, candidate.axis);- const referenceProjection = projection(reference, candidate.axis);- const gap = Math.max(subjectProjection.min - referenceProjection.max, referenceProjection.min - subjectProjection.max);- if (gap > maximumSeparation) {- maximumSeparation = gap;- separatingAxis = candidate.axis;- separatingLabel = candidate.label;- }- const overlap = Math.min(subjectProjection.max, referenceProjection.max) - Math.max(subjectProjection.min, referenceProjection.min);- if (overlap < minimumOverlap) {- minimumOverlap = overlap;- overlapAxis = candidate.axis;- overlapLabel = candidate.label;- }+function readEvidence(context) {+ const evidence = context.derivedEvidence?.["partPenetration"];+ return evidence?.schemaVersion === 1 ? evidence : undefined;+}+function acknowledgedFinding(acknowledged, pairs) {+ const groups = new Map;+ for (const { part, reason, intent } of acknowledged) {+ const key = JSON.stringify([intent, reason]);+ const group = groups.get(key);+ if (group)+ group.parts.push(part);+ else+ groups.set(key, { intent, reason, parts: [part] });}- if (maximumSeparation > 0) {- return {- separation: stable6(maximumSeparation),- penetration: 0,- axisWorld: orientFromReferenceToSubject(separatingAxis, subject, reference),- axisLabel: separatingLabel- };+ const listed = [...groups.values()];+ const shown = listed.slice(0, ACKNOWLEDGED_REASONS_SHOWN);+ const lines = shown.map(({ intent, reason, parts }) => `${parts.length} marked ${JSON.stringify(intent)}, because ${reason}: ${namedParts2(parts)}.`);+ const rest = listed.slice(ACKNOWLEDGED_REASONS_SHOWN);+ if (rest.length) {+ const count = rest.reduce((sum, group) => sum + group.parts.length, 0);+ lines.push(`${count} more ${count === 1 ? "part" : "parts"} marked with ${rest.length} other ${rest.length === 1 ? "reason" : "reasons"}.`);}+ const one = acknowledged.length === 1;+ const which = one ? "this part" : "these parts";+ const pairText = pairs === 1 ? ` 1 overlapping part pair was not measured because of ${which} alone; overlap there is not ruled out.` : pairs > 1 ? ` ${pairs} overlapping part pairs were not measured because of ${which} alone; overlap there is not ruled out.` : "";return {- separation: 0,- penetration: stable6(Math.max(0, minimumOverlap)),- axisWorld: orientFromReferenceToSubject(overlapAxis, subject, reference),- axisLabel: overlapLabel+ code: "GEO_PART_SELF_INTERSECTION_ACKNOWLEDGED",+ disposition: "observe",+ dimension: "visualQuality",+ profile: "geometry.selfIntersection",+ message: `${acknowledged.length} ${one ? "part" : "parts"} marked intentionally open (markOpenShell) ${one ? "was" : "were"} not measured as ${one ? "a closed solid" : "closed solids"}. ${lines.join(" ")}${pairText}`,+ measurement: {+ name: "acknowledgedOpenShells",+ actual: acknowledged.length,+ breakdown: { pairsUnmeasurable: pairs }+ }};}-function supportPoint(box, direction) {- let point = [...box.frame.origin];- axes(box.frame).forEach((boxAxis, index) => {- const projectionValue = dot2(boxAxis, direction);- if (Math.abs(projectionValue) <= EPSILON)- return;- point = add(point, scale(boxAxis, Math.sign(projectionValue) * box.halfExtents[index]));+function inspectPartPenetration(evidence) {+ if (!evidence)+ return [];+ const findings = evidence.penetrations.map((pair) => ({+ code: "GEO_PART_SELF_INTERSECTION",+ disposition: "observe",+ dimension: "visualQuality",+ profile: "geometry.selfIntersection",+ message: `Parts ${JSON.stringify(pair.a)} and ${JSON.stringify(pair.b)} occupy the same space: they share ${pair.volume.toPrecision(3)} m³, which is ${(pair.fraction * 100).toFixed(1)}% of the smaller part.`,+ affected: { node: pair.a },+ measurement: {+ name: "intersectionVolumeFraction",+ actual: pair.fraction,+ expected: CONTACT_VOLUME_FRACTION+ },+ repairText: "Check whether this overlap is intentional, such as a joined beam or embedded detail. For unintended solid overlap, move a part or use boolDiff to cut clearance. This observation does not test intersections within a single mesh, open surfaces, empty passage space or motion."+ }));+ const pairsUnmeasurable = evidence.pairsUnmeasurable ?? 0;+ const acknowledged = evidence.acknowledged ?? [];+ const pairsAcknowledged = acknowledged.length ? Math.min(evidence.pairsUnmeasurableAcknowledged ?? 0, pairsUnmeasurable) : 0;+ if (evidence.truncated) {+ const pairsNotReached = evidence.pairsNotReached ?? 0;+ findings.push({+ code: "GEO_PART_SELF_INTERSECTION_TRUNCATED",+ disposition: "observe",+ dimension: "visualQuality",+ profile: "geometry.selfIntersection",+ message: `Tested ${evidence.pairsTested} of ${evidence.broadPhaseTruncated ? "at least " : ""}${evidence.candidatePairs} overlapping part pairs: ${pairsUnmeasurable} involve parts that could not be measured, ${pairsNotReached} were beyond the analysis budget (${MAX_NARROW_PHASE_PAIRS} booleans, ${MAX_SOLID_BUILDS} solids).` + (evidence.broadPhaseTruncated ? ` Pair discovery stopped after ${MAX_BROAD_PHASE_PAIRS2} box comparisons.` : "") + " Unreached pairs were not examined; the most overlapping bounding boxes were tested first.",+ measurement: {+ name: "overlappingPartPairsTested",+ actual: evidence.pairsTested,+ expected: evidence.candidatePairs,+ breakdown: { pairsUnmeasurable, pairsNotReached }+ }+ });+ }+ if (evidence.skipped.length) {+ const byReason = new Map;+ for (const { part, reason } of evidence.skipped) {+ const parts = byReason.get(reason);+ if (parts)+ parts.push(part);+ else+ byReason.set(reason, [part]);+ }+ const reasons = [...byReason].map(([reason, parts]) => `${parts.length} because ${reason}: ${namedParts2(parts)}.`);+ const one = evidence.skipped.length === 1;+ const includes = one ? "this part" : "one of these parts";+ const unmarked = pairsUnmeasurable - pairsAcknowledged;+ const pairs = unmarked === 1 ? ` 1 overlapping part pair includes ${includes} and was not measured.` : unmarked > 1 ? ` ${unmarked} overlapping part pairs include ${includes} and were not measured.` : "";+ findings.push({+ code: "GEO_PART_SELF_INTERSECTION_UNMEASURED",+ disposition: "observe",+ dimension: "visualQuality",+ profile: "geometry.selfIntersection",+ message: `${evidence.skipped.length} part-volume ${one ? "measurement was" : "measurements were"} unavailable. ${reasons.join(" ")}${pairs} ${one ? "This part is" : "These parts are"} not certified clear.`+ });+ }+ if (acknowledged.length)+ findings.push(acknowledgedFinding(acknowledged, pairsAcknowledged));+ return findings;+}+var MAX_PART_TRIANGLES = 20000, MAX_NARROW_PHASE_PAIRS = 64, MAX_SOLID_BUILDS, MAX_SOLID_COMPONENTS = 32, MAX_BROAD_PHASE_PAIRS2 = 250000, CONTACT_VOLUME_FRACTION = 0.001, boxVolume = (box) => (box.max.x - box.min.x) * (box.max.y - box.min.y) * (box.max.z - box.min.z), round2 = (n) => Math.round(n * 1e9) / 1e9, roundVolume = (n) => Number(n.toPrecision(9)), SELF_INTERSECTION_QA_RULE, UNMEASURED_NAMES_SHOWN = 5, ACKNOWLEDGED_REASONS_SHOWN = 5, namedParts2 = (parts) => {+ const named = parts.slice(0, UNMEASURED_NAMES_SHOWN).map((part) => JSON.stringify(part));+ const more = parts.length > UNMEASURED_NAMES_SHOWN ? ` and ${parts.length - UNMEASURED_NAMES_SHOWN} more` : "";+ return `${named.join(", ")}${more}`;+};+var init_self_intersection = __esm(() => {+ init_open_shell();+ init_lod2();+ init_registry();+ MAX_SOLID_BUILDS = 2 * MAX_NARROW_PHASE_PAIRS;+ SELF_INTERSECTION_QA_RULE = Object.freeze({+ id: "GEO_PART_SELF_INTERSECTION",+ profile: "geometry.selfIntersection",+ scope: { kind: "universal" },+ ruleClass: "heuristic",+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: "observe",+ evaluate(context) {+ return inspectPartPenetration(readEvidence(context));+ }});- return stableVector(point);+});++// src/vehicle.ts+import * as THREE14 from "three";+function assertId(value, name) {+ if (!ID_PATTERN.test(value))+ throw new TypeError(`${name} must be a stable identifier`);+ return value;}-function evidence(subject, reference, points, axisWorld, axisLabel) {+function positive2(value, name) {+ assertDimension(name, value);+ return value;+}+function normalizedQuaternion(value) {+ const source = value ?? [0, 0, 0, 1];+ const length = Math.hypot(source[0], source[1], source[2], source[3]);+ if (!Number.isFinite(length) || length <= 0.000000001)+ throw new TypeError("socket rotation must be a finite quaternion");+ return [source[0] / length, source[1] / length, source[2] / length, source[3] / length];+}+function semantic2(roles, options = {}) {return {- subjectId: subject.id,- referenceId: reference.id,- coordinateSpace: "reference-local",- referenceFrameId: reference.frame.id,- ...axisWorld ? { axis: worldVectorToProbeLocal(reference.frame, axisWorld) } : {},- ...axisLabel ? { axisLabel } : {},- points+ roles,+ relationships: options.relationships ?? [],+ frames: options.frames ?? [],+ sockets: options.sockets ?? []};}-function satEvidencePoints(subject, reference, axisWorld) {- return [- {- label: `${reference.id}.support`,- position: worldPointToProbeLocal(reference.frame, supportPoint(reference, axisWorld))- },- {- label: `${subject.id}.support`,- position: worldPointToProbeLocal(reference.frame, supportPoint(subject, scale(axisWorld, -1)))- }- ];+function socketRole(kind, id) {+ if (kind === "chassis")+ return KILN_SEMANTIC_ROLES.chassisMain;+ return semanticRole(SOCKET_ROLE_BASE[kind], id);}-function probeOrientedPenetration(subject, reference, options = {}) {- const maxDepth = options.maxDepth ?? 0;- const tolerance = options.tolerance ?? DEFAULT_TOLERANCE;- assertNonNegative(maxDepth, "maxDepth");- assertNonNegative(tolerance, "tolerance");- const relation = sat(subject, reference);+function createTypedSocket(kind, input, parent) {+ const id = assertId(input.id, `${kind} socket id`);+ if (!input.position.every(Number.isFinite))+ throw new TypeError(`${kind}.${id} position must be finite`);+ const rotation = normalizedQuaternion(input.rotation);+ const node = new THREE14.Object3D;+ node.name = `Socket_${kind}_${id}`;+ node.position.set(...input.position);+ node.quaternion.set(...rotation);+ const socket = {+ id,+ type: `vehicle.${kind}`,+ frame: "socket",+ compatibleTypes: [...input.compatibleTypes ?? [`vehicle.${kind}`]]+ };+ stampSemanticMetadataV1(node, semantic2([semanticRole(KILN_SEMANTIC_ROLES.socket, kind, id), socketRole(kind, id)], {+ frames: [{ id: "socket", translation: [0, 0, 0], rotation: [0, 0, 0, 1] }],+ sockets: [socket],+ relationships: [+ { kind: "owned-by", target: KILN_SEMANTIC_ROLES.vehicleFrame, targetType: "role" }+ ]+ }));+ parent.add(node);+ return node;+}+function createVehicleFrame(name, options = {}) {+ const root = new THREE14.Object3D;+ root.name = name;+ stampSemanticMetadataV1(root, semantic2([KILN_SEMANTIC_ROLES.vehicleFrame, KILN_SEMANTIC_ROLES.vehicleForward], {+ frames: [+ { id: "origin", translation: [0, 0, 0], rotation: [0, 0, 0, 1] },+ { id: "forward.+x", translation: [0, 0, 0], rotation: [0, 0, 0, 1] },+ { id: "up.+y", translation: [0, 0, 0], rotation: [0, 0, 0, 1] },+ { id: "right.+z", translation: [0, 0, 0], rotation: [0, 0, 0, 1] }+ ]+ }));+ if (options.parent)+ options.parent.add(root);+ const chassis = createTypedSocket("chassis", options.chassis ?? { id: "main", position: [0, 0, 0] }, root);+ const build = (kind, values) => (values ?? []).map((value) => createTypedSocket(kind, value, root));return {- relation: "penetration",- pass: relation.penetration <= maxDepth + tolerance,- measurements: {- penetrationDepth: relation.penetration,- separation: relation.separation,- maxDepth,- tolerance- },- evidence: evidence(subject, reference, satEvidencePoints(subject, reference, relation.axisWorld), relation.axisWorld, relation.axisLabel)+ root,+ chassis,+ axles: build("axle", options.axles),+ seats: build("seat", options.seats),+ contacts: build("contact", options.contacts),+ steering: build("steering", options.steering),+ propulsion: build("propulsion", options.propulsion)};}-var EPSILON = 0.0000000001, DEFAULT_TOLERANCE = 0.000001, finiteVector = (value) => value.length === 3 && value.every((component) => Number.isFinite(component)), add = (a, b) => [- a[0] + b[0],- a[1] + b[1],- a[2] + b[2]-], subtract2 = (a, b) => [- a[0] - b[0],- a[1] - b[1],- a[2] - b[2]-], scale = (value, amount) => [- value[0] * amount,- value[1] * amount,- value[2] * amount-], dot2 = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2], cross = (a, b) => [- a[1] * b[2] - a[2] * b[1],- a[2] * b[0] - a[0] * b[2],- a[0] * b[1] - a[1] * b[0]-], length2 = (value) => Math.hypot(value[0], value[1], value[2]), normalize2 = (value) => {- const magnitude = length2(value);- if (magnitude <= EPSILON)- throw new TypeError("Cannot normalize a zero-length probe axis.");- return scale(value, 1 / magnitude);-}, stable6 = (value) => {- if (Math.abs(value) < 0.0000000001)- return 0;- return Number(value.toFixed(9));-}, stableVector = (value) => [- stable6(value[0]),- stable6(value[1]),- stable6(value[2])-], assertNonNegative = (value, name) => {- if (!Number.isFinite(value) || value < 0) {- throw new TypeError(`${name} must be a finite non-negative number.`);- }-}, axes = (frame) => [- frame.xAxis,- frame.yAxis,- frame.zAxis-];--// src/qa/vehicle-advisory.ts-import * as THREE13 from "three";-function advisory(context, value) {+function cylinderZ(radius, width, segments = 16) {+ const geometry = new THREE14.CylinderGeometry(radius, radius, width, segments);+ geometry.rotateX(Math.PI / 2);+ return geometry;+}+function createWheelGeometrySet(radius, width) {+ positive2(radius, "radius");+ positive2(width, "width");return {- ...value,- disposition: "warn",- dimension: "categoryReadiness",- profile: context.profile ?? "asset.requirements.v1",- viewHints: value.viewHints ?? [...VEHICLE_VIEWS]+ tire: defaultTireGeometry(radius, width),+ rim: cylinderZ(radius * 0.68, width * 0.8),+ hub: cylinderZ(radius * 0.34, width * 0.94)};}-function localPoint(inverse, point) {- return point.clone().applyMatrix4(inverse);+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 THREE14.TorusGeometry(radius - tube, tube, 8, 20);}-function wheelPairs(wheels) {- const groups = new Map;- for (const wheel of wheels) {- if (!wheel.index)- continue;- const group = groups.get(wheel.index) ?? [];- group.push(wheel);- groups.set(wheel.index, group);+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 THREE14.Box3;+ const point = new THREE14.Vector3;+ let actualRadius = 0;+ for (let i = 0;i < positions.count; i++) {+ point.fromBufferAttribute(positions, i);+ if (![point.x, point.y, point.z].every(Number.isFinite))+ throw new RangeError(`wheel ${part} position coordinates must be finite.`);+ bounds.expandByPoint(point);+ actualRadius = Math.max(actualRadius, Math.hypot(point.x, point.y));}- return [...groups.entries()].flatMap(([index, group]) => {- const left = group.find((wheel) => wheel.side === "left");- const right = group.find((wheel) => wheel.side === "right");- return left && right ? [[index, left, right]] : [];- });+ const actualWidth = bounds.max.z - bounds.min.z;+ const center = bounds.getCenter(new THREE14.Vector3);+ const tolerance = 0.00001 * Math.max(radius, width, actualRadius, actualWidth);+ const differences = [];+ if (Math.abs(actualRadius - radius) > tolerance)+ differences.push("radius");+ if (Math.abs(actualWidth - width) > tolerance)+ differences.push("width");+ if (Math.max(Math.abs(center.x), Math.abs(center.y), Math.abs(center.z)) > tolerance)+ differences.push("center");+ return {+ part,+ status: differences.length ? "mismatch" : "match",+ declared: { radius, width },+ observed: { radius: actualRadius, width: actualWidth, boundsCenter: center.toArray() },+ differences+ };}-function bilateralSymmetryFindings(context, root, wheels) {- root.updateMatrixWorld(true);- const inverse = root.matrixWorld.clone().invert();- const findings = [];- for (const [index, left, right] of wheelPairs(wheels)) {- const a = localPoint(inverse, left.centerWorld);- const b = localPoint(inverse, right.centerWorld);- const centerDelta = Math.hypot(a.x - b.x, a.y - b.y, a.z + b.z);- const radiusDelta = Math.abs((left.radius ?? 0) - (right.radius ?? 0));- const widthDelta = Math.abs((left.width ?? 0) - (right.width ?? 0));- const scale = Math.max(left.radius ?? 0, right.radius ?? 0, 0.25);- const threshold = Math.max(0.01, scale * SYMMETRY_RATIO);- const maximum = Math.max(centerDelta, radiusDelta, widthDelta);- if (maximum <= threshold)- continue;- const measurementName = maximum === centerDelta ? "bilateralCenterMirrorDelta" : maximum === radiusDelta ? "bilateralRadiusDelta" : "bilateralWidthDelta";- findings.push(advisory(context, {- code: "VEH_BILATERAL_SYMMETRY",- message: `Axle ${index} left/right assemblies differ in center, radius, or width ` + `(center=${centerDelta.toFixed(6)}, radius=${radiusDelta.toFixed(6)}, width=${widthDelta.toFixed(6)} m).`,- affected: { node: right.root.name },- measurement: {- name: measurementName,- actual: maximum,- expected: 0,- threshold,- unit: "m"- }+function createWheelAssembly(name, materials, options) {+ const radius = positive2(options.radius, "radius");+ const width = positive2(options.width, "width");+ const rimRadius = positive2(options.rimRadius ?? radius * 0.68, "rimRadius");+ const hubRadius = positive2(options.hubRadius ?? radius * 0.34, "hubRadius");+ const rimWidth = positive2(options.rimWidth ?? width * 0.8, "rimWidth");+ const hubWidth = positive2(options.hubWidth ?? width * 0.94, "hubWidth");+ if (rimRadius >= radius || hubRadius >= rimRadius)+ throw new RangeError("wheel radii must satisfy hub < rim < tire");+ if (rimWidth > width || hubWidth > width)+ throw new RangeError("rim/hub width must not exceed tire width");+ if (options.side !== "left" && options.side !== "right" && options.side !== "center")+ throw new RangeError("wheel side must be left, right or center");+ if (options.position !== undefined)+ assertFiniteTriple("wheel position", options.position);+ const geometryChecks = [];+ for (const [part, declaredRadius, declaredWidth] of [+ ["tire", radius, width],+ ["rim", rimRadius, rimWidth],+ ["hub", hubRadius, hubWidth]+ ]) {+ const geometry = options.geometries?.[part];+ if (geometry)+ geometryChecks.push(checkWheelGeometry(part, geometry, declaredRadius, declaredWidth));+ }+ const index = assertId(String(options.index), "wheel index");+ const key = `${options.side}.${index}`;+ const parent = options.parent;+ const root = new THREE14.Object3D;+ root.name = `${name}_Assembly_${options.side}_${index}`;+ let steeringPivot;+ if (options.steering) {+ steeringPivot = new THREE14.Object3D;+ steeringPivot.name = `SteeringPivot_${options.side}_${index}`;+ steeringPivot.position.set(...options.position ?? [0, 0, 0]);+ stampSemanticMetadataV1(steeringPivot, semantic2([semanticRole(ROLE.steeringPivot, key)], {+ frames: [{ id: "steering-axis.+y", translation: [0, 0, 0], rotation: [0, 0, 0, 1] }],+ relationships: [+ { kind: "steers", target: semanticRole(ROLE.wheelAssembly, key), targetType: "role" }+ ]}));+ root.add(steeringPivot);}- return findings;+ const spinPivot = new THREE14.Object3D;+ spinPivot.name = `WheelPivot_${options.side}_${index}`;+ if (!steeringPivot)+ spinPivot.position.set(...options.position ?? [0, 0, 0]);+ stampSemanticMetadataV1(spinPivot, semantic2([+ semanticRole(ROLE.wheelAssembly, key),+ semanticRole(ROLE.wheelPivot, key),+ ...options.loadBearing === false ? [] : [semanticRole(ROLE.wheelLoadBearing, key)]+ ], {+ frames: [+ { id: "axle-center", translation: [0, 0, 0], rotation: [0, 0, 0, 1] },+ { id: "spin-axis.+z", translation: [0, 0, 0], rotation: [0, 0, 0, 1] }+ ],+ relationships: [+ { kind: "mounted-on", target: semanticRole(ROLE.axle, index), targetType: "role" },+ { kind: "contains", target: semanticRole(ROLE.wheelTire, key), targetType: "role" },+ { kind: "contains", target: semanticRole(ROLE.wheelRim, key), targetType: "role" },+ { kind: "contains", target: semanticRole(ROLE.wheelHub, key), targetType: "role" }+ ]+ }));+ (steeringPivot ?? root).add(spinPivot);+ const tire = new THREE14.Mesh(options.geometries?.tire ?? defaultTireGeometry(radius, width), materials.tire);+ const rim = new THREE14.Mesh(options.geometries?.rim ?? cylinderZ(rimRadius, rimWidth), materials.rim);+ const hub = new THREE14.Mesh(options.geometries?.hub ?? cylinderZ(hubRadius, hubWidth), materials.hub ?? materials.rim);+ tire.name = `Tire_${options.side}_${index}`;+ rim.name = `Rim_${options.side}_${index}`;+ hub.name = `Hub_${options.side}_${index}`;+ stampSemanticMetadataV1(tire, semantic2([semanticRole(ROLE.wheelTire, key)], {+ relationships: [+ { kind: "descends-from", target: semanticRole(ROLE.wheelPivot, key), targetType: "role" }+ ]+ }));+ stampSemanticMetadataV1(rim, semantic2([semanticRole(ROLE.wheelRim, key)], {+ relationships: [+ { kind: "contained-by", target: semanticRole(ROLE.wheelTire, key), targetType: "role" }+ ]+ }));+ stampSemanticMetadataV1(hub, semantic2([semanticRole(ROLE.wheelHub, key)], {+ relationships: [+ { kind: "contained-by", target: semanticRole(ROLE.wheelRim, key), targetType: "role" }+ ]+ }));+ spinPivot.add(tire, rim, hub);+ const contact = new THREE14.Object3D;+ contact.name = `Contact_${options.side}_${index}`;+ contact.position.y = -radius;+ stampSemanticMetadataV1(contact, semantic2([semanticRole(ROLE.wheelContact, key), semanticRole(ROLE.contact, key)], {+ frames: [{ id: "contact", translation: [0, 0, 0], rotation: [0, 0, 0, 1] }],+ relationships: [{ kind: "supports", target: ROLE.vehicleFrame, targetType: "role" }]+ }));+ spinPivot.add(contact);+ if (parent)+ parent.add(root);+ return {+ root,+ ...steeringPivot ? { steeringPivot } : {},+ spinPivot,+ tire,+ rim,+ hub,+ contact,+ radius,+ width,+ side: options.side,+ index,+ spinAxis: VEHICLE_AXES.wheelAxle,+ geometryChecks+ };}-function semanticRoles(node) {+function roles(node) {return readSemanticMetadataV1(node)?.roles ?? [];}-function trackSide(node) {- for (const role of semanticRoles(node)) {- const match = role.match(/(?:track\.loop|support\.track|track\.road-wheel)\.(left|right)(?:\.|$)/);- if (match?.[1] === "left" || match?.[1] === "right")- return match[1];+function descendantWithRole(root, prefix) {+ let found;+ root.traverse((node) => {+ if (!found && roles(node).some((role) => role.startsWith(prefix)))+ found = node;+ });+ return found;+}+function ancestorWithRole(node, prefix) {+ let current = node.parent;+ while (current) {+ if (roles(current).some((role) => role.startsWith(prefix)))+ return current;+ current = current.parent;}return;}-function isFender(node) {- return semanticRoles(node).some((role) => /(?:^|\.)(?:fender|wheel-arch)(?:\.|$)/i.test(role)) || /fender|wheel[ _.-]?arch/i.test(node.name);+function parseWheelRole(role) {+ const parts = role.split(".");+ const side = parts.at(-2);+ return {+ ...side === "left" || side === "right" || side === "center" ? { side } : {},+ ...parts.at(-1) ? { index: parts.at(-1) } : {}+ };}-function isChassisMesh(node) {- if (!(node instanceof THREE13.Mesh) || isFender(node))- return false;- return semanticRoles(node).some((role) => /^(?:vehicle\.)?(?:chassis|body|hull)(?:\.|$)/i.test(role)) || /chassis|vehicle[ _.-]?body|fuselage|hull/i.test(node.name);-}-function objectBoundsInFrame2(object, frame) {+function objectBoundsInFrame(object, frame) {object.updateWorldMatrix(true, true);frame.updateWorldMatrix(true, false);const worldToFrame = frame.matrixWorld.clone().invert();- const bounds = new THREE13.Box3;+ const bounds = new THREE14.Box3;let found = false;- object.traverseVisible((part) => {- if (!(part instanceof THREE13.Mesh) || !(part.geometry instanceof THREE13.BufferGeometry))+ object.traverse((node) => {+ if (!(node instanceof THREE14.Mesh) || !(node.geometry instanceof THREE14.BufferGeometry))return;- part.geometry.computeBoundingBox();- const box = part.geometry.boundingBox;- if (!box)+ node.geometry.computeBoundingBox();+ const local = node.geometry.boundingBox;+ if (!local)return;- const matrix = worldToFrame.clone().multiply(part.matrixWorld);- for (const x of [box.min.x, box.max.x])- for (const y of [box.min.y, box.max.y])- for (const z of [box.min.z, box.max.z]) {- bounds.expandByPoint(new THREE13.Vector3(x, y, z).applyMatrix4(matrix));+ const matrix = worldToFrame.clone().multiply(node.matrixWorld);+ for (const x of [local.min.x, local.max.x])+ for (const y of [local.min.y, local.max.y])+ for (const z of [local.min.z, local.max.z]) {+ bounds.expandByPoint(new THREE14.Vector3(x, y, z).applyMatrix4(matrix));found = true;}});return found ? bounds : undefined;}-function tuple2(value) {- return [value.x, value.y, value.z];+function dimensions(object, frame) {+ if (!object)+ return;+ const bounds = objectBoundsInFrame(object, frame);+ if (!bounds)+ return;+ const size = bounds.getSize(new THREE14.Vector3);+ return {+ center: bounds.getCenter(new THREE14.Vector3),+ radius: Math.max(size.x, size.y) / 2,+ width: size.z+ };}-function probeBox(id, root, bounds) {- root.updateWorldMatrix(true, false);- const center = bounds.getCenter(new THREE13.Vector3).applyMatrix4(root.matrixWorld);- const size = bounds.getSize(new THREE13.Vector3);- const position = new THREE13.Vector3;- const quaternion = new THREE13.Quaternion;- const scale = new THREE13.Vector3;- root.matrixWorld.decompose(position, quaternion, scale);- const xAxis = new THREE13.Vector3(1, 0, 0).applyQuaternion(quaternion).normalize();- const yAxis = new THREE13.Vector3(0, 1, 0).applyQuaternion(quaternion).normalize();- const zAxis = new THREE13.Vector3(0, 0, 1).applyQuaternion(quaternion).normalize();- return createOrientedProbeBox3({+function resolved(source, id, root, pivot, parts) {+ pivot.updateWorldMatrix(true, false);+ const tire = dimensions(parts.tire, pivot);+ const rim = dimensions(parts.rim, pivot);+ const hub = dimensions(parts.hub, pivot);+ const centerLocal = tire?.center ?? rim?.center ?? hub?.center ?? new THREE14.Vector3;+ const toWorld = (value) => value.clone().applyMatrix4(pivot.matrixWorld);+ return {id,- frame: createProbeLocalFrame3({- id: `${id}.frame`,- origin: tuple2(center),- xAxis: tuple2(xAxis),- yAxis: tuple2(yAxis),- zAxis: tuple2(zAxis)- }),- halfExtents: [- size.x * Math.abs(scale.x) / 2,- size.y * Math.abs(scale.y) / 2,- size.z * Math.abs(scale.z) / 2- ]- });+ source,+ ...parts.side ? { side: parts.side } : {},+ ...parts.index ? { index: parts.index } : {},+ root,+ pivot,+ ...parts.steeringPivot ? { steeringPivot: parts.steeringPivot } : {},+ ...parts.tire ? { tire: parts.tire } : {},+ ...parts.rim ? { rim: parts.rim } : {},+ ...parts.hub ? { hub: parts.hub } : {},+ ...parts.contact ? { contact: parts.contact } : {},+ centerWorld: toWorld(centerLocal),+ pivotCenterWorld: new THREE14.Vector3().setFromMatrixPosition(pivot.matrixWorld),+ ...tire ? { tireCenterWorld: toWorld(tire.center) } : {},+ ...rim ? { rimCenterWorld: toWorld(rim.center) } : {},+ ...hub ? { hubCenterWorld: toWorld(hub.center) } : {},+ spinAxisWorld: new THREE14.Vector3(0, 0, 1).transformDirection(pivot.matrixWorld),+ ...tire ? { radius: tire.radius, width: tire.width } : {},+ ...rim ? { rimRadius: rim.radius, rimWidth: rim.width } : {},+ ...hub ? { hubRadius: hub.radius, hubWidth: hub.width } : {},+ loadBearing: hasSemanticRole(roles(pivot), ROLE.wheelLoadBearing)+ };}-function chassisMeshes(root) {- const meshes = [];- root.traverseVisible((node) => {- if (isChassisMesh(node))- meshes.push(node);+function semanticAssemblies(root) {+ const result = [];+ root.traverse((node) => {+ const assemblyRole = roles(node).find((role) => semanticRoleMatches(role, ROLE.wheelAssembly));+ if (!assemblyRole)+ return;+ const parsed = parseWheelRole(assemblyRole);+ result.push(resolved("semantic", assemblyRole, node, node, {+ ...parsed,+ tire: descendantWithRole(node, `${ROLE.wheelTire}.`),+ rim: descendantWithRole(node, `${ROLE.wheelRim}.`),+ hub: descendantWithRole(node, `${ROLE.wheelHub}.`),+ contact: descendantWithRole(node, `${ROLE.wheelContact}.`),+ steeringPivot: ancestorWithRole(node, `${ROLE.steeringPivot}.`)+ }));});- return meshes;+ return result;}-function penetrationFindings(context, root, wheels) {- const chassis = chassisMeshes(root);- const findings = [];- for (const wheel of wheels) {- if (!wheel.tire || wheel.radius === undefined)- continue;- const tireBounds = objectBoundsInFrame2(wheel.tire, root);- if (!tireBounds)- continue;- const threshold = Math.max(0.02, wheel.radius * PENETRATION_RATIO);- for (const body of chassis) {- const bodyBounds = objectBoundsInFrame2(body, root);- if (!bodyBounds)- continue;- const result = probeOrientedPenetration(probeBox(`${wheel.id}.tire`, root, tireBounds), probeBox(body.name || "vehicle.chassis", root, bodyBounds), { maxDepth: threshold });- if (result.pass)- continue;- findings.push(advisory(context, {- code: "VEH_WHEEL_CHASSIS_PENETRATION",- message: `Wheel ${wheel.id} penetrates chassis ${body.name || "(unnamed)"} by ` + `${result.measurements.penetrationDepth?.toFixed(6)} m beyond the allowed non-fender overlap.`,- affected: { node: wheel.tire.name || wheel.root.name },- measurement: {- name: "tireChassisPenetrationDepth",- actual: result.measurements.penetrationDepth ?? 0,- expected: 0,- threshold,- unit: "m"- },- viewHints: ["vehicle.underbody", "vehicle.wheel-section.right"]- }));- }- }- return findings;+function legacyCorner(name) {+ const value = name.toLowerCase().replace(/[^a-z0-9]+/g, "-");+ if (!/(wheel|tire|rim|hub)/.test(value))+ return;+ const side = /(?:left|(^|-)l($|-)|fl|rl)/.test(value) ? "left" : /(?:right|(^|-)r($|-)|fr|rr)/.test(value) ? "right" : undefined;+ const index = /(?:front|(^|-)f($|-)|fl|fr)/.test(value) ? "front" : /(?:rear|back|(^|-)r[lr]($|-)|rl|rr)/.test(value) ? "rear" : value.match(/\d+/)?.[0];+ return {+ key: `${side ?? "unknown"}.${index ?? value}`,+ ...side ? { side } : {},+ ...index ? { index } : {}+ };}-function wholeAssetBounds(root) {- return objectBoundsInFrame2(root, root);+function legacyAssemblies(root) {+ const groups = new Map;+ root.traverse((node) => {+ const corner = legacyCorner(node.name);+ if (!corner)+ return;+ const entry = groups.get(corner.key) ?? {+ ...corner.side ? { side: corner.side } : {},+ ...corner.index ? { index: corner.index } : {}+ };+ const lower = node.name.toLowerCase();+ if (lower.includes("pivot"))+ entry.pivot = node;+ else if (lower.includes("rim"))+ entry.rim = node;+ else if (lower.includes("hub"))+ entry.hub = node;+ else+ entry.tire = node;+ groups.set(corner.key, entry);+ });+ return [...groups.entries()].map(([key, parts]) => {+ const pivot = parts.pivot ?? parts.tire?.parent ?? parts.rim?.parent ?? parts.hub?.parent ?? root;+ return resolved("legacy", key, pivot, pivot, parts);+ });}-function orientationFindings(context, root, intent) {- if (intent.subtype === "fixed-wing" || intent.subtype === "rotorcraft" || intent.subtype === "walking" || intent.subtype === "custom") {- return [];- }- const bounds = wholeAssetBounds(root);- if (!bounds)- return [];- const size = bounds.getSize(new THREE13.Vector3);- const ratio = size.z / Math.max(size.x, 0.000000001);- if (ratio <= ORIENTATION_RATIO)- return [];- return [- advisory(context, {- code: "VEH_ORIENTATION_SIDEWAYS",- message: `${intent.subtype ?? "Mobility assembly"} bounds are Z-dominant despite canonical +X travel ` + `(spanX=${size.x.toFixed(6)}, spanZ=${size.z.toFixed(6)} m).`,- affected: { node: root.name || "vehicle-root" },- measurement: {- name: "boundsSpanZToSpanX",- actual: ratio,- expected: `<=${ORIENTATION_RATIO}`,- threshold: ORIENTATION_RATIO- },- viewHints: ["generic.top.semantic-overlay", "vehicle.underbody"]- })- ];+function resolveVehicleWheelAssemblies(root) {+ const semantic = semanticAssemblies(root);+ return semantic.length > 0 ? semantic : legacyAssemblies(root);}-function nodePath3(root, target) {- let found = "";- const visit = (node, parent, index) => {- if (found)- return;- const segment = `${node.name.trim() || node.type || "Object3D"}[${index}]`;- const path = parent ? `${parent}/${segment}` : segment;- if (node === target) {- found = path;- return;+function hasCanonicalVehicleFront(root) {+ let found = false;+ root.traverse((node) => {+ const metadata = readSemanticMetadataV1(node);+ if (metadata?.roles.includes(ROLE.vehicleFrame) && metadata.roles.includes(ROLE.vehicleForward) && metadata.frames.some((frame) => frame.id === "forward.+x")) {+ found = true;}- node.children.forEach((child, childIndex) => {- visit(child, path, childIndex);- });- };- visit(root, "", 0);+ });return found;}-function weldedBoundaryEdges(root, loop) {- root.updateMatrixWorld(true);- const inverse = loop.matrixWorld.clone().invert();- const edges = new Map;- let triangleCount = 0;- const vertexKey = (point) => [point.x, point.y, point.z].map((value) => Math.round(value * 1e6)).join(",");- loop.traverseVisible((node) => {- if (!(node instanceof THREE13.Mesh) || !(node.geometry instanceof THREE13.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 THREE13.Vector3().fromBufferAttribute(positions, index).applyMatrix4(matrix)));- const index = node.geometry.getIndex();- const indices = index ? Array.from(index.array, Number) : Array.from({ length: positions.count }, (_, value) => value);- for (let offset = 0;offset + 2 < indices.length; offset += 3) {- triangleCount++;- const triangle = [indices[offset], indices[offset + 1], indices[offset + 2]];- for (let edge = 0;edge < 3; edge++) {- const a = keys[triangle[edge]];- const b = keys[triangle[(edge + 1) % 3]];- const id = a < b ? `${a}|${b}` : `${b}|${a}`;- edges.set(id, (edges.get(id) ?? 0) + 1);- }- }+var ROLE, VEHICLE_AXES, ID_PATTERN, SOCKET_ROLE_BASE;+var init_vehicle = __esm(() => {+ init_geometry_budget();+ init_contracts();+ ROLE = KILN_SEMANTIC_ROLES;+ VEHICLE_AXES = Object.freeze({+ forward: Object.freeze([1, 0, 0]),+ up: Object.freeze([0, 1, 0]),+ right: Object.freeze([0, 0, 1]),+ wheelAxle: Object.freeze([0, 0, 1])});- if (triangleCount === 0)- return;- return [...edges.values()].filter((count) => count === 1).length;-}-function trackProfileFindings(context, root, intent) {- if (intent.subtype !== "tracked")- return [];- const loops = [];- const roadWheels = [];- root.traverseVisible((node) => {- const roles = semanticRoles(node);- if (roles.some((role) => role.startsWith("track.loop.")) || roles.some((role) => role.startsWith("support.track."))) {- loops.push(node);- }- if (roles.some((role) => role.startsWith("track.road-wheel.")) || /road[ _.-]?wheel/i.test(node.name)) {- roadWheels.push(node);- }+ ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;+ SOCKET_ROLE_BASE = Object.freeze({+ chassis: KILN_SEMANTIC_ROLES.chassis,+ axle: KILN_SEMANTIC_ROLES.axle,+ seat: KILN_SEMANTIC_ROLES.seat,+ contact: KILN_SEMANTIC_ROLES.contact,+ steering: KILN_SEMANTIC_ROLES.steering,+ propulsion: KILN_SEMANTIC_ROLES.propulsion});- if (loops.length === 0) {- return [- advisory(context, {- code: "VEH_TRACK_LOOP_MISSING",- message: "Tracked vehicle exposes no semantic track.loop.* assembly to inspect.",- affected: { node: root.name || "vehicle-root" },- measurement: { name: "trackLoopCount", actual: 0, expected: ">=1", threshold: 1 },- viewHints: ["vehicle.underbody", "generic.right.semantic-overlay"]- })- ];- }- const findings = [];- for (const loop of loops) {- const loopSide = trackSide(loop);- const declaredClosed = loop.userData["kilnTrackLoopClosed"];- const boundaryEdges = weldedBoundaryEdges(root, loop);- if (declaredClosed === false || boundaryEdges !== undefined && boundaryEdges > 0) {- findings.push(advisory(context, {- code: "VEH_TRACK_LOOP_OPEN",- message: `Track loop ${loop.name || "(unnamed)"} is open ` + `(boundary edges ${boundaryEdges ?? "declared"}).`,- affected: { node: loop.name || "track-loop", nodePath: nodePath3(root, loop) },- measurement: {- name: "trackLoopBoundaryEdgeCount",- actual: boundaryEdges ?? 1,- expected: 0,- threshold: 0- },- viewHints: ["vehicle.underbody", "generic.right.wireframe"]- }));- }- const loopBounds = objectBoundsInFrame2(loop, root);- if (!loopBounds)- continue;- const expanded = loopBounds.clone().expandByScalar(TRACK_CONTAINMENT_TOLERANCE);- for (const roadWheel of roadWheels.filter((candidate) => !loopSide || !trackSide(candidate) || trackSide(candidate) === loopSide)) {- const wheelBounds = objectBoundsInFrame2(roadWheel, root);- if (!wheelBounds)- continue;- const center = wheelBounds.getCenter(new THREE13.Vector3);- if (expanded.containsPoint(center))- continue;- const clamped = center.clone().clamp(expanded.min, expanded.max);- const overflow = center.distanceTo(clamped);- findings.push(advisory(context, {- code: "VEH_TRACK_ROAD_WHEEL_ESCAPED",- message: `Road wheel ${roadWheel.name || "(unnamed)"} escapes track loop ` + `${loop.name || "(unnamed)"} by ${overflow.toFixed(6)} m.`,- affected: {- node: roadWheel.name || "track-road-wheel",- nodePath: nodePath3(root, roadWheel)- },- measurement: {- name: "roadWheelTrackContainmentOverflow",- actual: overflow,- expected: 0,- threshold: TRACK_CONTAINMENT_TOLERANCE,- unit: "m"- },- viewHints: ["vehicle.underbody", "generic.right.semantic-overlay"]- }));+});++// src/qa/geometry-relations.ts+function createProbeLocalFrame3(input) {+ if (!input.id.trim())+ throw new TypeError("Probe frame ID must be non-empty.");+ if (!finiteVector(input.origin))+ throw new TypeError("Probe frame origin must be finite.");+ const basis = [input.xAxis, input.yAxis, input.zAxis];+ for (const [index, value] of basis.entries()) {+ if (!finiteVector(value) || Math.abs(length2(value) - 1) > 0.000001) {+ throw new TypeError(`Probe frame axis ${index} must be finite and normalized within 1e-6.`);}}- return findings;-}-function inspectMobilityAdvisory(context) {- if (!(context.scene instanceof THREE13.Object3D)) {- return [];+ if (Math.abs(dot2(input.xAxis, input.yAxis)) > 0.000001 || Math.abs(dot2(input.xAxis, input.zAxis)) > 0.000001 || Math.abs(dot2(input.yAxis, input.zAxis)) > 0.000001 || dot2(cross(input.xAxis, input.yAxis), input.zAxis) < 1 - 0.000001) {+ throw new TypeError("Probe frame axes must be orthonormal and right-handed.");}- const intent = context.mobility;- if (!intent)- return [];- const root = context.scene;- root.updateMatrixWorld(true);- const wheels = resolveVehicleWheelAssemblies(root);- return [- ...bilateralSymmetryFindings(context, root, wheels),- ...penetrationFindings(context, root, wheels),- ...orientationFindings(context, root, intent),- ...trackProfileFindings(context, root, intent)- ].sort((a, b) => `${a.code}:${a.affected?.nodePath ?? a.affected?.node ?? ""}`.localeCompare(`${b.code}:${b.affected?.nodePath ?? b.affected?.node ?? ""}`));+ return {+ id: input.id,+ origin: stableVector(input.origin),+ xAxis: stableVector(input.xAxis),+ yAxis: stableVector(input.yAxis),+ zAxis: stableVector(input.zAxis)+ };}-function evaluateVehicleAdvisoryQa(context) {- if (context.intent.category !== "vehicle")- return [];- return inspectMobilityAdvisory({- scene: context.scene,- profile: context.intent.qaProfile,- mobility: context.intent.vehicle+function probeLocalFrameFromQuaternion(id, origin, quaternion) {+ if (!quaternion.every((component) => Number.isFinite(component))) {+ throw new TypeError("Probe frame quaternion must be finite.");+ }+ const quaternionLength = Math.hypot(...quaternion);+ if (Math.abs(quaternionLength - 1) > 0.000001) {+ throw new TypeError("Probe frame quaternion must be normalized within 1e-6.");+ }+ const [x, y, z, w] = quaternion;+ const xx = x * x;+ const yy = y * y;+ const zz = z * z;+ const xy = x * y;+ const xz = x * z;+ const yz = y * z;+ const wx = w * x;+ const wy = w * y;+ const wz = w * z;+ return createProbeLocalFrame3({+ id,+ origin,+ xAxis: [1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy)],+ yAxis: [2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx)],+ zAxis: [2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy)]});}-var SYMMETRY_RATIO = 0.08, PENETRATION_RATIO = 0.25, ORIENTATION_RATIO = 1.15, TRACK_CONTAINMENT_TOLERANCE = 0.02, VEHICLE_VIEWS, VEHICLE_W6_ADVISORY_QA_RULE;-var init_vehicle_advisory = __esm(() => {- init_contracts();- init_vehicle();- init_registry();- VEHICLE_VIEWS = [- "vehicle.underbody",- "vehicle.wheel-section.right",- "generic.top.semantic-overlay"- ];- VEHICLE_W6_ADVISORY_QA_RULE = Object.freeze({- id: "VEHICLE_W6_ADVISORY_PROFILE",- profile: "vehicle.w6-advisory",- scope: { kind: "category", category: "vehicle" },- ruleClass: "heuristic",- owner: KILN_ENGINE_QA_OWNER,- defaultMode: "observe",- evaluate: evaluateVehicleAdvisoryQa- });-});--// src/qa/vehicle.ts-import * as THREE14 from "three";-function finding3(context, value) {+function createOrientedProbeBox3(input) {+ if (!input.id.trim())+ throw new TypeError("Oriented probe box ID must be non-empty.");+ if (!finiteVector(input.halfExtents) || input.halfExtents.some((extent) => extent <= 0)) {+ throw new TypeError("Oriented probe box half-extents must be finite and greater than zero.");+ }return {- ...value,- profile: context.profile ?? "asset.requirements.v1",- dimension: "categoryReadiness",- viewHints: value.viewHints ?? ["vehicle.underbody", "vehicle.wheel-section"]+ id: input.id,+ frame: createProbeLocalFrame3(input.frame),+ halfExtents: stableVector(input.halfExtents)};}-function localPoint2(rootInverse, value) {- return value.clone().applyMatrix4(rootInverse);-}-function rootAxis(root, axis) {- root.updateWorldMatrix(true, false);- return axis.clone().transformDirection(root.matrixWorld);+function worldPointToProbeLocal(frame, worldPoint) {+ const offset = subtract2(worldPoint, frame.origin);+ return stableVector([+ dot2(offset, frame.xAxis),+ dot2(offset, frame.yAxis),+ dot2(offset, frame.zAxis)+ ]);}-function angleDegrees(a, b) {- return THREE14.MathUtils.radToDeg(Math.acos(THREE14.MathUtils.clamp(a.clone().normalize().dot(b.clone().normalize()), -1, 1)));+function worldVectorToProbeLocal(frame, worldVector) {+ return stableVector([+ dot2(worldVector, frame.xAxis),+ dot2(worldVector, frame.yAxis),+ dot2(worldVector, frame.zAxis)+ ]);}-function isDescendant(node, ancestor) {- let current = node;- while (current) {- if (current === ancestor)- return true;- current = current.parent ?? undefined;- }- return false;+function projection(box, axisWorld) {+ const center = dot2(box.frame.origin, axisWorld);+ const radius = axes(box.frame).reduce((total, boxAxis, index) => total + Math.abs(dot2(boxAxis, axisWorld)) * box.halfExtents[index], 0);+ return { min: center - radius, max: center + radius };}-function componentDisposition(wheel) {- return wheel.source === "semantic" ? "block" : "warn";+function orientFromReferenceToSubject(axisWorld, subject, reference) {+ return dot2(subtract2(subject.frame.origin, reference.frame.origin), axisWorld) < 0 ? scale(axisWorld, -1) : axisWorld;}-function wheelCountFindings(context, intent, wheels) {- const findings = [];- if (intent.wheelCount !== undefined && wheels.length !== intent.wheelCount) {- findings.push(finding3(context, {- code: "VEH_WHEEL_COUNT",- disposition: "block",- message: `Trusted vehicle intent requires ${intent.wheelCount} wheel assemblies; resolved ${wheels.length}.`,- measurement: {- name: "wheelAssemblyCount",- actual: wheels.length,- expected: intent.wheelCount,- threshold: intent.wheelCount- },- repairText: "Create exactly the requested number of axle-centered wheel assemblies and remove duplicate or ungrouped wheel parts."- }));+function candidateSatAxes(subject, reference) {+ const subjectAxes = axes(subject.frame);+ const referenceAxes = axes(reference.frame);+ const candidates = [];+ const pushUnique = (rawAxis, label) => {+ if (length2(rawAxis) <= EPSILON)+ return;+ const axis = normalize2(rawAxis);+ if (candidates.some((candidate) => Math.abs(dot2(candidate.axis, axis)) > 1 - 0.000000001))+ return;+ candidates.push({ axis, label });+ };+ for (let index = 0;index < 3; index++) {+ pushUnique(referenceAxes[index], `reference.${["x", "y", "z"][index]}`);}- const axleIds = new Set(wheels.map((wheel) => wheel.index).filter(Boolean));- if (intent.axleCount !== undefined && axleIds.size !== intent.axleCount) {- findings.push(finding3(context, {- code: "VEH_AXLE_COUNT",- disposition: "block",- message: `Trusted vehicle intent requires ${intent.axleCount} axles; wheel grouping resolved ${axleIds.size}.`,- measurement: {- name: "wheelAxleCount",- actual: axleIds.size,- expected: intent.axleCount,- threshold: intent.axleCount- }- }));+ for (let index = 0;index < 3; index++) {+ pushUnique(subjectAxes[index], `subject.${["x", "y", "z"][index]}`);}- return findings;-}-function wheelGeometryFindings(context, root, wheels) {- const findings = [];- const expectedAxle = rootAxis(root, new THREE14.Vector3(0, 0, 1));- for (const wheel of wheels) {- const disposition = componentDisposition(wheel);- const centerTolerance = Math.max(CENTER_MINIMUM, (wheel.radius ?? 0) * CENTER_RATIO);- const pivotInverse = wheel.pivot.matrixWorld.clone().invert();- const componentCenters = [wheel.tireCenterWorld, wheel.rimCenterWorld, wheel.hubCenterWorld].filter((center) => !!center).map((center) => localPoint2(pivotInverse, center));- let centerDelta = 0;- for (let a = 0;a < componentCenters.length; a++) {- for (let b = a + 1;b < componentCenters.length; b++) {- centerDelta = Math.max(centerDelta, componentCenters[a].distanceTo(componentCenters[b]));- }- }- if (!wheel.tire || !wheel.rim || !wheel.hub || centerDelta > centerTolerance) {- findings.push(finding3(context, {- code: "VEH_WHEEL_CONCENTRICITY",- disposition,- message: `Wheel ${wheel.id} tire, rim, and hub must share one axle center.`,- affected: { node: wheel.root.name },- measurement: {- name: "maximumComponentCenterDelta",- actual: Number.isFinite(centerDelta) ? centerDelta : null,- expected: 0,- threshold: centerTolerance,- unit: "m"- },- repairText: `Move the tire, rim, and hub of ${wheel.id} to its axle-centered wheel pivot.`- }));+ for (let subjectIndex = 0;subjectIndex < 3; subjectIndex++) {+ for (let referenceIndex = 0;referenceIndex < 3; referenceIndex++) {+ pushUnique(cross(subjectAxes[subjectIndex], referenceAxes[referenceIndex]), `cross.subject.${["x", "y", "z"][subjectIndex]}.reference.${["x", "y", "z"][referenceIndex]}`);}- const nested = wheel.radius !== undefined && wheel.rimRadius !== undefined && wheel.hubRadius !== undefined && wheel.hubRadius < wheel.rimRadius && wheel.rimRadius < wheel.radius && wheel.rimWidth !== undefined && wheel.hubWidth !== undefined && wheel.width !== undefined && wheel.rimWidth <= wheel.width + 0.000001 && wheel.hubWidth <= wheel.width + 0.000001;- if (!nested) {- findings.push(finding3(context, {- code: "VEH_WHEEL_RADIUS",- disposition,- message: `Wheel ${wheel.id} must satisfy hub radius < rim radius < tire radius and keep rim/hub widths inside the tire envelope.`,- affected: { node: wheel.root.name },- measurement: {- name: "nestedRadii",- actual: false,- expected: true- },- repairText: `Resize ${wheel.id} so its hub is nested inside its rim and its rim is nested inside its tire.`- }));+ }+ return candidates;+}+function sat(subject, reference) {+ let maximumSeparation = -Infinity;+ let separatingAxis = reference.frame.xAxis;+ let separatingLabel = "reference.x";+ let minimumOverlap = Infinity;+ let overlapAxis = reference.frame.xAxis;+ let overlapLabel = "reference.x";+ for (const candidate of candidateSatAxes(subject, reference)) {+ const subjectProjection = projection(subject, candidate.axis);+ const referenceProjection = projection(reference, candidate.axis);+ const gap = Math.max(subjectProjection.min - referenceProjection.max, referenceProjection.min - subjectProjection.max);+ if (gap > maximumSeparation) {+ maximumSeparation = gap;+ separatingAxis = candidate.axis;+ separatingLabel = candidate.label;}- const axleAngle = angleDegrees(wheel.spinAxisWorld, expectedAxle);- if (axleAngle > AXIS_TOLERANCE_DEGREES) {- findings.push(finding3(context, {- code: "VEH_WHEEL_AXLE_AXIS",- disposition,- message: `Wheel ${wheel.id} spin axis must align with vehicle-local +Z.`,- affected: { node: wheel.pivot.name },- measurement: {- name: "axleAxisAngle",- actual: axleAngle,- expected: 0,- threshold: AXIS_TOLERANCE_DEGREES,- unit: "degrees"- },- repairText: `Orient ${wheel.pivot.name} so its local +Z is the axle/spin axis.`- }));+ const overlap = Math.min(subjectProjection.max, referenceProjection.max) - Math.max(subjectProjection.min, referenceProjection.min);+ if (overlap < minimumOverlap) {+ minimumOverlap = overlap;+ overlapAxis = candidate.axis;+ overlapLabel = candidate.label;}- const pivotDelta = localPoint2(pivotInverse, wheel.pivotCenterWorld).distanceTo(localPoint2(pivotInverse, wheel.centerWorld));- const descendants = [wheel.tire, wheel.rim, wheel.hub].every((part) => isDescendant(part, wheel.pivot));- if (!descendants || pivotDelta > centerTolerance) {- findings.push(finding3(context, {- code: "VEH_WHEEL_PIVOT",- disposition,- message: `Wheel ${wheel.id} pivot must be at the axle center and own every moving component.`,- affected: { node: wheel.pivot.name },- measurement: {- name: "pivotCenterDelta",- actual: pivotDelta,- expected: 0,- threshold: centerTolerance,- unit: "m"- },- repairText: `Place ${wheel.pivot.name} at the axle center and parent tire, rim, and hub beneath it.`- }));+ }+ if (maximumSeparation > 0) {+ return {+ separation: stable6(maximumSeparation),+ penetration: 0,+ axisWorld: orientFromReferenceToSubject(separatingAxis, subject, reference),+ axisLabel: separatingLabel+ };+ }+ return {+ separation: 0,+ penetration: stable6(Math.max(0, minimumOverlap)),+ axisWorld: orientFromReferenceToSubject(overlapAxis, subject, reference),+ axisLabel: overlapLabel+ };+}+function supportPoint(box, direction) {+ let point = [...box.frame.origin];+ axes(box.frame).forEach((boxAxis, index) => {+ const projectionValue = dot2(boxAxis, direction);+ if (Math.abs(projectionValue) <= EPSILON)+ return;+ point = add(point, scale(boxAxis, Math.sign(projectionValue) * box.halfExtents[index]));+ });+ return stableVector(point);+}+function evidence(subject, reference, points, axisWorld, axisLabel) {+ return {+ subjectId: subject.id,+ referenceId: reference.id,+ coordinateSpace: "reference-local",+ referenceFrameId: reference.frame.id,+ ...axisWorld ? { axis: worldVectorToProbeLocal(reference.frame, axisWorld) } : {},+ ...axisLabel ? { axisLabel } : {},+ points+ };+}+function satEvidencePoints(subject, reference, axisWorld) {+ return [+ {+ label: `${reference.id}.support`,+ position: worldPointToProbeLocal(reference.frame, supportPoint(reference, axisWorld))+ },+ {+ label: `${subject.id}.support`,+ position: worldPointToProbeLocal(reference.frame, supportPoint(subject, scale(axisWorld, -1)))}+ ];+}+function probeOrientedPenetration(subject, reference, options = {}) {+ const maxDepth = options.maxDepth ?? 0;+ const tolerance = options.tolerance ?? DEFAULT_TOLERANCE;+ assertNonNegative(maxDepth, "maxDepth");+ assertNonNegative(tolerance, "tolerance");+ const relation = sat(subject, reference);+ return {+ relation: "penetration",+ pass: relation.penetration <= maxDepth + tolerance,+ measurements: {+ penetrationDepth: relation.penetration,+ separation: relation.separation,+ maxDepth,+ tolerance+ },+ evidence: evidence(subject, reference, satEvidencePoints(subject, reference, relation.axisWorld), relation.axisWorld, relation.axisLabel)+ };+}+var EPSILON = 0.0000000001, DEFAULT_TOLERANCE = 0.000001, finiteVector = (value) => value.length === 3 && value.every((component) => Number.isFinite(component)), add = (a, b) => [+ a[0] + b[0],+ a[1] + b[1],+ a[2] + b[2]+], subtract2 = (a, b) => [+ a[0] - b[0],+ a[1] - b[1],+ a[2] - b[2]+], scale = (value, amount) => [+ value[0] * amount,+ value[1] * amount,+ value[2] * amount+], dot2 = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2], cross = (a, b) => [+ a[1] * b[2] - a[2] * b[1],+ a[2] * b[0] - a[0] * b[2],+ a[0] * b[1] - a[1] * b[0]+], length2 = (value) => Math.hypot(value[0], value[1], value[2]), normalize2 = (value) => {+ const magnitude = length2(value);+ if (magnitude <= EPSILON)+ throw new TypeError("Cannot normalize a zero-length probe axis.");+ return scale(value, 1 / magnitude);+}, stable6 = (value) => {+ if (Math.abs(value) < 0.0000000001)+ return 0;+ return Number(value.toFixed(9));+}, stableVector = (value) => [+ stable6(value[0]),+ stable6(value[1]),+ stable6(value[2])+], assertNonNegative = (value, name) => {+ if (!Number.isFinite(value) || value < 0) {+ throw new TypeError(`${name} must be a finite non-negative number.`);}- return findings;+}, axes = (frame) => [+ frame.xAxis,+ frame.yAxis,+ frame.zAxis+];++// src/qa/vehicle-advisory.ts+import * as THREE15 from "three";+function advisory(context, value) {+ return {+ ...value,+ disposition: "warn",+ dimension: "categoryReadiness",+ profile: context.profile ?? "asset.requirements.v1",+ viewHints: value.viewHints ?? [...VEHICLE_VIEWS]+ };}-function axlePairFindings(context, root, wheels) {- root.updateWorldMatrix(true, false);- const inverse = root.matrixWorld.clone().invert();+function localPoint(inverse, point) {+ return point.clone().applyMatrix4(inverse);+}+function wheelPairs(wheels) {const groups = new Map;for (const wheel of wheels) {if (!wheel.index)@@ -9115,1851 +9339,2362 @@ function axlePairFindings(context, root, wheels) {group.push(wheel);groups.set(wheel.index, group);}+ return [...groups.entries()].flatMap(([index, group]) => {+ const left = group.find((wheel) => wheel.side === "left");+ const right = group.find((wheel) => wheel.side === "right");+ return left && right ? [[index, left, right]] : [];+ });+}+function bilateralSymmetryFindings(context, root, wheels) {+ root.updateMatrixWorld(true);+ const inverse = root.matrixWorld.clone().invert();const findings = [];- for (const [index, pair] of groups) {- const left = pair.find((wheel) => wheel.side === "left");- const right = pair.find((wheel) => wheel.side === "right");- if (!left || !right)- continue;- const leftCenter = localPoint2(inverse, left.centerWorld);- const rightCenter = localPoint2(inverse, right.centerWorld);- const delta = Math.hypot(leftCenter.x - rightCenter.x, leftCenter.y - rightCenter.y);- if (delta > PAIR_TOLERANCE) {- findings.push(finding3(context, {- code: "VEH_AXLE_PAIR",- disposition: left.source === "semantic" && right.source === "semantic" ? "block" : "warn",- message: `Axle ${index} left/right wheel centers disagree in vehicle-local X/Y.`,- affected: { node: right.root.name },- measurement: {- name: "pairedCenterXYDelta",- actual: delta,- expected: 0,- threshold: PAIR_TOLERANCE,- unit: "m"- },- repairText: `Align both wheels on axle ${index} to the same local X and Y coordinates.`- }));- }+ for (const [index, left, right] of wheelPairs(wheels)) {+ const a = localPoint(inverse, left.centerWorld);+ const b = localPoint(inverse, right.centerWorld);+ const centerDelta = Math.hypot(a.x - b.x, a.y - b.y, a.z + b.z);+ const radiusDelta = Math.abs((left.radius ?? 0) - (right.radius ?? 0));+ const widthDelta = Math.abs((left.width ?? 0) - (right.width ?? 0));+ const scale = Math.max(left.radius ?? 0, right.radius ?? 0, 0.25);+ const threshold = Math.max(0.01, scale * SYMMETRY_RATIO);+ const maximum = Math.max(centerDelta, radiusDelta, widthDelta);+ if (maximum <= threshold)+ continue;+ const measurementName = maximum === centerDelta ? "bilateralCenterMirrorDelta" : maximum === radiusDelta ? "bilateralRadiusDelta" : "bilateralWidthDelta";+ findings.push(advisory(context, {+ code: "VEH_BILATERAL_SYMMETRY",+ message: `Axle ${index} left/right assemblies differ in center, radius, or width ` + `(center=${centerDelta.toFixed(6)}, radius=${radiusDelta.toFixed(6)}, width=${widthDelta.toFixed(6)} m).`,+ affected: { node: right.root.name },+ measurement: {+ name: measurementName,+ actual: maximum,+ expected: 0,+ threshold,+ unit: "m"+ }+ }));}return findings;}-function duplicateAssemblyFindings(context, root, wheels) {- root.updateMatrixWorld(true);- const inverse = root.matrixWorld.clone().invert();+function semanticRoles(node) {+ return readSemanticMetadataV1(node)?.roles ?? [];+}+function trackSide(node) {+ for (const role of semanticRoles(node)) {+ const match = role.match(/(?:track\.loop|support\.track|track\.road-wheel)\.(left|right)(?:\.|$)/);+ if (match?.[1] === "left" || match?.[1] === "right")+ return match[1];+ }+ return;+}+function isFender(node) {+ return semanticRoles(node).some((role) => /(?:^|\.)(?:fender|wheel-arch)(?:\.|$)/i.test(role)) || /fender|wheel[ _.-]?arch/i.test(node.name);+}+function isChassisMesh(node) {+ if (!(node instanceof THREE15.Mesh) || isFender(node))+ return false;+ return semanticRoles(node).some((role) => /^(?:vehicle\.)?(?:chassis|body|hull)(?:\.|$)/i.test(role)) || /chassis|vehicle[ _.-]?body|fuselage|hull/i.test(node.name);+}+function objectBoundsInFrame2(object, frame) {+ object.updateWorldMatrix(true, true);+ frame.updateWorldMatrix(true, false);+ const worldToFrame = frame.matrixWorld.clone().invert();+ const bounds = new THREE15.Box3;+ let found = false;+ object.traverseVisible((part) => {+ if (!(part instanceof THREE15.Mesh) || !(part.geometry instanceof THREE15.BufferGeometry))+ return;+ part.geometry.computeBoundingBox();+ const box = part.geometry.boundingBox;+ if (!box)+ return;+ const matrix = worldToFrame.clone().multiply(part.matrixWorld);+ for (const x of [box.min.x, box.max.x])+ for (const y of [box.min.y, box.max.y])+ for (const z of [box.min.z, box.max.z]) {+ bounds.expandByPoint(new THREE15.Vector3(x, y, z).applyMatrix4(matrix));+ found = true;+ }+ });+ return found ? bounds : undefined;+}+function tuple2(value) {+ return [value.x, value.y, value.z];+}+function probeBox(id, root, bounds) {+ root.updateWorldMatrix(true, false);+ const center = bounds.getCenter(new THREE15.Vector3).applyMatrix4(root.matrixWorld);+ const size = bounds.getSize(new THREE15.Vector3);+ const position = new THREE15.Vector3;+ const quaternion = new THREE15.Quaternion;+ const scale = new THREE15.Vector3;+ root.matrixWorld.decompose(position, quaternion, scale);+ const xAxis = new THREE15.Vector3(1, 0, 0).applyQuaternion(quaternion).normalize();+ const yAxis = new THREE15.Vector3(0, 1, 0).applyQuaternion(quaternion).normalize();+ const zAxis = new THREE15.Vector3(0, 0, 1).applyQuaternion(quaternion).normalize();+ return createOrientedProbeBox3({+ id,+ frame: createProbeLocalFrame3({+ id: `${id}.frame`,+ origin: tuple2(center),+ xAxis: tuple2(xAxis),+ yAxis: tuple2(yAxis),+ zAxis: tuple2(zAxis)+ }),+ halfExtents: [+ size.x * Math.abs(scale.x) / 2,+ size.y * Math.abs(scale.y) / 2,+ size.z * Math.abs(scale.z) / 2+ ]+ });+}+function chassisMeshes(root) {+ const meshes = [];+ root.traverseVisible((node) => {+ if (isChassisMesh(node))+ meshes.push(node);+ });+ return meshes;+}+function penetrationFindings(context, root, wheels) {+ const chassis = chassisMeshes(root);const findings = [];- for (let a = 0;a < wheels.length; a++) {- for (let b = a + 1;b < wheels.length; b++) {- const left = wheels[a];- const right = wheels[b];- const sameDeclaredCorner = left.side !== undefined && left.side === right.side && left.index !== undefined && left.index === right.index;- const centerDelta = localPoint2(inverse, left.centerWorld).distanceTo(localPoint2(inverse, right.centerWorld));- const scale = Math.max(left.radius ?? 0, right.radius ?? 0, 0.25);- const threshold = Math.max(CENTER_MINIMUM, scale * CENTER_RATIO);- if (!sameDeclaredCorner && centerDelta > threshold)+ for (const wheel of wheels) {+ if (!wheel.tire || wheel.radius === undefined)+ continue;+ const tireBounds = objectBoundsInFrame2(wheel.tire, root);+ if (!tireBounds)+ continue;+ const threshold = Math.max(0.02, wheel.radius * PENETRATION_RATIO);+ for (const body of chassis) {+ const bodyBounds = objectBoundsInFrame2(body, root);+ if (!bodyBounds)continue;- const semantic = left.source === "semantic" && right.source === "semantic";- findings.push(finding3(context, {- code: "VEH_DUPLICATE_ASSEMBLY",- disposition: semantic ? "block" : "warn",- message: `Wheel assemblies ${left.id} and ${right.id} resolve to the same ` + `${sameDeclaredCorner ? `${left.side}-${left.index} corner` : "scale-relative center"}.`,- affected: { node: right.root.name },+ const result = probeOrientedPenetration(probeBox(`${wheel.id}.tire`, root, tireBounds), probeBox(body.name || "vehicle.chassis", root, bodyBounds), { maxDepth: threshold });+ if (result.pass)+ continue;+ findings.push(advisory(context, {+ code: "VEH_WHEEL_CHASSIS_PENETRATION",+ message: `Wheel ${wheel.id} penetrates chassis ${body.name || "(unnamed)"} by ` + `${result.measurements.penetrationDepth?.toFixed(6)} m beyond the allowed non-fender overlap.`,+ affected: { node: wheel.tire.name || wheel.root.name },measurement: {- name: "duplicateAssemblyCenterDelta",- actual: centerDelta,- expected: `>${threshold}`,+ name: "tireChassisPenetrationDepth",+ actual: result.measurements.penetrationDepth ?? 0,+ expected: 0,threshold,unit: "m"},- viewHints: [- "vehicle.underbody",- "vehicle.wheel-section.right",- "generic.top.semantic-overlay"- ],- repairText: `Remove only duplicate assembly ${right.id} at the reported center; preserve ${left.id} and rebuild the actually missing corner from trusted wheel/axle intent.`+ viewHints: ["vehicle.underbody", "vehicle.wheel-section.right"]}));}}return findings;}-function contactFindings(context, root, intent, wheels) {- if (intent.supportPolicy !== "grounded")+function wholeAssetBounds(root) {+ return objectBoundsInFrame2(root, root);+}+function orientationFindings(context, root, intent) {+ if (intent.subtype === "fixed-wing" || intent.subtype === "rotorcraft" || intent.subtype === "walking" || intent.subtype === "custom") {return [];- root.updateWorldMatrix(true, false);- const inverse = root.matrixWorld.clone().invert();- const findings = [];- for (const wheel of wheels.filter((value) => value.loadBearing)) {- const center = localPoint2(inverse, wheel.centerWorld);- const contactY = center.y - (wheel.radius ?? 0);- if (wheel.radius === undefined || Math.abs(contactY - (context.groundPlaneY ?? 0)) > CONTACT_TOLERANCE) {- findings.push(finding3(context, {- code: "VEH_CONTACT_PLANE",- disposition: componentDisposition(wheel),- message: `Load-bearing wheel ${wheel.id} must touch the requested ground plane Y=${context.groundPlaneY ?? 0} without floating or burial.`,- affected: { node: wheel.tire?.name ?? wheel.root.name },- measurement: {- name: "tireContactY",- actual: wheel.radius === undefined ? null : contactY,- expected: context.groundPlaneY ?? 0,- threshold: CONTACT_TOLERANCE,- unit: "m"- },- repairText: `Set ${wheel.id} axle-center Y to its tire radius plus ${context.groundPlaneY ?? 0} so its contact point meets the requested plane.`- }));- }}- return findings;+ const bounds = wholeAssetBounds(root);+ if (!bounds)+ return [];+ const size = bounds.getSize(new THREE15.Vector3);+ const ratio = size.z / Math.max(size.x, 0.000000001);+ if (ratio <= ORIENTATION_RATIO)+ return [];+ return [+ advisory(context, {+ code: "VEH_ORIENTATION_SIDEWAYS",+ message: `${intent.subtype ?? "Mobility assembly"} bounds are Z-dominant despite canonical +X travel ` + `(spanX=${size.x.toFixed(6)}, spanZ=${size.z.toFixed(6)} m).`,+ affected: { node: root.name || "vehicle-root" },+ measurement: {+ name: "boundsSpanZToSpanX",+ actual: ratio,+ expected: `<=${ORIENTATION_RATIO}`,+ threshold: ORIENTATION_RATIO+ },+ viewHints: ["generic.top.semantic-overlay", "vehicle.underbody"]+ })+ ];}-function renderableMinYInRoot(rootInverse, node) {- let minimum = Infinity;- node.traverseVisible((part) => {- if (!(part instanceof THREE14.Mesh) || !(part.geometry instanceof THREE14.BufferGeometry))+function nodePath3(root, target) {+ let found = "";+ const visit = (node, parent, index) => {+ if (found)return;- part.geometry.computeBoundingBox();- const bounds = part.geometry.boundingBox;- if (!bounds)+ const segment = `${node.name.trim() || node.type || "Object3D"}[${index}]`;+ const path = parent ? `${parent}/${segment}` : segment;+ if (node === target) {+ found = path;return;- const matrix = rootInverse.clone().multiply(part.matrixWorld);- for (const x of [bounds.min.x, bounds.max.x]) {- for (const y of [bounds.min.y, bounds.max.y]) {- for (const z of [bounds.min.z, bounds.max.z]) {- minimum = Math.min(minimum, new THREE14.Vector3(x, y, z).applyMatrix4(matrix).y);- }+ }+ node.children.forEach((child, childIndex) => {+ visit(child, path, childIndex);+ });+ };+ visit(root, "", 0);+ return found;+}+function weldedBoundaryEdges(root, loop) {+ root.updateMatrixWorld(true);+ const inverse = loop.matrixWorld.clone().invert();+ const edges = new Map;+ let triangleCount = 0;+ const vertexKey = (point) => [point.x, point.y, point.z].map((value) => Math.round(value * 1e6)).join(",");+ loop.traverseVisible((node) => {+ if (!(node instanceof THREE15.Mesh) || !(node.geometry instanceof THREE15.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 THREE15.Vector3().fromBufferAttribute(positions, index).applyMatrix4(matrix)));+ const index = node.geometry.getIndex();+ const indices = index ? Array.from(index.array, Number) : Array.from({ length: positions.count }, (_, value) => value);+ for (let offset = 0;offset + 2 < indices.length; offset += 3) {+ triangleCount++;+ const triangle = [indices[offset], indices[offset + 1], indices[offset + 2]];+ for (let edge = 0;edge < 3; edge++) {+ const a = keys[triangle[edge]];+ const b = keys[triangle[(edge + 1) % 3]];+ const id = a < b ? `${a}|${b}` : `${b}|${a}`;+ edges.set(id, (edges.get(id) ?? 0) + 1);}}});- return Number.isFinite(minimum) ? minimum : undefined;-}-function supportContactFindings(context, root, intent) {- root.updateWorldMatrix(true, true);- const inverse = root.matrixWorld.clone().invert();- const explicitContacts = [];- const supports = [];+ if (triangleCount === 0)+ return;+ return [...edges.values()].filter((count) => count === 1).length;+}+function trackProfileFindings(context, root, intent) {+ if (intent.subtype !== "tracked")+ return [];+ const loops = [];+ const roadWheels = [];root.traverseVisible((node) => {- const roles = readSemanticMetadataV1(node)?.roles ?? [];- const isWheelContact = roles.some((role) => role.startsWith("wheel.contact."));- if (!isWheelContact && roles.some((role) => role.startsWith("contact."))) {- explicitContacts.push({- node,- contactY: localPoint2(inverse, new THREE14.Vector3().setFromMatrixPosition(node.matrixWorld)).y,- source: "contact"- });+ const roles = semanticRoles(node);+ if (roles.some((role) => role.startsWith("track.loop.")) || roles.some((role) => role.startsWith("support.track."))) {+ loops.push(node);}- if (roles.some((role) => role.startsWith("support."))) {- const contactY = renderableMinYInRoot(inverse, node);- if (contactY !== undefined)- supports.push({ node, contactY, source: "support" });+ if (roles.some((role) => role.startsWith("track.road-wheel.")) || /road[ _.-]?wheel/i.test(node.name)) {+ roadWheels.push(node);}});- const measurements = explicitContacts.length > 0 ? explicitContacts : supports;- const findings = measurements.flatMap((measurement) => {- if (intent.supportPolicy !== "grounded" || Math.abs(measurement.contactY - (context.groundPlaneY ?? 0)) <= CONTACT_TOLERANCE)- return [];+ if (loops.length === 0) {return [- finding3(context, {- code: "VEH_CONTACT_PLANE",- disposition: "block",- message: `Load-bearing ${measurement.source} ${measurement.node.name || "(unnamed)"} must touch the requested ground plane Y=${context.groundPlaneY ?? 0} without floating or burial.`,- affected: { node: measurement.node.name || "vehicle-support" },- measurement: {- name: "supportContactY",- actual: measurement.contactY,- expected: context.groundPlaneY ?? 0,- threshold: CONTACT_TOLERANCE,- unit: "m"- },- repairText: `Move ${measurement.node.name || "the support"} so its declared contact rests at asset-local Y=${context.groundPlaneY ?? 0}.`+ advisory(context, {+ code: "VEH_TRACK_LOOP_MISSING",+ message: "Tracked vehicle exposes no semantic track.loop.* assembly to inspect.",+ affected: { node: root.name || "vehicle-root" },+ measurement: { name: "trackLoopCount", actual: 0, expected: ">=1", threshold: 1 },+ viewHints: ["vehicle.underbody", "generic.right.semantic-overlay"]})];- });- for (const expected of intent.supportAssemblies ?? []) {- if (expected === "wheel" && resolveVehicleWheelAssemblies(root).length > 0)- continue;- const matches = [...explicitContacts, ...supports].filter((measurement) => (readSemanticMetadataV1(measurement.node)?.roles ?? []).some((role) => role === `support.${expected}` || role.startsWith(`support.${expected}.`) || role === `contact.${expected}` || role.startsWith(`contact.${expected}.`)));- if (matches.length > 0)- continue;- findings.push(finding3(context, {- code: "VEH_SUPPORT_SET_MISSING",- disposition: "block",- message: `Requested mobility requires semantic ${expected} supports or contacts.`,- affected: { node: root.name || "vehicle-root" },- measurement: {- name: `${expected}SupportCount`,- actual: 0,- expected: ">=1",- threshold: 1- },- viewHints: ["vehicle.underbody", "generic.front.depth-contact"],- repairText: `Add the requested semantic ${expected} support set.${intent.supportPolicy === "grounded" ? ` Place its contacts at asset-local Y=${context.groundPlaneY ?? 0}.` : ""}`- }));}- if (intent.supportPolicy === "grounded" && measurements.length > 1) {- const values = measurements.map((measurement) => measurement.contactY);- const range = Math.max(...values) - Math.min(...values);- if (range > CONTACT_TOLERANCE) {- findings.push(finding3(context, {- code: "VEH_SUPPORT_PLANE",- disposition: "block",- message: `Declared non-wheel supports do not share one stable vehicle-local contact plane.`,- affected: { node: root.name || "vehicle-root" },+ const findings = [];+ for (const loop of loops) {+ const loopSide = trackSide(loop);+ const declaredClosed = loop.userData["kilnTrackLoopClosed"];+ const boundaryEdges = weldedBoundaryEdges(root, loop);+ if (declaredClosed === false || boundaryEdges !== undefined && boundaryEdges > 0) {+ findings.push(advisory(context, {+ code: "VEH_TRACK_LOOP_OPEN",+ message: `Track loop ${loop.name || "(unnamed)"} is open ` + `(boundary edges ${boundaryEdges ?? "declared"}).`,+ affected: { node: loop.name || "track-loop", nodePath: nodePath3(root, loop) },measurement: {- name: "supportContactPlaneRange",- actual: range,+ name: "trackLoopBoundaryEdgeCount",+ actual: boundaryEdges ?? 1,expected: 0,- threshold: CONTACT_TOLERANCE,- unit: "m"+ threshold: 0},- viewHints: ["vehicle.underbody", "generic.front.depth-contact"],- repairText: `Move only the reported supports onto the requested asset-local Y=${context.groundPlaneY ?? 0} plane while preserving their stance.`+ viewHints: ["vehicle.underbody", "generic.right.wireframe"]}));}- }- return findings;-}-function steeringFindings(context, root, intent, wheels) {- if (intent.steering === undefined || intent.steering === "none" || wheels.length === 0)- return [];- root.updateWorldMatrix(true, false);- const inverse = root.matrixWorld.clone().invert();- const expectedAxis = rootAxis(root, new THREE14.Vector3(0, 1, 0));- const localCenters = wheels.map((wheel) => ({- wheel,- center: localPoint2(inverse, wheel.centerWorld)- }));- const extreme = intent.steering === "rear" ? Math.min(...localCenters.map((entry) => entry.center.x)) : Math.max(...localCenters.map((entry) => entry.center.x));- const targets = intent.steering === "all" ? localCenters : localCenters.filter((entry) => Math.abs(entry.center.x - extreme) <= PAIR_TOLERANCE);- const findings = [];- for (const { wheel } of targets) {- const steering = wheel.steeringPivot;- const centerDelta = steering ? localPoint2(inverse, new THREE14.Vector3().setFromMatrixPosition(steering.matrixWorld)).distanceTo(localPoint2(inverse, wheel.centerWorld)) : Infinity;- const axisAngle = steering ? angleDegrees(new THREE14.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, {- code: "VEH_STEERING_PIVOT",- disposition: componentDisposition(wheel),- message: `Declared steering wheel ${wheel.id} requires a centered +Y steering pivot owning its spin pivot.`,- affected: { node: steering?.name ?? wheel.pivot.name },+ const loopBounds = objectBoundsInFrame2(loop, root);+ if (!loopBounds)+ continue;+ const expanded = loopBounds.clone().expandByScalar(TRACK_CONTAINMENT_TOLERANCE);+ for (const roadWheel of roadWheels.filter((candidate) => !loopSide || !trackSide(candidate) || trackSide(candidate) === loopSide)) {+ const wheelBounds = objectBoundsInFrame2(roadWheel, root);+ if (!wheelBounds)+ continue;+ const center = wheelBounds.getCenter(new THREE15.Vector3);+ if (expanded.containsPoint(center))+ continue;+ const clamped = center.clone().clamp(expanded.min, expanded.max);+ const overflow = center.distanceTo(clamped);+ findings.push(advisory(context, {+ code: "VEH_TRACK_ROAD_WHEEL_ESCAPED",+ message: `Road wheel ${roadWheel.name || "(unnamed)"} escapes track loop ` + `${loop.name || "(unnamed)"} by ${overflow.toFixed(6)} m.`,+ affected: {+ node: roadWheel.name || "track-road-wheel",+ nodePath: nodePath3(root, roadWheel)+ },measurement: {- name: axisInvalid ? "steeringAxisAngle" : "steeringPivotCenterDelta",- actual: axisInvalid ? Number.isFinite(axisAngle) ? axisAngle : null : Number.isFinite(centerDelta) ? centerDelta : null,+ name: "roadWheelTrackContainmentOverflow",+ actual: overflow,expected: 0,- threshold: axisInvalid ? AXIS_TOLERANCE_DEGREES : CENTER_MINIMUM,- unit: axisInvalid ? "degrees" : "m"+ threshold: TRACK_CONTAINMENT_TOLERANCE,+ unit: "m"},- repairText: `Move the steering pivot for ${wheel.id} to the axle center, orient local +Y as steering axis, and parent the wheel spin pivot beneath it.`+ viewHints: ["vehicle.underbody", "generic.right.semantic-overlay"]}));}}return findings;}-function propulsionFindings(context, root, intent) {- const expectedKinds = (intent.propulsionAssemblies ?? []).filter((value) => value === "rotor" || value === "propeller");- if (expectedKinds.length === 0)+function inspectMobilityAdvisory(context) {+ if (!(context.scene instanceof THREE15.Object3D)) {return [];- const pivots = new Map;- const components = [];- root.traverseVisible((node) => {- const metadata = readSemanticMetadataV1(node);- for (const role of metadata?.roles ?? []) {- if (role.startsWith("propulsion.pivot."))- pivots.set(role.slice("propulsion.pivot.".length), node);- for (const kind of ["rotor", "propeller"]) {- if (role.startsWith(`propulsion.${kind}.`)) {- components.push({ id: role.slice(`propulsion.${kind}.`.length), kind, node });- }- }- }- });- const findings = [];- root.updateWorldMatrix(true, false);- const rootInverse = root.matrixWorld.clone().invert();- for (const kind of expectedKinds) {- const candidates = components.filter((part) => part.kind === kind);- if (candidates.length === 0) {- findings.push(finding3(context, {- code: "VEH_ROTOR_PIVOT",- disposition: "block",- message: `Trusted vehicle intent requires a semantic ${kind} assembly and centered pivot.`,- measurement: { name: `${kind}AssemblyCount`, actual: 0, expected: 1, threshold: 1 }- }));- continue;- }- for (const component of candidates) {- const pivot = pivots.get(component.id);- const box = new THREE14.Box3().setFromObject(component.node);- const center = box.isEmpty() ? undefined : box.getCenter(new THREE14.Vector3);- const pivotCenter = pivot ? new THREE14.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 THREE14.Vector3(0, 1, 0) : new THREE14.Vector3(1, 0, 0);- const axisAngle = pivot && axisFrame ? angleDegrees(canonicalAxis.clone().applyQuaternion(new THREE14.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",- disposition: "block",- message: `${kind} ${component.id} requires a centered owning pivot with ${frameId}.`,- affected: { node: pivot?.name ?? component.node.name },- measurement: {- name: axisAngle > AXIS_TOLERANCE_DEGREES ? "propulsionAxisAngle" : "propulsionPivotCenterDelta",- actual: axisAngle > AXIS_TOLERANCE_DEGREES ? Number.isFinite(axisAngle) ? axisAngle : null : Number.isFinite(delta) ? delta : null,- expected: 0,- threshold: axisAngle > AXIS_TOLERANCE_DEGREES ? AXIS_TOLERANCE_DEGREES : CENTER_MINIMUM,- unit: axisAngle > AXIS_TOLERANCE_DEGREES ? "degrees" : "m"- },- repairText: `Place the ${kind} pivot at the mast/shaft center, parent the moving geometry beneath it, and declare ${frameId}.`- }));- }- }}- return findings;-}-function inspectMobility(context) {- if (!(context.scene instanceof THREE14.Object3D))- return [];const intent = context.mobility;if (!intent)return [];const root = context.scene;root.updateMatrixWorld(true);const wheels = resolveVehicleWheelAssemblies(root);- const findings = [];- if (intent.frontFrame === "+X" && !hasCanonicalVehicleFront(root)) {- findings.push(finding3(context, {- code: "VEH_FRONT_AXIS",- disposition: "block",- message: "Generated vehicles must declare the trusted semantic +X front frame.",- affected: { node: root.name || "vehicle-root" },- measurement: { name: "canonicalFrontDeclared", actual: false, expected: true },- repairText: "Author the vehicle beneath createVehicleFrame() and preserve vehicle.front.+x semantics."- }));- }- if (intent.wheelCount !== undefined || intent.axleCount !== undefined || wheels.length > 0) {- findings.push(...wheelCountFindings(context, intent, wheels));- findings.push(...wheelGeometryFindings(context, root, wheels));- findings.push(...axlePairFindings(context, root, wheels));- findings.push(...duplicateAssemblyFindings(context, root, wheels));- findings.push(...contactFindings(context, root, intent, wheels));- findings.push(...steeringFindings(context, root, intent, wheels));- }- findings.push(...supportContactFindings(context, root, intent));- findings.push(...propulsionFindings(context, root, intent));- return findings;+ return [+ ...bilateralSymmetryFindings(context, root, wheels),+ ...penetrationFindings(context, root, wheels),+ ...orientationFindings(context, root, intent),+ ...trackProfileFindings(context, root, intent)+ ].sort((a, b) => `${a.code}:${a.affected?.nodePath ?? a.affected?.node ?? ""}`.localeCompare(`${b.code}:${b.affected?.nodePath ?? b.affected?.node ?? ""}`));}-function evaluateVehicleQa(context) {- if (context.intent.category !== "vehicle" || !context.intent.vehicle)+function evaluateVehicleAdvisoryQa(context) {+ if (context.intent.category !== "vehicle")return [];- return inspectMobility({+ return inspectMobilityAdvisory({scene: context.scene,- profile: context.intent.qaProfile || PROFILE2,- mobility: { ...context.intent.vehicle, frontFrame: "+X" }+ profile: context.intent.qaProfile,+ mobility: context.intent.vehicle});}-var PROFILE2 = "vehicle.semantic", CENTER_RATIO = 0.03, CENTER_MINIMUM = 0.01, AXIS_TOLERANCE_DEGREES = 1, PAIR_TOLERANCE = 0.015, CONTACT_TOLERANCE = 0.02, VEHICLE_QA_RULE, VEHICLE_ADVISORY_QA_RULE, VEHICLE_QA_RULES;-var init_vehicle2 = __esm(() => {- init_contracts();+var SYMMETRY_RATIO = 0.08, PENETRATION_RATIO = 0.25, ORIENTATION_RATIO = 1.15, TRACK_CONTAINMENT_TOLERANCE = 0.02, VEHICLE_VIEWS, VEHICLE_W6_ADVISORY_QA_RULE;+var init_vehicle_advisory = __esm(() => {+ init_contracts();init_vehicle();init_registry();- init_vehicle_advisory();- VEHICLE_QA_RULE = {- id: "VEHICLE_PROFILE",- profile: PROFILE2,- scope: { kind: "category", category: "vehicle" },- ruleClass: "exact",- owner: KILN_ENGINE_QA_OWNER,- promotion: conformancePromotionAuthorization("vehicle-qa-v1", "src/qa/vehicle.test.ts", "3dfd250883b2605a4e8e4fded5ed8ded9e891680853af3fca3c5127771db47d7"),- defaultMode: "enforce",- evaluate: (context) => evaluateVehicleQa(context).filter((finding) => finding.disposition === "block")- };- VEHICLE_ADVISORY_QA_RULE = {- id: "VEHICLE_ADVISORY_PROFILE",- profile: "vehicle.advisory",+ VEHICLE_VIEWS = [+ "vehicle.underbody",+ "vehicle.wheel-section.right",+ "generic.top.semantic-overlay"+ ];+ VEHICLE_W6_ADVISORY_QA_RULE = Object.freeze({+ id: "VEHICLE_W6_ADVISORY_PROFILE",+ profile: "vehicle.w6-advisory",scope: { kind: "category", category: "vehicle" },ruleClass: "heuristic",owner: KILN_ENGINE_QA_OWNER,defaultMode: "observe",- evaluate: (context) => evaluateVehicleQa(context).filter((finding) => finding.disposition !== "block")- };- VEHICLE_QA_RULES = [- VEHICLE_QA_RULE,- VEHICLE_ADVISORY_QA_RULE,- VEHICLE_W6_ADVISORY_QA_RULE- ];+ evaluate: evaluateVehicleAdvisoryQa+ });});-// src/qa/vegetation.ts-import * as THREE15 from "three";-function rolesOf2(node) {- return readSemanticMetadataV1(node)?.roles ?? [];-}-function pathOf(node, root) {- const names = [];- let cursor = node;- while (cursor) {- names.push(cursor.name || cursor.type);- if (cursor === root)- break;- cursor = cursor.parent;- }- return names.reverse().join("/");+// src/qa/vehicle.ts+import * as THREE16 from "three";+function finding3(context, value) {+ return {+ ...value,+ profile: context.profile ?? "asset.requirements.v1",+ dimension: "categoryReadiness",+ viewHints: value.viewHints ?? ["vehicle.underbody", "vehicle.wheel-section"]+ };}-function localPoint3(rootInverse, node) {- return node.getWorldPosition(new THREE15.Vector3).applyMatrix4(rootInverse);+function localPoint2(rootInverse, value) {+ return value.clone().applyMatrix4(rootInverse);}-function meshLocalBox(mesh, rootInverse) {- if (!(mesh.geometry instanceof THREE15.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 THREE15.Box3;- const count = mesh instanceof THREE15.InstancedMesh ? mesh.count : 1;- for (let index = 0;index < count; index++) {- const transform = base.clone();- if (mesh instanceof THREE15.InstancedMesh) {- const instance = new THREE15.Matrix4;- mesh.getMatrixAt(index, instance);- transform.multiply(instance);- }- result.union(source.clone().applyMatrix4(transform));- }- return result;+function rootAxis(root, axis) {+ root.updateWorldMatrix(true, false);+ return axis.clone().transformDirection(root.matrixWorld);}-function collectRenderableBounds(root) {- root.updateWorldMatrix(true, true);- const inverse = root.matrixWorld.clone().invert();- const values = [];- root.traverseVisible((node) => {- if (!(node instanceof THREE15.Mesh))- return;- const box = meshLocalBox(node, inverse);- if (!box)- return;- const roles = rolesOf2(node);- values.push({ node, box, roles, source: roles.length > 0 ? "semantic" : "fallback" });- });- return values;+function angleDegrees(a, b) {+ return THREE16.MathUtils.radToDeg(Math.acos(THREE16.MathUtils.clamp(a.clone().normalize().dot(b.clone().normalize()), -1, 1)));}-function finding4(context, value) {- return { ...value, profile: context.profile || PROFILE3 };+function isDescendant(node, ancestor) {+ let current = node;+ while (current) {+ if (current === ancestor)+ return true;+ current = current.parent ?? undefined;+ }+ return false;}-function vegetationIntent(intent) {- return intent.category === "vegetation" ? intent.vegetation : undefined;+function componentDisposition(wheel) {+ return wheel.source === "semantic" ? "block" : "warn";}-function inspectFoliageContact(context) {- const trusted = context.foliage;- if (!trusted?.grounded || !(context.scene instanceof THREE15.Object3D))- return [];- const planeY = context.groundPlaneY ?? 0;- const root = context.scene;- root.updateWorldMatrix(true, true);- const inverse = root.matrixWorld.clone().invert();- const contacts = [];- const semanticSupports = [];- root.traverseVisible((node) => {- const metadata = readSemanticMetadataV1(node);- const roles = metadata?.roles ?? [];- if (roles.some((role) => role === "vegetation.contact" || role === "vegetation.contact.ground" || role === "contact.ground")) {- const frame = metadata?.frames.find((value) => value.id === "ground-contact" || value.id === "vegetation-ground-contact");- contacts.push({- node,- ...frame ? { frameTranslation: frame.translation } : {}- });- }- if (roles.some((role) => role === "vegetation.trunk" || role === "vegetation.stem" || role === "vegetation.root" || role === "vegetation.base" || role.startsWith("vegetation.support."))) {- semanticSupports.push(node);- }- });- if (contacts.length === 0) {- return [- finding4(context, {- code: "VEG_CONTACT_MISSING",- disposition: "block",- dimension: "categoryReadiness",- message: "Grounded foliage requires one semantic ground-contact marker.",- affected: { node: root.name || "vegetation-root" },- measurement: { name: "groundContactCount", actual: 0, expected: ">=1" },- viewHints: ["right", "vegetation.base-contact"],- repairText: `Add a vegetation.contact.ground semantic marker at asset-local Y=${planeY} and seat the plant base on it.`- })- ];- }+function wheelCountFindings(context, intent, wheels) {const findings = [];- for (const contact of contacts) {- const contactPoint = contact.frameTranslation ? new THREE15.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)- continue;- const floating = offset > 0;- findings.push(finding4(context, {- code: floating ? "VEG_CONTACT_FLOATING" : "VEG_CONTACT_BURIED",+ if (intent.wheelCount !== undefined && wheels.length !== intent.wheelCount) {+ findings.push(finding3(context, {+ code: "VEH_WHEEL_COUNT",disposition: "block",- dimension: "categoryReadiness",- message: `${contact.node.name || "Vegetation contact"} is ${Math.abs(offset).toFixed(6)} m ${floating ? "above" : "below"} asset-local ground.`,- affected: {- node: contact.node.name || "vegetation-contact",- nodePath: pathOf(contact.node, root)- },+ message: `Trusted vehicle intent requires ${intent.wheelCount} wheel assemblies; resolved ${wheels.length}.`,measurement: {- name: "contactY",- actual: stable7(y),- expected: planeY,- threshold: VEGETATION_CONTACT_TOLERANCE_METERS,- unit: "m"+ name: "wheelAssemblyCount",+ actual: wheels.length,+ expected: intent.wheelCount,+ threshold: intent.wheelCount},- viewHints: ["right", "vegetation.base-contact"],- repairText: `Move ${contact.node.name || "the contact marker"} or its ground-contact frame to asset-local Y=${planeY} without moving unrelated canopy parts.`+ repairText: "Create exactly the requested number of axle-centered wheel assemblies and remove duplicate or ungrouped wheel parts."}));}- for (const support of semanticSupports) {- let minimumY = Infinity;- support.traverseVisible((node) => {- if (!(node instanceof THREE15.Mesh))- return;- const box = meshLocalBox(node, inverse);- if (box)- minimumY = Math.min(minimumY, box.min.y);- });- if (!Number.isFinite(minimumY) || minimumY >= planeY - VEGETATION_CONTACT_TOLERANCE_METERS)- continue;- findings.push(finding4(context, {- code: "VEG_MATERIAL_BURIED",+ const axleIds = new Set(wheels.map((wheel) => wheel.index).filter(Boolean));+ if (intent.axleCount !== undefined && axleIds.size !== intent.axleCount) {+ findings.push(finding3(context, {+ code: "VEH_AXLE_COUNT",disposition: "block",- dimension: "categoryReadiness",- message: `${support.name || "Vegetation support"} extends materially below the standalone ground plane.`,- affected: { node: support.name || "vegetation-support", nodePath: pathOf(support, root) },+ message: `Trusted vehicle intent requires ${intent.axleCount} axles; wheel grouping resolved ${axleIds.size}.`,measurement: {- name: "supportMinimumY",- actual: stable7(minimumY),- expected: planeY,- threshold: VEGETATION_CONTACT_TOLERANCE_METERS,- unit: "m"- },- viewHints: ["right", "vegetation.base-contact"],- repairText: `Raise or trim the declared trunk/stem/root support so its visible material stops at Y=${planeY}.`+ name: "wheelAxleCount",+ actual: axleIds.size,+ expected: intent.axleCount,+ threshold: intent.axleCount+ }}));}return findings;}-function materialNames(node) {- if (!(node instanceof THREE15.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 THREE15.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 THREE15.Box3);- const overallSize = overall.getSize(new THREE15.Vector3);+function wheelGeometryFindings(context, root, wheels) {const findings = [];- for (const value of renderables) {- const size = value.box.getSize(new THREE15.Vector3);- const center = value.box.getCenter(new THREE15.Vector3);- const names = [value.node.name, ...value.roles];- const nameEvidence = names.some((name) => CLUTTER_NAME.test(name));- const roleEvidence = value.roles.some((role) => /(?:terrain|soil|rock|pot|planter|base)/i.test(role));- const materialEvidence = materialNames(value.node).some((name) => CLUTTER_NAME.test(name));- const footprintRatio = size.x * size.z / Math.max(0.000000001, overallSize.x * overallSize.z);- const flatEvidence = footprintRatio >= 0.35 && size.y <= Math.max(0.08, overallSize.y * 0.08) && center.y <= (context.groundPlaneY ?? 0) + VEGETATION_CONTACT_TOLERANCE_METERS + size.y;- const evidence = [nameEvidence, roleEvidence, materialEvidence, flatEvidence].filter(Boolean);- if (evidence.length < 2)- continue;- findings.push(finding4(context, {- code: "VEG_SCOPE_EXTRA",- disposition: "warn",- dimension: "promptAlignment",- message: `${value.node.name || "Renderable"} is likely unrequested standalone-vegetation base clutter; review before removal.`,- affected: {- node: value.node.name || "vegetation-extra",- nodePath: pathOf(value.node, root)- },- measurement: {- name: "scopeEvidence",- actual: [- nameEvidence ? "name" : "",- roleEvidence ? "role" : "",- materialEvidence ? "material" : "",- flatEvidence ? "flat-footprint" : ""- ].filter(Boolean).join(","),- expected: "standalone plant/fungus only"- },- viewHints: ["top", "three-quarter", "vegetation.base-contact"]- }));- }- return findings;-}-function unionVolume(boxes) {- if (boxes.length === 0)- return 0;- const union = boxes.reduce((result, box) => result.union(box), new THREE15.Box3);- const size = union.getSize(new THREE15.Vector3);- return size.x * size.y * size.z;-}-function projectedOccupancy(boxes, axes) {- if (boxes.length === 0)- return 0;- const minimum = [Infinity, Infinity];- const maximum = [-Infinity, -Infinity];- for (const box of boxes) {- const min = [box.min.x, box.min.y, box.min.z];- const max = [box.max.x, box.max.y, box.max.z];- for (const dimension of [0, 1]) {- minimum[dimension] = Math.min(minimum[dimension], min[axes[dimension]]);- maximum[dimension] = Math.max(maximum[dimension], max[axes[dimension]]);+ const expectedAxle = rootAxis(root, new THREE16.Vector3(0, 0, 1));+ for (const wheel of wheels) {+ const disposition = componentDisposition(wheel);+ const centerTolerance = Math.max(CENTER_MINIMUM, (wheel.radius ?? 0) * CENTER_RATIO);+ const pivotInverse = wheel.pivot.matrixWorld.clone().invert();+ const componentCenters = [wheel.tireCenterWorld, wheel.rimCenterWorld, wheel.hubCenterWorld].filter((center) => !!center).map((center) => localPoint2(pivotInverse, center));+ let centerDelta = 0;+ for (let a = 0;a < componentCenters.length; a++) {+ for (let b = a + 1;b < componentCenters.length; b++) {+ centerDelta = Math.max(centerDelta, componentCenters[a].distanceTo(componentCenters[b]));+ }}- }- const spans = [maximum[0] - minimum[0], maximum[1] - minimum[1]];- if (spans[0] <= 0.000000001 || spans[1] <= 0.000000001)- return 0;- const occupied = new Uint8Array(RASTER_SIZE * RASTER_SIZE);- for (const box of boxes) {- const min = [box.min.x, box.min.y, box.min.z];- const max = [box.max.x, box.max.y, box.max.z];- const x0 = Math.max(0, Math.floor((min[axes[0]] - minimum[0]) / spans[0] * (RASTER_SIZE - 1)));- const x1 = Math.min(RASTER_SIZE - 1, Math.ceil((max[axes[0]] - minimum[0]) / spans[0] * (RASTER_SIZE - 1)));- const y0 = Math.max(0, Math.floor((min[axes[1]] - minimum[1]) / spans[1] * (RASTER_SIZE - 1)));- const y1 = Math.min(RASTER_SIZE - 1, Math.ceil((max[axes[1]] - minimum[1]) / spans[1] * (RASTER_SIZE - 1)));- for (let y = y0;y <= y1; y++) {- for (let x = x0;x <= x1; x++)- occupied[y * RASTER_SIZE + x] = 1;+ if (!wheel.tire || !wheel.rim || !wheel.hub || centerDelta > centerTolerance) {+ findings.push(finding3(context, {+ code: "VEH_WHEEL_CONCENTRICITY",+ disposition,+ message: `Wheel ${wheel.id} tire, rim, and hub must share one axle center.`,+ affected: { node: wheel.root.name },+ measurement: {+ name: "maximumComponentCenterDelta",+ actual: Number.isFinite(centerDelta) ? centerDelta : null,+ expected: 0,+ threshold: centerTolerance,+ unit: "m"+ },+ repairText: `Move the tire, rim, and hub of ${wheel.id} to its axle-centered wheel pivot.`+ }));}- }- return stable7(occupied.reduce((sum, value) => sum + value, 0) / occupied.length);-}-function matchesAny(value, patterns) {- const candidates = [value.node.name, ...value.roles];- return candidates.some((candidate) => patterns.some((pattern) => pattern.test(candidate)));-}-function measurementSource(values) {- if (values.length === 0)- return "none";- const semantic = values.some((value) => value.source === "semantic");- const fallback = values.some((value) => value.source === "fallback");- return semantic && fallback ? "mixed" : semantic ? "semantic" : "fallback";-}-function roleOrNameSource(value, patterns) {- if (value.roles.some((role) => patterns.some((pattern) => pattern.test(role))))- return "semantic";- if (patterns.some((pattern) => pattern.test(value.node.name)))- return "fallback";- return;-}-function growthCandidates(root) {- const result = [];- for (const value of collectRenderableBounds(root)) {- const branchSource = roleOrNameSource(value, BRANCH_PATTERNS);- const trunkSource = roleOrNameSource(value, TRUNK_PATTERNS);- if (branchSource)- result.push({ ...value, kind: "branch", growthSource: branchSource });- else if (trunkSource)- result.push({ ...value, kind: "trunk", growthSource: trunkSource });- }- return result;-}-function boxDistanceToPoint(box, point) {- return box.distanceToPoint(point);-}-function endpointRadius(position, axis, axisValue, tolerance, scale) {- const radialAxes = [0, 1, 2].filter((value) => value !== axis);- const points = [];- const point = new THREE15.Vector3;- for (let index = 0;index < position.count; index++) {- point.fromBufferAttribute(position, index);- if (Math.abs(point.getComponent(axis) - axisValue) <= tolerance)- points.push(point.clone());- }- if (points.length === 0)- return;- const center = new THREE15.Vector3;- center.setComponent(axis, axisValue);- for (const radialAxis of radialAxes) {- center.setComponent(radialAxis, points.reduce((sum, value) => sum + value.getComponent(radialAxis), 0) / points.length);- }- let radius = 0;- for (const value of points) {- const a = (value.getComponent(radialAxes[0]) - center.getComponent(radialAxes[0])) * Math.abs(scale.getComponent(radialAxes[0]));- const b = (value.getComponent(radialAxes[1]) - center.getComponent(radialAxes[1])) * Math.abs(scale.getComponent(radialAxes[1]));- radius = Math.max(radius, Math.hypot(a, b));- }- return { center, radius };-}-function growthNodeMeasurement(root, candidate, allCandidates, band) {- if (!(candidate.node instanceof THREE15.Mesh))- return;- const geometry = candidate.node.geometry;- const position = geometry.getAttribute("position");- if (!position || position.count < 2)- return;- geometry.computeBoundingBox();- const geometryBox = geometry.boundingBox;- if (!geometryBox || geometryBox.isEmpty())- return;- root.updateWorldMatrix(true, true);- const relative = root.matrixWorld.clone().invert().multiply(candidate.node.matrixWorld);- const relativeScale = new THREE15.Vector3;- relative.decompose(new THREE15.Vector3, new THREE15.Quaternion, relativeScale);- const size = geometryBox.getSize(new THREE15.Vector3);- const scaledSizes = [- Math.abs(size.x * relativeScale.x),- Math.abs(size.y * relativeScale.y),- Math.abs(size.z * relativeScale.z)- ];- const axis = scaledSizes.indexOf(Math.max(...scaledSizes));- const minimum = geometryBox.min.getComponent(axis);- const maximum = geometryBox.max.getComponent(axis);- const tolerance = Math.max(0.000001, (maximum - minimum) * 0.0001);- const first = endpointRadius(position, axis, minimum, tolerance, relativeScale);- const second = endpointRadius(position, axis, maximum, tolerance, relativeScale);- if (!first || !second)- return;- const firstPoint = first.center.clone().applyMatrix4(relative);- const secondPoint = second.center.clone().applyMatrix4(relative);- const supportBoxes = allCandidates.filter((value) => value !== candidate).map((value) => value.box);- let firstIsBase;- if (candidate.kind === "trunk") {- firstIsBase = firstPoint.y <= secondPoint.y;- } else if (supportBoxes.length > 0) {- const firstGap = Math.min(...supportBoxes.map((box) => boxDistanceToPoint(box, firstPoint)));- const secondGap = Math.min(...supportBoxes.map((box) => boxDistanceToPoint(box, secondPoint)));- firstIsBase = Math.abs(firstGap - secondGap) > 0.000001 ? firstGap < secondGap : first.radius >= second.radius;- } else {- firstIsBase = first.radius >= second.radius;- }- const baseRadius = firstIsBase ? first.radius : second.radius;- const tipRadius = firstIsBase ? second.radius : first.radius;- const length = firstPoint.distanceTo(secondPoint);- const averageRadius = (baseRadius + tipRadius) / 2;- const taperRatio = baseRadius > 0.000000001 ? tipRadius / baseRadius : null;- const lengthRadiusRatio = averageRadius > 0.000000001 ? length / averageRadius : null;- const selected = band[candidate.kind];- const taperOutlier = taperRatio !== null && (taperRatio < selected.taper[0] || taperRatio > selected.taper[1]);- const lengthRadiusOutlier = lengthRadiusRatio !== null && (lengthRadiusRatio < selected.lengthRadius[0] || lengthRadiusRatio > selected.lengthRadius[1]);- return {- node: candidate.node.name || candidate.kind,- nodePath: pathOf(candidate.node, root),- kind: candidate.kind,- source: candidate.growthSource,- lengthMeters: stable7(length),- baseRadiusMeters: stable7(baseRadius),- tipRadiusMeters: stable7(tipRadius),- taperRatio: taperRatio === null ? null : stable7(taperRatio),- lengthRadiusRatio: lengthRadiusRatio === null ? null : stable7(lengthRadiusRatio),- expectedTaperRatio: `${selected.taper[0]}..${selected.taper[1]}`,- expectedLengthRadiusRatio: `${selected.lengthRadius[0]}..${selected.lengthRadius[1]}`,- taperOutlier,- lengthRadiusOutlier- };-}-function measureFoliageGrowth(foliage, root) {- const requested = foliage?.subtype;- const subtype = requested && Object.hasOwn(VEGETATION_GROWTH_BANDS_V1, requested) ? requested : "custom";- const candidates = growthCandidates(root);- const nodes = candidates.map((candidate) => growthNodeMeasurement(root, candidate, candidates, VEGETATION_GROWTH_BANDS_V1[subtype])).filter((value) => Boolean(value));- return {- schemaVersion: 1,- subtype,- source: measurementSource(nodes),- trunkCount: nodes.filter((value) => value.kind === "trunk").length,- branchCount: nodes.filter((value) => value.kind === "branch").length,- nodes- };-}-function inspectFoliageGrowth(context) {- if (!context.foliage || !(context.scene instanceof THREE15.Object3D))- return [];- const measured = measureFoliageGrowth(context.foliage, context.scene);- const findings = [];- for (const node of measured.nodes) {- if (node.taperOutlier) {- findings.push(finding4(context, {- code: "VEG_GROWTH_TAPER_OUTLIER",- disposition: "warn",- dimension: "categoryReadiness",- message: `${node.kind} taper measurement is outside the ${measured.subtype} measurement band.`,- affected: { node: node.node, nodePath: node.nodePath },+ const nested = wheel.radius !== undefined && wheel.rimRadius !== undefined && wheel.hubRadius !== undefined && wheel.hubRadius < wheel.rimRadius && wheel.rimRadius < wheel.radius && wheel.rimWidth !== undefined && wheel.hubWidth !== undefined && wheel.width !== undefined && wheel.rimWidth <= wheel.width + 0.000001 && wheel.hubWidth <= wheel.width + 0.000001;+ if (!nested) {+ findings.push(finding3(context, {+ code: "VEH_WHEEL_RADIUS",+ disposition,+ message: `Wheel ${wheel.id} must satisfy hub radius < rim radius < tire radius and keep rim/hub widths inside the tire envelope.`,+ affected: { node: wheel.root.name },measurement: {- name: "tipToBaseRadiusRatio",- actual: node.taperRatio ?? "unmeasurable",- expected: node.expectedTaperRatio,- unit: "ratio"+ name: "nestedRadii",+ actual: false,+ expected: true},- viewHints: ["front", "right", "three-quarter"]+ repairText: `Resize ${wheel.id} so its hub is nested inside its rim and its rim is nested inside its tire.`}));}- if (node.lengthRadiusOutlier) {- findings.push(finding4(context, {- code: "VEG_GROWTH_LENGTH_RADIUS_OUTLIER",- disposition: "warn",- dimension: "categoryReadiness",- message: `${node.kind} length/radius measurement is outside the ${measured.subtype} measurement band.`,- affected: { node: node.node, nodePath: node.nodePath },+ const axleAngle = angleDegrees(wheel.spinAxisWorld, expectedAxle);+ if (axleAngle > AXIS_TOLERANCE_DEGREES) {+ findings.push(finding3(context, {+ code: "VEH_WHEEL_AXLE_AXIS",+ disposition,+ message: `Wheel ${wheel.id} spin axis must align with vehicle-local +Z.`,+ affected: { node: wheel.pivot.name },measurement: {- name: "lengthToAverageRadiusRatio",- actual: node.lengthRadiusRatio ?? "unmeasurable",- expected: node.expectedLengthRadiusRatio,- unit: "ratio"+ name: "axleAxisAngle",+ actual: axleAngle,+ expected: 0,+ threshold: AXIS_TOLERANCE_DEGREES,+ unit: "degrees"},- viewHints: ["front", "right", "three-quarter"]+ repairText: `Orient ${wheel.pivot.name} so its local +Z is the axle/spin axis.`}));}- }- return findings;-}-function distanceBetweenBoxes(a, b) {- const dx = Math.max(0, a.min.x - b.max.x, b.min.x - a.max.x);- const dy = Math.max(0, a.min.y - b.max.y, b.min.y - a.max.y);- const dz = Math.max(0, a.min.z - b.max.z, b.min.z - a.max.z);- return Math.hypot(dx, dy, dz);-}-function measureVegetationFoliageAttachment(root) {- const renderables = collectRenderableBounds(root);- const support = renderables.filter((value) => roleOrNameSource(value, TRUNK_PATTERNS) || roleOrNameSource(value, BRANCH_PATTERNS));- const foliage = renderables.filter((value) => roleOrNameSource(value, CANOPY_PATTERNS));- const clusters = foliage.map((value) => {- const size = value.box.getSize(new THREE15.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";- return {- node: value.node.name || "foliage-cluster",- nodePath: pathOf(value.node, root),- source,- nearestSupport: nearest?.candidate.node.name || null,- gapMeters: nearest ? stable7(nearest.gap) : null,- thresholdMeters: threshold,- detached: !nearest || nearest.gap > threshold- };- });- return {- schemaVersion: 1,- source: measurementSource(clusters),- supportNodeCount: support.length,- foliageClusterCount: foliage.length,- clusters- };-}-function inspectFoliageAttachment(context) {- if (!context.foliage || !(context.scene instanceof THREE15.Object3D))- return [];- return measureVegetationFoliageAttachment(context.scene).clusters.filter((cluster) => cluster.detached).map((cluster) => finding4(context, {- code: "VEG_FOLIAGE_DETACHED",- disposition: "warn",- dimension: "categoryReadiness",- message: `${cluster.node} is detached from the nearest inferred or semantic branch/twig support.`,- affected: { node: cluster.node, nodePath: cluster.nodePath },- measurement: {- name: "foliageSupportGap",- actual: cluster.gapMeters ?? "no support found",- expected: `<=${cluster.thresholdMeters}`,- threshold: cluster.thresholdMeters,- unit: "m"- },- viewHints: ["front", "right", "three-quarter"]- }));-}-function relativeTransformSignature(root, node) {- const matrix = root.matrixWorld.clone().invert().multiply(node.matrixWorld);- const scale = new THREE15.Vector3;- const quaternion = new THREE15.Quaternion;- matrix.decompose(new THREE15.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));- return values.join(",");+ const pivotDelta = localPoint2(pivotInverse, wheel.pivotCenterWorld).distanceTo(localPoint2(pivotInverse, wheel.centerWorld));+ const descendants = [wheel.tire, wheel.rim, wheel.hub].every((part) => isDescendant(part, wheel.pivot));+ if (!descendants || pivotDelta > centerTolerance) {+ findings.push(finding3(context, {+ code: "VEH_WHEEL_PIVOT",+ disposition,+ message: `Wheel ${wheel.id} pivot must be at the axle center and own every moving component.`,+ affected: { node: wheel.pivot.name },+ measurement: {+ name: "pivotCenterDelta",+ actual: pivotDelta,+ expected: 0,+ threshold: centerTolerance,+ unit: "m"+ },+ repairText: `Place ${wheel.pivot.name} at the axle center and parent tire, rim, and hub beneath it.`+ }));+ }+ }+ return findings;}-function measureFoliageRepetition(requirements, root) {- root.updateWorldMatrix(true, true);- const foliage = collectRenderableBounds(root).filter((value) => roleOrNameSource(value, CANOPY_PATTERNS));- const bySignature = new Map;- for (const value of foliage) {- const signature = relativeTransformSignature(root, value.node);- const entries = bySignature.get(signature) ?? [];- entries.push(value);- bySignature.set(signature, entries);+function axlePairFindings(context, root, wheels) {+ root.updateWorldMatrix(true, false);+ const inverse = root.matrixWorld.clone().invert();+ const groups = new Map;+ for (const wheel of wheels) {+ if (!wheel.index)+ continue;+ const group = groups.get(wheel.index) ?? [];+ group.push(wheel);+ groups.set(wheel.index, group);}- const identicalTransformGroups = [...bySignature.entries()].filter(([, values]) => values.length >= 3).map(([signature, values]) => ({- signature,- nodes: values.map((value) => value.node.name || "foliage-cluster").sort()- })).sort((a, b) => a.signature.localeCompare(b.signature));- const supports = collectRenderableBounds(root).filter((value) => roleOrNameSource(value, TRUNK_PATTERNS));- const centerBox = supports.reduce((box, value) => box.union(value.box), new THREE15.Box3);- const centers = foliage.map((value) => value.box.getCenter(new THREE15.Vector3));- const center = centerBox.isEmpty() ? centers.reduce((result, value) => result.add(value), new THREE15.Vector3).multiplyScalar(centers.length > 0 ? 1 / centers.length : 0) : centerBox.getCenter(new THREE15.Vector3);- const radial = centers.map((value) => ({- angle: Math.atan2(value.z - center.z, value.x - center.x),- radius: Math.hypot(value.x - center.x, value.z - center.z)- })).filter((value) => value.radius > 0.000001).sort((a, b) => a.angle - b.angle);- let radialGapRangeRadians = null;- let radialRadiusSpreadRatio = null;- let perfectRadialLockstep = false;- if (radial.length >= 4) {- const gaps = radial.map((value, index) => {- const next = radial[(index + 1) % radial.length];- const raw = next.angle - value.angle;- return raw > 0 ? raw : raw + Math.PI * 2;- });- radialGapRangeRadians = stable7(Math.max(...gaps) - Math.min(...gaps));- const radii = radial.map((value) => value.radius);- const meanRadius = radii.reduce((sum, value) => sum + value, 0) / radii.length;- radialRadiusSpreadRatio = stable7((Math.max(...radii) - Math.min(...radii)) / meanRadius);- perfectRadialLockstep = radialGapRangeRadians <= 0.02 && radialRadiusSpreadRatio <= 0.02;+ const findings = [];+ for (const [index, pair] of groups) {+ const left = pair.find((wheel) => wheel.side === "left");+ const right = pair.find((wheel) => wheel.side === "right");+ if (!left || !right)+ continue;+ const leftCenter = localPoint2(inverse, left.centerWorld);+ const rightCenter = localPoint2(inverse, right.centerWorld);+ const delta = Math.hypot(leftCenter.x - rightCenter.x, leftCenter.y - rightCenter.y);+ if (delta > PAIR_TOLERANCE) {+ findings.push(finding3(context, {+ code: "VEH_AXLE_PAIR",+ disposition: left.source === "semantic" && right.source === "semantic" ? "block" : "warn",+ message: `Axle ${index} left/right wheel centers disagree in vehicle-local X/Y.`,+ affected: { node: right.root.name },+ measurement: {+ name: "pairedCenterXYDelta",+ actual: delta,+ expected: 0,+ threshold: PAIR_TOLERANCE,+ unit: "m"+ },+ repairText: `Align both wheels on axle ${index} to the same local X and Y coordinates.`+ }));+ }}- const suppressedForTopiary = requirements?.canopyProfile === "topiary";- return {- schemaVersion: 1,- source: measurementSource(foliage.map((value) => ({- source: roleOrNameSource(value, CANOPY_PATTERNS) ?? "fallback"- }))),- clusterCount: foliage.length,- identicalTransformGroups,- radialGapRangeRadians,- radialRadiusSpreadRatio,- perfectRadialLockstep,- suppressedForTopiary- };+ return findings;}-function inspectFoliageRepetition(context) {- if (!context.foliage || !(context.scene instanceof THREE15.Object3D))- return [];- const measured = measureFoliageRepetition(context.foliage, context.scene);- if (measured.suppressedForTopiary)- return [];- const findings = measured.identicalTransformGroups.map((group) => finding4(context, {- code: "VEG_CLUSTER_TRANSFORM_REPEAT",- disposition: "warn",- dimension: "visualQuality",- message: `${group.nodes.length} foliage clusters use an identical scale/rotation signature.`,- affected: { node: group.nodes[0], nodePath: group.nodes.join(",") },- measurement: {- name: "identicalClusterTransformCount",- actual: group.nodes.length,- expected: "<3 outside formal topiary intent"- },- viewHints: ["front", "right", "top", "three-quarter"]- }));- if (measured.perfectRadialLockstep) {- findings.push(finding4(context, {- code: "VEG_CLUSTER_RADIAL_LOCKSTEP",- disposition: "warn",- dimension: "visualQuality",- message: "Foliage clusters form a perfect equal-radius, equal-angle radial sequence.",- measurement: {- name: "radialGapAndRadiusSpread",- actual: `${measured.radialGapRangeRadians},${measured.radialRadiusSpreadRatio}`,- expected: "angle gap range >0.02 or radius spread ratio >0.02",- unit: "ratio"- },- viewHints: ["top", "three-quarter"]- }));+function duplicateAssemblyFindings(context, root, wheels) {+ root.updateMatrixWorld(true);+ const inverse = root.matrixWorld.clone().invert();+ const findings = [];+ for (let a = 0;a < wheels.length; a++) {+ for (let b = a + 1;b < wheels.length; b++) {+ const left = wheels[a];+ const right = wheels[b];+ const sameDeclaredCorner = left.side !== undefined && left.side === right.side && left.index !== undefined && left.index === right.index;+ const centerDelta = localPoint2(inverse, left.centerWorld).distanceTo(localPoint2(inverse, right.centerWorld));+ const scale = Math.max(left.radius ?? 0, right.radius ?? 0, 0.25);+ const threshold = Math.max(CENTER_MINIMUM, scale * CENTER_RATIO);+ if (!sameDeclaredCorner && centerDelta > threshold)+ continue;+ const semantic = left.source === "semantic" && right.source === "semantic";+ findings.push(finding3(context, {+ code: "VEH_DUPLICATE_ASSEMBLY",+ disposition: semantic ? "block" : "warn",+ message: `Wheel assemblies ${left.id} and ${right.id} resolve to the same ` + `${sameDeclaredCorner ? `${left.side}-${left.index} corner` : "scale-relative center"}.`,+ affected: { node: right.root.name },+ measurement: {+ name: "duplicateAssemblyCenterDelta",+ actual: centerDelta,+ expected: `>${threshold}`,+ threshold,+ unit: "m"+ },+ viewHints: [+ "vehicle.underbody",+ "vehicle.wheel-section.right",+ "generic.top.semantic-overlay"+ ],+ repairText: `Remove only duplicate assembly ${right.id} at the reported center; preserve ${left.id} and rebuild the actually missing corner from trusted wheel/axle intent.`+ }));+ }}return findings;}-function measureFoliageCanopy(profile, root) {- const renderables = collectRenderableBounds(root);- const canopy = renderables.filter((value) => matchesAny(value, CANOPY_PATTERNS));- const trunk = renderables.filter((value) => matchesAny(value, TRUNK_PATTERNS));- const semanticCanopy = canopy.some((value) => value.roles.length > 0);- const source = canopy.length === 0 ? "none" : semanticCanopy ? "semantic" : "fallback";- const canopyBoxes = canopy.map((value) => value.box);- const trunkVolume = unionVolume(trunk.map((value) => value.box));- const ratio = trunkVolume > 0.000000001 ? unionVolume(canopyBoxes) / trunkVolume : null;- return {- schemaVersion: 1,- profile,- source,- canopyNodeCount: canopy.length,- trunkNodeCount: trunk.length,- frontOccupancy: projectedOccupancy(canopyBoxes, [2, 1]),- sideOccupancy: projectedOccupancy(canopyBoxes, [0, 1]),- topOccupancy: projectedOccupancy(canopyBoxes, [0, 2]),- canopyToTrunkVolumeRatio: ratio === null ? null : stable7(ratio)- };-}-function inspectFoliageCanopy(context) {- const trusted = context.foliage;- if (!trusted?.canopyProfile || !(context.scene instanceof THREE15.Object3D))+function contactFindings(context, root, intent, wheels) {+ if (intent.supportPolicy !== "grounded")return [];- const measurements = measureFoliageCanopy(trusted.canopyProfile, context.scene);- const bands = PROFILE_BANDS[measurements.profile];- const sparseFactor = trusted.growthState === "sparse" ? 0.55 : 1;- const values = [- ["FRONT", "frontOccupancy", measurements.frontOccupancy, bands.occupancy.front, "front"],- ["SIDE", "sideOccupancy", measurements.sideOccupancy, bands.occupancy.side, "right"],- ["TOP", "topOccupancy", measurements.topOccupancy, bands.occupancy.top, "top"]- ];+ root.updateWorldMatrix(true, false);+ const inverse = root.matrixWorld.clone().invert();const findings = [];- if (measurements.canopyNodeCount === 0 && measurements.profile !== "bare/dead") {- findings.push(finding4(context, {- code: "VEG_CANOPY_MISSING",- disposition: "warn",- dimension: "categoryReadiness",- message: `The ${trusted.subtype ?? trusted.canopyProfile} profile resolved no semantic or inferred canopy renderables.`,- measurement: { name: "canopyNodeCount", actual: 0, expected: ">=1" },- viewHints: ["front", "right", "top"]- }));- return findings;+ for (const wheel of wheels.filter((value) => value.loadBearing)) {+ const center = localPoint2(inverse, wheel.centerWorld);+ const contactY = center.y - (wheel.radius ?? 0);+ if (wheel.radius === undefined || Math.abs(contactY - (context.groundPlaneY ?? 0)) > CONTACT_TOLERANCE) {+ findings.push(finding3(context, {+ code: "VEH_CONTACT_PLANE",+ disposition: componentDisposition(wheel),+ message: `Load-bearing wheel ${wheel.id} must touch the requested ground plane Y=${context.groundPlaneY ?? 0} without floating or burial.`,+ affected: { node: wheel.tire?.name ?? wheel.root.name },+ measurement: {+ name: "tireContactY",+ actual: wheel.radius === undefined ? null : contactY,+ expected: context.groundPlaneY ?? 0,+ threshold: CONTACT_TOLERANCE,+ unit: "m"+ },+ repairText: `Set ${wheel.id} axle-center Y to its tire radius plus ${context.groundPlaneY ?? 0} so its contact point meets the requested plane.`+ }));+ }}- for (const [suffix, name, actual, [minimum, maximum], view] of values) {- const adjustedMinimum = minimum * sparseFactor;- if (actual >= adjustedMinimum && actual <= maximum)+ return findings;+}+function renderableMinYInRoot(rootInverse, node) {+ let minimum = Infinity;+ node.traverseVisible((part) => {+ if (!(part instanceof THREE16.Mesh) || !(part.geometry instanceof THREE16.BufferGeometry))+ return;+ part.geometry.computeBoundingBox();+ const bounds = part.geometry.boundingBox;+ if (!bounds)+ return;+ const matrix = rootInverse.clone().multiply(part.matrixWorld);+ for (const x of [bounds.min.x, bounds.max.x]) {+ for (const y of [bounds.min.y, bounds.max.y]) {+ for (const z of [bounds.min.z, bounds.max.z]) {+ minimum = Math.min(minimum, new THREE16.Vector3(x, y, z).applyMatrix4(matrix).y);+ }+ }+ }+ });+ return Number.isFinite(minimum) ? minimum : undefined;+}+function supportContactFindings(context, root, intent) {+ root.updateWorldMatrix(true, true);+ const inverse = root.matrixWorld.clone().invert();+ const explicitContacts = [];+ const supports = [];+ root.traverseVisible((node) => {+ const roles = readSemanticMetadataV1(node)?.roles ?? [];+ const isWheelContact = roles.some((role) => role.startsWith("wheel.contact."));+ if (!isWheelContact && roles.some((role) => role.startsWith("contact."))) {+ explicitContacts.push({+ node,+ contactY: localPoint2(inverse, new THREE16.Vector3().setFromMatrixPosition(node.matrixWorld)).y,+ source: "contact"+ });+ }+ if (roles.some((role) => role.startsWith("support."))) {+ const contactY = renderableMinYInRoot(inverse, node);+ if (contactY !== undefined)+ supports.push({ node, contactY, source: "support" });+ }+ });+ const measurements = explicitContacts.length > 0 ? explicitContacts : supports;+ const findings = measurements.flatMap((measurement) => {+ if (intent.supportPolicy !== "grounded" || Math.abs(measurement.contactY - (context.groundPlaneY ?? 0)) <= CONTACT_TOLERANCE)+ return [];+ return [+ finding3(context, {+ code: "VEH_CONTACT_PLANE",+ disposition: "block",+ message: `Load-bearing ${measurement.source} ${measurement.node.name || "(unnamed)"} must touch the requested ground plane Y=${context.groundPlaneY ?? 0} without floating or burial.`,+ affected: { node: measurement.node.name || "vehicle-support" },+ measurement: {+ name: "supportContactY",+ actual: measurement.contactY,+ expected: context.groundPlaneY ?? 0,+ threshold: CONTACT_TOLERANCE,+ unit: "m"+ },+ repairText: `Move ${measurement.node.name || "the support"} so its declared contact rests at asset-local Y=${context.groundPlaneY ?? 0}.`+ })+ ];+ });+ for (const expected of intent.supportAssemblies ?? []) {+ if (expected === "wheel" && resolveVehicleWheelAssemblies(root).length > 0)continue;- findings.push(finding4(context, {- code: `VEG_CANOPY_OCCUPANCY_${suffix}`,- disposition: "warn",- dimension: "categoryReadiness",- message: `${measurements.profile} ${name} is outside its measured ${trusted.growthState ?? "default"} profile band.`,+ const matches = [...explicitContacts, ...supports].filter((measurement) => (readSemanticMetadataV1(measurement.node)?.roles ?? []).some((role) => role === `support.${expected}` || role.startsWith(`support.${expected}.`) || role === `contact.${expected}` || role.startsWith(`contact.${expected}.`)));+ if (matches.length > 0)+ continue;+ findings.push(finding3(context, {+ code: "VEH_SUPPORT_SET_MISSING",+ disposition: "block",+ message: `Requested mobility requires semantic ${expected} supports or contacts.`,+ affected: { node: root.name || "vehicle-root" },measurement: {- name,- actual,- expected: `${stable7(adjustedMinimum)}..${maximum}`,- threshold: adjustedMinimum,- unit: "ratio"+ name: `${expected}SupportCount`,+ actual: 0,+ expected: ">=1",+ threshold: 1},- viewHints: [view, "three-quarter"]+ viewHints: ["vehicle.underbody", "generic.front.depth-contact"],+ repairText: `Add the requested semantic ${expected} support set.${intent.supportPolicy === "grounded" ? ` Place its contacts at asset-local Y=${context.groundPlaneY ?? 0}.` : ""}`}));}- const ratio = measurements.canopyToTrunkVolumeRatio;- if (ratio !== null && (ratio < bands.ratio[0] || ratio > bands.ratio[1])) {- findings.push(finding4(context, {- code: "VEG_CANOPY_TRUNK_RATIO",- disposition: "warn",- dimension: "categoryReadiness",- message: `${measurements.profile} canopy-to-trunk volume ratio is outside its subtype band.`,- measurement: {- name: "canopyToTrunkVolumeRatio",- actual: ratio,- expected: `${bands.ratio[0]}..${bands.ratio[1]}`,- threshold: bands.ratio[0],- unit: "ratio"- },- viewHints: ["front", "right", "top"]- }));+ if (intent.supportPolicy === "grounded" && measurements.length > 1) {+ const values = measurements.map((measurement) => measurement.contactY);+ const range = Math.max(...values) - Math.min(...values);+ if (range > CONTACT_TOLERANCE) {+ findings.push(finding3(context, {+ code: "VEH_SUPPORT_PLANE",+ disposition: "block",+ message: `Declared non-wheel supports do not share one stable vehicle-local contact plane.`,+ affected: { node: root.name || "vehicle-root" },+ measurement: {+ name: "supportContactPlaneRange",+ actual: range,+ expected: 0,+ threshold: CONTACT_TOLERANCE,+ unit: "m"+ },+ viewHints: ["vehicle.underbody", "generic.front.depth-contact"],+ repairText: `Move only the reported supports onto the requested asset-local Y=${context.groundPlaneY ?? 0} plane while preserving their stance.`+ }));+ }}return findings;}-function materialValue(material) {- if (!(material instanceof THREE15.MeshStandardMaterial) && !(material instanceof THREE15.MeshBasicMaterial)) {- return;+function steeringFindings(context, root, intent, wheels) {+ if (intent.steering === undefined || intent.steering === "none" || wheels.length === 0)+ return [];+ root.updateWorldMatrix(true, false);+ const inverse = root.matrixWorld.clone().invert();+ const expectedAxis = rootAxis(root, new THREE16.Vector3(0, 1, 0));+ const localCenters = wheels.map((wheel) => ({+ wheel,+ center: localPoint2(inverse, wheel.centerWorld)+ }));+ const extreme = intent.steering === "rear" ? Math.min(...localCenters.map((entry) => entry.center.x)) : Math.max(...localCenters.map((entry) => entry.center.x));+ const targets = intent.steering === "all" ? localCenters : localCenters.filter((entry) => Math.abs(entry.center.x - extreme) <= PAIR_TOLERANCE);+ const findings = [];+ for (const { wheel } of targets) {+ const steering = wheel.steeringPivot;+ const centerDelta = steering ? localPoint2(inverse, new THREE16.Vector3().setFromMatrixPosition(steering.matrixWorld)).distanceTo(localPoint2(inverse, wheel.centerWorld)) : Infinity;+ const axisAngle = steering ? angleDegrees(new THREE16.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, {+ code: "VEH_STEERING_PIVOT",+ disposition: componentDisposition(wheel),+ message: `Declared steering wheel ${wheel.id} requires a centered +Y steering pivot owning its spin pivot.`,+ affected: { node: steering?.name ?? wheel.pivot.name },+ measurement: {+ name: axisInvalid ? "steeringAxisAngle" : "steeringPivotCenterDelta",+ actual: axisInvalid ? Number.isFinite(axisAngle) ? axisAngle : null : Number.isFinite(centerDelta) ? centerDelta : null,+ expected: 0,+ threshold: axisInvalid ? AXIS_TOLERANCE_DEGREES : CENTER_MINIMUM,+ unit: axisInvalid ? "degrees" : "m"+ },+ repairText: `Move the steering pivot for ${wheel.id} to the axle center, orient local +Y as steering axis, and parent the wheel spin pivot beneath it.`+ }));+ }}- const color = material.color;- return 0.2126 * color.r + 0.7152 * color.g + 0.0722 * color.b;+ return findings;}-function measureFoliageMaterials(mode, root) {- const values = [];- let foliageNodeCount = 0;+function propulsionFindings(context, root, intent) {+ const expectedKinds = (intent.propulsionAssemblies ?? []).filter((value) => value === "rotor" || value === "propeller");+ if (expectedKinds.length === 0)+ return [];+ const pivots = new Map;+ const components = [];root.traverseVisible((node) => {- if (!(node instanceof THREE15.Mesh))- return;- const bounds = {- node,- box: new THREE15.Box3,- roles: rolesOf2(node),- source: rolesOf2(node).length > 0 ? "semantic" : "fallback"- };- if (!matchesAny(bounds, CANOPY_PATTERNS))- return;- foliageNodeCount++;- const materials = Array.isArray(node.material) ? node.material : [node.material];- for (const material of materials) {- const value = materialValue(material);- if (value !== undefined)- values.push(value);+ const metadata = readSemanticMetadataV1(node);+ for (const role of metadata?.roles ?? []) {+ if (role.startsWith("propulsion.pivot."))+ pivots.set(role.slice("propulsion.pivot.".length), node);+ for (const kind of ["rotor", "propeller"]) {+ if (role.startsWith(`propulsion.${kind}.`)) {+ components.push({ id: role.slice(`propulsion.${kind}.`.length), kind, node });+ }+ }}});- const buckets = new Set(values.map((value) => Math.round(value * 20) / 20));- const valueRange = values.length > 0 ? Math.max(...values) - Math.min(...values) : 0;- const optimized = mode === "flatOptimized";- return {- schemaVersion: 1,- mode,- foliageNodeCount,- valueRoleCount: buckets.size,- valueRange: stable7(valueRange),- coherent: optimized ? buckets.size <= 1 : buckets.size >= 2 && buckets.size <= 6 && valueRange >= 0.03- };-}-function inspectFoliageMaterial(context) {- if (!context.foliage || !(context.scene instanceof THREE15.Object3D))- return [];- if (!context.materialMode)- return [];- const measured = measureFoliageMaterials(context.materialMode, context.scene);- if (measured.foliageNodeCount === 0 || measured.coherent)- return [];- const optimized = measured.mode === "flatOptimized";- return [- finding4(context, {- code: "VEG_FOLIAGE_VALUE_ROLES",- disposition: "warn",- dimension: "visualQuality",- message: optimized ? "Optimized vegetation should retain one coherent foliage value role." : "Rich organic vegetation should use two to six restrained foliage value roles with visible value separation.",- measurement: {- name: "foliageValueRoles",- actual: `${measured.valueRoleCount} roles; range ${measured.valueRange}`,- expected: optimized ? "1 role" : "2..6 roles; range >=0.03"- },- viewHints: ["front", "three-quarter"]- })- ];-}-function inspectFoliageAdvisory(context) {- return [- ...inspectFoliageScope(context),- ...inspectFoliageGrowth(context),- ...inspectFoliageCanopy(context),- ...inspectFoliageAttachment(context),- ...inspectFoliageRepetition(context),- ...inspectFoliageMaterial(context)- ];-}-function fixtureInput(context) {- return {- scene: context.scene,- profile: context.intent.qaProfile,- foliage: vegetationIntent(context.intent),- materialMode: context.intent.material.mode- };+ const findings = [];+ root.updateWorldMatrix(true, false);+ const rootInverse = root.matrixWorld.clone().invert();+ for (const kind of expectedKinds) {+ const candidates = components.filter((part) => part.kind === kind);+ if (candidates.length === 0) {+ findings.push(finding3(context, {+ code: "VEH_ROTOR_PIVOT",+ disposition: "block",+ message: `Trusted vehicle intent requires a semantic ${kind} assembly and centered pivot.`,+ measurement: { name: `${kind}AssemblyCount`, actual: 0, expected: 1, threshold: 1 }+ }));+ continue;+ }+ for (const component of candidates) {+ const pivot = pivots.get(component.id);+ const box = new THREE16.Box3().setFromObject(component.node);+ const center = box.isEmpty() ? undefined : box.getCenter(new THREE16.Vector3);+ const pivotCenter = pivot ? new THREE16.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 THREE16.Vector3(0, 1, 0) : new THREE16.Vector3(1, 0, 0);+ const axisAngle = pivot && axisFrame ? angleDegrees(canonicalAxis.clone().applyQuaternion(new THREE16.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",+ disposition: "block",+ message: `${kind} ${component.id} requires a centered owning pivot with ${frameId}.`,+ affected: { node: pivot?.name ?? component.node.name },+ measurement: {+ name: axisAngle > AXIS_TOLERANCE_DEGREES ? "propulsionAxisAngle" : "propulsionPivotCenterDelta",+ actual: axisAngle > AXIS_TOLERANCE_DEGREES ? Number.isFinite(axisAngle) ? axisAngle : null : Number.isFinite(delta) ? delta : null,+ expected: 0,+ threshold: axisAngle > AXIS_TOLERANCE_DEGREES ? AXIS_TOLERANCE_DEGREES : CENTER_MINIMUM,+ unit: axisAngle > AXIS_TOLERANCE_DEGREES ? "degrees" : "m"+ },+ repairText: `Place the ${kind} pivot at the mast/shaft center, parent the moving geometry beneath it, and declare ${frameId}.`+ }));+ }+ }+ }+ return findings;}-function evaluateVegetationContactQa(context) {- return inspectFoliageContact(fixtureInput(context));+function inspectMobility(context) {+ if (!(context.scene instanceof THREE16.Object3D))+ return [];+ const intent = context.mobility;+ if (!intent)+ return [];+ const root = context.scene;+ root.updateMatrixWorld(true);+ const wheels = resolveVehicleWheelAssemblies(root);+ const findings = [];+ if (intent.frontFrame === "+X" && !hasCanonicalVehicleFront(root)) {+ findings.push(finding3(context, {+ code: "VEH_FRONT_AXIS",+ disposition: "block",+ message: "Generated vehicles must declare the trusted semantic +X front frame.",+ affected: { node: root.name || "vehicle-root" },+ measurement: { name: "canonicalFrontDeclared", actual: false, expected: true },+ repairText: "Author the vehicle beneath createVehicleFrame() and preserve vehicle.front.+x semantics."+ }));+ }+ if (intent.wheelCount !== undefined || intent.axleCount !== undefined || wheels.length > 0) {+ findings.push(...wheelCountFindings(context, intent, wheels));+ findings.push(...wheelGeometryFindings(context, root, wheels));+ findings.push(...axlePairFindings(context, root, wheels));+ findings.push(...duplicateAssemblyFindings(context, root, wheels));+ findings.push(...contactFindings(context, root, intent, wheels));+ findings.push(...steeringFindings(context, root, intent, wheels));+ }+ findings.push(...supportContactFindings(context, root, intent));+ findings.push(...propulsionFindings(context, root, intent));+ return findings;}-function evaluateVegetationAdvisoryQa(context) {- return inspectFoliageAdvisory(fixtureInput(context));+function evaluateVehicleQa(context) {+ if (context.intent.category !== "vehicle" || !context.intent.vehicle)+ return [];+ return inspectMobility({+ scene: context.scene,+ profile: context.intent.qaProfile || PROFILE2,+ mobility: { ...context.intent.vehicle, frontFrame: "+X" }+ });}-var PROFILE3 = "vegetation.semantic", VEGETATION_CONTACT_TOLERANCE_METERS = 0.02, RASTER_SIZE = 48, stable7 = (value) => Math.round(value * 1e6) / 1e6, CLUTTER_NAME, CANOPY_PATTERNS, TRUNK_PATTERNS, BRANCH_PATTERNS, VEGETATION_GROWTH_BANDS_V1, PROFILE_BANDS, VEGETATION_CONTACT_QA_RULE, VEGETATION_ADVISORY_QA_RULE, VEGETATION_QA_RULES;-var init_vegetation = __esm(() => {+var PROFILE2 = "vehicle.semantic", CENTER_RATIO = 0.03, CENTER_MINIMUM = 0.01, AXIS_TOLERANCE_DEGREES = 1, PAIR_TOLERANCE = 0.015, CONTACT_TOLERANCE = 0.02, VEHICLE_QA_RULE, VEHICLE_ADVISORY_QA_RULE, VEHICLE_QA_RULES;+var init_vehicle2 = __esm(() => {init_contracts();+ init_vehicle();init_registry();- CLUTTER_NAME = /(?:^|[._ -])(?:terrain|soil|dirt|mound|rock|stone|pot|planter|grass[._ -]?skirt|base[._ -]?(?:disk|plate))(?:$|[._ -])/i;- CANOPY_PATTERNS = [/(?:^|[._ -])(?:canopy|foliage|leaf|leaves|needle|frond)(?:$|[._ -])/i];- TRUNK_PATTERNS = [/(?:^|[._ -])(?:trunk|stem|stalk|branch-primary)(?:$|[._ -])/i];- BRANCH_PATTERNS = [- /(?:^|[._ -])(?:branch|twig|bough|limb)(?:$|[._ -])/i,- /^vegetation\.branch(?:\.|$)/i- ];- VEGETATION_GROWTH_BANDS_V1 = Object.freeze({- tree: {- trunk: { taper: [0.35, 1.05], lengthRadius: [4, 80] },- branch: { taper: [0.12, 1.05], lengthRadius: [4, 100] }- },- conifer: {- trunk: { taper: [0.25, 1.05], lengthRadius: [6, 110] },- branch: { taper: [0.1, 1.05], lengthRadius: [5, 140] }- },- shrub: {- trunk: { taper: [0.25, 1.1], lengthRadius: [2, 65] },- branch: { taper: [0.1, 1.1], lengthRadius: [2, 80] }- },- grass: {- trunk: { taper: [0.05, 1.15], lengthRadius: [6, 260] },- branch: { taper: [0.05, 1.15], lengthRadius: [5, 260] }- },- "frond/palm": {- trunk: { taper: [0.35, 1.05], lengthRadius: [6, 140] },- branch: { taper: [0.04, 1.1], lengthRadius: [8, 300] }- },- vine: {- trunk: { taper: [0.1, 1.15], lengthRadius: [8, 320] },- branch: { taper: [0.04, 1.15], lengthRadius: [8, 360] }- },- "crop/flower": {- trunk: { taper: [0.15, 1.1], lengthRadius: [5, 220] },- branch: { taper: [0.05, 1.15], lengthRadius: [4, 240] }- },- succulent: {- trunk: { taper: [0.3, 1.2], lengthRadius: [1.2, 35] },- branch: { taper: [0.15, 1.2], lengthRadius: [1.2, 50] }- },- cactus: {- trunk: { taper: [0.45, 1.15], lengthRadius: [1.5, 45] },- branch: { taper: [0.35, 1.15], lengthRadius: [1.5, 35] }- },- fungus: {- trunk: { taper: [0.25, 1.25], lengthRadius: [1.2, 45] },- branch: { taper: [0.1, 1.25], lengthRadius: [1.2, 60] }- },- aquatic: {- trunk: { taper: [0.08, 1.15], lengthRadius: [4, 260] },- branch: { taper: [0.04, 1.15], lengthRadius: [4, 300] }- },- "bare/dead": {- trunk: { taper: [0.25, 1.05], lengthRadius: [4, 100] },- branch: { taper: [0.08, 1.05], lengthRadius: [3, 140] }- },- custom: {- trunk: { taper: [0.05, 1.25], lengthRadius: [1.2, 320] },- branch: { taper: [0.03, 1.25], lengthRadius: [1.2, 360] }- }- });- PROFILE_BANDS = Object.freeze({- broadleaf: {- occupancy: { front: [0.4, 0.99], side: [0.4, 0.99], top: [0.32, 0.99] },- ratio: [1.5, 120]- },- conifer: {- occupancy: { front: [0.32, 0.97], side: [0.32, 0.97], top: [0.2, 0.95] },- ratio: [1, 100]- },- topiary: {- occupancy: { front: [0.62, 1], side: [0.62, 1], top: [0.58, 1] },- ratio: [1, 120]- },- "bare/dead": {- occupancy: { front: [0, 0.08], side: [0, 0.08], top: [0, 0.08] },- ratio: [0, 0.2]- }- });- VEGETATION_CONTACT_QA_RULE = {- id: "VEGETATION_CONTACT_PROFILE",- profile: PROFILE3,- scope: { kind: "category", category: "vegetation" },+ init_vehicle_advisory();+ VEHICLE_QA_RULE = {+ id: "VEHICLE_PROFILE",+ profile: PROFILE2,+ scope: { kind: "category", category: "vehicle" },ruleClass: "exact",owner: KILN_ENGINE_QA_OWNER,- promotion: conformancePromotionAuthorization("vegetation-contact-v1", "src/qa/vegetation.test.ts", "8ad8f1753fc76e5e1b0114ad7d7f2c6c02c6f1c60953727027219424422a8ac4"),+ promotion: conformancePromotionAuthorization("vehicle-qa-v1", "src/qa/vehicle.test.ts", "3dfd250883b2605a4e8e4fded5ed8ded9e891680853af3fca3c5127771db47d7"),defaultMode: "enforce",- evaluate: evaluateVegetationContactQa+ evaluate: (context) => evaluateVehicleQa(context).filter((finding) => finding.disposition === "block")};- VEGETATION_ADVISORY_QA_RULE = {- id: "VEGETATION_ADVISORY_PROFILE",- profile: "vegetation.advisory",- scope: { kind: "category", category: "vegetation" },+ VEHICLE_ADVISORY_QA_RULE = {+ id: "VEHICLE_ADVISORY_PROFILE",+ profile: "vehicle.advisory",+ scope: { kind: "category", category: "vehicle" },ruleClass: "heuristic",owner: KILN_ENGINE_QA_OWNER,defaultMode: "observe",- evaluate: evaluateVegetationAdvisoryQa+ evaluate: (context) => evaluateVehicleQa(context).filter((finding) => finding.disposition !== "block")};- VEGETATION_QA_RULES = [- VEGETATION_CONTACT_QA_RULE,- VEGETATION_ADVISORY_QA_RULE+ VEHICLE_QA_RULES = [+ VEHICLE_QA_RULE,+ VEHICLE_ADVISORY_QA_RULE,+ VEHICLE_W6_ADVISORY_QA_RULE];});-// src/skin-binding.ts-import * as THREE16 from "three";-function topRoot(node) {- while (node.parent)- node = node.parent;- return node;+// src/qa/vegetation.ts+import * as THREE17 from "three";+function rolesOf2(node) {+ return readSemanticMetadataV1(node)?.roles ?? [];}-function assertMatrix(matrix, label) {- if (!matrix.elements.every((value) => Number.isFinite(value) && Number.isFinite(Math.fround(value))) || !Number.isFinite(matrix.determinant()) || matrix.determinant() === 0 || !matrix.clone().invert().elements.every((value) => Number.isFinite(value) && Number.isFinite(Math.fround(value))))- throw new RangeError(`createSkinnedPart ${label} must have finite invertible bind transforms.`);+function pathOf(node, root) {+ const names = [];+ let cursor = node;+ while (cursor) {+ names.push(cursor.name || cursor.type);+ if (cursor === root)+ break;+ cursor = cursor.parent;+ }+ return names.reverse().join("/");}-function createSkinnedPart(name, geometry, material, options) {- try {- return buildSkinnedPart(name, geometry, material, options);- } catch (error) {- if (error instanceof TypeError || error instanceof RangeError)- throw new AuthoringDiagnosticError("SKIN_BINDING_ARGUMENT", error.message);- throw error;+function localPoint3(rootInverse, node) {+ return node.getWorldPosition(new THREE17.Vector3).applyMatrix4(rootInverse);+}+function meshLocalBox(mesh, rootInverse) {+ if (!(mesh.geometry instanceof THREE17.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 THREE17.Box3;+ const count = mesh instanceof THREE17.InstancedMesh ? mesh.count : 1;+ for (let index = 0;index < count; index++) {+ const transform = base.clone();+ if (mesh instanceof THREE17.InstancedMesh) {+ const instance = new THREE17.Matrix4;+ mesh.getMatrixAt(index, instance);+ transform.multiply(instance);+ }+ result.union(source.clone().applyMatrix4(transform));}+ return result;}-function buildSkinnedPart(name, geometry, material, options) {- if (typeof name !== "string" || !name.trim() || THREE16.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.");- const materials = Array.isArray(material) ? material : [material];- if (!materials.length || materials.some((value) => !value?.isMaterial))- throw new TypeError("createSkinnedPart requires a material or nonempty material array.");- if (!options?.parent?.isObject3D)- throw new TypeError("createSkinnedPart requires an existing parent in the bone hierarchy.");- const { bones, indices, weights, parent } = options;- if (!Array.isArray(bones) || bones.length < 1 || bones.length > GEOMETRY_ALLOCATION_LIMITS.skinBones)- throw new RangeError(`createSkinnedPart bone limit is 1..${GEOMETRY_ALLOCATION_LIMITS.skinBones}.`);- if (options.normalizeWeights !== undefined && typeof options.normalizeWeights !== "boolean")- throw new TypeError("createSkinnedPart normalizeWeights must be boolean.");- const top = topRoot(parent), names = new Set, members = new Set;- 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 || THREE16.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);- }- top.traverse((node) => {- if (names.has(node.name) && !members.has(node))- throw new TypeError(`createSkinnedPart ambiguous bone name: ${node.name}.`);+function collectRenderableBounds(root) {+ root.updateWorldMatrix(true, true);+ const inverse = root.matrixWorld.clone().invert();+ const values = [];+ root.traverseVisible((node) => {+ if (!(node instanceof THREE17.Mesh))+ return;+ const box = meshLocalBox(node, inverse);+ if (!box)+ return;+ const roles = rolesOf2(node);+ values.push({ node, box, roles, source: roles.length > 0 ? "semantic" : "fallback" });});- const position = geometry.getAttribute("position"), count = position?.count;- if (position?.itemSize !== 3 || !Number.isSafeInteger(count) || count < 1 || count > GEOMETRY_ALLOCATION_LIMITS.skinVertices)- throw new RangeError(`createSkinnedPart position vertex limit is 1..${GEOMETRY_ALLOCATION_LIMITS.skinVertices} xyz vertices.`);- if (geometry.hasAttribute("skinIndex") || geometry.hasAttribute("skinWeight"))- throw new TypeError("createSkinnedPart geometry already contains binding attributes; provide unbound geometry.");- let bytes = count * 4 * (2 + 4);- const attributes = [- geometry.getIndex(),- ...Object.values(geometry.attributes),- ...Object.values(geometry.morphAttributes).flat()- ];- for (const attribute of attributes) {- if (!attribute)- continue;- bytes += attribute.array.byteLength;- if (!Number.isSafeInteger(bytes) || bytes > GEOMETRY_ALLOCATION_LIMITS.skinAttributeBytes)- throw new RangeError(`createSkinnedPart attribute allocation limit is ${GEOMETRY_ALLOCATION_LIMITS.skinAttributeBytes} bytes.`);- }- if (!indices || !weights || indices.length !== count * 4 || weights.length !== count * 4)- throw new RangeError("createSkinnedPart requires exactly four indices and weights per vertex.");- for (let vertex = 0;vertex < count; vertex++) {- let sum = 0;- for (let lane = 0;lane < 4; lane++) {- const i = vertex * 4 + lane, index = indices[i], weight = weights[i];- if (!Number.isInteger(index) || index < 0 || index >= bones.length)- throw new RangeError(`createSkinnedPart vertex ${vertex} lane ${lane} has an invalid bone index.`);- if (!Number.isFinite(weight) || weight < 0)- throw new RangeError(`createSkinnedPart vertex ${vertex} lane ${lane} needs a finite nonnegative weight.`);- if (!options.normalizeWeights && weight > 1)- throw new RangeError(`createSkinnedPart vertex ${vertex} weights must be <=1 and sum to one; request normalizeWeights explicitly.`);- sum += weight;+ return values;+}+function finding4(context, value) {+ return { ...value, profile: context.profile || PROFILE3 };+}+function vegetationIntent(intent) {+ return intent.category === "vegetation" ? intent.vegetation : undefined;+}+function inspectFoliageContact(context) {+ const trusted = context.foliage;+ if (!trusted?.grounded || !(context.scene instanceof THREE17.Object3D))+ return [];+ const planeY = context.groundPlaneY ?? 0;+ const root = context.scene;+ root.updateWorldMatrix(true, true);+ const inverse = root.matrixWorld.clone().invert();+ const contacts = [];+ const semanticSupports = [];+ root.traverseVisible((node) => {+ const metadata = readSemanticMetadataV1(node);+ const roles = metadata?.roles ?? [];+ if (roles.some((role) => role === "vegetation.contact" || role === "vegetation.contact.ground" || role === "contact.ground")) {+ const frame = metadata?.frames.find((value) => value.id === "ground-contact" || value.id === "vegetation-ground-contact");+ contacts.push({+ node,+ ...frame ? { frameTranslation: frame.translation } : {}+ });}- if (!Number.isFinite(sum) || sum <= 0 || !options.normalizeWeights && Math.abs(sum - 1) > 0.00001)- throw new RangeError(`createSkinnedPart vertex ${vertex} has an invalid weight sum; require one or explicitly normalize a positive finite sum.`);+ if (roles.some((role) => role === "vegetation.trunk" || role === "vegetation.stem" || role === "vegetation.root" || role === "vegetation.base" || role.startsWith("vegetation.support."))) {+ semanticSupports.push(node);+ }+ });+ if (contacts.length === 0) {+ return [+ finding4(context, {+ code: "VEG_CONTACT_MISSING",+ disposition: "block",+ dimension: "categoryReadiness",+ message: "Grounded foliage requires one semantic ground-contact marker.",+ affected: { node: root.name || "vegetation-root" },+ measurement: { name: "groundContactCount", actual: 0, expected: ">=1" },+ viewHints: ["right", "vegetation.base-contact"],+ repairText: `Add a vegetation.contact.ground semantic marker at asset-local Y=${planeY} and seat the plant base on it.`+ })+ ];}- for (const key of ["position", "rotation", "scale"])- if (options[key] !== undefined)- assertFiniteTriple(`createSkinnedPart ${key}`, options[key]);- const local = new THREE16.Matrix4().compose(new THREE16.Vector3(...options.position ?? [0, 0, 0]), new THREE16.Quaternion().setFromEuler(new THREE16.Euler(...(options.rotation ?? [0, 0, 0]).map(THREE16.MathUtils.degToRad))), new THREE16.Vector3(...options.scale ?? [1, 1, 1]));- top.updateWorldMatrix(true, true);- const bind = new THREE16.Matrix4().multiplyMatrices(parent.matrixWorld, local);- assertMatrix(bind, "mesh");- for (const bone of bones) {- assertMatrix(bone.matrixWorld, `bone ${bone.name}`);+ const findings = [];+ for (const contact of contacts) {+ const contactPoint = contact.frameTranslation ? new THREE17.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)+ continue;+ const floating = offset > 0;+ findings.push(finding4(context, {+ code: floating ? "VEG_CONTACT_FLOATING" : "VEG_CONTACT_BURIED",+ disposition: "block",+ dimension: "categoryReadiness",+ message: `${contact.node.name || "Vegetation contact"} is ${Math.abs(offset).toFixed(6)} m ${floating ? "above" : "below"} asset-local ground.`,+ affected: {+ node: contact.node.name || "vegetation-contact",+ nodePath: pathOf(contact.node, root)+ },+ measurement: {+ name: "contactY",+ actual: stable7(y),+ expected: planeY,+ threshold: VEGETATION_CONTACT_TOLERANCE_METERS,+ unit: "m"+ },+ viewHints: ["right", "vegetation.base-contact"],+ repairText: `Move ${contact.node.name || "the contact marker"} or its ground-contact frame to asset-local Y=${planeY} without moving unrelated canopy parts.`+ }));}- const skinIndices = new Uint16Array(indices.length), skinWeights = new Float32Array(weights.length);- for (let vertex = 0;vertex < count; vertex++) {- const start = vertex * 4;- const sum = options.normalizeWeights ? weights[start] + weights[start + 1] + weights[start + 2] + weights[start + 3] : 1;- for (let lane = 0;lane < 4; lane++) {- skinIndices[start + lane] = indices[start + lane];- skinWeights[start + lane] = weights[start + lane] / sum;- }+ for (const support of semanticSupports) {+ let minimumY = Infinity;+ support.traverseVisible((node) => {+ if (!(node instanceof THREE17.Mesh))+ return;+ const box = meshLocalBox(node, inverse);+ if (box)+ minimumY = Math.min(minimumY, box.min.y);+ });+ if (!Number.isFinite(minimumY) || minimumY >= planeY - VEGETATION_CONTACT_TOLERANCE_METERS)+ continue;+ findings.push(finding4(context, {+ code: "VEG_MATERIAL_BURIED",+ disposition: "block",+ dimension: "categoryReadiness",+ message: `${support.name || "Vegetation support"} extends materially below the standalone ground plane.`,+ affected: { node: support.name || "vegetation-support", nodePath: pathOf(support, root) },+ measurement: {+ name: "supportMinimumY",+ actual: stable7(minimumY),+ expected: planeY,+ threshold: VEGETATION_CONTACT_TOLERANCE_METERS,+ unit: "m"+ },+ viewHints: ["right", "vegetation.base-contact"],+ repairText: `Raise or trim the declared trunk/stem/root support so its visible material stops at Y=${planeY}.`+ }));}- const owned = geometry.clone();- owned.setAttribute("skinIndex", new THREE16.BufferAttribute(skinIndices, 4));- owned.setAttribute("skinWeight", new THREE16.BufferAttribute(skinWeights, 4));- const mesh = new THREE16.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(THREE16.MathUtils.degToRad));- if (options.scale)- mesh.scale.fromArray(options.scale);- if (options.semantic)- stampSemanticMetadataV1(mesh, options.semantic);- const skeleton = new THREE16.Skeleton([...bones], bones.map((bone) => bone.matrixWorld.clone().invert()));- mesh.bind(skeleton, bind);- parent.add(mesh);- mesh.updateWorldMatrix(true, false);- return mesh;+ return findings;}-var init_skin_binding = __esm(() => {- init_authoring_diagnostic();- init_contracts();- init_geometry_budget();-});--// src/character.ts-import * as THREE17 from "three";-function validRole(value) {- return typeof value === "string" && /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(value);+function materialNames(node) {+ if (!(node instanceof THREE17.Mesh))+ return [];+ const materials = Array.isArray(node.material) ? node.material : [node.material];+ return materials.filter(Boolean).map((material) => material.name ?? "");}-function validateUnitVector(value, path, issues) {- if (!isFiniteTuple2(value, 3)) {- issues.push({ code: "INVALID_AXIS", path, message: `${path} must be three finite numbers.` });- return false;- }- const magnitude = Math.hypot(...value);- if (Math.abs(magnitude - 1) > 0.000001) {- issues.push({ code: "NON_UNIT_AXIS", path, message: `${path} must be normalized.` });- return false;+function inspectFoliageScope(context) {+ const trusted = context.foliage;+ if (!trusted?.standalone || !(context.scene instanceof THREE17.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 THREE17.Box3);+ const overallSize = overall.getSize(new THREE17.Vector3);+ const findings = [];+ for (const value of renderables) {+ const size = value.box.getSize(new THREE17.Vector3);+ const center = value.box.getCenter(new THREE17.Vector3);+ const names = [value.node.name, ...value.roles];+ const nameEvidence = names.some((name) => CLUTTER_NAME.test(name));+ const roleEvidence = value.roles.some((role) => /(?:terrain|soil|rock|pot|planter|base)/i.test(role));+ const materialEvidence = materialNames(value.node).some((name) => CLUTTER_NAME.test(name));+ const footprintRatio = size.x * size.z / Math.max(0.000000001, overallSize.x * overallSize.z);+ const flatEvidence = footprintRatio >= 0.35 && size.y <= Math.max(0.08, overallSize.y * 0.08) && center.y <= (context.groundPlaneY ?? 0) + VEGETATION_CONTACT_TOLERANCE_METERS + size.y;+ const evidence = [nameEvidence, roleEvidence, materialEvidence, flatEvidence].filter(Boolean);+ if (evidence.length < 2)+ continue;+ findings.push(finding4(context, {+ code: "VEG_SCOPE_EXTRA",+ disposition: "warn",+ dimension: "promptAlignment",+ message: `${value.node.name || "Renderable"} is likely unrequested standalone-vegetation base clutter; review before removal.`,+ affected: {+ node: value.node.name || "vegetation-extra",+ nodePath: pathOf(value.node, root)+ },+ measurement: {+ name: "scopeEvidence",+ actual: [+ nameEvidence ? "name" : "",+ roleEvidence ? "role" : "",+ materialEvidence ? "material" : "",+ flatEvidence ? "flat-footprint" : ""+ ].filter(Boolean).join(","),+ expected: "standalone plant/fungus only"+ },+ viewHints: ["top", "three-quarter", "vegetation.base-contact"]+ }));}- return true;+ return findings;}-function cloneCharacterJointDescriptorV1(descriptor) {- return {- schemaVersion: KILN_CHARACTER_JOINT_SCHEMA_VERSION,- role: descriptor.role,- aliases: [...descriptor.aliases],- ...descriptor.parentRole ? { parentRole: descriptor.parentRole } : {},- side: descriptor.side,- rest: {- translation: tuple3(descriptor.rest.translation),- rotation: tuple4(descriptor.rest.rotation),- scale: tuple3(descriptor.rest.scale)- },- localForwardAxis: tuple3(descriptor.localForwardAxis),- localBendAxis: tuple3(descriptor.localBendAxis),- endEffector: descriptor.endEffector,- contact: descriptor.contact- };+function unionVolume(boxes) {+ if (boxes.length === 0)+ return 0;+ const union = boxes.reduce((result, box) => result.union(box), new THREE17.Box3);+ const size = union.getSize(new THREE17.Vector3);+ return size.x * size.y * size.z;}-function validateCharacterJointDescriptorV1(value) {- const issues = [];- if (!isRecord2(value)) {- return {- valid: false,- issues: [- { code: "EXPECTED_OBJECT", path: "", message: "Joint descriptor must be an object." }- ]- };- }- if (value.schemaVersion !== KILN_CHARACTER_JOINT_SCHEMA_VERSION) {- issues.push({- code: "UNSUPPORTED_SCHEMA_VERSION",- path: "schemaVersion",- message: `schemaVersion must be ${KILN_CHARACTER_JOINT_SCHEMA_VERSION}.`- });- }- if (!validRole(value.role)) {- issues.push({- code: "INVALID_ROLE",- path: "role",- message: "role must be a stable lowercase ID."- });- }- if (!Array.isArray(value.aliases) || value.aliases.some((alias) => typeof alias !== "string" || alias.trim().length === 0)) {- issues.push({- code: "INVALID_ALIASES",- path: "aliases",- message: "aliases must be non-empty strings."- });- } else if (new Set(value.aliases).size !== value.aliases.length) {- issues.push({ code: "DUPLICATE_ALIAS", path: "aliases", message: "aliases must be unique." });- }- if (value.parentRole !== undefined && !validRole(value.parentRole)) {- issues.push({- code: "INVALID_PARENT_ROLE",- path: "parentRole",- message: "parentRole must be a stable lowercase ID."- });- }- if (!CHARACTER_JOINT_SIDES.includes(value.side)) {- issues.push({- code: "INVALID_SIDE",- path: "side",- message: "side must be left, right, or center."- });- }- if (!isRecord2(value.rest)) {- issues.push({ code: "INVALID_REST", path: "rest", message: "rest transform is required." });- } else {- if (!isFiniteTuple2(value.rest.translation, 3)) {- issues.push({- code: "INVALID_REST_TRANSLATION",- path: "rest.translation",- message: "rest.translation must be three finite meters."- });- }- if (!isFiniteTuple2(value.rest.rotation, 4)) {- issues.push({- code: "INVALID_REST_ROTATION",- path: "rest.rotation",- message: "rest.rotation must be a finite quaternion."- });- } else if (Math.abs(Math.hypot(...value.rest.rotation) - 1) > 0.000001) {- issues.push({- code: "NON_UNIT_REST_ROTATION",- path: "rest.rotation",- message: "rest.rotation must be normalized."- });- }- if (!isFiniteTuple2(value.rest.scale, 3) || value.rest.scale.some((component) => component <= 0)) {- issues.push({- code: "INVALID_REST_SCALE",- path: "rest.scale",- message: "rest.scale must contain three positive finite values."- });+function projectedOccupancy(boxes, axes) {+ if (boxes.length === 0)+ return 0;+ const minimum = [Infinity, Infinity];+ const maximum = [-Infinity, -Infinity];+ for (const box of boxes) {+ const min = [box.min.x, box.min.y, box.min.z];+ const max = [box.max.x, box.max.y, box.max.z];+ for (const dimension of [0, 1]) {+ minimum[dimension] = Math.min(minimum[dimension], min[axes[dimension]]);+ maximum[dimension] = Math.max(maximum[dimension], max[axes[dimension]]);}}- const forwardAxis = value.localForwardAxis;- const bendAxis = value.localBendAxis;- const forwardValid = validateUnitVector(forwardAxis, "localForwardAxis", issues);- const bendValid = validateUnitVector(bendAxis, "localBendAxis", issues);- if (forwardValid && bendValid) {- const dot = forwardAxis[0] * bendAxis[0] + forwardAxis[1] * bendAxis[1] + forwardAxis[2] * bendAxis[2];- if (Math.abs(dot) > 0.000001) {- issues.push({- code: "NON_ORTHOGONAL_AXES",- path: "localBendAxis",- message: "local forward and bend axes must be orthogonal."- });+ const spans = [maximum[0] - minimum[0], maximum[1] - minimum[1]];+ if (spans[0] <= 0.000000001 || spans[1] <= 0.000000001)+ return 0;+ const occupied = new Uint8Array(RASTER_SIZE * RASTER_SIZE);+ for (const box of boxes) {+ const min = [box.min.x, box.min.y, box.min.z];+ const max = [box.max.x, box.max.y, box.max.z];+ const x0 = Math.max(0, Math.floor((min[axes[0]] - minimum[0]) / spans[0] * (RASTER_SIZE - 1)));+ const x1 = Math.min(RASTER_SIZE - 1, Math.ceil((max[axes[0]] - minimum[0]) / spans[0] * (RASTER_SIZE - 1)));+ const y0 = Math.max(0, Math.floor((min[axes[1]] - minimum[1]) / spans[1] * (RASTER_SIZE - 1)));+ const y1 = Math.min(RASTER_SIZE - 1, Math.ceil((max[axes[1]] - minimum[1]) / spans[1] * (RASTER_SIZE - 1)));+ for (let y = y0;y <= y1; y++) {+ for (let x = x0;x <= x1; x++)+ occupied[y * RASTER_SIZE + x] = 1;}}- if (typeof value.endEffector !== "boolean") {- issues.push({- code: "INVALID_END_EFFECTOR",- path: "endEffector",- message: "endEffector must be boolean."- });- }- if (typeof value.contact !== "boolean") {- issues.push({ code: "INVALID_CONTACT", path: "contact", message: "contact must be boolean." });- }- if (issues.length > 0)- return { valid: false, issues };- return {- valid: true,- value: cloneCharacterJointDescriptorV1(value),- issues- };+ return stable7(occupied.reduce((sum, value) => sum + value, 0) / occupied.length);}-function createCharacterJointDescriptorV1(input) {- const descriptor = {- schemaVersion: KILN_CHARACTER_JOINT_SCHEMA_VERSION,- role: input.role,- aliases: [...input.aliases ?? []],- ...input.parentRole ? { parentRole: input.parentRole } : {},- side: input.side ?? "center",- rest: {- translation: tuple3(input.rest?.translation ?? [0, 0, 0]),- rotation: tuple4(input.rest?.rotation ?? IDENTITY_QUATERNION),- scale: tuple3(input.rest?.scale ?? UNIT_SCALE)- },- localForwardAxis: tuple3(input.localForwardAxis ?? FORWARD_AXIS),- localBendAxis: tuple3(input.localBendAxis ?? BEND_AXIS),- endEffector: input.endEffector ?? false,- contact: input.contact ?? false- };- const validation = validateCharacterJointDescriptorV1(descriptor);- if (!validation.valid || !validation.value) {- throw new TypeError(`Invalid CharacterJointDescriptorV1: ${validation.issues.map((issue) => `${issue.path}: ${issue.message}`).join("; ")}`);- }- return validation.value;+function matchesAny(value, patterns) {+ const candidates = [value.node.name, ...value.roles];+ return candidates.some((candidate) => patterns.some((pattern) => pattern.test(candidate)));}-function validateCharacterRigGraphV1(value) {- const issues = [];- if (!isRecord2(value)) {- return {- valid: false,- issues: [{ code: "EXPECTED_OBJECT", path: "", message: "Rig graph must be an object." }]- };- }- if (value.schemaVersion !== KILN_CHARACTER_JOINT_SCHEMA_VERSION) {- issues.push({- code: "UNSUPPORTED_SCHEMA_VERSION",- path: "schemaVersion",- message: `schemaVersion must be ${KILN_CHARACTER_JOINT_SCHEMA_VERSION}.`- });+function measurementSource(values) {+ if (values.length === 0)+ return "none";+ const semantic = values.some((value) => value.source === "semantic");+ const fallback = values.some((value) => value.source === "fallback");+ return semantic && fallback ? "mixed" : semantic ? "semantic" : "fallback";+}+function roleOrNameSource(value, patterns) {+ if (value.roles.some((role) => patterns.some((pattern) => pattern.test(role))))+ return "semantic";+ if (patterns.some((pattern) => pattern.test(value.node.name)))+ return "fallback";+ return;+}+function growthCandidates(root) {+ const result = [];+ for (const value of collectRenderableBounds(root)) {+ const branchSource = roleOrNameSource(value, BRANCH_PATTERNS);+ const trunkSource = roleOrNameSource(value, TRUNK_PATTERNS);+ if (branchSource)+ result.push({ ...value, kind: "branch", growthSource: branchSource });+ else if (trunkSource)+ result.push({ ...value, kind: "trunk", growthSource: trunkSource });}- if (!CHARACTER_BODY_PLANS2.includes(value.bodyPlan)) {- issues.push({- code: "INVALID_BODY_PLAN",- path: "bodyPlan",- message: "bodyPlan is unsupported."- });+ return result;+}+function boxDistanceToPoint(box, point) {+ return box.distanceToPoint(point);+}+function endpointRadius(position, axis, axisValue, tolerance, scale) {+ const radialAxes = [0, 1, 2].filter((value) => value !== axis);+ const points = [];+ const point = new THREE17.Vector3;+ for (let index = 0;index < position.count; index++) {+ point.fromBufferAttribute(position, index);+ if (Math.abs(point.getComponent(axis) - axisValue) <= tolerance)+ points.push(point.clone());}- if (!Array.isArray(value.joints) || value.joints.length === 0) {- issues.push({ code: "INVALID_JOINTS", path: "joints", message: "joints must not be empty." });+ if (points.length === 0)+ return;+ const center = new THREE17.Vector3;+ center.setComponent(axis, axisValue);+ for (const radialAxis of radialAxes) {+ center.setComponent(radialAxis, points.reduce((sum, value) => sum + value.getComponent(radialAxis), 0) / points.length);}- const joints = [];- if (Array.isArray(value.joints)) {- value.joints.forEach((joint, index) => {- const result = validateCharacterJointDescriptorV1(joint);- if (result.value)- joints.push(result.value);- for (const issue of result.issues) {- issues.push({ ...issue, path: `joints[${index}]${issue.path ? `.${issue.path}` : ""}` });- }- });+ let radius = 0;+ for (const value of points) {+ const a = (value.getComponent(radialAxes[0]) - center.getComponent(radialAxes[0])) * Math.abs(scale.getComponent(radialAxes[0]));+ const b = (value.getComponent(radialAxes[1]) - center.getComponent(radialAxes[1])) * Math.abs(scale.getComponent(radialAxes[1]));+ radius = Math.max(radius, Math.hypot(a, b));}- const byRole = new Map;- const aliasOwners = new Map;- joints.forEach((joint, index) => {- const prior = byRole.get(joint.role);- if (prior !== undefined) {- issues.push({- code: "DUPLICATE_JOINT_ROLE",- path: `joints[${index}].role`,- message: `role ${joint.role} duplicates joints[${prior}].role.`- });- } else- byRole.set(joint.role, index);- for (const alias of joint.aliases) {- const owner = aliasOwners.get(alias);- if (owner && owner !== joint.role) {- issues.push({- code: "AMBIGUOUS_JOINT_ALIAS",- path: `joints[${index}].aliases`,- message: `alias ${alias} is already owned by ${owner}.`- });- } else- aliasOwners.set(alias, joint.role);- }- });- joints.forEach((joint, index) => {- if (joint.parentRole && !byRole.has(joint.parentRole)) {- issues.push({- code: "UNKNOWN_PARENT_ROLE",- path: `joints[${index}].parentRole`,- message: `parentRole ${joint.parentRole} is not declared.`- });- }- const seen = new Set([joint.role]);- let cursor = joint.parentRole;- while (cursor) {- if (seen.has(cursor)) {- issues.push({- code: "JOINT_PARENT_CYCLE",- path: `joints[${index}].parentRole`,- message: `parent chain for ${joint.role} contains a cycle at ${cursor}.`- });- break;- }- seen.add(cursor);- const parentIndex = byRole.get(cursor);- cursor = parentIndex === undefined ? undefined : joints[parentIndex]?.parentRole;- }- });- if (issues.length > 0)- return { valid: false, issues };+ return { center, radius };+}+function growthNodeMeasurement(root, candidate, allCandidates, band) {+ if (!(candidate.node instanceof THREE17.Mesh))+ return;+ const geometry = candidate.node.geometry;+ const position = geometry.getAttribute("position");+ if (!position || position.count < 2)+ return;+ geometry.computeBoundingBox();+ const geometryBox = geometry.boundingBox;+ if (!geometryBox || geometryBox.isEmpty())+ return;+ root.updateWorldMatrix(true, true);+ const relative = root.matrixWorld.clone().invert().multiply(candidate.node.matrixWorld);+ const relativeScale = new THREE17.Vector3;+ relative.decompose(new THREE17.Vector3, new THREE17.Quaternion, relativeScale);+ const size = geometryBox.getSize(new THREE17.Vector3);+ const scaledSizes = [+ Math.abs(size.x * relativeScale.x),+ Math.abs(size.y * relativeScale.y),+ Math.abs(size.z * relativeScale.z)+ ];+ const axis = scaledSizes.indexOf(Math.max(...scaledSizes));+ const minimum = geometryBox.min.getComponent(axis);+ const maximum = geometryBox.max.getComponent(axis);+ const tolerance = Math.max(0.000001, (maximum - minimum) * 0.0001);+ const first = endpointRadius(position, axis, minimum, tolerance, relativeScale);+ const second = endpointRadius(position, axis, maximum, tolerance, relativeScale);+ if (!first || !second)+ return;+ const firstPoint = first.center.clone().applyMatrix4(relative);+ const secondPoint = second.center.clone().applyMatrix4(relative);+ const supportBoxes = allCandidates.filter((value) => value !== candidate).map((value) => value.box);+ let firstIsBase;+ if (candidate.kind === "trunk") {+ firstIsBase = firstPoint.y <= secondPoint.y;+ } else if (supportBoxes.length > 0) {+ const firstGap = Math.min(...supportBoxes.map((box) => boxDistanceToPoint(box, firstPoint)));+ const secondGap = Math.min(...supportBoxes.map((box) => boxDistanceToPoint(box, secondPoint)));+ firstIsBase = Math.abs(firstGap - secondGap) > 0.000001 ? firstGap < secondGap : first.radius >= second.radius;+ } else {+ firstIsBase = first.radius >= second.radius;+ }+ const baseRadius = firstIsBase ? first.radius : second.radius;+ const tipRadius = firstIsBase ? second.radius : first.radius;+ const length = firstPoint.distanceTo(secondPoint);+ const averageRadius = (baseRadius + tipRadius) / 2;+ const taperRatio = baseRadius > 0.000000001 ? tipRadius / baseRadius : null;+ const lengthRadiusRatio = averageRadius > 0.000000001 ? length / averageRadius : null;+ const selected = band[candidate.kind];+ const taperOutlier = taperRatio !== null && (taperRatio < selected.taper[0] || taperRatio > selected.taper[1]);+ const lengthRadiusOutlier = lengthRadiusRatio !== null && (lengthRadiusRatio < selected.lengthRadius[0] || lengthRadiusRatio > selected.lengthRadius[1]);return {- valid: true,- value: {- schemaVersion: KILN_CHARACTER_JOINT_SCHEMA_VERSION,- bodyPlan: value.bodyPlan,- joints: joints.map(cloneCharacterJointDescriptorV1)- },- issues+ node: candidate.node.name || candidate.kind,+ nodePath: pathOf(candidate.node, root),+ kind: candidate.kind,+ source: candidate.growthSource,+ lengthMeters: stable7(length),+ baseRadiusMeters: stable7(baseRadius),+ tipRadiusMeters: stable7(tipRadius),+ taperRatio: taperRatio === null ? null : stable7(taperRatio),+ lengthRadiusRatio: lengthRadiusRatio === null ? null : stable7(lengthRadiusRatio),+ expectedTaperRatio: `${selected.taper[0]}..${selected.taper[1]}`,+ expectedLengthRadiusRatio: `${selected.lengthRadius[0]}..${selected.lengthRadius[1]}`,+ taperOutlier,+ lengthRadiusOutlier};}-function createCharacterRigGraphV1(input) {- const graph = {- schemaVersion: KILN_CHARACTER_JOINT_SCHEMA_VERSION,- bodyPlan: input.bodyPlan,- joints: input.joints.map((joint) => ("schemaVersion" in joint) ? cloneCharacterJointDescriptorV1(joint) : createCharacterJointDescriptorV1(joint))+function measureFoliageGrowth(foliage, root) {+ const requested = foliage?.subtype;+ const subtype = requested && Object.hasOwn(VEGETATION_GROWTH_BANDS_V1, requested) ? requested : "custom";+ const candidates = growthCandidates(root);+ const nodes = candidates.map((candidate) => growthNodeMeasurement(root, candidate, candidates, VEGETATION_GROWTH_BANDS_V1[subtype])).filter((value) => Boolean(value));+ return {+ schemaVersion: 1,+ subtype,+ source: measurementSource(nodes),+ trunkCount: nodes.filter((value) => value.kind === "trunk").length,+ branchCount: nodes.filter((value) => value.kind === "branch").length,+ nodes};- const result = validateCharacterRigGraphV1(graph);- if (!result.valid || !result.value) {- throw new TypeError(`Invalid CharacterRigGraphV1: ${result.issues.map((issue) => `${issue.path}: ${issue.message}`).join("; ")}`);+}+function inspectFoliageGrowth(context) {+ if (!context.foliage || !(context.scene instanceof THREE17.Object3D))+ return [];+ const measured = measureFoliageGrowth(context.foliage, context.scene);+ const findings = [];+ for (const node of measured.nodes) {+ if (node.taperOutlier) {+ findings.push(finding4(context, {+ code: "VEG_GROWTH_TAPER_OUTLIER",+ disposition: "warn",+ dimension: "categoryReadiness",+ message: `${node.kind} taper measurement is outside the ${measured.subtype} measurement band.`,+ affected: { node: node.node, nodePath: node.nodePath },+ measurement: {+ name: "tipToBaseRadiusRatio",+ actual: node.taperRatio ?? "unmeasurable",+ expected: node.expectedTaperRatio,+ unit: "ratio"+ },+ viewHints: ["front", "right", "three-quarter"]+ }));+ }+ if (node.lengthRadiusOutlier) {+ findings.push(finding4(context, {+ code: "VEG_GROWTH_LENGTH_RADIUS_OUTLIER",+ disposition: "warn",+ dimension: "categoryReadiness",+ message: `${node.kind} length/radius measurement is outside the ${measured.subtype} measurement band.`,+ affected: { node: node.node, nodePath: node.nodePath },+ measurement: {+ name: "lengthToAverageRadiusRatio",+ actual: node.lengthRadiusRatio ?? "unmeasurable",+ expected: node.expectedLengthRadiusRatio,+ unit: "ratio"+ },+ viewHints: ["front", "right", "three-quarter"]+ }));+ }}- return result.value;+ return findings;}-function readCharacterRigGraphV1(target) {- const value = target.userData?.[KILN_CHARACTER_RIG_EXTRAS_KEY];- const result = validateCharacterRigGraphV1(value);- return result.valid ? result.value : undefined;+function distanceBetweenBoxes(a, b) {+ const dx = Math.max(0, a.min.x - b.max.x, b.min.x - a.max.x);+ const dy = Math.max(0, a.min.y - b.max.y, b.min.y - a.max.y);+ const dz = Math.max(0, a.min.z - b.max.z, b.min.z - a.max.z);+ return Math.hypot(dx, dy, dz);}-function axisQuaternion(from, to) {- const value = new THREE17.Quaternion().setFromUnitVectors(new THREE17.Vector3(...from), new THREE17.Vector3(...to));- return [value.x, value.y, value.z, value.w];+function measureVegetationFoliageAttachment(root) {+ const renderables = collectRenderableBounds(root);+ const support = renderables.filter((value) => roleOrNameSource(value, TRUNK_PATTERNS) || roleOrNameSource(value, BRANCH_PATTERNS));+ const foliage = renderables.filter((value) => roleOrNameSource(value, CANOPY_PATTERNS));+ const clusters = foliage.map((value) => {+ const size = value.box.getSize(new THREE17.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";+ return {+ node: value.node.name || "foliage-cluster",+ nodePath: pathOf(value.node, root),+ source,+ nearestSupport: nearest?.candidate.node.name || null,+ gapMeters: nearest ? stable7(nearest.gap) : null,+ thresholdMeters: threshold,+ detached: !nearest || nearest.gap > threshold+ };+ });+ return {+ schemaVersion: 1,+ source: measurementSource(clusters),+ supportNodeCount: support.length,+ foliageClusterCount: foliage.length,+ clusters+ };}-function stampCharacterJointDescriptorV1(target, input) {- const descriptor = createCharacterJointDescriptorV1(input);- const frames = [- { id: "rest", translation: [0, 0, 0], rotation: IDENTITY_QUATERNION },- {- id: "forward",- translation: [0, 0, 0],- rotation: axisQuaternion(FORWARD_AXIS, descriptor.localForwardAxis)- },- {- id: "bend",- translation: [0, 0, 0],- rotation: axisQuaternion([0, 1, 0], descriptor.localBendAxis)+function inspectFoliageAttachment(context) {+ if (!context.foliage || !(context.scene instanceof THREE17.Object3D))+ return [];+ return measureVegetationFoliageAttachment(context.scene).clusters.filter((cluster) => cluster.detached).map((cluster) => finding4(context, {+ code: "VEG_FOLIAGE_DETACHED",+ disposition: "warn",+ dimension: "categoryReadiness",+ message: `${cluster.node} is detached from the nearest inferred or semantic branch/twig support.`,+ affected: { node: cluster.node, nodePath: cluster.nodePath },+ measurement: {+ name: "foliageSupportGap",+ actual: cluster.gapMeters ?? "no support found",+ expected: `<=${cluster.thresholdMeters}`,+ threshold: cluster.thresholdMeters,+ unit: "m"},- ...descriptor.endEffector ? [- {- id: "end-effector",- translation: [0, 0, 0],- rotation: IDENTITY_QUATERNION- }- ] : [],- ...descriptor.contact ? [- {- id: "contact",- translation: [0, 0, 0],- rotation: IDENTITY_QUATERNION- }- ] : []- ];- stampSemanticMetadataV1(target, {- roles: [- "skeleton.joint",- `joint.${descriptor.role}`,- `joint.side.${descriptor.side}`,- ...descriptor.aliases.map((alias) => `joint.alias.${alias}`),- ...descriptor.endEffector ? ["joint.end-effector"] : [],- ...descriptor.contact ? ["contact.ground"] : []- ],- relationships: descriptor.parentRole ? [{ kind: "parent-joint", target: `joint.${descriptor.parentRole}`, targetType: "role" }] : [],- frames,- sockets: [- ...descriptor.endEffector ? [- {- id: "end-effector",- type: "character.attachment",- frame: "end-effector",- compatibleTypes: ["character.held-item"]- }- ] : [],- ...descriptor.contact ? [- {- id: "ground-contact",- type: "character.contact",- frame: "contact",- compatibleTypes: ["world.ground"]- }- ] : []- ]- });- target.userData[KILN_CHARACTER_JOINT_EXTRAS_KEY] = cloneCharacterJointDescriptorV1(descriptor);- return target;-}-function readCharacterJointDescriptorV1(target) {- const value = target.userData?.[KILN_CHARACTER_JOINT_EXTRAS_KEY];- const result = validateCharacterJointDescriptorV1(value);- return result.valid ? result.value : undefined;+ viewHints: ["front", "right", "three-quarter"]+ }));}-function characterJointNodeName(chainName, role) {- const safeChain = chainName.trim().replace(/[^A-Za-z0-9]+/g, "_").replace(/^_+|_+$/g, "");- const safeRole = role.replace(/[^A-Za-z0-9]+/g, "_");- if (!safeChain)- throw new TypeError("createJointChain chainName must contain a letter or number.");- return `Joint_${safeChain}_${safeRole}`;+function relativeTransformSignature(root, node) {+ const matrix = root.matrixWorld.clone().invert().multiply(node.matrixWorld);+ const scale = new THREE17.Vector3;+ const quaternion = new THREE17.Quaternion;+ matrix.decompose(new THREE17.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));+ return values.join(",");}-function createJointChain(chainName, segments, options = {}) {- if (segments.length === 0)- throw new TypeError("createJointChain requires at least one segment.");- const seen = new Set;- const nodes = [];- const descriptors = [];- const byRole = new Map;- let parent = options.parent;- let parentRole = options.parentRole;- for (const segment of segments) {- if (seen.has(segment.role))- throw new TypeError(`Duplicate joint-chain role: ${segment.role}.`);- seen.add(segment.role);- const descriptor = createCharacterJointDescriptorV1({- role: segment.role,- aliases: segment.aliases,- ...parentRole ? { parentRole } : {},- side: segment.side,- rest: {- translation: segment.offset,- rotation: segment.restRotation,- scale: segment.restScale- },- localForwardAxis: segment.localForwardAxis,- localBendAxis: segment.localBendAxis,- endEffector: segment.endEffector,- contact: segment.contact+function measureFoliageRepetition(requirements, root) {+ root.updateWorldMatrix(true, true);+ const foliage = collectRenderableBounds(root).filter((value) => roleOrNameSource(value, CANOPY_PATTERNS));+ const bySignature = new Map;+ for (const value of foliage) {+ const signature = relativeTransformSignature(root, value.node);+ const entries = bySignature.get(signature) ?? [];+ entries.push(value);+ bySignature.set(signature, entries);+ }+ const identicalTransformGroups = [...bySignature.entries()].filter(([, values]) => values.length >= 3).map(([signature, values]) => ({+ signature,+ nodes: values.map((value) => value.node.name || "foliage-cluster").sort()+ })).sort((a, b) => a.signature.localeCompare(b.signature));+ const supports = collectRenderableBounds(root).filter((value) => roleOrNameSource(value, TRUNK_PATTERNS));+ const centerBox = supports.reduce((box, value) => box.union(value.box), new THREE17.Box3);+ const centers = foliage.map((value) => value.box.getCenter(new THREE17.Vector3));+ const center = centerBox.isEmpty() ? centers.reduce((result, value) => result.add(value), new THREE17.Vector3).multiplyScalar(centers.length > 0 ? 1 / centers.length : 0) : centerBox.getCenter(new THREE17.Vector3);+ const radial = centers.map((value) => ({+ angle: Math.atan2(value.z - center.z, value.x - center.x),+ radius: Math.hypot(value.x - center.x, value.z - center.z)+ })).filter((value) => value.radius > 0.000001).sort((a, b) => a.angle - b.angle);+ let radialGapRangeRadians = null;+ let radialRadiusSpreadRatio = null;+ let perfectRadialLockstep = false;+ if (radial.length >= 4) {+ const gaps = radial.map((value, index) => {+ const next = radial[(index + 1) % radial.length];+ const raw = next.angle - value.angle;+ return raw > 0 ? raw : raw + Math.PI * 2;});- const node = new THREE17.Object3D;- node.name = characterJointNodeName(chainName, segment.role);- node.position.fromArray(descriptor.rest.translation);- node.quaternion.fromArray(descriptor.rest.rotation);- node.scale.fromArray(descriptor.rest.scale);- stampCharacterJointDescriptorV1(node, descriptor);- if (parent)- parent.add(node);- parent = node;- parentRole = descriptor.role;- nodes.push(node);- descriptors.push(descriptor);- byRole.set(descriptor.role, node);+ radialGapRangeRadians = stable7(Math.max(...gaps) - Math.min(...gaps));+ const radii = radial.map((value) => value.radius);+ const meanRadius = radii.reduce((sum, value) => sum + value, 0) / radii.length;+ radialRadiusSpreadRatio = stable7((Math.max(...radii) - Math.min(...radii)) / meanRadius);+ perfectRadialLockstep = radialGapRangeRadians <= 0.02 && radialRadiusSpreadRatio <= 0.02;}+ const suppressedForTopiary = requirements?.canopyProfile === "topiary";return {- root: nodes[0],- end: nodes[nodes.length - 1],- nodes,- byRole,- descriptors+ schemaVersion: 1,+ source: measurementSource(foliage.map((value) => ({+ source: roleOrNameSource(value, CANOPY_PATTERNS) ?? "fallback"+ }))),+ clusterCount: foliage.length,+ identicalTransformGroups,+ radialGapRangeRadians,+ radialRadiusSpreadRatio,+ perfectRadialLockstep,+ suppressedForTopiary};}-function createBoneChain(chainName, segments, options = {}) {- try {- return buildBoneChain(chainName, segments, options);- } catch (error) {- if (error instanceof TypeError || error instanceof RangeError)- throw new AuthoringDiagnosticError("BONE_CHAIN_ARGUMENT", error.message);- throw error;+function inspectFoliageRepetition(context) {+ if (!context.foliage || !(context.scene instanceof THREE17.Object3D))+ return [];+ const measured = measureFoliageRepetition(context.foliage, context.scene);+ if (measured.suppressedForTopiary)+ return [];+ const findings = measured.identicalTransformGroups.map((group) => finding4(context, {+ code: "VEG_CLUSTER_TRANSFORM_REPEAT",+ disposition: "warn",+ dimension: "visualQuality",+ message: `${group.nodes.length} foliage clusters use an identical scale/rotation signature.`,+ affected: { node: group.nodes[0], nodePath: group.nodes.join(",") },+ measurement: {+ name: "identicalClusterTransformCount",+ actual: group.nodes.length,+ expected: "<3 outside formal topiary intent"+ },+ viewHints: ["front", "right", "top", "three-quarter"]+ }));+ if (measured.perfectRadialLockstep) {+ findings.push(finding4(context, {+ code: "VEG_CLUSTER_RADIAL_LOCKSTEP",+ disposition: "warn",+ dimension: "visualQuality",+ message: "Foliage clusters form a perfect equal-radius, equal-angle radial sequence.",+ measurement: {+ name: "radialGapAndRadiusSpread",+ actual: `${measured.radialGapRangeRadians},${measured.radialRadiusSpreadRatio}`,+ expected: "angle gap range >0.02 or radius spread ratio >0.02",+ unit: "ratio"+ },+ viewHints: ["top", "three-quarter"]+ }));}+ return findings;}-function buildBoneChain(chainName, segments, options = {}) {- if (!Array.isArray(segments) || segments.length < 1 || segments.length > GEOMETRY_ALLOCATION_LIMITS.skinBones)- throw new RangeError(`createBoneChain segment limit is 1..${GEOMETRY_ALLOCATION_LIMITS.skinBones}.`);- if (options.parent !== undefined && !options.parent.isObject3D)- throw new TypeError("createBoneChain parent must be an Object3D.");- const parentDescriptor = options.parent ? readCharacterJointDescriptorV1(options.parent) : undefined;- if (options.parentRole !== undefined && options.parentRole !== parentDescriptor?.role)- throw new TypeError("createBoneChain parentRole must match the declared parent joint.");- const roles = new Set, names = new Set;- if (options.parent) {- let top = options.parent;- while (top.parent)- top = top.parent;- top.traverse((node) => {- if (node.name)- names.add(node.name);- const descriptor = readCharacterJointDescriptorV1(node);- if (descriptor)- roles.add(descriptor.role);- });- }- let parentRole = parentDescriptor?.role;- const descriptors = segments.map((segment) => {- const descriptor = createCharacterJointDescriptorV1({- role: segment.role,- aliases: segment.aliases,- parentRole,- side: segment.side,- rest: {- translation: segment.offset,- rotation: segment.restRotation,- scale: segment.restScale- },- localForwardAxis: segment.localForwardAxis,- localBendAxis: segment.localBendAxis,- endEffector: segment.endEffector,- contact: segment.contact- });- const name = characterJointNodeName(chainName, descriptor.role);- if (roles.has(descriptor.role))- throw new TypeError(`createBoneChain duplicate role: ${descriptor.role}.`);- if (names.has(name))- throw new TypeError(`createBoneChain duplicate node name after sanitization: ${name}.`);- roles.add(descriptor.role);- names.add(name);- parentRole = descriptor.role;- return descriptor;- });- const nodes = descriptors.map((descriptor) => {- const node = new THREE17.Bone;- node.name = characterJointNodeName(chainName, descriptor.role);- node.position.fromArray(descriptor.rest.translation);- node.quaternion.fromArray(descriptor.rest.rotation);- node.scale.fromArray(descriptor.rest.scale);- stampCharacterJointDescriptorV1(node, descriptor);- return node;- });- for (let i = 1;i < nodes.length; i++)- nodes[i - 1].add(nodes[i]);- if (options.parent)- options.parent.add(nodes[0]);+function measureFoliageCanopy(profile, root) {+ const renderables = collectRenderableBounds(root);+ const canopy = renderables.filter((value) => matchesAny(value, CANOPY_PATTERNS));+ const trunk = renderables.filter((value) => matchesAny(value, TRUNK_PATTERNS));+ const semanticCanopy = canopy.some((value) => value.roles.length > 0);+ const source = canopy.length === 0 ? "none" : semanticCanopy ? "semantic" : "fallback";+ const canopyBoxes = canopy.map((value) => value.box);+ const trunkVolume = unionVolume(trunk.map((value) => value.box));+ const ratio = trunkVolume > 0.000000001 ? unionVolume(canopyBoxes) / trunkVolume : null;return {- root: nodes[0],- end: nodes[nodes.length - 1],- nodes,- byRole: new Map(descriptors.map((descriptor, i) => [descriptor.role, nodes[i]])),- descriptors- };-}-function collectCharacterJointNodes(root) {- const joints = [];- const visit = (node, parentPath, siblingIndex) => {+ schemaVersion: 1,+ profile,+ source,+ canopyNodeCount: canopy.length,+ trunkNodeCount: trunk.length,+ frontOccupancy: projectedOccupancy(canopyBoxes, [2, 1]),+ sideOccupancy: projectedOccupancy(canopyBoxes, [0, 1]),+ topOccupancy: projectedOccupancy(canopyBoxes, [0, 2]),+ canopyToTrunkVolumeRatio: ratio === null ? null : stable7(ratio)+ };+}+function inspectFoliageCanopy(context) {+ const trusted = context.foliage;+ if (!trusted?.canopyProfile || !(context.scene instanceof THREE17.Object3D))+ return [];+ const measurements = measureFoliageCanopy(trusted.canopyProfile, context.scene);+ const bands = PROFILE_BANDS[measurements.profile];+ const sparseFactor = trusted.growthState === "sparse" ? 0.55 : 1;+ const values = [+ ["FRONT", "frontOccupancy", measurements.frontOccupancy, bands.occupancy.front, "front"],+ ["SIDE", "sideOccupancy", measurements.sideOccupancy, bands.occupancy.side, "right"],+ ["TOP", "topOccupancy", measurements.topOccupancy, bands.occupancy.top, "top"]+ ];+ const findings = [];+ if (measurements.canopyNodeCount === 0 && measurements.profile !== "bare/dead") {+ findings.push(finding4(context, {+ code: "VEG_CANOPY_MISSING",+ disposition: "warn",+ dimension: "categoryReadiness",+ message: `The ${trusted.subtype ?? trusted.canopyProfile} profile resolved no semantic or inferred canopy renderables.`,+ measurement: { name: "canopyNodeCount", actual: 0, expected: ">=1" },+ viewHints: ["front", "right", "top"]+ }));+ return findings;+ }+ for (const [suffix, name, actual, [minimum, maximum], view] of values) {+ const adjustedMinimum = minimum * sparseFactor;+ if (actual >= adjustedMinimum && actual <= maximum)+ continue;+ findings.push(finding4(context, {+ code: `VEG_CANOPY_OCCUPANCY_${suffix}`,+ disposition: "warn",+ dimension: "categoryReadiness",+ message: `${measurements.profile} ${name} is outside its measured ${trusted.growthState ?? "default"} profile band.`,+ measurement: {+ name,+ actual,+ expected: `${stable7(adjustedMinimum)}..${maximum}`,+ threshold: adjustedMinimum,+ unit: "ratio"+ },+ viewHints: [view, "three-quarter"]+ }));+ }+ const ratio = measurements.canopyToTrunkVolumeRatio;+ if (ratio !== null && (ratio < bands.ratio[0] || ratio > bands.ratio[1])) {+ findings.push(finding4(context, {+ code: "VEG_CANOPY_TRUNK_RATIO",+ disposition: "warn",+ dimension: "categoryReadiness",+ message: `${measurements.profile} canopy-to-trunk volume ratio is outside its subtype band.`,+ measurement: {+ name: "canopyToTrunkVolumeRatio",+ actual: ratio,+ expected: `${bands.ratio[0]}..${bands.ratio[1]}`,+ threshold: bands.ratio[0],+ unit: "ratio"+ },+ viewHints: ["front", "right", "top"]+ }));+ }+ return findings;+}+function materialValue(material) {+ if (!(material instanceof THREE17.MeshStandardMaterial) && !(material instanceof THREE17.MeshBasicMaterial)) {+ return;+ }+ const color = material.color;+ return 0.2126 * color.r + 0.7152 * color.g + 0.0722 * color.b;+}+function measureFoliageMaterials(mode, root) {+ const values = [];+ let foliageNodeCount = 0;+ root.traverseVisible((node) => {+ if (!(node instanceof THREE17.Mesh))+ return;+ const bounds = {+ node,+ box: new THREE17.Box3,+ roles: rolesOf2(node),+ source: rolesOf2(node).length > 0 ? "semantic" : "fallback"+ };+ if (!matchesAny(bounds, CANOPY_PATTERNS))+ return;+ foliageNodeCount++;+ const materials = Array.isArray(node.material) ? node.material : [node.material];+ for (const material of materials) {+ const value = materialValue(material);+ if (value !== undefined)+ values.push(value);+ }+ });+ const buckets = new Set(values.map((value) => Math.round(value * 20) / 20));+ const valueRange = values.length > 0 ? Math.max(...values) - Math.min(...values) : 0;+ const optimized = mode === "flatOptimized";+ return {+ schemaVersion: 1,+ mode,+ foliageNodeCount,+ valueRoleCount: buckets.size,+ valueRange: stable7(valueRange),+ coherent: optimized ? buckets.size <= 1 : buckets.size >= 2 && buckets.size <= 6 && valueRange >= 0.03+ };+}+function inspectFoliageMaterial(context) {+ if (!context.foliage || !(context.scene instanceof THREE17.Object3D))+ return [];+ if (!context.materialMode)+ return [];+ const measured = measureFoliageMaterials(context.materialMode, context.scene);+ if (measured.foliageNodeCount === 0 || measured.coherent)+ return [];+ const optimized = measured.mode === "flatOptimized";+ return [+ finding4(context, {+ code: "VEG_FOLIAGE_VALUE_ROLES",+ disposition: "warn",+ dimension: "visualQuality",+ message: optimized ? "Optimized vegetation should retain one coherent foliage value role." : "Rich organic vegetation should use two to six restrained foliage value roles with visible value separation.",+ measurement: {+ name: "foliageValueRoles",+ actual: `${measured.valueRoleCount} roles; range ${measured.valueRange}`,+ expected: optimized ? "1 role" : "2..6 roles; range >=0.03"+ },+ viewHints: ["front", "three-quarter"]+ })+ ];+}+function inspectFoliageAdvisory(context) {+ return [+ ...inspectFoliageScope(context),+ ...inspectFoliageGrowth(context),+ ...inspectFoliageCanopy(context),+ ...inspectFoliageAttachment(context),+ ...inspectFoliageRepetition(context),+ ...inspectFoliageMaterial(context)+ ];+}+function fixtureInput(context) {+ return {+ scene: context.scene,+ profile: context.intent.qaProfile,+ foliage: vegetationIntent(context.intent),+ materialMode: context.intent.material.mode+ };+}+function evaluateVegetationContactQa(context) {+ return inspectFoliageContact(fixtureInput(context));+}+function evaluateVegetationAdvisoryQa(context) {+ return inspectFoliageAdvisory(fixtureInput(context));+}+var PROFILE3 = "vegetation.semantic", VEGETATION_CONTACT_TOLERANCE_METERS = 0.02, RASTER_SIZE = 48, stable7 = (value) => Math.round(value * 1e6) / 1e6, CLUTTER_NAME, CANOPY_PATTERNS, TRUNK_PATTERNS, BRANCH_PATTERNS, VEGETATION_GROWTH_BANDS_V1, PROFILE_BANDS, VEGETATION_CONTACT_QA_RULE, VEGETATION_ADVISORY_QA_RULE, VEGETATION_QA_RULES;+var init_vegetation = __esm(() => {+ init_contracts();+ init_registry();+ CLUTTER_NAME = /(?:^|[._ -])(?:terrain|soil|dirt|mound|rock|stone|pot|planter|grass[._ -]?skirt|base[._ -]?(?:disk|plate))(?:$|[._ -])/i;+ CANOPY_PATTERNS = [/(?:^|[._ -])(?:canopy|foliage|leaf|leaves|needle|frond)(?:$|[._ -])/i];+ TRUNK_PATTERNS = [/(?:^|[._ -])(?:trunk|stem|stalk|branch-primary)(?:$|[._ -])/i];+ BRANCH_PATTERNS = [+ /(?:^|[._ -])(?:branch|twig|bough|limb)(?:$|[._ -])/i,+ /^vegetation\.branch(?:\.|$)/i+ ];+ VEGETATION_GROWTH_BANDS_V1 = Object.freeze({+ tree: {+ trunk: { taper: [0.35, 1.05], lengthRadius: [4, 80] },+ branch: { taper: [0.12, 1.05], lengthRadius: [4, 100] }+ },+ conifer: {+ trunk: { taper: [0.25, 1.05], lengthRadius: [6, 110] },+ branch: { taper: [0.1, 1.05], lengthRadius: [5, 140] }+ },+ shrub: {+ trunk: { taper: [0.25, 1.1], lengthRadius: [2, 65] },+ branch: { taper: [0.1, 1.1], lengthRadius: [2, 80] }+ },+ grass: {+ trunk: { taper: [0.05, 1.15], lengthRadius: [6, 260] },+ branch: { taper: [0.05, 1.15], lengthRadius: [5, 260] }+ },+ "frond/palm": {+ trunk: { taper: [0.35, 1.05], lengthRadius: [6, 140] },+ branch: { taper: [0.04, 1.1], lengthRadius: [8, 300] }+ },+ vine: {+ trunk: { taper: [0.1, 1.15], lengthRadius: [8, 320] },+ branch: { taper: [0.04, 1.15], lengthRadius: [8, 360] }+ },+ "crop/flower": {+ trunk: { taper: [0.15, 1.1], lengthRadius: [5, 220] },+ branch: { taper: [0.05, 1.15], lengthRadius: [4, 240] }+ },+ succulent: {+ trunk: { taper: [0.3, 1.2], lengthRadius: [1.2, 35] },+ branch: { taper: [0.15, 1.2], lengthRadius: [1.2, 50] }+ },+ cactus: {+ trunk: { taper: [0.45, 1.15], lengthRadius: [1.5, 45] },+ branch: { taper: [0.35, 1.15], lengthRadius: [1.5, 35] }+ },+ fungus: {+ trunk: { taper: [0.25, 1.25], lengthRadius: [1.2, 45] },+ branch: { taper: [0.1, 1.25], lengthRadius: [1.2, 60] }+ },+ aquatic: {+ trunk: { taper: [0.08, 1.15], lengthRadius: [4, 260] },+ branch: { taper: [0.04, 1.15], lengthRadius: [4, 300] }+ },+ "bare/dead": {+ trunk: { taper: [0.25, 1.05], lengthRadius: [4, 100] },+ branch: { taper: [0.08, 1.05], lengthRadius: [3, 140] }+ },+ custom: {+ trunk: { taper: [0.05, 1.25], lengthRadius: [1.2, 320] },+ branch: { taper: [0.03, 1.25], lengthRadius: [1.2, 360] }+ }+ });+ PROFILE_BANDS = Object.freeze({+ broadleaf: {+ occupancy: { front: [0.4, 0.99], side: [0.4, 0.99], top: [0.32, 0.99] },+ ratio: [1.5, 120]+ },+ conifer: {+ occupancy: { front: [0.32, 0.97], side: [0.32, 0.97], top: [0.2, 0.95] },+ ratio: [1, 100]+ },+ topiary: {+ occupancy: { front: [0.62, 1], side: [0.62, 1], top: [0.58, 1] },+ ratio: [1, 120]+ },+ "bare/dead": {+ occupancy: { front: [0, 0.08], side: [0, 0.08], top: [0, 0.08] },+ ratio: [0, 0.2]+ }+ });+ VEGETATION_CONTACT_QA_RULE = {+ id: "VEGETATION_CONTACT_PROFILE",+ profile: PROFILE3,+ scope: { kind: "category", category: "vegetation" },+ ruleClass: "exact",+ owner: KILN_ENGINE_QA_OWNER,+ promotion: conformancePromotionAuthorization("vegetation-contact-v1", "src/qa/vegetation.test.ts", "8ad8f1753fc76e5e1b0114ad7d7f2c6c02c6f1c60953727027219424422a8ac4"),+ defaultMode: "enforce",+ evaluate: evaluateVegetationContactQa+ };+ VEGETATION_ADVISORY_QA_RULE = {+ id: "VEGETATION_ADVISORY_PROFILE",+ profile: "vegetation.advisory",+ scope: { kind: "category", category: "vegetation" },+ ruleClass: "heuristic",+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: "observe",+ evaluate: evaluateVegetationAdvisoryQa+ };+ VEGETATION_QA_RULES = [+ VEGETATION_CONTACT_QA_RULE,+ VEGETATION_ADVISORY_QA_RULE+ ];+});++// src/skin-binding.ts+import * as THREE18 from "three";+function topRoot(node) {+ while (node.parent)+ node = node.parent;+ return node;+}+function assertMatrix(matrix, label) {+ if (!matrix.elements.every((value) => Number.isFinite(value) && Number.isFinite(Math.fround(value))) || !Number.isFinite(matrix.determinant()) || matrix.determinant() === 0 || !matrix.clone().invert().elements.every((value) => Number.isFinite(value) && Number.isFinite(Math.fround(value))))+ throw new RangeError(`createSkinnedPart ${label} must have finite invertible bind transforms.`);+}+function createSkinnedPart(name, geometry, material, options) {+ try {+ return buildSkinnedPart(name, geometry, material, options);+ } catch (error) {+ if (error instanceof TypeError || error instanceof RangeError)+ throw new AuthoringDiagnosticError("SKIN_BINDING_ARGUMENT", error.message);+ throw error;+ }+}+function buildSkinnedPart(name, geometry, material, options) {+ if (typeof name !== "string" || !name.trim() || THREE18.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.");+ const materials = Array.isArray(material) ? material : [material];+ if (!materials.length || materials.some((value) => !value?.isMaterial))+ throw new TypeError("createSkinnedPart requires a material or nonempty material array.");+ if (!options?.parent?.isObject3D)+ throw new TypeError("createSkinnedPart requires an existing parent in the bone hierarchy.");+ const { bones, indices, weights, parent } = options;+ if (!Array.isArray(bones) || bones.length < 1 || bones.length > GEOMETRY_ALLOCATION_LIMITS.skinBones)+ throw new RangeError(`createSkinnedPart bone limit is 1..${GEOMETRY_ALLOCATION_LIMITS.skinBones}.`);+ if (options.normalizeWeights !== undefined && typeof options.normalizeWeights !== "boolean")+ throw new TypeError("createSkinnedPart normalizeWeights must be boolean.");+ const top = topRoot(parent), names = new Set, members = new Set;+ 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 || THREE18.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);+ }+ top.traverse((node) => {+ if (names.has(node.name) && !members.has(node))+ throw new TypeError(`createSkinnedPart ambiguous bone name: ${node.name}.`);+ });+ const position = geometry.getAttribute("position"), count = position?.count;+ if (position?.itemSize !== 3 || !Number.isSafeInteger(count) || count < 1 || count > GEOMETRY_ALLOCATION_LIMITS.skinVertices)+ throw new RangeError(`createSkinnedPart position vertex limit is 1..${GEOMETRY_ALLOCATION_LIMITS.skinVertices} xyz vertices.`);+ if (geometry.hasAttribute("skinIndex") || geometry.hasAttribute("skinWeight"))+ throw new TypeError("createSkinnedPart geometry already contains binding attributes; provide unbound geometry.");+ let bytes = count * 4 * (2 + 4);+ const attributes = [+ geometry.getIndex(),+ ...Object.values(geometry.attributes),+ ...Object.values(geometry.morphAttributes).flat()+ ];+ for (const attribute of attributes) {+ if (!attribute)+ continue;+ bytes += attribute.array.byteLength;+ if (!Number.isSafeInteger(bytes) || bytes > GEOMETRY_ALLOCATION_LIMITS.skinAttributeBytes)+ throw new RangeError(`createSkinnedPart attribute allocation limit is ${GEOMETRY_ALLOCATION_LIMITS.skinAttributeBytes} bytes.`);+ }+ if (!indices || !weights || indices.length !== count * 4 || weights.length !== count * 4)+ throw new RangeError("createSkinnedPart requires exactly four indices and weights per vertex.");+ for (let vertex = 0;vertex < count; vertex++) {+ let sum = 0;+ for (let lane = 0;lane < 4; lane++) {+ const i = vertex * 4 + lane, index = indices[i], weight = weights[i];+ if (!Number.isInteger(index) || index < 0 || index >= bones.length)+ throw new RangeError(`createSkinnedPart vertex ${vertex} lane ${lane} has an invalid bone index.`);+ if (!Number.isFinite(weight) || weight < 0)+ throw new RangeError(`createSkinnedPart vertex ${vertex} lane ${lane} needs a finite nonnegative weight.`);+ if (!options.normalizeWeights && weight > 1)+ throw new RangeError(`createSkinnedPart vertex ${vertex} weights must be <=1 and sum to one; request normalizeWeights explicitly.`);+ sum += weight;+ }+ if (!Number.isFinite(sum) || sum <= 0 || !options.normalizeWeights && Math.abs(sum - 1) > 0.00001)+ throw new RangeError(`createSkinnedPart vertex ${vertex} has an invalid weight sum; require one or explicitly normalize a positive finite sum.`);+ }+ for (const key of ["position", "rotation", "scale"])+ if (options[key] !== undefined)+ assertFiniteTriple(`createSkinnedPart ${key}`, options[key]);+ const local = new THREE18.Matrix4().compose(new THREE18.Vector3(...options.position ?? [0, 0, 0]), new THREE18.Quaternion().setFromEuler(new THREE18.Euler(...(options.rotation ?? [0, 0, 0]).map(THREE18.MathUtils.degToRad))), new THREE18.Vector3(...options.scale ?? [1, 1, 1]));+ top.updateWorldMatrix(true, true);+ const bind = new THREE18.Matrix4().multiplyMatrices(parent.matrixWorld, local);+ assertMatrix(bind, "mesh");+ for (const bone of bones) {+ assertMatrix(bone.matrixWorld, `bone ${bone.name}`);+ }+ const skinIndices = new Uint16Array(indices.length), skinWeights = new Float32Array(weights.length);+ for (let vertex = 0;vertex < count; vertex++) {+ const start = vertex * 4;+ const sum = options.normalizeWeights ? weights[start] + weights[start + 1] + weights[start + 2] + weights[start + 3] : 1;+ for (let lane = 0;lane < 4; lane++) {+ skinIndices[start + lane] = indices[start + lane];+ skinWeights[start + lane] = weights[start + lane] / sum;+ }+ }+ const owned = geometry.clone();+ owned.setAttribute("skinIndex", new THREE18.BufferAttribute(skinIndices, 4));+ owned.setAttribute("skinWeight", new THREE18.BufferAttribute(skinWeights, 4));+ const mesh = new THREE18.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(THREE18.MathUtils.degToRad));+ if (options.scale)+ mesh.scale.fromArray(options.scale);+ if (options.semantic)+ stampSemanticMetadataV1(mesh, options.semantic);+ const skeleton = new THREE18.Skeleton([...bones], bones.map((bone) => bone.matrixWorld.clone().invert()));+ mesh.bind(skeleton, bind);+ parent.add(mesh);+ mesh.updateWorldMatrix(true, false);+ return mesh;+}+var init_skin_binding = __esm(() => {+ init_authoring_diagnostic();+ init_contracts();+ init_geometry_budget();+});++// src/character.ts+import * as THREE19 from "three";+function validRole(value) {+ return typeof value === "string" && /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(value);+}+function validateUnitVector(value, path, issues) {+ if (!isFiniteTuple2(value, 3)) {+ issues.push({ code: "INVALID_AXIS", path, message: `${path} must be three finite numbers.` });+ return false;+ }+ const magnitude = Math.hypot(...value);+ if (Math.abs(magnitude - 1) > 0.000001) {+ issues.push({ code: "NON_UNIT_AXIS", path, message: `${path} must be normalized.` });+ return false;+ }+ return true;+}+function cloneCharacterJointDescriptorV1(descriptor) {+ return {+ schemaVersion: KILN_CHARACTER_JOINT_SCHEMA_VERSION,+ role: descriptor.role,+ aliases: [...descriptor.aliases],+ ...descriptor.parentRole ? { parentRole: descriptor.parentRole } : {},+ side: descriptor.side,+ rest: {+ translation: tuple3(descriptor.rest.translation),+ rotation: tuple4(descriptor.rest.rotation),+ scale: tuple3(descriptor.rest.scale)+ },+ localForwardAxis: tuple3(descriptor.localForwardAxis),+ localBendAxis: tuple3(descriptor.localBendAxis),+ endEffector: descriptor.endEffector,+ contact: descriptor.contact+ };+}+function validateCharacterJointDescriptorV1(value) {+ const issues = [];+ if (!isRecord2(value)) {+ return {+ valid: false,+ issues: [+ { code: "EXPECTED_OBJECT", path: "", message: "Joint descriptor must be an object." }+ ]+ };+ }+ if (value.schemaVersion !== KILN_CHARACTER_JOINT_SCHEMA_VERSION) {+ issues.push({+ code: "UNSUPPORTED_SCHEMA_VERSION",+ path: "schemaVersion",+ message: `schemaVersion must be ${KILN_CHARACTER_JOINT_SCHEMA_VERSION}.`+ });+ }+ if (!validRole(value.role)) {+ issues.push({+ code: "INVALID_ROLE",+ path: "role",+ message: "role must be a stable lowercase ID."+ });+ }+ if (!Array.isArray(value.aliases) || value.aliases.some((alias) => typeof alias !== "string" || alias.trim().length === 0)) {+ issues.push({+ code: "INVALID_ALIASES",+ path: "aliases",+ message: "aliases must be non-empty strings."+ });+ } else if (new Set(value.aliases).size !== value.aliases.length) {+ issues.push({ code: "DUPLICATE_ALIAS", path: "aliases", message: "aliases must be unique." });+ }+ if (value.parentRole !== undefined && !validRole(value.parentRole)) {+ issues.push({+ code: "INVALID_PARENT_ROLE",+ path: "parentRole",+ message: "parentRole must be a stable lowercase ID."+ });+ }+ if (!CHARACTER_JOINT_SIDES.includes(value.side)) {+ issues.push({+ code: "INVALID_SIDE",+ path: "side",+ message: "side must be left, right, or center."+ });+ }+ if (!isRecord2(value.rest)) {+ issues.push({ code: "INVALID_REST", path: "rest", message: "rest transform is required." });+ } else {+ if (!isFiniteTuple2(value.rest.translation, 3)) {+ issues.push({+ code: "INVALID_REST_TRANSLATION",+ path: "rest.translation",+ message: "rest.translation must be three finite meters."+ });+ }+ if (!isFiniteTuple2(value.rest.rotation, 4)) {+ issues.push({+ code: "INVALID_REST_ROTATION",+ path: "rest.rotation",+ message: "rest.rotation must be a finite quaternion."+ });+ } else if (Math.abs(Math.hypot(...value.rest.rotation) - 1) > 0.000001) {+ issues.push({+ code: "NON_UNIT_REST_ROTATION",+ path: "rest.rotation",+ message: "rest.rotation must be normalized."+ });+ }+ if (!isFiniteTuple2(value.rest.scale, 3) || value.rest.scale.some((component) => component <= 0)) {+ issues.push({+ code: "INVALID_REST_SCALE",+ path: "rest.scale",+ message: "rest.scale must contain three positive finite values."+ });+ }+ }+ const forwardAxis = value.localForwardAxis;+ const bendAxis = value.localBendAxis;+ const forwardValid = validateUnitVector(forwardAxis, "localForwardAxis", issues);+ const bendValid = validateUnitVector(bendAxis, "localBendAxis", issues);+ if (forwardValid && bendValid) {+ const dot = forwardAxis[0] * bendAxis[0] + forwardAxis[1] * bendAxis[1] + forwardAxis[2] * bendAxis[2];+ if (Math.abs(dot) > 0.000001) {+ issues.push({+ code: "NON_ORTHOGONAL_AXES",+ path: "localBendAxis",+ message: "local forward and bend axes must be orthogonal."+ });+ }+ }+ if (typeof value.endEffector !== "boolean") {+ issues.push({+ code: "INVALID_END_EFFECTOR",+ path: "endEffector",+ message: "endEffector must be boolean."+ });+ }+ if (typeof value.contact !== "boolean") {+ issues.push({ code: "INVALID_CONTACT", path: "contact", message: "contact must be boolean." });+ }+ if (issues.length > 0)+ return { valid: false, issues };+ return {+ valid: true,+ value: cloneCharacterJointDescriptorV1(value),+ issues+ };+}+function createCharacterJointDescriptorV1(input) {+ const descriptor = {+ schemaVersion: KILN_CHARACTER_JOINT_SCHEMA_VERSION,+ role: input.role,+ aliases: [...input.aliases ?? []],+ ...input.parentRole ? { parentRole: input.parentRole } : {},+ side: input.side ?? "center",+ rest: {+ translation: tuple3(input.rest?.translation ?? [0, 0, 0]),+ rotation: tuple4(input.rest?.rotation ?? IDENTITY_QUATERNION),+ scale: tuple3(input.rest?.scale ?? UNIT_SCALE)+ },+ localForwardAxis: tuple3(input.localForwardAxis ?? FORWARD_AXIS),+ localBendAxis: tuple3(input.localBendAxis ?? BEND_AXIS),+ endEffector: input.endEffector ?? false,+ contact: input.contact ?? false+ };+ const validation = validateCharacterJointDescriptorV1(descriptor);+ if (!validation.valid || !validation.value) {+ throw new TypeError(`Invalid CharacterJointDescriptorV1: ${validation.issues.map((issue) => `${issue.path}: ${issue.message}`).join("; ")}`);+ }+ return validation.value;+}+function validateCharacterRigGraphV1(value) {+ const issues = [];+ if (!isRecord2(value)) {+ return {+ valid: false,+ issues: [{ code: "EXPECTED_OBJECT", path: "", message: "Rig graph must be an object." }]+ };+ }+ if (value.schemaVersion !== KILN_CHARACTER_JOINT_SCHEMA_VERSION) {+ issues.push({+ code: "UNSUPPORTED_SCHEMA_VERSION",+ path: "schemaVersion",+ message: `schemaVersion must be ${KILN_CHARACTER_JOINT_SCHEMA_VERSION}.`+ });+ }+ if (!CHARACTER_BODY_PLANS2.includes(value.bodyPlan)) {+ issues.push({+ code: "INVALID_BODY_PLAN",+ path: "bodyPlan",+ message: "bodyPlan is unsupported."+ });+ }+ if (!Array.isArray(value.joints) || value.joints.length === 0) {+ issues.push({ code: "INVALID_JOINTS", path: "joints", message: "joints must not be empty." });+ }+ const joints = [];+ if (Array.isArray(value.joints)) {+ value.joints.forEach((joint, index) => {+ const result = validateCharacterJointDescriptorV1(joint);+ if (result.value)+ joints.push(result.value);+ for (const issue of result.issues) {+ issues.push({ ...issue, path: `joints[${index}]${issue.path ? `.${issue.path}` : ""}` });+ }+ });+ }+ const byRole = new Map;+ const aliasOwners = new Map;+ joints.forEach((joint, index) => {+ const prior = byRole.get(joint.role);+ if (prior !== undefined) {+ issues.push({+ code: "DUPLICATE_JOINT_ROLE",+ path: `joints[${index}].role`,+ message: `role ${joint.role} duplicates joints[${prior}].role.`+ });+ } else+ byRole.set(joint.role, index);+ for (const alias of joint.aliases) {+ const owner = aliasOwners.get(alias);+ if (owner && owner !== joint.role) {+ issues.push({+ code: "AMBIGUOUS_JOINT_ALIAS",+ path: `joints[${index}].aliases`,+ message: `alias ${alias} is already owned by ${owner}.`+ });+ } else+ aliasOwners.set(alias, joint.role);+ }+ });+ joints.forEach((joint, index) => {+ if (joint.parentRole && !byRole.has(joint.parentRole)) {+ issues.push({+ code: "UNKNOWN_PARENT_ROLE",+ path: `joints[${index}].parentRole`,+ message: `parentRole ${joint.parentRole} is not declared.`+ });+ }+ const seen = new Set([joint.role]);+ let cursor = joint.parentRole;+ while (cursor) {+ if (seen.has(cursor)) {+ issues.push({+ code: "JOINT_PARENT_CYCLE",+ path: `joints[${index}].parentRole`,+ message: `parent chain for ${joint.role} contains a cycle at ${cursor}.`+ });+ break;+ }+ seen.add(cursor);+ const parentIndex = byRole.get(cursor);+ cursor = parentIndex === undefined ? undefined : joints[parentIndex]?.parentRole;+ }+ });+ if (issues.length > 0)+ return { valid: false, issues };+ return {+ valid: true,+ value: {+ schemaVersion: KILN_CHARACTER_JOINT_SCHEMA_VERSION,+ bodyPlan: value.bodyPlan,+ joints: joints.map(cloneCharacterJointDescriptorV1)+ },+ issues+ };+}+function createCharacterRigGraphV1(input) {+ const graph = {+ schemaVersion: KILN_CHARACTER_JOINT_SCHEMA_VERSION,+ bodyPlan: input.bodyPlan,+ joints: input.joints.map((joint) => ("schemaVersion" in joint) ? cloneCharacterJointDescriptorV1(joint) : createCharacterJointDescriptorV1(joint))+ };+ const result = validateCharacterRigGraphV1(graph);+ if (!result.valid || !result.value) {+ throw new TypeError(`Invalid CharacterRigGraphV1: ${result.issues.map((issue) => `${issue.path}: ${issue.message}`).join("; ")}`);+ }+ return result.value;+}+function readCharacterRigGraphV1(target) {+ const value = target.userData?.[KILN_CHARACTER_RIG_EXTRAS_KEY];+ const result = validateCharacterRigGraphV1(value);+ return result.valid ? result.value : undefined;+}+function axisQuaternion(from, to) {+ const value = new THREE19.Quaternion().setFromUnitVectors(new THREE19.Vector3(...from), new THREE19.Vector3(...to));+ return [value.x, value.y, value.z, value.w];+}+function stampCharacterJointDescriptorV1(target, input) {+ const descriptor = createCharacterJointDescriptorV1(input);+ const frames = [+ { id: "rest", translation: [0, 0, 0], rotation: IDENTITY_QUATERNION },+ {+ id: "forward",+ translation: [0, 0, 0],+ rotation: axisQuaternion(FORWARD_AXIS, descriptor.localForwardAxis)+ },+ {+ id: "bend",+ translation: [0, 0, 0],+ rotation: axisQuaternion([0, 1, 0], descriptor.localBendAxis)+ },+ ...descriptor.endEffector ? [+ {+ id: "end-effector",+ translation: [0, 0, 0],+ rotation: IDENTITY_QUATERNION+ }+ ] : [],+ ...descriptor.contact ? [+ {+ id: "contact",+ translation: [0, 0, 0],+ rotation: IDENTITY_QUATERNION+ }+ ] : []+ ];+ stampSemanticMetadataV1(target, {+ roles: [+ "skeleton.joint",+ `joint.${descriptor.role}`,+ `joint.side.${descriptor.side}`,+ ...descriptor.aliases.map((alias) => `joint.alias.${alias}`),+ ...descriptor.endEffector ? ["joint.end-effector"] : [],+ ...descriptor.contact ? ["contact.ground"] : []+ ],+ relationships: descriptor.parentRole ? [{ kind: "parent-joint", target: `joint.${descriptor.parentRole}`, targetType: "role" }] : [],+ frames,+ sockets: [+ ...descriptor.endEffector ? [+ {+ id: "end-effector",+ type: "character.attachment",+ frame: "end-effector",+ compatibleTypes: ["character.held-item"]+ }+ ] : [],+ ...descriptor.contact ? [+ {+ id: "ground-contact",+ type: "character.contact",+ frame: "contact",+ compatibleTypes: ["world.ground"]+ }+ ] : []+ ]+ });+ target.userData[KILN_CHARACTER_JOINT_EXTRAS_KEY] = cloneCharacterJointDescriptorV1(descriptor);+ return target;+}+function readCharacterJointDescriptorV1(target) {+ const value = target.userData?.[KILN_CHARACTER_JOINT_EXTRAS_KEY];+ const result = validateCharacterJointDescriptorV1(value);+ return result.valid ? result.value : undefined;+}+function characterJointNodeName(chainName, role) {+ const safeChain = chainName.trim().replace(/[^A-Za-z0-9]+/g, "_").replace(/^_+|_+$/g, "");+ const safeRole = role.replace(/[^A-Za-z0-9]+/g, "_");+ if (!safeChain)+ throw new TypeError("createJointChain chainName must contain a letter or number.");+ return `Joint_${safeChain}_${safeRole}`;+}+function createJointChain(chainName, segments, options = {}) {+ if (segments.length === 0)+ throw new TypeError("createJointChain requires at least one segment.");+ const seen = new Set;+ const nodes = [];+ const descriptors = [];+ const byRole = new Map;+ let parent = options.parent;+ let parentRole = options.parentRole;+ for (const segment of segments) {+ if (seen.has(segment.role))+ throw new TypeError(`Duplicate joint-chain role: ${segment.role}.`);+ seen.add(segment.role);+ const descriptor = createCharacterJointDescriptorV1({+ role: segment.role,+ aliases: segment.aliases,+ ...parentRole ? { parentRole } : {},+ side: segment.side,+ rest: {+ translation: segment.offset,+ rotation: segment.restRotation,+ scale: segment.restScale+ },+ localForwardAxis: segment.localForwardAxis,+ localBendAxis: segment.localBendAxis,+ endEffector: segment.endEffector,+ contact: segment.contact+ });+ const node = new THREE19.Object3D;+ node.name = characterJointNodeName(chainName, segment.role);+ node.position.fromArray(descriptor.rest.translation);+ node.quaternion.fromArray(descriptor.rest.rotation);+ node.scale.fromArray(descriptor.rest.scale);+ stampCharacterJointDescriptorV1(node, descriptor);+ if (parent)+ parent.add(node);+ parent = node;+ parentRole = descriptor.role;+ nodes.push(node);+ descriptors.push(descriptor);+ byRole.set(descriptor.role, node);+ }+ return {+ root: nodes[0],+ end: nodes[nodes.length - 1],+ nodes,+ byRole,+ descriptors+ };+}+function createBoneChain(chainName, segments, options = {}) {+ try {+ return buildBoneChain(chainName, segments, options);+ } catch (error) {+ if (error instanceof TypeError || error instanceof RangeError)+ throw new AuthoringDiagnosticError("BONE_CHAIN_ARGUMENT", error.message);+ throw error;+ }+}+function buildBoneChain(chainName, segments, options = {}) {+ if (!Array.isArray(segments) || segments.length < 1 || segments.length > GEOMETRY_ALLOCATION_LIMITS.skinBones)+ throw new RangeError(`createBoneChain segment limit is 1..${GEOMETRY_ALLOCATION_LIMITS.skinBones}.`);+ if (options.parent !== undefined && !options.parent.isObject3D)+ throw new TypeError("createBoneChain parent must be an Object3D.");+ const parentDescriptor = options.parent ? readCharacterJointDescriptorV1(options.parent) : undefined;+ if (options.parentRole !== undefined && options.parentRole !== parentDescriptor?.role)+ throw new TypeError("createBoneChain parentRole must match the declared parent joint.");+ const roles = new Set, names = new Set;+ if (options.parent) {+ let top = options.parent;+ while (top.parent)+ top = top.parent;+ top.traverse((node) => {+ if (node.name)+ names.add(node.name);+ const descriptor = readCharacterJointDescriptorV1(node);+ if (descriptor)+ roles.add(descriptor.role);+ });+ }+ let parentRole = parentDescriptor?.role;+ const descriptors = segments.map((segment) => {+ const descriptor = createCharacterJointDescriptorV1({+ role: segment.role,+ aliases: segment.aliases,+ parentRole,+ side: segment.side,+ rest: {+ translation: segment.offset,+ rotation: segment.restRotation,+ scale: segment.restScale+ },+ localForwardAxis: segment.localForwardAxis,+ localBendAxis: segment.localBendAxis,+ endEffector: segment.endEffector,+ contact: segment.contact+ });+ const name = characterJointNodeName(chainName, descriptor.role);+ if (roles.has(descriptor.role))+ throw new TypeError(`createBoneChain duplicate role: ${descriptor.role}.`);+ if (names.has(name))+ throw new TypeError(`createBoneChain duplicate node name after sanitization: ${name}.`);+ roles.add(descriptor.role);+ names.add(name);+ parentRole = descriptor.role;+ return descriptor;+ });+ const nodes = descriptors.map((descriptor) => {+ const node = new THREE19.Bone;+ node.name = characterJointNodeName(chainName, descriptor.role);+ node.position.fromArray(descriptor.rest.translation);+ node.quaternion.fromArray(descriptor.rest.rotation);+ node.scale.fromArray(descriptor.rest.scale);+ stampCharacterJointDescriptorV1(node, descriptor);+ return node;+ });+ for (let i = 1;i < nodes.length; i++)+ nodes[i - 1].add(nodes[i]);+ if (options.parent)+ options.parent.add(nodes[0]);+ return {+ root: nodes[0],+ end: nodes[nodes.length - 1],+ nodes,+ byRole: new Map(descriptors.map((descriptor, i) => [descriptor.role, nodes[i]])),+ descriptors+ };+}+function collectCharacterJointNodes(root) {+ const joints = [];+ const visit = (node, parentPath, siblingIndex) => {const segment = `${node.name.trim() || node.type || "Object3D"}[${siblingIndex}]`;const nodePath = parentPath ? `${parentPath}/${segment}` : segment;const descriptor = readCharacterJointDescriptorV1(node);@@ -11126,7 +11861,7 @@ var init_character_repairs = __esm(() => {});// src/qa/character.ts-import * as THREE18 from "three";+import * as THREE20 from "three";function isClipLike(value) {if (typeof value !== "object" || value === null)return false;@@ -11364,7 +12099,7 @@ function contactFindings2(input, root) {const planeY = input.groundPlaneY ?? 0;const findings = [];for (const contact of contacts) {- const point = contact.node.getWorldPosition(new THREE18.Vector3).applyMatrix4(rootInverse);+ const point = contact.node.getWorldPosition(new THREE20.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.`, {@@ -11629,13 +12364,13 @@ function declaredHeldItem(nodes) {function characterJointScale(root) {root.updateMatrixWorld(true);const inverse = root.matrixWorld.clone().invert();- const bounds = new THREE18.Box3;+ const bounds = new THREE20.Box3;for (const joint of collectCharacterJointNodes(root)) {- bounds.expandByPoint(joint.node.getWorldPosition(new THREE18.Vector3).applyMatrix4(inverse));+ bounds.expandByPoint(joint.node.getWorldPosition(new THREE20.Vector3).applyMatrix4(inverse));}if (bounds.isEmpty())return 1;- const size = bounds.getSize(new THREE18.Vector3);+ const size = bounds.getSize(new THREE20.Vector3);return Math.max(size.x, size.y, size.z, 1);}function heldItemMotionFindings(input, root, clips) {@@ -11671,8 +12406,8 @@ function heldItemMotionFindings(input, root, clips) {if (!cloneItem || !cloneAttachment)continue;const inverse = clone.matrixWorld.clone().invert();- const itemPoint = cloneItem.getWorldPosition(new THREE18.Vector3).applyMatrix4(inverse);- const gripPoint = cloneAttachment.getWorldPosition(new THREE18.Vector3).applyMatrix4(inverse);+ const itemPoint = cloneItem.getWorldPosition(new THREE20.Vector3).applyMatrix4(inverse);+ const gripPoint = cloneAttachment.getWorldPosition(new THREE20.Vector3).applyMatrix4(inverse);const distance = itemPoint.distanceTo(gripPoint);baseline ??= distance;const drift = Math.abs(distance - baseline);@@ -11705,7 +12440,7 @@ function heldItemMotionFindings(input, root, clips) {function inspectRig(context) {if (!context.rig)return [];- const root = context.scene instanceof THREE18.Object3D ? context.scene : undefined;+ const root = context.scene instanceof THREE20.Object3D ? context.scene : undefined;const clips = (context.clips ?? []).filter(isClipLike);const findings = [];if (root) {@@ -11755,7 +12490,7 @@ var init_character2 = __esm(() => {});// src/qa/character-advisory.ts-import * as THREE19 from "three";+import * as THREE21 from "three";function isClipLike2(value) {if (typeof value !== "object" || value === null)return false;@@ -11778,16 +12513,16 @@ function jointPoints(root) {const inverse = rootInverse(root);return collectCharacterJointNodes(root).map((evidence) => ({evidence,- local: evidence.node.getWorldPosition(new THREE19.Vector3).applyMatrix4(inverse)+ local: evidence.node.getWorldPosition(new THREE21.Vector3).applyMatrix4(inverse)}));}function characterScale(points) {if (points.length === 0)return 1;- const bounds = new THREE19.Box3;+ const bounds = new THREE21.Box3;for (const point of points)bounds.expandByPoint(point.local);- const size = bounds.getSize(new THREE19.Vector3);+ const size = bounds.getSize(new THREE21.Vector3);return Math.max(size.x, size.y, size.z, 1);}function pairKey(descriptor) {@@ -11886,12 +12621,12 @@ function restChainFindings(context, root) {}function forwardMarkerFindings(context, root) {root.updateMatrixWorld(true);- const expected = new THREE19.Vector3(1, 0, 0).transformDirection(root.matrixWorld);+ const expected = new THREE21.Vector3(1, 0, 0).transformDirection(root.matrixWorld);const markers = collectCharacterJointNodes(root).filter((joint) => /(?:^|[._-])(?:toe|muzzle|head)(?:$|[._-])/i.test(joint.descriptor.role));return markers.flatMap((marker) => {- const quaternion = marker.node.getWorldQuaternion(new THREE19.Quaternion);- const actual = new THREE19.Vector3(...marker.descriptor.localForwardAxis).applyQuaternion(quaternion).normalize();- const angle = THREE19.MathUtils.radToDeg(Math.acos(THREE19.MathUtils.clamp(actual.dot(expected), -1, 1)));+ const quaternion = marker.node.getWorldQuaternion(new THREE21.Quaternion);+ const actual = new THREE21.Vector3(...marker.descriptor.localForwardAxis).applyQuaternion(quaternion).normalize();+ const angle = THREE21.MathUtils.radToDeg(Math.acos(THREE21.MathUtils.clamp(actual.dot(expected), -1, 1)));if (angle <= FORWARD_ANGLE_DEGREES)return [];return [@@ -11945,7 +12680,7 @@ function sampleClip(root, clip) {byRole: new Map(collectCharacterJointNodes(clone).map((evidence) => [evidence.descriptor.role,{- point: evidence.node.getWorldPosition(new THREE19.Vector3).applyMatrix4(inverse),+ point: evidence.node.getWorldPosition(new THREE21.Vector3).applyMatrix4(inverse),evidence}]))@@ -12057,12 +12792,12 @@ function phaseOppositionFindings(context, root, clips) {return findings;}function signedBendDegrees(descriptor, quaternion) {- const rest = new THREE19.Quaternion(...descriptor.rest.rotation);+ const rest = new THREE21.Quaternion(...descriptor.rest.rotation);const delta = rest.invert().multiply(quaternion).normalize();- const axis = new THREE19.Vector3(delta.x, delta.y, delta.z);- const signedMagnitude = axis.dot(new THREE19.Vector3(...descriptor.localBendAxis));+ const axis = new THREE21.Vector3(delta.x, delta.y, delta.z);+ const signedMagnitude = axis.dot(new THREE21.Vector3(...descriptor.localBendAxis));const angle = 2 * Math.atan2(signedMagnitude, delta.w);- return THREE19.MathUtils.radToDeg(THREE19.MathUtils.euclideanModulo(angle + Math.PI, Math.PI * 2) - Math.PI);+ return THREE21.MathUtils.radToDeg(THREE21.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));@@ -12076,7 +12811,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 THREE19.Quaternion().fromArray(value).normalize());+ const bend = signedBendDegrees(joint.descriptor, new THREE21.Quaternion().fromArray(value).normalize());if (Math.abs(bend) > Math.abs(maximum)) {maximum = bend;maximumFraction = fraction;@@ -12159,7 +12894,7 @@ function footSlideFindings(context, root, clips) {return findings;}function inspectRigAdvisory(context) {- if (!context.rig || !(context.scene instanceof THREE19.Object3D)) {+ if (!context.rig || !(context.scene instanceof THREE21.Object3D)) {return [];}const root = context.scene;@@ -12278,7 +13013,7 @@ var init_architecture_repairs = __esm(() => {});// src/qa/architecture.ts-import * as THREE20 from "three";+import * as THREE22 from "three";function hasRoofDimensions(value) {return value.footprint !== undefined && value.roof?.ridgeAxis !== undefined && value.roof.rise !== undefined && value.roof.overhang !== undefined;}@@ -12288,7 +13023,7 @@ function semanticMetadata(node) {function markerBounds(matrix) {const bounds = emptyBounds();for (let corner = 0;corner < 8; corner++) {- expandBounds(bounds, new THREE20.Vector3(corner & 1 ? 0.5 : -0.5, corner & 2 ? 0.5 : -0.5, corner & 4 ? 0.5 : -0.5).applyMatrix4(matrix));+ expandBounds(bounds, new THREE22.Vector3(corner & 1 ? 0.5 : -0.5, corner & 2 ? 0.5 : -0.5, corner & 4 ? 0.5 : -0.5).applyMatrix4(matrix));}return bounds;}@@ -12297,7 +13032,7 @@ function geometryPlaneNormal(geometry, relativeMatrix) {const local = geometry.boundingBox;if (!local)return;- const size = local.getSize(new THREE20.Vector3);+ const size = local.getSize(new THREE22.Vector3);const dimensions = [["x", size.x],["y", size.y],@@ -12307,7 +13042,7 @@ function geometryPlaneNormal(geometry, relativeMatrix) {const axis = dimensions[0]?.[0];if (!axis)return;- const normal = new THREE20.Vector3(axis === "x" ? 1 : 0, axis === "y" ? 1 : 0, axis === "z" ? 1 : 0).transformDirection(relativeMatrix);+ const normal = new THREE22.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();@@ -12319,7 +13054,7 @@ function geometryEvidence(geometry, relativeMatrix) {if (position?.itemSize !== 3)return { bounds, vertices, triangles: [] };for (let index = 0;index < position.count; index++) {- const point = new THREE20.Vector3(position.getX(index), position.getY(index), position.getZ(index));+ const point = new THREE22.Vector3(position.getX(index), position.getY(index), position.getZ(index));point.applyMatrix4(relativeMatrix);vertices.push(point);expandBounds(bounds, point);@@ -12346,7 +13081,7 @@ function geometryEvidence(geometry, relativeMatrix) {return { bounds, vertices, triangles, ...planeNormal ? { planeNormal } : {} };}function collectArchitectureEvidence(scene) {- if (!(scene instanceof THREE20.Object3D))+ if (!(scene instanceof THREE22.Object3D))return;scene.updateMatrixWorld(true);const rootInverse = scene.matrixWorld.clone().invert();@@ -12366,7 +13101,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 THREE20.BufferGeometry;+ const isMesh = mesh.isMesh === true && mesh.geometry instanceof THREE22.BufferGeometry;const evidence = isMesh ? geometryEvidence(mesh.geometry, relativeMatrix) : {bounds: markerBounds(relativeMatrix),vertices: [],@@ -12425,7 +13160,7 @@ function architectureFinding(context, value) {function averageNormal(normals) {if (normals.length === 0)return;- const result = normals.reduce((sum, normal) => sum.add(normal), new THREE20.Vector3);+ const result = normals.reduce((sum, normal) => sum.add(normal), new THREE22.Vector3);return result.lengthSq() > EPSILON2 ? result.normalize() : undefined;}function intervalCoverage(min, max, expectedMin, expectedMax) {@@ -13136,8 +13871,8 @@ function evaluateArchitectureQa(context) {});}var PROFILE_RULE_ID2 = "ARCHITECTURE_PROFILE", EPSILON2 = 0.000001, ARCHITECTURE_REALISTIC_SCALE_BANDS, emptyBounds = () => ({- min: new THREE20.Vector3(Infinity, Infinity, Infinity),- max: new THREE20.Vector3(-Infinity, -Infinity, -Infinity)+ min: new THREE22.Vector3(Infinity, Infinity, Infinity),+ max: new THREE22.Vector3(-Infinity, -Infinity, -Infinity)}), expandBounds = (bounds, point) => {bounds.min.min(point);bounds.max.max(point);@@ -13181,7 +13916,7 @@ var init_architecture = __esm(() => {});// src/qa/environment.ts-import * as THREE21 from "three";+import * as THREE23 from "three";function finding5(context, value) {return { ...value, profile: context.profile ?? "asset.requirements.v1" };}@@ -13200,11 +13935,11 @@ function nodePath4(root, node) {return names.reverse().join("/");}function transformedBox2(source, transform) {- const result = new THREE21.Box3;+ const result = new THREE23.Box3;for (const x of [source.min.x, source.max.x]) {for (const y of [source.min.y, source.max.y]) {for (const z of [source.min.z, source.max.z]) {- result.expandByPoint(new THREE21.Vector3(x, y, z).applyMatrix4(transform));+ result.expandByPoint(new THREE23.Vector3(x, y, z).applyMatrix4(transform));}}}@@ -13213,16 +13948,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 THREE21.Vector3;- const rotation = new THREE21.Quaternion;- const scale = new THREE21.Vector3;+ const position = new THREE23.Vector3;+ const rotation = new THREE23.Quaternion;+ const scale = new THREE23.Vector3;relative.decompose(position, rotation, scale);- const recomposed = new THREE21.Matrix4().compose(position, rotation, scale);+ const recomposed = new THREE23.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 THREE21.Vector3).applyMatrix4(relative);- const sourceHalf = source.getSize(new THREE21.Vector3).multiplyScalar(0.5);+ const center = source.getCenter(new THREE23.Vector3).applyMatrix4(relative);+ const sourceHalf = source.getSize(new THREE23.Vector3).multiplyScalar(0.5);const halfExtents = [Math.abs(sourceHalf.x * scale.x),Math.abs(sourceHalf.y * scale.y),@@ -13237,30 +13972,30 @@ function orientedBoxFromLocalBounds(root, node, source, relative = root.matrixWohalfExtents});}-function collectParts4(root) {+function collectParts5(root) {root.updateWorldMatrix(true, true);const rootInverse = root.matrixWorld.clone().invert();const result = [];root.traverseVisible((node) => {const roles = rolesOf3(node);- const renderable = node instanceof THREE21.Mesh;+ const renderable = node instanceof THREE23.Mesh;let box;let orientedBox;let source;- if (renderable && node.geometry instanceof THREE21.BufferGeometry) {+ if (renderable && node.geometry instanceof THREE23.BufferGeometry) {node.geometry.computeBoundingBox();if (node.geometry.boundingBox) {source = node.geometry.boundingBox;}} else if (roles.length > 0) {- source = new THREE21.Box3(new THREE21.Vector3(-0.5, -0.5, -0.5), new THREE21.Vector3(0.5, 0.5, 0.5));+ source = new THREE23.Box3(new THREE23.Vector3(-0.5, -0.5, -0.5), new THREE23.Vector3(0.5, 0.5, 0.5));}const relative = rootInverse.clone().multiply(node.matrixWorld);- const count = node instanceof THREE21.InstancedMesh ? node.count : 1;+ const count = node instanceof THREE23.InstancedMesh ? node.count : 1;for (let index = 0;index < count; index++) {const transform = relative.clone();- if (node instanceof THREE21.InstancedMesh) {- const instance = new THREE21.Matrix4;+ if (node instanceof THREE23.InstancedMesh) {+ const instance = new THREE23.Matrix4;node.getMatrixAt(index, instance);transform.multiply(instance);}@@ -13291,9 +14026,9 @@ function resolveSocket(root, node, socket) {return;root.updateWorldMatrix(true, true);const rootInverse = root.matrixWorld.clone().invert();- const point = new THREE21.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);- const rootInverseQuaternion = root.getWorldQuaternion(new THREE21.Quaternion).invert();- const rotation = node.getWorldQuaternion(new THREE21.Quaternion).multiply(new THREE21.Quaternion(...frame.rotation)).premultiply(rootInverseQuaternion).normalize();+ const point = new THREE23.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);+ const rootInverseQuaternion = root.getWorldQuaternion(new THREE23.Quaternion).invert();+ const rotation = node.getWorldQuaternion(new THREE23.Quaternion).multiply(new THREE23.Quaternion(...frame.rotation)).premultiply(rootInverseQuaternion).normalize();return {id: socket.id,type: socket.type,@@ -13322,7 +14057,7 @@ function socketByType(sockets, type) {return sockets.find((socket) => socket.type === type);}function inspectPlacementSockets(context) {- if (!(context.scene instanceof THREE21.Object3D)) {+ if (!(context.scene instanceof THREE23.Object3D)) {return [];}const root = context.scene;@@ -13386,8 +14121,8 @@ function materialSignature(material) {function boundarySamples(root, axis, side, bins = 12) {root.updateWorldMatrix(true, true);const inverse = root.matrixWorld.clone().invert();- const localBounds = new THREE21.Box3;- for (const part of collectParts4(root))+ const localBounds = new THREE23.Box3;+ for (const part of collectParts5(root))if (part.renderable && part.box)localBounds.union(part.box);if (localBounds.isEmpty())@@ -13400,30 +14135,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 THREE21.Mesh) || !(node.geometry instanceof THREE21.BufferGeometry))+ if (!(node instanceof THREE23.Mesh) || !(node.geometry instanceof THREE23.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 THREE21.InstancedMesh ? node.count : 1;+ const count = node instanceof THREE23.InstancedMesh ? node.count : 1;for (let instanceIndex = 0;instanceIndex < count; instanceIndex++) {const transform = relative.clone();- if (node instanceof THREE21.InstancedMesh) {- const instance = new THREE21.Matrix4;+ if (node instanceof THREE23.InstancedMesh) {+ const instance = new THREE23.Matrix4;node.getMatrixAt(instanceIndex, instance);transform.multiply(instance);}- const normalMatrix = new THREE21.Matrix3().getNormalMatrix(transform);+ const normalMatrix = new THREE23.Matrix3().getNormalMatrix(transform);const material = materialSignature(node.material);for (let index = 0;index < positions.count; index++) {- const point = new THREE21.Vector3(positions.getX(index), positions.getY(index), positions.getZ(index)).applyMatrix4(transform);+ const point = new THREE23.Vector3(positions.getX(index), positions.getY(index), positions.getZ(index)).applyMatrix4(transform);if (Math.abs(point[axis] - edge) > band)continue;- const t = THREE21.MathUtils.clamp((point[crossAxis] - crossMin) / crossExtent, 0, 1);+ const t = THREE23.MathUtils.clamp((point[crossAxis] - crossMin) / crossExtent, 0, 1);const bin = Math.min(bins - 1, Math.floor(t * bins));- const normal = normals ? new THREE21.Vector3(normals.getX(index), normals.getY(index), normals.getZ(index)).applyMatrix3(normalMatrix).normalize() : new THREE21.Vector3(0, 1, 0);+ const normal = normals ? new THREE23.Vector3(normals.getX(index), normals.getY(index), normals.getZ(index)).applyMatrix3(normalMatrix).normalize() : new THREE23.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 });@@ -13446,7 +14181,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]) => THREE21.MathUtils.radToDeg(Math.acos(THREE21.MathUtils.clamp(a.normal.dot(b.normal), -1, 1))))) : 180;+ const maximumNormalDeltaDegrees = pairs.length ? Math.max(...pairs.map(([a, b]) => THREE23.MathUtils.radToDeg(Math.acos(THREE23.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`);@@ -13463,7 +14198,7 @@ function edgePairMeasurements(root, axis, sockets) {};}function inspectTileEdges(context) {- if (context.tileable !== true || !(context.scene instanceof THREE21.Object3D)) {+ if (context.tileable !== true || !(context.scene instanceof THREE23.Object3D)) {return [];}const root = context.scene;@@ -13546,11 +14281,11 @@ function isCorridor(part) {return part.roles.some((role) => /^environment\.(?:navigation\.)?corridor(?:\.|$)/.test(role));}function inspectNavigationClearance(context) {- if (context.navigable !== true || !(context.scene instanceof THREE21.Object3D)) {+ if (context.navigable !== true || !(context.scene instanceof THREE23.Object3D)) {return [];}const root = context.scene;- const parts = collectParts4(root);+ const parts = collectParts5(root);const corridors = parts.filter((part) => isCorridor(part));if (corridors.length === 0) {return [@@ -13676,11 +14411,11 @@ 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 THREE21.Object3D)) {+ if (context.groundPlaneY === undefined || !(context.scene instanceof THREE23.Object3D)) {return [];}const root = context.scene;- const parts = collectParts4(root).filter((part) => part.renderable && part.box);+ const parts = collectParts5(root).filter((part) => part.renderable && part.box);const findings = [];for (const part of parts) {const box = part.box;@@ -13723,7 +14458,7 @@ function inspectSpatialSupport(context) {}));}}- const size = box.getSize(new THREE21.Vector3);+ const size = box.getSize(new THREE23.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",@@ -14031,6 +14766,13 @@ var init_requirements_applicability = __esm(() => {observation: true,kernel: "connectivity"},+ {+ id: "GEO_OPEN_SURFACE_PENETRATION",+ mode: "observe",+ keys: [],+ observation: true,+ kernel: "openSurface"+ },{ id: "REF_COMPARISON", mode: "observe", keys: [], observation: true },{ id: "SWEEP_SELF_INTERSECTION", mode: "observe", keys: [], observation: true, kernel: "sweep" },{ id: "HOST_VALIDATION_PROFILE", mode: "enforce", keys: ["validation"], kernel: "validation" }@@ -14365,7 +15107,7 @@ function writtenNodeResolver(root, doc, purpose) {// src/node-visibility.tsimport { KHRNodeVisibility } from "@gltf-transform/extensions";-import * as THREE22 from "three";+import * as THREE24 from "three";function applyNodeVisibility(root, doc) {const hidden = [];root.traverse((node) => {@@ -14408,7 +15150,7 @@ function drawnSceneBounds(scene) {return;const mesh = node.getMesh();if (mesh) {- const base = new THREE22.Matrix4().fromArray(node.getWorldMatrix());+ const base = new THREE24.Matrix4().fromArray(node.getWorldMatrix());const instances = node.getExtension("EXT_mesh_gpu_instancing");const translation = instances?.getAttribute("TRANSLATION");const rotation = instances?.getAttribute("ROTATION");@@ -14419,7 +15161,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 THREE22.Matrix4().compose(new THREE22.Vector3().fromArray(t), new THREE22.Quaternion().fromArray(r), new THREE22.Vector3().fromArray(s));+ const localMatrix = new THREE24.Matrix4().compose(new THREE24.Vector3().fromArray(t), new THREE24.Quaternion().fromArray(r), new THREE24.Vector3().fromArray(s));matrices.push(base.clone().multiply(localMatrix).toArray());}const local = [0, 0, 0];@@ -14460,12 +15202,12 @@ var init_node_visibility = __esm(() => {});// src/delivery-inspect.ts-import * as THREE23 from "three";+import * as THREE25 from "three";import { PropertyType as PropertyType2 } from "@gltf-transform/core";function decompose(matrix) {- const translation = new THREE23.Vector3;- const rotation = new THREE23.Quaternion;- const scale = new THREE23.Vector3;+ const translation = new THREE25.Vector3;+ const rotation = new THREE25.Quaternion;+ const scale = new THREE25.Vector3;matrix.decompose(translation, rotation, scale);const clean = (value) => Object.is(value, -0) ? 0 : value;return {@@ -14477,7 +15219,7 @@ function decompose(matrix) {function drawnTriangles(visited) {const values = [];const local = [0, 0, 0];- const point = new THREE23.Vector3;+ const point = new THREE25.Vector3;for (const { node, roles, hidden } of visited) {const mesh = node.getMesh();if (!mesh || hidden || roles.some((role) => role.startsWith("collider.")))@@ -14490,7 +15232,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 THREE23.Matrix4().compose(new THREE23.Vector3().fromArray(translation?.getElement(i, []) ?? [0, 0, 0]), new THREE23.Quaternion().fromArray(rotation?.getElement(i, []) ?? [0, 0, 0, 1]), new THREE23.Vector3().fromArray(scale?.getElement(i, []) ?? [1, 1, 1]));+ const instance = new THREE25.Matrix4().compose(new THREE25.Vector3().fromArray(translation?.getElement(i, []) ?? [0, 0, 0]), new THREE25.Quaternion().fromArray(rotation?.getElement(i, []) ?? [0, 0, 0, 1]), new THREE25.Vector3().fromArray(scale?.getElement(i, []) ?? [1, 1, 1]));matrices.push(base.clone().multiply(instance));}for (const primitive of mesh.listPrimitives()) {@@ -14521,20 +15263,20 @@ function triangleOverlapsBox(a, b, c, h, tolerance) {return false;}const e = [- new THREE23.Vector3().subVectors(b, a),- new THREE23.Vector3().subVectors(c, b),- new THREE23.Vector3().subVectors(a, c)+ new THREE25.Vector3().subVectors(b, a),+ new THREE25.Vector3().subVectors(c, b),+ new THREE25.Vector3().subVectors(a, c)];- const normal = new THREE23.Vector3().crossVectors(e[0], e[1]);+ const normal = new THREE25.Vector3().crossVectors(e[0], e[1]);const axes = [normal];const units = [- new THREE23.Vector3(1, 0, 0),- new THREE23.Vector3(0, 1, 0),- new THREE23.Vector3(0, 0, 1)+ new THREE25.Vector3(1, 0, 0),+ new THREE25.Vector3(0, 1, 0),+ new THREE25.Vector3(0, 0, 1)];for (const unit of units)for (const edge of e)- axes.push(new THREE23.Vector3().crossVectors(unit, edge));+ axes.push(new THREE25.Vector3().crossVectors(unit, edge));for (const axis of axes) {if (axis.lengthSq() < 0.000000000000000000000001)continue;@@ -14546,14 +15288,14 @@ function triangleOverlapsBox(a, b, c, h, tolerance) {return true;}function closestPointOnTriangle(p, a, b, c) {- const ab = new THREE23.Vector3().subVectors(b, a);- const ac = new THREE23.Vector3().subVectors(c, a);- const ap = new THREE23.Vector3().subVectors(p, a);+ const ab = new THREE25.Vector3().subVectors(b, a);+ const ac = new THREE25.Vector3().subVectors(c, a);+ const ap = new THREE25.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 THREE23.Vector3().subVectors(p, b);+ const bp = new THREE25.Vector3().subVectors(p, b);const d3 = ab.dot(bp);const d4 = ac.dot(bp);if (d3 >= 0 && d4 <= d3)@@ -14561,7 +15303,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 THREE23.Vector3().subVectors(p, c);+ const cp = new THREE25.Vector3().subVectors(p, c);const d5 = ab.dot(cp);const d6 = ac.dot(cp);if (d6 >= 0 && d5 <= d6)@@ -14571,14 +15313,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 THREE23.Vector3().subVectors(c, b), (d4 - d3) / (d4 - d3 + (d5 - d6)));+ return b.clone().addScaledVector(new THREE25.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 THREE23.Vector3().subVectors(q1, p1);- const d2 = new THREE23.Vector3().subVectors(q2, p2);- const r = new THREE23.Vector3().subVectors(p1, p2);+ const d1 = new THREE25.Vector3().subVectors(q1, p1);+ const d2 = new THREE25.Vector3().subVectors(q2, p2);+ const r = new THREE25.Vector3().subVectors(p1, p2);const a = d1.dot(d1);const e = d2.dot(d2);const f = d2.dot(r);@@ -14587,22 +15329,22 @@ function segmentSegmentDistanceSq(p1, q1, p2, q2) {if (a <= 0.000000000000000000000001 && e <= 0.000000000000000000000001)return r.lengthSq();if (a <= 0.000000000000000000000001)- t = THREE23.MathUtils.clamp(f / e, 0, 1);+ t = THREE25.MathUtils.clamp(f / e, 0, 1);else {const c = d1.dot(r);if (e <= 0.000000000000000000000001)- s = THREE23.MathUtils.clamp(-c / a, 0, 1);+ s = THREE25.MathUtils.clamp(-c / a, 0, 1);else {const b = d1.dot(d2);const denominator = a * e - b * b;- s = denominator !== 0 ? THREE23.MathUtils.clamp((b * f - c * e) / denominator, 0, 1) : 0;+ s = denominator !== 0 ? THREE25.MathUtils.clamp((b * f - c * e) / denominator, 0, 1) : 0;t = (b * s + f) / e;if (t < 0) {t = 0;- s = THREE23.MathUtils.clamp(-c / a, 0, 1);+ s = THREE25.MathUtils.clamp(-c / a, 0, 1);} else if (t > 1) {t = 1;- s = THREE23.MathUtils.clamp((b - c) / a, 0, 1);+ s = THREE25.MathUtils.clamp((b - c) / a, 0, 1);}}}@@ -14611,8 +15353,8 @@ function segmentSegmentDistanceSq(p1, q1, p2, q2) {return c1.distanceToSquared(c2);}function segmentCrossesTriangle(p, q, a, b, c) {- const hit = new THREE23.Vector3;- const ray = new THREE23.Ray(p, new THREE23.Vector3().subVectors(q, p));+ const hit = new THREE25.Vector3;+ const ray = new THREE25.Ray(p, new THREE25.Vector3().subVectors(q, p));const length = ray.direction.length();if (length === 0)return false;@@ -14729,9 +15471,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 THREE23.Box3(new THREE23.Vector3(...min), new THREE23.Vector3(...max));+ const bounds = new THREE25.Box3(new THREE25.Vector3(...min), new THREE25.Vector3(...max));const finiteBounds = [...min, ...max].every(Number.isFinite);- const diagonal = finiteBounds ? bounds.getSize(new THREE23.Vector3).length() : 0;+ const diagonal = finiteBounds ? bounds.getSize(new THREE25.Vector3).length() : 0;const tolerance = Math.max(0.0001, diagonal * 0.0001);const colliderNodes = [];for (const entry of visited) {@@ -14810,23 +15552,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 THREE23.Vector3;- const b = new THREE23.Vector3;- const c = new THREE23.Vector3;+ const a = new THREE25.Vector3;+ const b = new THREE25.Vector3;+ const c = new THREE25.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 THREE23.Box3;+ const proxyBounds = new THREE25.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 THREE23.Vector3().fromArray(position.getElement(i, local)).applyMatrix4(matrix));+ proxyBounds.expandByPoint(new THREE25.Vector3().fromArray(position.getElement(i, local)).applyMatrix4(matrix));}if (proxyBounds.isEmpty())- proxyBounds.expandByPoint(new THREE23.Vector3().setFromMatrixPosition(matrix));+ proxyBounds.expandByPoint(new THREE25.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.");@@ -14837,11 +15579,11 @@ function inspectDelivery(doc) {continue;}overlapTests += triangleCount;- const toLocal = new THREE23.Matrix4;+ const toLocal = new THREE25.Matrix4;let touches = false;if (record.shape.kind === "box") {toLocal.copy(matrix).invert();- const half = new THREE23.Vector3(0.5, 0.5, 0.5);+ const half = new THREE25.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);@@ -14851,10 +15593,10 @@ function inspectDelivery(doc) {}} else {const { translation, rotation } = record.transform;- toLocal.compose(new THREE23.Vector3(...translation), new THREE23.Quaternion(...rotation), new THREE23.Vector3(1, 1, 1)).invert();+ toLocal.compose(new THREE25.Vector3(...translation), new THREE25.Quaternion(...rotation), new THREE25.Vector3(1, 1, 1)).invert();const { radius, height } = record.shape;- const p = new THREE23.Vector3(0, -height / 2 + radius, 0);- const q = new THREE23.Vector3(0, height / 2 - radius, 0);+ const p = new THREE25.Vector3(0, -height / 2 + radius, 0);+ const q = new THREE25.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);@@ -14873,7 +15615,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 THREE23.Vector3(...record.transform.translation).applyMatrix4(worldMatrix(moduleEntry.node).invert());+ const point = new THREE25.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);@@ -14887,7 +15629,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 THREE23.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 THREE25.Matrix4().fromArray(node.getWorldMatrix());var init_delivery_inspect = __esm(() => {init_gltf_io();init_semantic();@@ -15029,16 +15771,16 @@ function evaluateValidationProfileDocument(profile, doc, options = {}) {measurement: { actual: null }}, "observe");} else if (outcome.failures.length > 0)- report("HOST_VALIDATION_ATTRIBUTE_GRADIENT", "gradient", `${where} ${check.gradient.attribute}[${check.gradient.component}] fails the ${outcome.failures.join(" and ")} test along local ${check.gradient.axis}: ${round2(outcome.fromMean)} to ${round2(outcome.toMean)}, expected ${check.gradient.from} to ${check.gradient.to} within ${check.gradient.tolerance}.`, {+ report("HOST_VALIDATION_ATTRIBUTE_GRADIENT", "gradient", `${where} ${check.gradient.attribute}[${check.gradient.component}] fails the ${outcome.failures.join(" and ")} test along local ${check.gradient.axis}: ${round3(outcome.fromMean)} to ${round3(outcome.toMean)}, expected ${check.gradient.from} to ${check.gradient.to} within ${check.gradient.tolerance}.`, {affected: { ...affected, attribute: check.gradient.attribute },measurement: {- actual: `${round2(outcome.fromMean)}..${round2(outcome.toMean)}`,+ actual: `${round3(outcome.fromMean)}..${round3(outcome.toMean)}`,expected: `${check.gradient.from}..${check.gradient.to}`,threshold: check.gradient.tolerance,breakdown: {- fromMean: round2(outcome.fromMean),- toMean: round2(outcome.toMean),- worstRegression: round2(outcome.worstRegression)+ fromMean: round3(outcome.fromMean),+ toMean: round3(outcome.toMean),+ worstRegression: round3(outcome.worstRegression)}}});@@ -15063,10 +15805,10 @@ function evaluateValidationProfileDocument(profile, doc, options = {}) {}const { tolerance } = check.range;if (accessor.getCount() > 0 && (min < check.range.min - tolerance || max > check.range.max + tolerance))- report("HOST_VALIDATION_ATTRIBUTE_RANGE", "range", `${where} ${check.range.attribute}[${check.range.component}] spans ${round2(min)}..${round2(max)}; the host allows ${check.range.min}..${check.range.max} within ${tolerance}.`, {+ report("HOST_VALIDATION_ATTRIBUTE_RANGE", "range", `${where} ${check.range.attribute}[${check.range.component}] spans ${round3(min)}..${round3(max)}; the host allows ${check.range.min}..${check.range.max} within ${tolerance}.`, {affected: { ...affected, attribute: check.range.attribute },measurement: {- actual: `${round2(min)}..${round2(max)}`,+ actual: `${round3(min)}..${round3(max)}`,expected: `${check.range.min}..${check.range.max}`,threshold: tolerance}@@ -15230,7 +15972,7 @@ async function evaluateValidationProfileGlb(profile, bytes, options = {}) {}return evaluateValidationProfileDocument(profile, doc, options);}-var HOST_VALIDATION_RULE_ID = "HOST_VALIDATION_PROFILE", MAX_VALIDATION_ATTRIBUTE_READS = 4000000, MAX_VALIDATION_FINDINGS_PER_CODE = 32, ENDPOINT_BAND = 0.05, GRADIENT_BINS = 16, MIN_AXIS_EXTENT = 0.000001, HOST_VALIDATION_QA_RULE, round2 = (value) => Math.round(value * 1e6) / 1e6, AXIS_INDEX;+var HOST_VALIDATION_RULE_ID = "HOST_VALIDATION_PROFILE", MAX_VALIDATION_ATTRIBUTE_READS = 4000000, MAX_VALIDATION_FINDINGS_PER_CODE = 32, ENDPOINT_BAND = 0.05, GRADIENT_BINS = 16, MIN_AXIS_EXTENT = 0.000001, HOST_VALIDATION_QA_RULE, round3 = (value) => Math.round(value * 1e6) / 1e6, AXIS_INDEX;var init_validation_profile2 = __esm(() => {init_gltf_io();init_delivery_inspect();@@ -15426,6 +16168,7 @@ var init_run = __esm(() => {init_part_connectivity();init_reference_comparison();init_self_intersection();+ init_open_surface_penetration();init_sweep();init_environment2();init_breadth2();@@ -15446,6 +16189,7 @@ var init_run = __esm(() => {...ENVIRONMENT_QA_RULES,...W7_BREADTH_QA_RULES,SELF_INTERSECTION_QA_RULE,+ OPEN_SURFACE_PENETRATION_QA_RULE,SWEEP_QA_RULE,PART_CONNECTIVITY_QA_RULE,REFERENCE_COMPARISON_QA_RULE,@@ -15469,13 +16213,13 @@ var init_run = __esm(() => {});// src/qa/requirements-run.ts-import { Object3D as Object3D15 } from "three";+import { Object3D as Object3D16 } 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"))+ if (!(scene instanceof Object3D16) || !sceneDecisions(context, policy).some((d) => d.ruleId === SELF_INTERSECTION_QA_RULE.id && d.mode !== "off"))return {};try {return { partPenetration: await analyzePartPenetration(scene) };@@ -15516,12 +16260,12 @@ function runRequirementsSceneQa(context, scene, clips, policy = {}, evidence = {};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 scopeObservation = scope?.state === "requested" && scene instanceof Object3D16 && 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) } : {}+ ...effects && scene instanceof Object3D16 && decisions.some((d) => d.ruleId.startsWith("VFX_") && d.mode !== "off") ? { vfxArtifact: analyzeVfxArtifactEvidenceV1(effects, scene, clips) } : {}}};const spatialInput = {@@ -15581,11 +16325,32 @@ function runRequirementsSceneQa(context, scene, clips, policy = {}, evidence = {}continue;}+ if (decision.ruleId === OPEN_SURFACE_PENETRATION_QA_RULE.id) {+ if (!(scene instanceof Object3D16))+ continue;+ const surfaces = analyzeOpenSurfacePenetration(scene);+ executedRules.push(decision.ruleId);+ findings.push(...inspectOpenSurfacePenetration(surfaces));+ Object.assign(geometryMetrics, {+ openSurfaceCoverage: surfaces.truncated || surfaces.skipped.length > 0 ? "partial" : "complete-surface-pairs",+ openSurfaceScope: "Visible static open surfaces sampled at their vertices against visible static closed solids, except alternates on different LOD levels; excludes open-vs-open pairs, motion, and any solid thinner than the sampled surface's facet spacing. Penetration within the contact tolerance is treated as intended contact, and penetration beyond it may still be intentional, as a fitting socketed into a shell is.",+ openSurfaceContactTolerance: surfaces.contactTolerance,+ openSurfaceOpenParts: surfaces.openParts,+ openSurfaceClosedParts: surfaces.closedParts,+ openSurfaceCandidatePairs: surfaces.candidatePairs,+ openSurfacePairsSampled: surfaces.pairsTested,+ openSurfacePairsNotReached: surfaces.pairsNotReached,+ openSurfaceVerticesUnresolved: surfaces.verticesUnresolved,+ openSurfaceLodAlternatePairs: surfaces.pairsLodAlternates,+ openSurfaceSkipped: surfaces.skipped.length+ });+ continue;+ }if (decision.ruleId === ASSET_SCOPE_QA_RULE.id && !scopeObservation)continue;if (decision.ruleId === HOST_VALIDATION_QA_RULE.id)continue;- if (decision.ruleId === PART_CONNECTIVITY_QA_RULE.id && !(scene instanceof Object3D15))+ if (decision.ruleId === PART_CONNECTIVITY_QA_RULE.id && !(scene instanceof Object3D16))continue;executedRules.push(decision.ruleId);if (decision.ruleId === PROP_EXACT_QA_RULE.id) {@@ -15731,6 +16496,7 @@ var init_requirements_run = __esm(() => {init_material();init_prop();init_part_connectivity();+ init_open_surface_penetration();init_sweep();init_self_intersection();init_vehicle2();@@ -15751,6 +16517,7 @@ var init_requirements_run = __esm(() => {PROP_ADVISORY_QA_RULE,PART_CONNECTIVITY_QA_RULE,SELF_INTERSECTION_QA_RULE,+ OPEN_SURFACE_PENETRATION_QA_RULE,SWEEP_QA_RULE,...VEHICLE_QA_RULES,...ARCHITECTURE_QA_RULES,@@ -15766,7 +16533,7 @@ var init_requirements_run = __esm(() => {});// src/qa/skin-integrity.ts-import * as THREE24 from "three";+import * as THREE26 from "three";function validAttribute(a, count, size) {if (!a || a.itemSize !== size || a.count !== count || !Number.isSafeInteger(count) || count < 1)return false;@@ -15813,9 +16580,9 @@ function inspectSkinIntegrity(root) {}while (chain.length) {const n = chain.pop();- const local = n.matrixAutoUpdate ? new THREE24.Matrix4().compose(n.position, n.quaternion, n.scale) : n.matrix.clone();+ const local = n.matrixAutoUpdate ? new THREE26.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 THREE24.Matrix4().multiplyMatrices(parent, local) : local;+ const value = n.matrixWorldAutoUpdate === false ? n.matrixWorld.clone() : parent ? new THREE26.Matrix4().multiplyMatrices(parent, local) : local;worlds.set(n, value);}return worlds.get(node);@@ -15865,7 +16632,7 @@ function inspectSkinIntegrity(root) {if (result.truncated)break;}- if (!finiteAffine(mesh.bindMatrix) || !Number.isFinite(mesh.bindMatrix.determinant()) || mesh.bindMatrix.determinant() === 0 || ![THREE24.AttachedBindMode, THREE24.DetachedBindMode].includes(mesh.bindMode)) {+ if (!finiteAffine(mesh.bindMatrix) || !Number.isFinite(mesh.bindMatrix.determinant()) || mesh.bindMatrix.determinant() === 0 || ![THREE26.AttachedBindMode, THREE26.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;@@ -15914,7 +16681,7 @@ function inspectSkinIntegrity(root) {add("SKIN_POSE_TRANSFORM", "Current mesh world transform must be finite and affine.");continue;}- const inverse = mesh.bindMode === THREE24.AttachedBindMode ? meshWorld.clone().invert() : mesh.bindMatrix.clone().invert();+ const inverse = mesh.bindMode === THREE26.AttachedBindMode ? meshWorld.clone().invert() : mesh.bindMatrix.clone().invert();const matrices = [];for (let joint = 0;joint < bones.length; joint++) {const boneWorld = world(bones[joint]);@@ -15922,13 +16689,13 @@ function inspectSkinIntegrity(root) {add("SKIN_POSE_TRANSFORM", `Current transform for joint ${joint} must be finite and affine.`, `joints[${joint}]`);break;}- matrices.push(new THREE24.Matrix4().multiplyMatrices(boneWorld, skeleton.boneInverses[joint]).multiply(mesh.bindMatrix));+ matrices.push(new THREE26.Matrix4().multiplyMatrices(boneWorld, skeleton.boneInverses[joint]).multiply(mesh.bindMatrix));}if (result.findings.length !== start)continue;- const base = new THREE24.Vector3, posed = new THREE24.Vector3, temp = new THREE24.Vector3, box = new THREE24.Box3;+ const base = new THREE26.Vector3, posed = new THREE26.Vector3, temp = new THREE26.Vector3, box = new THREE26.Box3;for (let vertex = 0;vertex < count; vertex++) {- THREE24.Mesh.prototype.getVertexPosition.call(mesh, vertex, base);+ THREE26.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);@@ -16075,7 +16842,7 @@ var init_material_export = __esm(() => {});// src/community-exporter.ts-import * as THREE25 from "three";+import * as THREE27 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) {@@ -16105,7 +16872,7 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, areturn found;const copy = cleanClone(source);normalizeTextureTransform(copy);- copy.source = new THREE25.TextureSource(source.image);+ copy.source = new THREE27.TextureSource(source.image);textures.set(source, copy);const bytes = source.userData["encoded"];if (bytes?.bytes) {@@ -16114,8 +16881,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 = THREE25.RGBAFormat;- copy.type = THREE25.UnsignedByteType;+ copy.format = THREE27.RGBAFormat;+ copy.type = THREE27.UnsignedByteType;})());}return copy;@@ -16132,7 +16899,7 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, aphysical.sheen = 1;}for (const [key, value] of Object.entries(copy)) {- if (value instanceof THREE25.Texture)+ if (value instanceof THREE27.Texture)copy[key] = texture(value);}materials.set(source, copy);@@ -16148,15 +16915,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 THREE25.Group;+ copy = new THREE27.Group;copy.copy(shadow, false);}if (source.isSprite) {const sprite = source;- const geometry = new THREE25.PlaneGeometry(1, 1);+ const geometry = new THREE27.PlaneGeometry(1, 1);geometry.translate(0.5 - sprite.center.x, 0.5 - sprite.center.y, 0);geometry.rotateZ(sprite.material.rotation);- const spriteMaterial = new THREE25.MeshBasicMaterial({+ const spriteMaterial = new THREE27.MeshBasicMaterial({name: sprite.material.name,color: sprite.material.color,opacity: sprite.material.opacity,@@ -16167,8 +16934,8 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, a});Object.assign(spriteMaterial.userData, authorExtras?.material(sprite.material));originalMaterials.set(spriteMaterial, sprite.material);- copy = new THREE25.Mesh(geometry, spriteMaterial);- THREE25.Object3D.prototype.copy.call(copy, shadow, false);+ copy = new THREE27.Mesh(geometry, spriteMaterial);+ THREE27.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];@@ -16232,8 +16999,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 THREE25.Texture().copy(map);- adapted.source = new THREE25.TextureSource(canvas);+ const adapted = new THREE27.Texture().copy(map);+ adapted.source = new THREE27.TextureSource(canvas);canvasInputs.set(map, adapted);const direct = directImages.get(map);if (direct)@@ -16242,7 +17009,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 THREE25.Texture && value.flipY && value.image?.data)+ if (value instanceof THREE27.Texture && value.flipY && value.image?.data)material[key] = canvasInput(value);}const standard = material;@@ -16264,8 +17031,8 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, a}cloned.tracks = cloned.tracks.filter((track) => {try {- const binding = THREE25.PropertyBinding.parseTrackName(track.name);- return ["position", "quaternion", "scale", "morphTargetInfluences"].includes(binding.propertyName) && THREE25.PropertyBinding.findNode(copy, binding.nodeName) !== null;+ const binding = THREE27.PropertyBinding.parseTrackName(track.name);+ return ["position", "quaternion", "scale", "morphTargetInfluences"].includes(binding.propertyName) && THREE27.PropertyBinding.findNode(copy, binding.nodeName) !== null;} catch {return false;}@@ -16460,7 +17227,7 @@ function applyIndexPolicy(doc, policy) {var init_index_policy = () => {};// src/surface-bake.ts-import * as THREE26 from "three";+import * as THREE28 from "three";function settings(value, label) {if (value === false)return;@@ -16502,13 +17269,13 @@ function drawnMeshes(root) {function weld(mesh) {const position = mesh.geometry.getAttribute("position");const world = [];- const box = new THREE26.Box3;+ const box = new THREE28.Box3;for (let i = 0;i < position.count; i++) {- const point = new THREE26.Vector3().fromBufferAttribute(position, i).applyMatrix4(mesh.matrixWorld);+ const point = new THREE28.Vector3().fromBufferAttribute(position, i).applyMatrix4(mesh.matrixWorld);world.push(point);box.expandByPoint(point);}- const size = box.isEmpty() ? 0 : box.getSize(new THREE26.Vector3).length();+ const size = box.isEmpty() ? 0 : box.getSize(new THREE28.Vector3).length();const tolerance = size > 0 ? size * 0.000001 : 0.000000001;const keys = new Map;const ids = new Int32Array(position.count);@@ -16542,7 +17309,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 THREE26.Vector3().subVectors(b, a).cross(new THREE26.Vector3().subVectors(c, a)).normalize());+ normals.push(new THREE28.Vector3().subVectors(b, a).cross(new THREE28.Vector3().subVectors(c, a)).normalize());}const edges = new Map;const neighbours = points.map(() => new Set);@@ -16561,658 +17328,346 @@ function bakeEdge(topology, thresholdDegrees, smoothing) {edges.set(key, list);}}- const threshold = THREE26.MathUtils.degToRad(thresholdDegrees);+ const threshold = THREE28.MathUtils.degToRad(thresholdDegrees);const weights = new Float64Array(points.length);- for (const [key, incidences] of edges) {- let weight;- if (incidences.length !== 2)- weight = 1;- else {- const [[f1], [f2, opposite2]] = incidences;- const n1 = normals[f1];- const n2 = normals[f2];- const angle = Math.acos(THREE26.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 THREE26.Vector3().subVectors(points[opposite2], points[u]).dot(n1) / scale;- weight = side < -0.000000001 ? smoothstep(threshold / 2, threshold, angle) : 0;- }- for (const id of key.split(":").map(Number))- weights[id] = Math.max(weights[id], weight);- }- let current = weights;- for (let step = 0;step < smoothing; step++) {- const next = new Float64Array(current.length);- for (let id = 0;id < current.length; id++) {- const ring = neighbours[id];- if (ring.size === 0) {- next[id] = current[id];- continue;- }- let sum = 0;- for (const other of ring)- sum += current[other];- next[id] = 0.5 * current[id] + 0.5 * sum / ring.size;- }- current = next;- }- return current;-}--class TriangleBvh {- triangles;- bounds;- children;- firsts;- counts;- order;- nodes = 0;- constructor(triangles) {- this.triangles = triangles;- const count = triangles.length / 9;- const capacity = Math.max(1, 2 * count);- this.bounds = new Float64Array(capacity * 6);- this.children = new Int32Array(capacity * 2).fill(-1);- this.firsts = new Int32Array(capacity);- this.counts = new Int32Array(capacity);- this.order = Int32Array.from({ length: count }, (_, i) => i);- const centroids = new Float64Array(count * 3);- for (let t = 0;t < count; t++)- for (let k = 0;k < 3; k++)- centroids[t * 3 + k] = (triangles[t * 9 + k] + triangles[t * 9 + 3 + k] + triangles[t * 9 + 6 + k]) / 3;- if (count > 0)- this.build(0, count, centroids);- }- build(first, count, centroids) {- const node = this.nodes++;- const b = node * 6;- this.bounds.fill(Infinity, b, b + 3);- this.bounds.fill(-Infinity, b + 3, b + 6);- for (let i = first;i < first + count; i++) {- const t = this.order[i];- for (let v = 0;v < 3; v++)- for (let k = 0;k < 3; k++) {- const value = this.triangles[t * 9 + v * 3 + k];- if (value < this.bounds[b + k])- this.bounds[b + k] = value;- if (value > this.bounds[b + 3 + k])- this.bounds[b + 3 + k] = value;- }- }- if (count <= 4) {- this.firsts[node] = first;- this.counts[node] = count;- return node;- }- let axis = 0;- let extent = -1;- for (let k = 0;k < 3; k++) {- const size = this.bounds[b + 3 + k] - this.bounds[b + k];- if (size > extent) {- extent = size;- axis = k;- }- }- const slice = Array.from(this.order.subarray(first, first + count));- slice.sort((x, y) => centroids[x * 3 + axis] - centroids[y * 3 + axis] || x - y);- this.order.set(slice, first);- const half = count >> 1;- this.children[node * 2] = this.build(first, half, centroids);- this.children[node * 2 + 1] = this.build(first + half, count - half, centroids);- return node;- }- hits(origin, direction, near, far) {- if (this.nodes === 0)- return false;- const stack = [0];- const inverse = [1 / direction.x, 1 / direction.y, 1 / direction.z];- const o = [origin.x, origin.y, origin.z];- while (stack.length) {- const node = stack.pop();- const b = node * 6;- let tmin = near;- let tmax = far;- for (let k = 0;k < 3; k++) {- let t0 = (this.bounds[b + k] - o[k]) * inverse[k];- let t1 = (this.bounds[b + 3 + k] - o[k]) * inverse[k];- if (t0 > t1)- [t0, t1] = [t1, t0];- if (Number.isNaN(t0))- t0 = -Infinity;- if (Number.isNaN(t1))- t1 = Infinity;- tmin = Math.max(tmin, t0);- tmax = Math.min(tmax, t1);- }- if (tmin > tmax)- continue;- const left = this.children[node * 2];- if (left >= 0) {- stack.push(left, this.children[node * 2 + 1]);- continue;- }- for (let i = this.firsts[node];i < this.firsts[node] + this.counts[node]; i++)- if (this.intersect(this.order[i], origin, direction, near, far))- return true;- }- return false;- }- intersect(t, origin, d, near, far) {- const v = this.triangles;- const o = t * 9;- const e1x = v[o + 3] - v[o];- const e1y = v[o + 4] - v[o + 1];- const e1z = v[o + 5] - v[o + 2];- const e2x = v[o + 6] - v[o];- const e2y = v[o + 7] - v[o + 1];- const e2z = v[o + 8] - v[o + 2];- const px = d.y * e2z - d.z * e2y;- const py = d.z * e2x - d.x * e2z;- const pz = d.x * e2y - d.y * e2x;- const det = e1x * px + e1y * py + e1z * pz;- if (Math.abs(det) < 0.000000000000000001)- return false;- const inv = 1 / det;- const sx = origin.x - v[o];- const sy = origin.y - v[o + 1];- const sz = origin.z - v[o + 2];- const u = (sx * px + sy * py + sz * pz) * inv;- if (u < 0 || u > 1)- return false;- const qx = sy * e1z - sz * e1y;- const qy = sz * e1x - sx * e1z;- const qz = sx * e1y - sy * e1x;- const w = (d.x * qx + d.y * qy + d.z * qz) * inv;- if (w < 0 || u + w > 1)- return false;- const distance = (e2x * qx + e2y * qy + e2z * qz) * inv;- return distance > near && distance <= far;- }-}-function hemisphereDirections(count) {- const golden = Math.PI * (3 - Math.sqrt(5));- return Array.from({ length: count }, (_, i) => {- const r = Math.sqrt((i + 0.5) / count);- const phi = i * golden;- const x = r * Math.cos(phi);- const y = r * Math.sin(phi);- return new THREE26.Vector3(x, y, Math.sqrt(Math.max(0, 1 - x * x - y * y)));- });-}-function occluderTriangles(occluders, bakedTier) {- const values = [];- const point = new THREE26.Vector3;- for (const mesh of drawnMeshes(occluders)) {- if (!drawn(mesh, null))- continue;- const tier = tierOf(mesh);- if (tier && tier.tier !== bakedTier?.tier && (bakedTier || tier.level > 0))- continue;- const position = mesh.geometry.getAttribute("position");- const index = mesh.geometry.getIndex();- const count = index ? index.count : position.count;- for (let i = 0;i + 2 < count; i += 3)- for (let k = 0;k < 3; k++) {- point.fromBufferAttribute(position, index ? index.getX(i + k) : i + k).applyMatrix4(mesh.matrixWorld);- values.push(point.x, point.y, point.z);+ for (const [key, incidences] of edges) {+ let weight;+ if (incidences.length !== 2)+ weight = 1;+ else {+ const [[f1], [f2, opposite2]] = incidences;+ const n1 = normals[f1];+ const n2 = normals[f2];+ const angle = Math.acos(THREE28.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 THREE28.Vector3().subVectors(points[opposite2], points[u]).dot(n1) / scale;+ weight = side < -0.000000001 ? smoothstep(threshold / 2, threshold, angle) : 0;+ }+ for (const id of key.split(":").map(Number))+ weights[id] = Math.max(weights[id], weight);+ }+ let current = weights;+ for (let step = 0;step < smoothing; step++) {+ const next = new Float64Array(current.length);+ for (let id = 0;id < current.length; id++) {+ const ring = neighbours[id];+ if (ring.size === 0) {+ next[id] = current[id];+ continue;}- if (values.length / 9 > GEOMETRY_ALLOCATION_LIMITS.surfaceBakeTriangles)- throw new RangeError(`bakeSurfaceAttributes: the occluders hold more than ${GEOMETRY_ALLOCATION_LIMITS.surfaceBakeTriangles} triangles; pass a smaller cavity.occluders subtree.`);+ let sum = 0;+ for (const other of ring)+ sum += current[other];+ next[id] = 0.5 * current[id] + 0.5 * sum / ring.size;+ }+ current = next;}- return Float64Array.from(values);-}-function positiveInteger(label, value, min, max) {- if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min || value > max)- throw new RangeError(`bakeSurfaceAttributes: ${label} must be an integer from ${min} to ${max}.`);- return value;+ return current;}-function bakeSurfaceAttributes(target, options = {}) {- if (!isObject3D2(target))- throw new TypeError("bakeSurfaceAttributes: target must be a mesh or a scene node.");- if (!options || typeof options !== "object" || Array.isArray(options))- throw new TypeError("bakeSurfaceAttributes: options must be { edge?, cavity? }.");- const edgeOptions = settings(options.edge, "edge");- const cavityOptions = settings(options.cavity, "cavity");- const thresholdDegrees = edgeOptions?.thresholdDegrees ?? SURFACE_BAKE_DEFAULTS.edge.thresholdDegrees;- if (edgeOptions && (typeof thresholdDegrees !== "number" || !Number.isFinite(thresholdDegrees) || thresholdDegrees <= 0 || thresholdDegrees >= 180))- throw new RangeError("bakeSurfaceAttributes: edge.thresholdDegrees must be greater than 0 and less than 180.");- const smoothing = edgeOptions ? positiveInteger("edge.smoothing", edgeOptions.smoothing ?? SURFACE_BAKE_DEFAULTS.edge.smoothing, 0, 8) : 0;- const rays = cavityOptions ? positiveInteger("cavity.rays", cavityOptions.rays ?? SURFACE_BAKE_DEFAULTS.cavity.rays, 1, GEOMETRY_ALLOCATION_LIMITS.surfaceBakeRayDirections) : 0;- if (cavityOptions?.occluders !== undefined && !isObject3D2(cavityOptions.occluders))- throw new TypeError("bakeSurfaceAttributes: cavity.occluders must be a scene node.");- if (cavityOptions?.radius !== undefined && (typeof cavityOptions.radius !== "number" || !Number.isFinite(cavityOptions.radius) || cavityOptions.radius <= 0))- throw new RangeError("bakeSurfaceAttributes: cavity.radius must be a positive finite number.");- if (!edgeOptions && !cavityOptions)- return target;- let top = target;- while (top.parent)- top = top.parent;- top.updateMatrixWorld(true);- const occluders = cavityOptions?.occluders ?? top;- if (occluders !== top)- occluders.updateMatrixWorld(true);- const meshes = drawnMeshes(target).filter((mesh) => drawn(mesh, null));- const topologies = meshes.map(weld);- const vertices = topologies.reduce((sum, topology) => sum + topology.points.length, 0);- if (vertices > GEOMETRY_ALLOCATION_LIMITS.surfaceBakeVertices)- throw new RangeError(`bakeSurfaceAttributes: ${vertices} welded vertices exceed ${GEOMETRY_ALLOCATION_LIMITS.surfaceBakeVertices}; bake smaller subtrees.`);- if (vertices * rays > GEOMETRY_ALLOCATION_LIMITS.surfaceBakeRays)- throw new RangeError(`bakeSurfaceAttributes: ${vertices} vertices x ${rays} rays exceed ${GEOMETRY_ALLOCATION_LIMITS.surfaceBakeRays} rays; lower cavity.rays or bake smaller subtrees.`);- const directions = hemisphereDirections(rays);- const bvhs = new Map;- const occlusion = (tier) => {- const key = tier?.tier;- let entry = bvhs.get(key);- if (!entry) {- const triangles = occluderTriangles(occluders, tier);- const box = new THREE26.Box3;- for (let i = 0;i < triangles.length; i += 3)- box.expandByPoint(new THREE26.Vector3(triangles[i], triangles[i + 1], triangles[i + 2]));- entry = {- bvh: new TriangleBvh(triangles),- diagonal: box.isEmpty() ? 0 : box.getSize(new THREE26.Vector3).length()- };- bvhs.set(key, entry);++class TriangleBvh {+ triangles;+ bounds;+ children;+ firsts;+ counts;+ order;+ nodes = 0;+ constructor(triangles) {+ this.triangles = triangles;+ const count = triangles.length / 9;+ const capacity = Math.max(1, 2 * count);+ this.bounds = new Float64Array(capacity * 6);+ this.children = new Int32Array(capacity * 2).fill(-1);+ this.firsts = new Int32Array(capacity);+ this.counts = new Int32Array(capacity);+ this.order = Int32Array.from({ length: count }, (_, i) => i);+ const centroids = new Float64Array(count * 3);+ for (let t = 0;t < count; t++)+ for (let k = 0;k < 3; k++)+ centroids[t * 3 + k] = (triangles[t * 9 + k] + triangles[t * 9 + 3 + k] + triangles[t * 9 + 6 + k]) / 3;+ if (count > 0)+ this.build(0, count, centroids);+ }+ build(first, count, centroids) {+ const node = this.nodes++;+ const b = node * 6;+ this.bounds.fill(Infinity, b, b + 3);+ this.bounds.fill(-Infinity, b + 3, b + 6);+ for (let i = first;i < first + count; i++) {+ const t = this.order[i];+ for (let v = 0;v < 3; v++)+ for (let k = 0;k < 3; k++) {+ const value = this.triangles[t * 9 + v * 3 + k];+ if (value < this.bounds[b + k])+ this.bounds[b + k] = value;+ if (value > this.bounds[b + 3 + k])+ this.bounds[b + 3 + k] = value;+ }}- return entry;- };- meshes.forEach((mesh, meshIndex) => {- const topology = topologies[meshIndex];- const record = {- ...mesh.geometry.userData?.[SURFACE_BAKE_KEY] ?? {}- };- const geometry = mesh.geometry.clone();- const sourceCount = geometry.getAttribute("position").count;- if (edgeOptions) {- const welded = bakeEdge(topology, thresholdDegrees, smoothing);- const values = new Float32Array(sourceCount);- for (let i = 0;i < sourceCount; i++)- values[i] = THREE26.MathUtils.clamp(welded[topology.ids[i]], 0, 1);- geometry.setAttribute("_edge", new THREE26.BufferAttribute(values, 1));- record._EDGE = { thresholdDegrees, smoothing };+ if (count <= 4) {+ this.firsts[node] = first;+ this.counts[node] = count;+ return node;}- 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 THREE26.Vector3);- const { points, triangles } = topology;- for (let t = 0;t < triangles.length; t += 3) {- const a = points[triangles[t]];- const face = new THREE26.Vector3().subVectors(points[triangles[t + 1]], a).cross(new THREE26.Vector3().subVectors(points[triangles[t + 2]], a));- for (let k = 0;k < 3; k++)- normals[triangles[t + k]].add(face);+ let axis = 0;+ let extent = -1;+ for (let k = 0;k < 3; k++) {+ const size = this.bounds[b + 3 + k] - this.bounds[b + k];+ if (size > extent) {+ extent = size;+ axis = k;}- const exposure = new Float64Array(points.length);- const tangent = new THREE26.Vector3;- const bitangent = new THREE26.Vector3;- const origin = new THREE26.Vector3;- const direction = new THREE26.Vector3;- points.forEach((point, id) => {- const normal = normals[id];- if (normal.lengthSq() === 0) {- exposure[id] = 1;- return;- }- normal.normalize();- tangent.set(Math.abs(normal.x) < 0.9 ? 1 : 0, Math.abs(normal.x) < 0.9 ? 0 : 1, 0);- tangent.cross(normal).normalize();- bitangent.crossVectors(normal, tangent);- origin.copy(point).addScaledVector(normal, epsilon);- let hits = 0;- for (const local of directions) {- direction.copy(tangent).multiplyScalar(local.x).addScaledVector(bitangent, local.y).addScaledVector(normal, local.z);- if (bvh.hits(origin, direction, epsilon, radius))- hits++;- }- exposure[id] = 1 - hits / directions.length;- });- const values = new Float32Array(sourceCount);- for (let i = 0;i < sourceCount; i++)- values[i] = THREE26.MathUtils.clamp(exposure[topology.ids[i]], 0, 1);- geometry.setAttribute("_cavity", new THREE26.BufferAttribute(values, 1));- record._CAVITY = { rays, radius };}- geometry.userData = { ...geometry.userData, [SURFACE_BAKE_KEY]: record };- mesh.geometry = geometry;- });- return target;-}-function surfaceBakeRecord(geometry) {- const value = geometry.userData?.[SURFACE_BAKE_KEY];- if (!value || typeof value !== "object")- return;- const record = {};- if (value._EDGE)- record._EDGE = { ...value._EDGE };- if (value._CAVITY)- record._CAVITY = { ...value._CAVITY };- return record;-}-var SURFACE_ATTRIBUTES, SURFACE_BAKE_KEY = "kilnSurfaceBakeV1", SURFACE_BAKE_DEFAULTS, isObject3D2 = (value) => value?.isObject3D === true, smoothstep = (edge0, edge1, x) => {- const t = THREE26.MathUtils.clamp((x - edge0) / (edge1 - edge0), 0, 1);- return t * t * (3 - 2 * t);-};-var init_surface_bake = __esm(() => {- init_geometry_budget();- init_lod();- SURFACE_ATTRIBUTES = Object.freeze({ _edge: "_EDGE", _cavity: "_CAVITY" });- SURFACE_BAKE_DEFAULTS = Object.freeze({- edge: Object.freeze({ thresholdDegrees: 35, smoothing: 1 }),- cavity: Object.freeze({ rays: 32, radiusFactor: 0.5 })- });-});--// src/geometry.ts-import * as THREE27 from "three";-function finiteArray(values, label, length) {- const result = Array.from(values);- if (length !== undefined && result.length !== length)- throw new Error(`${label}: expected ${length} values, got ${result.length}`);- if (!result.every((n) => Number.isFinite(Math.fround(n))))- throw new AuthoringDiagnosticError("MESH_DATA_NONFINITE", `${label}: all values must be finite Float32 values`);- return result;-}-function meshGeo(data) {- const positions = finiteArray(data.positions, "meshGeo positions");- if (positions.length < 9 || positions.length % 3)- throw new Error("meshGeo positions: need at least three xyz vertices");- const count = positions.length / 3;- const geometry = new THREE27.BufferGeometry;- geometry.setAttribute("position", new THREE27.Float32BufferAttribute(positions, 3));- if (data.indices) {- const indices = Array.from(data.indices);- if (!indices.length || indices.length % 3)- throw new Error("meshGeo indices: need complete triangles");- if (!indices.every((i) => Number.isInteger(i) && i >= 0 && i < count))- throw new Error("meshGeo index out of bounds or not an integer");- geometry.setIndex(indices);- } else if (count % 3)- throw new Error("meshGeo: non-indexed positions must form complete triangles");- if (data.normals) {- const normals = finiteArray(data.normals, "meshGeo normals", count * 3);- geometry.setAttribute("normal", new THREE27.Float32BufferAttribute(normals, 3));- for (let i = 0;i < count; i++)- if (Math.hypot(normals[i * 3], normals[i * 3 + 1], normals[i * 3 + 2]) === 0)- throw new Error("meshGeo normals: zero-length normal");- geometry.normalizeNormals();- } else- geometry.computeVertexNormals();- if (data.uvs)- geometry.setAttribute("uv", new THREE27.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");+ const slice = Array.from(this.order.subarray(first, first + count));+ slice.sort((x, y) => centroids[x * 3 + axis] - centroids[y * 3 + axis] || x - y);+ this.order.set(slice, first);+ const half = count >> 1;+ this.children[node * 2] = this.build(first, half, centroids);+ this.children[node * 2 + 1] = this.build(first + half, count - half, centroids);+ return node;+ }+ hits(origin, direction, near, far) {+ if (this.nodes === 0)+ return false;+ const stack = [0];+ const inverse = [1 / direction.x, 1 / direction.y, 1 / direction.z];+ const o = [origin.x, origin.y, origin.z];+ while (stack.length) {+ const node = stack.pop();+ const b = node * 6;+ let tmin = near;+ let tmax = far;+ for (let k = 0;k < 3; k++) {+ let t0 = (this.bounds[b + k] - o[k]) * inverse[k];+ let t1 = (this.bounds[b + 3 + k] - o[k]) * inverse[k];+ if (t0 > t1)+ [t0, t1] = [t1, t0];+ if (Number.isNaN(t0))+ t0 = -Infinity;+ if (Number.isNaN(t1))+ t1 = Infinity;+ tmin = Math.max(tmin, t0);+ tmax = Math.min(tmax, t1);+ }+ if (tmin > tmax)+ continue;+ const left = this.children[node * 2];+ if (left >= 0) {+ stack.push(left, this.children[node * 2 + 1]);+ continue;+ }+ for (let i = this.firsts[node];i < this.firsts[node] + this.counts[node]; i++)+ if (this.intersect(this.order[i], origin, direction, near, far))+ return true;}- geometry.setAttribute("tangent", new THREE27.Float32BufferAttribute(tangents, 4));+ return false;}- geometry.computeBoundingBox();- geometry.computeBoundingSphere();- return geometry;-}-function boundsScale(bounds) {- const size = bounds.getSize(new THREE27.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 THREE27.Box3;- const point = new THREE27.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);+ intersect(t, origin, d, near, far) {+ const v = this.triangles;+ const o = t * 9;+ const e1x = v[o + 3] - v[o];+ const e1y = v[o + 4] - v[o + 1];+ const e1z = v[o + 5] - v[o + 2];+ const e2x = v[o + 6] - v[o];+ const e2y = v[o + 7] - v[o + 1];+ const e2z = v[o + 8] - v[o + 2];+ const px = d.y * e2z - d.z * e2y;+ const py = d.z * e2x - d.x * e2z;+ const pz = d.x * e2y - d.y * e2x;+ const det = e1x * px + e1y * py + e1z * pz;+ if (Math.abs(det) < 0.000000000000000001)+ return false;+ const inv = 1 / det;+ const sx = origin.x - v[o];+ const sy = origin.y - v[o + 1];+ const sz = origin.z - v[o + 2];+ const u = (sx * px + sy * py + sz * pz) * inv;+ if (u < 0 || u > 1)+ return false;+ const qx = sy * e1z - sz * e1y;+ const qy = sz * e1x - sx * e1z;+ const qz = sx * e1y - sy * e1x;+ const w = (d.x * qx + d.y * qy + d.z * qz) * inv;+ if (w < 0 || u + w > 1)+ return false;+ const distance = (e2x * qx + e2y * qy + e2z * qz) * inv;+ return distance > near && distance <= far;}- return {- origin: bounds.isEmpty() ? new THREE27.Vector3 : bounds.min,- scale: boundsScale(bounds)- };}-function positionTolerance(scale, supplied, relative) {- if (supplied === undefined)- return scale * relative;- if (!Number.isFinite(supplied) || supplied <= 0)- throw new Error("Geometry tolerance must be positive and finite");- if (scale / supplied > Number.MAX_SAFE_INTEGER)- throw new Error("Geometry tolerance is too small to resolve the position extent safely");- return supplied;-}-function positionKey(point, origin, tolerance) {- if (tolerance === 0)- return point.toArray().join(",");- return point.clone().sub(origin).toArray().map((x) => Math.round(x / tolerance)).join(",");+function hemisphereDirections(count) {+ const golden = Math.PI * (3 - Math.sqrt(5));+ return Array.from({ length: count }, (_, i) => {+ const r = Math.sqrt((i + 0.5) / count);+ const phi = i * golden;+ const x = r * Math.cos(phi);+ const y = r * Math.sin(phi);+ return new THREE28.Vector3(x, y, Math.sqrt(Math.max(0, 1 - x * x - y * y)));+ });}-function geometryDiagnostics(geometry, tolerance) {- const p = geometry.getAttribute("position");- if (p?.itemSize !== 3)- throw new Error("geometryDiagnostics requires xyz positions");- const frame = positionFrame(p);- const distance = positionTolerance(frame.scale, tolerance, 0.000001);- const result = {- tolerance: distance,- toleranceMode: tolerance === undefined ? "relative" : "absolute",- positionScale: frame.scale,- vertices: p.count,- triangles: 0,- boundaryEdges: 0,- nonManifoldEdges: 0,- orientationConflicts: 0,- degenerateTriangles: 0,- collapsedByToleranceTriangles: 0,- invalidIndices: 0,- nonFiniteVertices: 0,- solid: { closed: false, manifold: true, orientation: "mixed", signedVolume: 0 }- };- let signedVolume = 0;- const pa = new THREE27.Vector3, pb = new THREE27.Vector3, pc = new THREE27.Vector3;- const ids = [];- const points = new Map;- const finite = [];- const point = new THREE27.Vector3;- for (let i = 0;i < p.count; i++) {- point.fromBufferAttribute(p, i);- finite[i] = [point.x, point.y, point.z].every(Number.isFinite);- if (!finite[i])- result.nonFiniteVertices++;- const key = finite[i] ? positionKey(point, frame.origin, distance) : `invalid:${i}`;- if (!points.has(key))- points.set(key, points.size);- ids.push(points.get(key));- }- const indices = geometry.index ? Array.from(geometry.index.array) : Array.from({ length: p.count }, (_, i) => i);- const edges = new Map;- const a = new THREE27.Vector3, b = new THREE27.Vector3, c = new THREE27.Vector3;- for (let i = 0;i < indices.length; i += 3) {- result.triangles++;- const triangle = indices.slice(i, i + 3);- if (triangle.length !== 3 || triangle.some((n) => !Number.isInteger(n) || n < 0 || n >= p.count)) {- result.invalidIndices++;- continue;- }- const [ia, ib, ic] = triangle;- if (!finite[ia] || !finite[ib] || !finite[ic])+function occluderTriangles(occluders, bakedTier) {+ const values = [];+ const point = new THREE28.Vector3;+ for (const mesh of drawnMeshes(occluders)) {+ if (!drawn(mesh, null))continue;- pa.fromBufferAttribute(p, ia);- pb.fromBufferAttribute(p, ib);- pc.fromBufferAttribute(p, ic);- signedVolume += pa.dot(pb.cross(pc)) / 6;- a.fromBufferAttribute(p, ia);- b.fromBufferAttribute(p, ib);- c.fromBufferAttribute(p, ic);- const scale = frame.scale || 1;- b.sub(a).divideScalar(scale);- c.sub(a).divideScalar(scale);- if (b.cross(c).length() <= (distance / scale) ** 2)- result.degenerateTriangles++;- if (ids[ia] === ids[ib] || ids[ib] === ids[ic] || ids[ic] === ids[ia]) {- result.collapsedByToleranceTriangles++;+ const tier = tierOf(mesh);+ if (tier && tier.tier !== bakedTier?.tier && (bakedTier || tier.level > 0))continue;- }- for (const [start, end] of [- [ia, ib],- [ib, ic],- [ic, ia]- ]) {- const u = ids[start], v = ids[end];- const key = u < v ? `${u}:${v}` : `${v}:${u}`;- const edge = edges.get(key) ?? { count: 0, direction: 0 };- edge.count++;- edge.direction += u < v ? 1 : -1;- edges.set(key, edge);- }- }- for (const edge of edges.values()) {- if (edge.count === 1)- result.boundaryEdges++;- else if (edge.count > 2)- result.nonManifoldEdges++;- else if (edge.direction !== 0)- result.orientationConflicts++;+ const position = mesh.geometry.getAttribute("position");+ const index = mesh.geometry.getIndex();+ const count = index ? index.count : position.count;+ for (let i = 0;i + 2 < count; i += 3)+ for (let k = 0;k < 3; k++) {+ point.fromBufferAttribute(position, index ? index.getX(i + k) : i + k).applyMatrix4(mesh.matrixWorld);+ values.push(point.x, point.y, point.z);+ }+ if (values.length / 9 > GEOMETRY_ALLOCATION_LIMITS.surfaceBakeTriangles)+ throw new RangeError(`bakeSurfaceAttributes: the occluders hold more than ${GEOMETRY_ALLOCATION_LIMITS.surfaceBakeTriangles} triangles; pass a smaller cavity.occluders subtree.`);}- const volumeFloor = (frame.scale || 1) ** 3 * 0.000000000001;- result.solid = {- closed: result.boundaryEdges === 0 && edges.size > 0,- manifold: result.nonManifoldEdges === 0,- orientation: result.orientationConflicts > 0 || Math.abs(signedVolume) <= volumeFloor ? "mixed" : signedVolume > 0 ? "outward" : "inward",- signedVolume: Object.is(signedVolume, -0) ? 0 : signedVolume- };- return result;+ return Float64Array.from(values);}-function parametricSurface(sample, options = {}) {- const {- u = [0, 1],- v = [0, 1],- uSegments: nu = 24,- vSegments: nv = 24,- periodicU = false,- periodicV = false,- orientation = "uv"- } = options;- for (const [name, n] of [- ["uSegments", nu],- ["vSegments", nv]- ])- if (!Number.isSafeInteger(n) || n < 1)- throw new Error(`parametricSurface ${name} must be a positive integer`);- const sampleCount = (nu + 1) * (nv + 1);- if (!Number.isSafeInteger(sampleCount) || sampleCount > GEOMETRY_ALLOCATION_LIMITS.parametricSamples)- throw new RangeError(`parametricSurface sample budget exceeded: requested ${sampleCount}, limit ${GEOMETRY_ALLOCATION_LIMITS.parametricSamples}. Reduce uSegments/vSegments or split the surface.`);- for (const [name, range] of [- ["u", u],- ["v", v]- ])- if (range.length !== 2 || !range.every(Number.isFinite) || range[0] === range[1] || !Number.isFinite(range[1] - range[0]))- throw new Error(`parametricSurface ${name} must be a finite nonzero domain`);- if (orientation !== "uv" && orientation !== "vu")- throw new Error("parametricSurface orientation must be uv or vu");- const positions = [], uvs = [], indices = [];- const sampledBounds = new THREE27.Box3;- const sampledPoint = new THREE27.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);- if (point.length !== 3 || !point.every(Number.isFinite))- throw new Error(`parametricSurface: sample (${i},${j}) must return three finite coordinates`);- positions.push(...point);- sampledBounds.expandByPoint(sampledPoint.set(...point));- uvs.push(i / nu, j / nv);+function positiveInteger(label, value, min, max) {+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min || value > max)+ throw new RangeError(`bakeSurfaceAttributes: ${label} must be an integer from ${min} to ${max}.`);+ return value;+}+function bakeSurfaceAttributes(target, options = {}) {+ if (!isObject3D2(target))+ throw new TypeError("bakeSurfaceAttributes: target must be a mesh or a scene node.");+ if (!options || typeof options !== "object" || Array.isArray(options))+ throw new TypeError("bakeSurfaceAttributes: options must be { edge?, cavity? }.");+ const edgeOptions = settings(options.edge, "edge");+ const cavityOptions = settings(options.cavity, "cavity");+ const thresholdDegrees = edgeOptions?.thresholdDegrees ?? SURFACE_BAKE_DEFAULTS.edge.thresholdDegrees;+ if (edgeOptions && (typeof thresholdDegrees !== "number" || !Number.isFinite(thresholdDegrees) || thresholdDegrees <= 0 || thresholdDegrees >= 180))+ throw new RangeError("bakeSurfaceAttributes: edge.thresholdDegrees must be greater than 0 and less than 180.");+ const smoothing = edgeOptions ? positiveInteger("edge.smoothing", edgeOptions.smoothing ?? SURFACE_BAKE_DEFAULTS.edge.smoothing, 0, 8) : 0;+ const rays = cavityOptions ? positiveInteger("cavity.rays", cavityOptions.rays ?? SURFACE_BAKE_DEFAULTS.cavity.rays, 1, GEOMETRY_ALLOCATION_LIMITS.surfaceBakeRayDirections) : 0;+ if (cavityOptions?.occluders !== undefined && !isObject3D2(cavityOptions.occluders))+ throw new TypeError("bakeSurfaceAttributes: cavity.occluders must be a scene node.");+ if (cavityOptions?.radius !== undefined && (typeof cavityOptions.radius !== "number" || !Number.isFinite(cavityOptions.radius) || cavityOptions.radius <= 0))+ throw new RangeError("bakeSurfaceAttributes: cavity.radius must be a positive finite number.");+ if (!edgeOptions && !cavityOptions)+ return target;+ let top = target;+ while (top.parent)+ top = top.parent;+ top.updateMatrixWorld(true);+ const occluders = cavityOptions?.occluders ?? top;+ if (occluders !== top)+ occluders.updateMatrixWorld(true);+ const meshes = drawnMeshes(target).filter((mesh) => drawn(mesh, null));+ const topologies = meshes.map(weld);+ const vertices = topologies.reduce((sum, topology) => sum + topology.points.length, 0);+ if (vertices > GEOMETRY_ALLOCATION_LIMITS.surfaceBakeVertices)+ throw new RangeError(`bakeSurfaceAttributes: ${vertices} welded vertices exceed ${GEOMETRY_ALLOCATION_LIMITS.surfaceBakeVertices}; bake smaller subtrees.`);+ if (vertices * rays > GEOMETRY_ALLOCATION_LIMITS.surfaceBakeRays)+ throw new RangeError(`bakeSurfaceAttributes: ${vertices} vertices x ${rays} rays exceed ${GEOMETRY_ALLOCATION_LIMITS.surfaceBakeRays} rays; lower cavity.rays or bake smaller subtrees.`);+ const directions = hemisphereDirections(rays);+ const bvhs = new Map;+ const occlusion = (tier) => {+ const key = tier?.tier;+ let entry = bvhs.get(key);+ if (!entry) {+ const triangles = occluderTriangles(occluders, tier);+ const box = new THREE28.Box3;+ for (let i = 0;i < triangles.length; i += 3)+ box.expandByPoint(new THREE28.Vector3(triangles[i], triangles[i + 1], triangles[i + 2]));+ entry = {+ bvh: new TriangleBvh(triangles),+ diagonal: box.isEmpty() ? 0 : box.getSize(new THREE28.Vector3).length()+ };+ bvhs.set(key, entry);}- const groups = Array.from({ length: (nu + 1) * (nv + 1) }, (_, i) => i);- const seamScale = boundsScale(sampledBounds);- const find = (i) => {- while (groups[i] !== i)- i = groups[i];- return i;- };- const join = (a, b, _label) => {- const pa = positions.slice(a * 3, a * 3 + 3), pb = positions.slice(b * 3, b * 3 + 3);- if (Math.hypot(...pa.map((x, k) => x - pb[k])) > seamScale * 0.000001)- throw new AuthoringDiagnosticError("PARAMETRIC_PERIODIC_ENDPOINT");- groups[find(b)] = find(a);- for (let k = 0;k < 3; k++)- positions[b * 3 + k] = positions[a * 3 + k];+ return entry;};- if (periodicU)- for (let j = 0;j <= nv; j++)- join(j * (nu + 1), j * (nu + 1) + nu, "periodicU");- if (periodicV)- for (let i = 0;i <= nu; i++)- join(i, nv * (nu + 1) + i, "periodicV");- for (let j = 0;j < nv; j++)- for (let i = 0;i < nu; i++) {- const a = j * (nu + 1) + i, b = a + 1, c = a + nu + 1, d = c + 1;- indices.push(...orientation === "uv" ? [a, b, c, b, d, c] : [a, c, b, b, c, d]);- }- const out = meshGeo({ positions, indices, uvs });- if (periodicU || periodicV) {- const normal = out.getAttribute("normal");- const sums = new Map;- for (let i = 0;i < normal.count; i++) {- const id = find(i);- const sum = sums.get(id) ?? new THREE27.Vector3;- sum.add(new THREE27.Vector3().fromBufferAttribute(normal, i));- sums.set(id, sum);+ meshes.forEach((mesh, meshIndex) => {+ const topology = topologies[meshIndex];+ const record = {+ ...mesh.geometry.userData?.[SURFACE_BAKE_KEY] ?? {}+ };+ const geometry = mesh.geometry.clone();+ const sourceCount = geometry.getAttribute("position").count;+ if (edgeOptions) {+ const welded = bakeEdge(topology, thresholdDegrees, smoothing);+ const values = new Float32Array(sourceCount);+ for (let i = 0;i < sourceCount; i++)+ values[i] = THREE28.MathUtils.clamp(welded[topology.ids[i]], 0, 1);+ geometry.setAttribute("_edge", new THREE28.BufferAttribute(values, 1));+ record._EDGE = { thresholdDegrees, smoothing };}- for (let i = 0;i < normal.count; i++) {- const n = sums.get(find(i)).clone().normalize();- normal.setXYZ(i, n.x, n.y, n.z);+ 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 THREE28.Vector3);+ const { points, triangles } = topology;+ for (let t = 0;t < triangles.length; t += 3) {+ const a = points[triangles[t]];+ const face = new THREE28.Vector3().subVectors(points[triangles[t + 1]], a).cross(new THREE28.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 THREE28.Vector3;+ const bitangent = new THREE28.Vector3;+ const origin = new THREE28.Vector3;+ const direction = new THREE28.Vector3;+ points.forEach((point, id) => {+ const normal = normals[id];+ if (normal.lengthSq() === 0) {+ exposure[id] = 1;+ return;+ }+ normal.normalize();+ tangent.set(Math.abs(normal.x) < 0.9 ? 1 : 0, Math.abs(normal.x) < 0.9 ? 0 : 1, 0);+ tangent.cross(normal).normalize();+ bitangent.crossVectors(normal, tangent);+ origin.copy(point).addScaledVector(normal, epsilon);+ let hits = 0;+ for (const local of directions) {+ direction.copy(tangent).multiplyScalar(local.x).addScaledVector(bitangent, local.y).addScaledVector(normal, local.z);+ if (bvh.hits(origin, direction, epsilon, radius))+ hits++;+ }+ exposure[id] = 1 - hits / directions.length;+ });+ const values = new Float32Array(sourceCount);+ for (let i = 0;i < sourceCount; i++)+ values[i] = THREE28.MathUtils.clamp(exposure[topology.ids[i]], 0, 1);+ geometry.setAttribute("_cavity", new THREE28.BufferAttribute(values, 1));+ record._CAVITY = { rays, radius };}- }- return out;+ geometry.userData = { ...geometry.userData, [SURFACE_BAKE_KEY]: record };+ mesh.geometry = geometry;+ });+ return target;}-function creaseNormals(geometry, options = {}) {- const angle = options.angle ?? 60;- if (!Number.isFinite(angle) || angle < 0 || angle > 180)- throw new Error("creaseNormals angle must be between 0 and 180 degrees");- const out = geometry.index ? geometry.toNonIndexed() : geometry.clone();- const position = out.getAttribute("position");- if (position?.itemSize !== 3 || position.count % 3 !== 0)- throw new Error("creaseNormals requires complete xyz triangles");- const frame = positionFrame(position);- const tolerance = positionTolerance(frame.scale, options.tolerance, 0.00000001);- const scale = frame.scale || 1;- const adjacent = new Map;- const keys = [];- const faces = [];- for (let i = 0;i < position.count; i += 3) {- const a = new THREE27.Vector3().fromBufferAttribute(position, i);- const b = new THREE27.Vector3().fromBufferAttribute(position, i + 1);- const c = new THREE27.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 THREE27.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);- keys.push(key);- const neighbors = adjacent.get(key) ?? new Set;- neighbors.add(i / 3);- adjacent.set(key, neighbors);- }- }- const normals = new Float32Array(position.count * 3);- const threshold = Math.cos(THREE27.MathUtils.degToRad(angle));- for (let i = 0;i < position.count; i++) {- const face = faces[Math.floor(i / 3)], sum = new THREE27.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 THREE27.BufferAttribute(normals, 3));- out.deleteAttribute("tangent");- out.computeBoundingBox();- out.computeBoundingSphere();- return out;+function surfaceBakeRecord(geometry) {+ const value = geometry.userData?.[SURFACE_BAKE_KEY];+ if (!value || typeof value !== "object")+ return;+ const record = {};+ if (value._EDGE)+ record._EDGE = { ...value._EDGE };+ if (value._CAVITY)+ record._CAVITY = { ...value._CAVITY };+ return record;}-var init_geometry = __esm(() => {+var SURFACE_ATTRIBUTES, SURFACE_BAKE_KEY = "kilnSurfaceBakeV1", SURFACE_BAKE_DEFAULTS, isObject3D2 = (value) => value?.isObject3D === true, smoothstep = (edge0, edge1, x) => {+ const t = THREE28.MathUtils.clamp((x - edge0) / (edge1 - edge0), 0, 1);+ return t * t * (3 - 2 * t);+};+var init_surface_bake = __esm(() => {init_geometry_budget();- init_authoring_diagnostic();+ init_lod();+ SURFACE_ATTRIBUTES = Object.freeze({ _edge: "_EDGE", _cavity: "_CAVITY" });+ SURFACE_BAKE_DEFAULTS = Object.freeze({+ edge: Object.freeze({ thresholdDegrees: 35, smoothing: 1 }),+ cavity: Object.freeze({ rays: 32, radiusFactor: 0.5 })+ });});// src/require-solid.ts@@ -17693,16 +18148,16 @@ function buildWallPanels(length, height, thickness, apertures) {}// src/assembly-transform.ts-import * as THREE28 from "three";+import * as THREE29 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 THREE28.Vector3, quaternion = new THREE28.Quaternion, scale = new THREE28.Vector3;+ const position = new THREE29.Vector3, quaternion = new THREE29.Quaternion, scale = new THREE29.Vector3;matrix.decompose(position, quaternion, scale);- const rebuilt = new THREE28.Matrix4().compose(position, quaternion, scale);+ const rebuilt = new THREE29.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 };@@ -17710,7 +18165,7 @@ function checkedTrs(matrix, label) {var init_assembly_transform = () => {};// src/assembly.ts-import * as THREE29 from "three";+import * as THREE30 from "three";function jsonData(value, label, ancestors = new Set) {if (value === null || typeof value === "string" || typeof value === "boolean")return;@@ -17757,7 +18212,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 THREE29.Matrix4().compose(node.position, node.quaternion, node.scale) : node.matrix.clone();+ return node.matrixAutoUpdate ? new THREE30.Matrix4().compose(node.position, node.quaternion, node.scale) : node.matrix.clone();}function worldMatrix2(node) {const chain = [], seen = new Set;@@ -17767,7 +18222,7 @@ function worldMatrix2(node) {seen.add(cursor);chain.push(cursor);}- const result = new THREE29.Matrix4;+ const result = new THREE30.Matrix4;for (const entry of chain.reverse())result.multiply(localMatrix(entry));return result;@@ -17783,7 +18238,7 @@ function census(root) {const stack = [root];while (stack.length) {const node = stack.pop();- if (!(node instanceof THREE29.Object3D) || ![THREE29.Object3D, THREE29.Group, THREE29.Mesh].includes(node.constructor))+ if (!(node instanceof THREE30.Object3D) || ![THREE30.Object3D, THREE30.Group, THREE30.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.");@@ -17799,21 +18254,21 @@ function census(root) {checkedTrs(matrix, node.name || "unnamed node");nodes.push(node);matrices.set(node, matrix);- if (node.onBeforeRender !== THREE29.Object3D.prototype.onBeforeRender || node.onAfterRender !== THREE29.Object3D.prototype.onAfterRender || node.onBeforeShadow !== THREE29.Object3D.prototype.onBeforeShadow || node.onAfterShadow !== THREE29.Object3D.prototype.onAfterShadow)+ if (node.onBeforeRender !== THREE30.Object3D.prototype.onBeforeRender || node.onAfterRender !== THREE30.Object3D.prototype.onAfterRender || node.onBeforeShadow !== THREE30.Object3D.prototype.onBeforeShadow || node.onAfterShadow !== THREE30.Object3D.prototype.onAfterShadow)throw new Error("Custom node render callbacks are unsupported in assembly replication.");- if (node instanceof THREE29.Mesh) {- if (!(node.geometry instanceof THREE29.BufferGeometry) || node.geometry instanceof THREE29.InstancedBufferGeometry)+ if (node instanceof THREE30.Mesh) {+ if (!(node.geometry instanceof THREE30.BufferGeometry) || node.geometry instanceof THREE30.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 THREE29.Material)))+ if (materials.length === 0 || materials.some((material) => !(material instanceof THREE30.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 THREE29.AnimationClip)))+ if (!Array.isArray(node.animations) || node.animations.some((clip) => !(clip instanceof THREE30.AnimationClip)))throw new Error("Assembly node animations must contain AnimationClip instances.");if (node.userData[KILN_SEMANTIC_EXTRAS_KEY] !== undefined) {const metadata = readSemanticMetadataV1(node);@@ -17854,11 +18309,11 @@ function describeAssembly(root, options = {}) {const state = census(root), roles = new Map;const frames = [], sockets = [], joints = [], materials = [];const relative = new Map;- const bounds = new THREE29.Box3, point = new THREE29.Vector3;+ const bounds = new THREE30.Box3, point = new THREE30.Vector3;let positionSamples = 0;for (const [index, node] of state.nodes.entries()) {const nodeId = `n${index}`;- const matrix = node === root ? new THREE29.Matrix4 : relative.get(node.parent).clone().multiply(state.matrices.get(node));+ const matrix = node === root ? new THREE30.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);@@ -17880,7 +18335,7 @@ function describeAssembly(root, options = {}) {for (const role of metadata?.roles ?? [])addIndex(roles, role, node);for (const frame of metadata?.frames ?? []) {- const local = new THREE29.Matrix4().compose(new THREE29.Vector3(...frame.translation), new THREE29.Quaternion(...frame.rotation), new THREE29.Vector3(1, 1, 1));+ const local = new THREE30.Matrix4().compose(new THREE30.Vector3(...frame.translation), new THREE30.Quaternion(...frame.rotation), new THREE30.Vector3(1, 1, 1));frames.push({node,nodeId,@@ -17890,7 +18345,7 @@ function describeAssembly(root, options = {}) {}for (const socket of metadata?.sockets ?? [])sockets.push({ node, nodeId, socket: structuredClone(socket) });- if (!(node instanceof THREE29.Mesh))+ if (!(node instanceof THREE30.Mesh))continue;for (const [materialIndex, material] of (Array.isArray(node.material) ? node.material : [node.material]).entries())materials.push({ node, nodeId, index: materialIndex, material });@@ -17925,7 +18380,7 @@ function describeAssembly(root, options = {}) {space: "root-local",min: bounds.min.toArray(),max: bounds.max.toArray(),- size: bounds.getSize(new THREE29.Vector3).toArray()+ size: bounds.getSize(new THREE30.Vector3).toArray()},clips,ownership: {@@ -17964,7 +18419,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 THREE29.Object3D))+ if (options.parent !== undefined && !(options.parent instanceof THREE30.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))@@ -17997,16 +18452,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 THREE29.Mesh) {+ if (node instanceof THREE30.Mesh) {if (options.geometry === "copy") {jsonData(node.geometry.userData, `${node.name} geometry`);- if (node.geometry.clone !== THREE29.BufferGeometry.prototype.clone || !threeConstructors.has(node.geometry.constructor))+ if (node.geometry.clone !== THREE30.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 !== THREE29.Material.prototype.onBeforeCompile || material.onBeforeRender !== THREE29.Material.prototype.onBeforeRender || material.clone !== THREE29.Material.prototype.clone || !threeConstructors.has(material.constructor) || material.customProgramCacheKey !== THREE29.Material.prototype.customProgramCacheKey || material instanceof THREE29.ShaderMaterial)+ if (material.onBeforeCompile !== THREE30.Material.prototype.onBeforeCompile || material.onBeforeRender !== THREE30.Material.prototype.onBeforeRender || material.clone !== THREE30.Material.prototype.clone || !threeConstructors.has(material.constructor) || material.customProgramCacheKey !== THREE30.Material.prototype.customProgramCacheKey || material instanceof THREE30.ShaderMaterial)throw new Error("Copying custom/shader materials is unsupported; explicit sharing preserves their existing implementation.");}}@@ -18094,9 +18549,9 @@ function replicateAssembly(source, options) {const trackTargets = new Map;const animatedNodes = new Set;for (const clip of fresh.clips) {- if (!(clip instanceof THREE29.AnimationClip))+ if (!(clip instanceof THREE30.AnimationClip))throw new Error("Assembly clips must be AnimationClip instances.");- if (clip.blendMode !== THREE29.NormalAnimationBlendMode)+ if (clip.blendMode !== THREE30.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")@@ -18123,7 +18578,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 THREE29.Matrix4;+ const parentWorld = options.parent ? worldMatrix2(options.parent) : new THREE30.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));@@ -18164,7 +18619,7 @@ function replicateAssembly(source, options) {return materials.get(material);};for (const node of state.nodes) {- const copy = node instanceof THREE29.Mesh ? new THREE29.Mesh(node.geometry, node.material) : node instanceof THREE29.Group ? new THREE29.Group : new THREE29.Object3D;+ const copy = node instanceof THREE30.Mesh ? new THREE30.Mesh(node.geometry, node.material) : node instanceof THREE30.Group ? new THREE30.Group : new THREE30.Object3D;copy.copy(node, false);copy.name = names.get(node);copy.animations = [];@@ -18177,7 +18632,7 @@ function replicateAssembly(source, options) {}copy.matrix.copy(matrix);copy.matrixWorldNeedsUpdate = true;- if (node instanceof THREE29.Mesh && copy instanceof THREE29.Mesh) {+ if (node instanceof THREE30.Mesh && copy instanceof THREE30.Mesh) {if (options.geometry === "copy") {if (!geometries.has(node.geometry))geometries.set(node.geometry, node.geometry.clone());@@ -18242,7 +18697,7 @@ var init_assembly = __esm(() => {KILN_CHARACTER_JOINT_EXTRAS_KEY,KILN_CHARACTER_RIG_EXTRAS_KEY]);- threeConstructors = new Set(Object.values(THREE29));+ threeConstructors = new Set(Object.values(THREE30));});// src/palette-check.ts@@ -18783,7 +19238,7 @@ var init_budget = __esm(() => {});// src/animation-cubic.ts-import * as THREE30 from "three";+import * as THREE31 from "three";function useCubicSpline(track) {track.createInterpolant = cubicSplineFactory;return track;@@ -18791,7 +19246,7 @@ function useCubicSpline(track) {var CubicSplineInterpolant, CubicSplineQuaternionInterpolant, cubicSplineFactory;var init_animation_cubic = __esm(() => {init_animation_spline();- CubicSplineInterpolant = class CubicSplineInterpolant extends THREE30.Interpolant {+ CubicSplineInterpolant = class CubicSplineInterpolant extends THREE31.Interpolant {copySampleValue_(index) {const result = this.resultBuffer;const size = this.valueSize;@@ -18819,7 +19274,7 @@ var init_animation_cubic = __esm(() => {});// src/architecture.ts-import * as THREE31 from "three";+import * as THREE32 from "three";function positive4(value, name) {if (!Number.isFinite(value) || value <= 0)throw new RangeError(`${name} must be finite and > 0`);@@ -18884,17 +19339,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 THREE31.Vector3(0, -verticalRun, sideSign * horizontalRun).normalize() : new THREE31.Vector3(sideSign * horizontalRun, -verticalRun, 0).normalize();- const tangent = profile.ridgeAxis === "x" ? new THREE31.Vector3(sideSign, 0, 0) : new THREE31.Vector3(0, 0, -sideSign);+ const downhill = profile.ridgeAxis === "x" ? new THREE32.Vector3(0, -verticalRun, sideSign * horizontalRun).normalize() : new THREE32.Vector3(sideSign * horizontalRun, -verticalRun, 0).normalize();+ const tangent = profile.ridgeAxis === "x" ? new THREE32.Vector3(sideSign, 0, 0) : new THREE32.Vector3(0, 0, -sideSign);const normal = downhill.clone().cross(tangent).normalize();- const localToRoof = new THREE31.Matrix4().makeBasis(tangent, normal, downhill);+ const localToRoof = new THREE32.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 THREE31.Vector3(x, 0, z).applyMatrix4(world());+ const point = (x, z) => new THREE32.Vector3(x, 0, z).applyMatrix4(world());return {side,ridgeAxis: profile.ridgeAxis,@@ -18904,13 +19359,13 @@ function buildFace(roofRoot, profile, sideSign) {return world();},get ridgeTangent() {- return direction(new THREE31.Vector3(1, 0, 0));+ return direction(new THREE32.Vector3(1, 0, 0));},get downhillDirection() {- return direction(new THREE31.Vector3(0, 0, 1));+ return direction(new THREE32.Vector3(0, 0, 1));},get outwardNormal() {- return direction(new THREE31.Vector3(0, 1, 0));+ return direction(new THREE32.Vector3(0, 1, 0));},get ridgeStart() {return point(-alongRidge / 2, 0);@@ -18928,17 +19383,17 @@ function buildFace(roofRoot, profile, sideSign) {};}function buildRoof(name, material, profile, parent) {- const root = new THREE31.Object3D;+ const root = new THREE32.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 THREE31.BoxGeometry(face.dimensions.alongRidge, profile.thickness, face.dimensions.downhill);- const mesh = new THREE31.Mesh(geometry, material);+ const geometry = new THREE32.BoxGeometry(face.dimensions.alongRidge, profile.thickness, face.dimensions.downhill);+ const mesh = new THREE32.Mesh(geometry, material);mesh.name = `Mesh_${name}_${face.side}`;- const center = new THREE31.Matrix4().makeTranslation(0, -profile.thickness / 2, face.dimensions.downhill / 2);+ const center = new THREE32.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)], [@@ -19008,7 +19463,7 @@ function createGableEndPanel(name, material, options) {const ridgeAxis = options.ridgeAxis ?? "x";const side = options.side ?? "positive";const half = span / 2;- const shape = new THREE31.Shape;+ const shape = new THREE32.Shape;shape.moveTo(-half, 0);shape.lineTo(half, 0);shape.lineTo(0, rise);@@ -19027,7 +19482,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 THREE31.Path;+ const hole = new THREE32.Path;hole.moveTo(left, bottom);hole.lineTo(left, top);hole.lineTo(right, top);@@ -19035,7 +19490,7 @@ function createGableEndPanel(name, material, options) {hole.closePath();shape.holes.push(hole);}- const geometry = new THREE31.ExtrudeGeometry(shape, {+ const geometry = new THREE32.ExtrudeGeometry(shape, {depth: thickness,bevelEnabled: false,steps: 1@@ -19044,7 +19499,7 @@ function createGableEndPanel(name, material, options) {if (ridgeAxis === "x")geometry.rotateY(-Math.PI / 2);geometry.computeVertexNormals();- const root = new THREE31.Mesh(geometry, material);+ const root = new THREE32.Mesh(geometry, material);root.name = `Mesh_${name}`;stampSemanticMetadataV1(root, roleMetadata([`roof.gable.${side}`], [relationship("adjacent-to", "roof.slope.positive"),@@ -19060,7 +19515,7 @@ function createGableEndPanel(name, material, options) {}]));const markers = normalized.map((opening, index) => {- const marker = new THREE31.Object3D;+ const marker = new THREE32.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);@@ -19080,7 +19535,7 @@ function wallNeighbors(wall) {}function createShellWall(name, wall, material, length, height, thickness, openings) {const axis = wallRunAxis(wall);- const root = new THREE31.Object3D;+ const root = new THREE32.Object3D;root.name = `${name}_Wall_${wall}`;const neighbors = wallNeighbors(wall);stampSemanticMetadataV1(root, roleMetadata([`wall.${wall}`], [@@ -19092,8 +19547,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 THREE31.BoxGeometry(hi - lo, y1 - y0, thickness) : new THREE31.BoxGeometry(thickness, y1 - y0, hi - lo);- const mesh = new THREE31.Mesh(geometry, material);+ const geometry = axis === "x" ? new THREE32.BoxGeometry(hi - lo, y1 - y0, thickness) : new THREE32.BoxGeometry(thickness, y1 - y0, hi - lo);+ const mesh = new THREE32.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);@@ -19110,7 +19565,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 THREE31.Object3D;+ const marker = new THREE32.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);@@ -19133,7 +19588,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 THREE31.Object3D;+ const root = new THREE32.Object3D;root.name = name;stampSemanticMetadataV1(root, roleMetadata(["architecture.shell.gable"], [relationship("contains", "floor"), relationship("contains", "roof.assembly")]));const wallSpecs = {@@ -19151,7 +19606,7 @@ function createGableShell(name, materials, options) {walls[wall] = built.root;openingMarkers.push(...built.openings);}- const floor = new THREE31.Mesh(new THREE31.BoxGeometry(spanX, floorThickness, spanZ), materials.floor ?? materials.wall);+ const floor = new THREE32.Mesh(new THREE32.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}`))));@@ -19266,13 +19721,13 @@ function createRoofSurfaceLayout(name, material, options) {assertDimension("createRoofSurfaceLayout generated width", spec.width);assertDimension("createRoofSurfaceLayout generated length", spec.length);}- const root = new THREE31.Object3D;+ const root = new THREE32.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 THREE31.Mesh(new THREE31.BoxGeometry(spec.width, thickness, spec.length), material);+ const mesh = new THREE32.Mesh(new THREE32.BoxGeometry(spec.width, thickness, spec.length), material);mesh.name = `Mesh_${name}_${index + 1}`;- const local = new THREE31.Matrix4().makeTranslation(spec.x, thickness / 2 + 0.002, spec.z);+ const local = new THREE32.Matrix4().makeTranslation(spec.x, thickness / 2 + 0.002, spec.z);setTransform(mesh, faceToRoot.clone().multiply(local));root.add(mesh);return mesh;@@ -19289,7 +19744,7 @@ var init_architecture2 = __esm(() => {});// src/gears.ts-import * as THREE32 from "three";+import * as THREE33 from "three";function gearGeo(opts = {}) {const {teeth = 12,@@ -19388,8 +19843,8 @@ function gearGeo(opts = {}) {indices.push(tA, bA, bB);indices.push(tA, bB, tB);}- const geo = new THREE32.BufferGeometry;- geo.setAttribute("position", new THREE32.Float32BufferAttribute(positions, 3));+ const geo = new THREE33.BufferGeometry;+ geo.setAttribute("position", new THREE33.Float32BufferAttribute(positions, 3));geo.setIndex(indices);const nonIndexed = geo.toNonIndexed();nonIndexed.computeVertexNormals();@@ -19474,8 +19929,8 @@ function bladeGeo(opts = {}) {indices.push(count + i, tip, count + j);}}- const geo = new THREE32.BufferGeometry;- geo.setAttribute("position", new THREE32.Float32BufferAttribute(positions, 3));+ const geo = new THREE33.BufferGeometry;+ geo.setAttribute("position", new THREE33.Float32BufferAttribute(positions, 3));geo.setIndex(indices);const nonIndexed = geo.toNonIndexed();nonIndexed.computeVertexNormals();@@ -19487,7 +19942,7 @@ var init_gears = __esm(() => {});// src/ops.ts-import * as THREE33 from "three";+import * as THREE34 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) {@@ -19521,9 +19976,9 @@ function arrayLinear(namePrefix, source, count, offset, parent) {}function degreesOf(euler) {return [- THREE33.MathUtils.radToDeg(euler.x),- THREE33.MathUtils.radToDeg(euler.y),- THREE33.MathUtils.radToDeg(euler.z)+ THREE34.MathUtils.radToDeg(euler.x),+ THREE34.MathUtils.radToDeg(euler.y),+ THREE34.MathUtils.radToDeg(euler.z)];}function arrayRadial(namePrefix, source, count, axis = "y", parent, center, options = {}) {@@ -19536,12 +19991,12 @@ function arrayRadial(namePrefix, source, count, axis = "y", parent, center, optiif (center)assertFiniteTriple("arrayRadial center", center);const out = [];- const pivot = center ? new THREE33.Vector3(...center) : new THREE33.Vector3;+ const pivot = center ? new THREE34.Vector3(...center) : new THREE34.Vector3;const basePos = source.position.clone().sub(pivot);- const axisVec = axis === "x" ? new THREE33.Vector3(1, 0, 0) : axis === "z" ? new THREE33.Vector3(0, 0, 1) : new THREE33.Vector3(0, 1, 0);+ const axisVec = axis === "x" ? new THREE34.Vector3(1, 0, 0) : axis === "z" ? new THREE34.Vector3(0, 0, 1) : new THREE34.Vector3(0, 1, 0);const positions = [];for (let i = 1;i < count; i++) {- const position = basePos.clone().applyMatrix4(new THREE33.Matrix4().makeRotationAxis(axisVec, i / count * Math.PI * 2)).add(pivot);+ const position = basePos.clone().applyMatrix4(new THREE34.Matrix4().makeRotationAxis(axisVec, i / count * Math.PI * 2)).add(pivot);assertFiniteTriple("arrayRadial resulting position", position.toArray());positions.push(position);}@@ -19580,7 +20035,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 THREE33.Vector3(...up);+ const upVector = new THREE34.Vector3(...up);if (upVector.lengthSq() === 0)throw new RangeError(`${name} up must not be zero.`);upVector.normalize();@@ -19619,13 +20074,13 @@ function repeatAlongCurve(source, points, options) {segment++;while (segment < points.length - 2 && cumulative[segment + 1] === cumulative[segment])segment++;- const a = new THREE33.Vector3(...points[segment]);- const b = new THREE33.Vector3(...points[segment + 1]);+ const a = new THREE34.Vector3(...points[segment]);+ const b = new THREE34.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 = THREE33.MathUtils.lerp(scale[0], scale[1], t);- const rotation = new THREE33.Matrix4;+ const k = THREE34.MathUtils.lerp(scale[0], scale[1], t);+ const rotation = new THREE34.Matrix4;let angle = 0;if (align === "tangent") {const tangent = b.clone().sub(a).normalize();@@ -19633,17 +20088,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 THREE33.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 THREE34.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 THREE33.Vector3().crossVectors(tangent, side));- angle = THREE33.MathUtils.degToRad(THREE33.MathUtils.lerp(twist[0], twist[1], t));+ rotation.makeBasis(tangent, side, new THREE34.Vector3().crossVectors(tangent, side));+ angle = THREE34.MathUtils.degToRad(THREE34.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 THREE33.Matrix4().makeRotationX(angle + extra));- const matrix = new THREE33.Matrix4().makeTranslation(position.x, position.y, position.z).multiply(turned).multiply(new THREE33.Matrix4().makeScale(k, k, k));+ turned.multiply(new THREE34.Matrix4().makeRotationX(angle + extra));+ const matrix = new THREE34.Matrix4().makeTranslation(position.x, position.y, position.z).multiply(turned).multiply(new THREE34.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 });@@ -19675,9 +20130,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 THREE33.BufferGeometry;- const vector = new THREE33.Vector3;- const normalMatrix = new THREE33.Matrix3;+ const merged = new THREE34.BufferGeometry;+ const vector = new THREE34.Vector3;+ const normalMatrix = new THREE34.Matrix3;for (const [key, attribute] of Object.entries(geometry.attributes)) {const size = attribute.itemSize;const transformed = key === "position" || key === "normal" || key === "tangent";@@ -19701,13 +20156,13 @@ function repeatAlongCurve(source, points, options) {}}}- merged.setAttribute(key, new THREE33.BufferAttribute(out, size, transformed ? false : attribute.normalized));+ merged.setAttribute(key, new THREE34.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 THREE33.BufferAttribute(along, 1));+ merged.setAttribute("_along", new THREE34.BufferAttribute(along, 1));}const index = geometry.getIndex();if (index) {@@ -19715,7 +20170,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 THREE33.BufferAttribute(indices, 1));+ merged.setIndex(new THREE34.BufferAttribute(indices, 1));}merged.computeBoundingBox();merged.computeBoundingSphere();@@ -19724,15 +20179,15 @@ function repeatAlongCurve(source, points, options) {function mirror(name, source, axis, parent) {if (source.matrixAutoUpdate)source.updateMatrix();- const reflected = new THREE33.Matrix4().makeScale(axis === "x" ? -1 : 1, axis === "y" ? -1 : 1, axis === "z" ? -1 : 1).multiply(source.matrix);+ const reflected = new THREE34.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 THREE33.Vector3;- const quaternion = new THREE33.Quaternion;- const scale = new THREE33.Vector3;+ const position = new THREE34.Vector3;+ const quaternion = new THREE34.Quaternion;+ const scale = new THREE34.Vector3;reflected.decompose(position, quaternion, scale);- const recomposed = new THREE33.Matrix4().compose(position, quaternion, scale);+ const recomposed = new THREE34.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.`);}@@ -19748,13 +20203,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 THREE33.BufferGeometry;+ const stripped = new THREE34.BufferGeometry;const pos = geometry.getAttribute("position");if (!pos)return geometry;- stripped.setAttribute("position", new THREE33.BufferAttribute(new Float32Array(pos.array), pos.itemSize, pos.normalized));+ stripped.setAttribute("position", new THREE34.BufferAttribute(new Float32Array(pos.array), pos.itemSize, pos.normalized));if (geometry.index) {- stripped.setIndex(new THREE33.BufferAttribute(new Uint32Array(geometry.index.array), 1));+ stripped.setIndex(new THREE34.BufferAttribute(new Uint32Array(geometry.index.array), 1));}return threeMergeVertices(stripped, tolerance);}@@ -19789,8 +20244,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 THREE33.Vector3);- const extent = prepared.boundingBox.getSize(new THREE33.Vector3);+ const center = prepared.boundingBox.getCenter(new THREE34.Vector3);+ const extent = prepared.boundingBox.getSize(new THREE34.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))@@ -19820,13 +20275,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 THREE33.BufferAttribute(values, 1));+ input.setAttribute(lane, new THREE34.BufferAttribute(values, 1));lanes.push(lane);}input.deleteAttribute(name);fourthComponents.push({ name, lanes });} else- input.setAttribute(name, new THREE33.BufferAttribute(decoded, components));+ input.setAttribute(name, new THREE34.BufferAttribute(decoded, components));}for (const targets of Object.values(input.morphAttributes))for (let target = 0;target < targets.length; target++) {@@ -19835,7 +20290,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 THREE33.BufferAttribute(decoded, 3);+ targets[target] = new THREE34.BufferAttribute(decoded, 3);}if (preserveUV)subOpts.uvSmooth = false;@@ -19849,7 +20304,7 @@ function subdivide(geometry, iterations = 1, opts = {}) {values[i * 4 + component] = lane.getX(i);output.deleteAttribute(lanes[component]);}- output.setAttribute(name, new THREE33.BufferAttribute(values, 4));+ output.setAttribute(name, new THREE34.BufferAttribute(values, 4));}output.scale(1 / normalizationScale, 1 / normalizationScale, 1 / normalizationScale).translate(center.x, center.y, center.z);output.userData = structuredClone(geometry.userData);@@ -19914,9 +20369,9 @@ function assertTubeRadius(radius) {}function curveToMesh(points, radius, tubularSegments = 32, radialSegments = 8, closed = false) {assertTubeRadius(radius);- const vectors = points.map((p) => new THREE33.Vector3(p[0], p[1], p[2]));- const curve = new THREE33.CatmullRomCurve3(vectors, closed);- return new THREE33.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);+ const vectors = points.map((p) => new THREE34.Vector3(p[0], p[1], p[2]));+ const curve = new THREE34.CatmullRomCurve3(vectors, closed);+ return new THREE34.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);}function normalizeSurfaceNormals(geo) {const normal = geo.getAttribute("normal");@@ -19947,15 +20402,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 THREE33.Vector2(p[0], p[1]));- const geo = normalizeSurfaceNormals(new THREE33.LatheGeometry(points2d, segments, 0, angle));- const n = new THREE33.Vector3(axis[0], axis[1], axis[2]);+ const points2d = profile.map((p) => new THREE34.Vector2(p[0], p[1]));+ const geo = normalizeSurfaceNormals(new THREE34.LatheGeometry(points2d, segments, 0, angle));+ const n = new THREE34.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 THREE33.Quaternion().setFromUnitVectors(new THREE33.Vector3(0, 1, 0), n);+ const q = new THREE34.Quaternion().setFromUnitVectors(new THREE34.Vector3(0, 1, 0), n);geo.applyQuaternion(q);}return geo;@@ -19971,9 +20426,9 @@ function pipeAlongPath(points, radius, options = {}) {const smoothed = [];smoothed.push(points[0]);for (let i = 1;i < points.length - 1; i++) {- const prev = new THREE33.Vector3(...points[i - 1]);- const cur = new THREE33.Vector3(...points[i]);- const next = new THREE33.Vector3(...points[i + 1]);+ const prev = new THREE34.Vector3(...points[i - 1]);+ const cur = new THREE34.Vector3(...points[i]);+ const next = new THREE34.Vector3(...points[i + 1]);const inDir = cur.clone().sub(prev);const outDir = next.clone().sub(cur);const inLen = inDir.length();@@ -19991,12 +20446,12 @@ function pipeAlongPath(points, radius, options = {}) {return curveToMesh(pathPoints, radius, tubularSegments, radialSegments, closed);}function bezierCurve(controlPoints, samples = 32) {- const vecs = controlPoints.map((p) => new THREE33.Vector3(p[0], p[1], p[2]));+ const vecs = controlPoints.map((p) => new THREE34.Vector3(p[0], p[1], p[2]));let curve;if (vecs.length === 3) {- curve = new THREE33.QuadraticBezierCurve3(vecs[0], vecs[1], vecs[2]);+ curve = new THREE34.QuadraticBezierCurve3(vecs[0], vecs[1], vecs[2]);} else if (vecs.length === 4) {- curve = new THREE33.CubicBezierCurve3(vecs[0], vecs[1], vecs[2], vecs[3]);+ curve = new THREE34.CubicBezierCurve3(vecs[0], vecs[1], vecs[2], vecs[3]);} else {throw new Error(`bezierCurve: need 3 or 4 control points, got ${vecs.length}`);}@@ -20009,20 +20464,20 @@ var init_ops = __esm(() => {});// src/deformation-normals.ts-import * as THREE34 from "three";+import * as THREE35 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 THREE34.Box3().setFromBufferAttribute(attribute);+ const box = new THREE35.Box3().setFromBufferAttribute(attribute);return {- center: box.getCenter(new THREE34.Vector3),- size: box.getSize(new THREE34.Vector3).length() || 1+ center: box.getCenter(new THREE35.Vector3),+ size: box.getSize(new THREE35.Vector3).length() || 1};};const before = bounds(original), after = bounds(position);- const point = new THREE34.Vector3, normal = new THREE34.Vector3;+ const point = new THREE35.Vector3, normal = new THREE35.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(",");@@ -20045,7 +20500,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 THREE34.Vector3, b = new THREE34.Vector3, c = new THREE34.Vector3;+ const a = new THREE35.Vector3, b = new THREE35.Vector3, c = new THREE35.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;@@ -20066,17 +20521,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 THREE34.BufferAttribute(normals, 3));+ output.setAttribute("normal", new THREE35.BufferAttribute(normals, 3));}var init_deformation_normals = () => {};// src/deform.ts-import * as THREE35 from "three";+import * as THREE36 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 THREE35.Matrix4().compose(new THREE35.Vector3(...origin), new THREE35.Quaternion().setFromEuler(new THREE35.Euler(...rotation.map(THREE35.MathUtils.degToRad), "XYZ")), new THREE35.Vector3(1, 1, 1));+ return new THREE36.Matrix4().compose(new THREE36.Vector3(...origin), new THREE36.Quaternion().setFromEuler(new THREE36.Euler(...rotation.map(THREE36.MathUtils.degToRad), "XYZ")), new THREE36.Vector3(1, 1, 1));}function deform(geometry, options, map) {const source = geometry.getAttribute("position");@@ -20103,7 +20558,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 THREE35.Vector3().fromBufferAttribute(source, i).applyMatrix4(inverse));+ const points = Array.from({ length: source.count }, (_, i) => new THREE36.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;@@ -20126,7 +20581,7 @@ function deform(geometry, options, map) {const point = points[i];if (point.y < low - epsilon || point.y > high + epsilon)continue;- const t = length > 0 ? THREE35.MathUtils.clamp((point.y - low) / length, 0, 1) : 0;+ const t = length > 0 ? THREE36.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");@@ -20160,31 +20615,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 THREE35.Vector3(0, 1, 0), THREE35.MathUtils.degToRad(options.angle) * t));+ return deform(geometry, options, (p, t) => p.applyAxisAngle(new THREE36.Vector3(0, 1, 0), THREE36.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 = THREE35.MathUtils.degToRad(options.angle);+ const angle = THREE36.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 THREE35.Vector3(radius - (radius - p.x) * Math.cos(theta), low + (radius - p.x) * Math.sin(theta), p.z);+ return new THREE36.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 * THREE35.MathUtils.lerp(start[0], end[0], t), p.y, p.z * THREE35.MathUtils.lerp(start[1], end[1], t)));+ return deform(geometry, options, (p, t) => p.set(p.x * THREE36.MathUtils.lerp(start[0], end[0], t), p.y, p.z * THREE36.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 THREE35.Vector3(...delta));+ return p.add(new THREE36.Vector3(...delta));});}var init_deform = __esm(() => {@@ -20192,7 +20647,7 @@ var init_deform = __esm(() => {});// src/sweep.ts-import * as THREE36 from "three";+import * as THREE37 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.`);@@ -20200,9 +20655,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 THREE36.Vector2(...p));- const bounds = new THREE36.Box2().setFromPoints(points);- const extent = bounds.getSize(new THREE36.Vector2).length();+ const points = profile.map((p) => new THREE37.Vector2(...p));+ const bounds = new THREE37.Box2().setFromPoints(points);+ const extent = bounds.getSize(new THREE37.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));@@ -20225,7 +20680,7 @@ function profilePoints(profile) {throw new Error("profile self-intersects or touches itself");}}- const area = THREE36.ShapeUtils.area(normalized);+ const area = THREE37.ShapeUtils.area(normalized);if (Math.abs(area) < 0.000000000001)throw new Error("profile area must be nonzero");if (area < 0)@@ -20239,11 +20694,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 THREE36.MathUtils.radToDeg(angle) > creaseAngle + CREASE_TOLERANCE_DEGREES;+ return THREE37.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 THREE36.Vector3).multiplyScalar(1 / n));+ const centers = rings.map((r) => r.reduce((sum, p) => sum.add(p), new THREE37.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]));@@ -20303,13 +20758,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 THREE36.Box2().setFromPoints(profile);- const size = bounds.getSize(new THREE36.Vector2);+ const bounds = new THREE37.Box2().setFromPoints(profile);+ const size = bounds.getSize(new THREE37.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 THREE36.ShapeUtils.triangulateShape(profile, [])) {+ for (const tri of THREE37.ShapeUtils.triangulateShape(profile, [])) {if (station === 0)indices.push(...tri.map((j) => start + j));else@@ -20322,7 +20777,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 THREE36.Vector3().fromBufferAttribute(normal, a).add(new THREE36.Vector3().fromBufferAttribute(normal, b)).normalize();+ const sum = new THREE37.Vector3().fromBufferAttribute(normal, a).add(new THREE37.Vector3().fromBufferAttribute(normal, b)).normalize();normal.setXYZ(a, sum.x, sum.y, sum.z);normal.setXYZ(b, sum.x, sum.y, sum.z);};@@ -20360,8 +20815,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 THREE36.Vector3(p.x, 0, p.y).applyMatrix4(frames[i])));- const out = buildLoft(rings, profiles, false, loftCapEnds(options.cap), new THREE36.Vector3(0, 1, 0).transformDirection(frames[0]));+ const rings = profiles.map((profile, i) => profile.map((p) => new THREE37.Vector3(p.x, 0, p.y).applyMatrix4(frames[i])));+ const out = buildLoft(rings, profiles, false, loftCapEnds(options.cap), new THREE37.Vector3(0, 1, 0).transformDirection(frames[0]));const analysis = recordSweepAnalysis(out, rings, profiles, false);out.userData.kilnGeometryWarnings = analysis.complete ? [] : [{@@ -20384,8 +20839,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 THREE36.Vector3(...p));- const pathExtent = new THREE36.Box3().setFromPoints(stations).getSize(new THREE36.Vector3).length();+ const stations = path.map((p) => new THREE37.Vector3(...p));+ const pathExtent = new THREE37.Box3().setFromPoints(stations).getSize(new THREE37.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;@@ -20426,7 +20881,7 @@ function sweepProfile(profile, path, options = {}) {});return incoming.clone().add(outgoing).normalize();});- const up = options.up ? new THREE36.Vector3(...options.up) : Math.abs(tangents[0].z) < 0.9 ? new THREE36.Vector3(0, 0, 1) : new THREE36.Vector3(1, 0, 0);+ const up = options.up ? new THREE37.Vector3(...options.up) : Math.abs(tangents[0].z) < 0.9 ? new THREE37.Vector3(0, 0, 1) : new THREE37.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");@@ -20443,7 +20898,7 @@ function sweepProfile(profile, path, options = {}) {}const distances = [0];for (let i = 1;i < stations.length; i++) {- z = z.clone().applyQuaternion(new THREE36.Quaternion().setFromUnitVectors(tangents[i - 1], tangents[i]));+ z = z.clone().applyQuaternion(new THREE37.Quaternion().setFromUnitVectors(tangents[i - 1], tangents[i]));normals.push(z);distances.push(distances[i - 1] + stations[i].distanceTo(stations[i - 1]));}@@ -20453,7 +20908,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 + THREE36.MathUtils.degToRad(twist)) * t);+ const axisZ = normals[i].clone().applyAxisAngle(tangent, (correction + THREE37.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]));});@@ -20478,7 +20933,7 @@ var init_sweep2 = __esm(() => {});// src/simplify.ts-import * as THREE37 from "three";+import * as THREE38 from "three";function loadSimplifier() {simplifierReady ??= import("meshoptimizer/simplifier").then(async ({ MeshoptSimplifier }) => {await MeshoptSimplifier.ready;@@ -20500,7 +20955,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 THREE37.BufferAttribute(values, attribute.itemSize, attribute.normalized);+ const out = new THREE38.BufferAttribute(values, attribute.itemSize, attribute.normalized);out.name = attribute.name;return out;}@@ -20785,14 +21240,14 @@ async function simplifyGeometry(geometry, options) {indexValues[i] = remap[w];}const sources = Uint32Array.from(used, (w) => representative[w]);- const out = new THREE37.BufferGeometry;+ const out = new THREE38.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 THREE37.BufferAttribute(outPosition, 3);+ const attr = new THREE38.BufferAttribute(outPosition, 3);attr.name = attribute.name;out.setAttribute(name, attr);} else@@ -20801,7 +21256,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 THREE37.BufferAttribute(indexValues, 1));+ out.setIndex(new THREE38.BufferAttribute(indexValues, 1));for (const group of outGroups)out.addGroup(group.start, group.count, group.materialIndex);out.computeBoundingBox();@@ -20856,7 +21311,7 @@ var init_simplify = __esm(() => {});// src/solids.ts-import * as THREE38 from "three";+import * as THREE39 from "three";async function getManifoldModule() {if (_module)return _module;@@ -20886,10 +21341,10 @@ function computationFrame(parts) {meshes.push(mesh);});}- const origin = meshes.length ? new THREE38.Vector3().setFromMatrixPosition(meshes[0].matrixWorld) : new THREE38.Vector3;+ const origin = meshes.length ? new THREE39.Vector3().setFromMatrixPosition(meshes[0].matrixWorld) : new THREE39.Vector3;const matrices = new Map;- const bounds = new THREE38.Box3;- const point = new THREE38.Vector3;+ const bounds = new THREE39.Box3;+ const point = new THREE39.Vector3;for (const mesh of meshes) {const matrix = mesh.matrixWorld.clone();matrix.elements[12] -= origin.x;@@ -20906,11 +21361,11 @@ function computationFrame(parts) {bounds.expandByPoint(point);}}- const size = bounds.getSize(new THREE38.Vector3);+ const size = bounds.getSize(new THREE39.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 THREE38.Vector3), scale: scale || 1, matrices };+ return { origin, center: bounds.getCenter(new THREE39.Vector3), scale: scale || 1, matrices };}function retainNotes(target, notes) {if (!Array.isArray(notes))@@ -20990,7 +21445,7 @@ function threeToManifold(src, mod, label, context) {elsecontext.missingUV.add(mesh.name || label);}- const point = new THREE38.Vector3;+ const point = new THREE39.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))))@@ -21133,11 +21588,11 @@ function solidMeshToGeometry({ mesh, collapsed }, opts = {}) {if (uvs)uvs.set(mesh.vertProperties.subarray(i + 3, i + 5), v * 2);}- const geometry = new THREE38.BufferGeometry;- geometry.setAttribute("position", new THREE38.BufferAttribute(positions, 3));- geometry.setIndex(new THREE38.BufferAttribute(new Uint32Array(mesh.triVerts), 1));+ const geometry = new THREE39.BufferGeometry;+ geometry.setAttribute("position", new THREE39.BufferAttribute(positions, 3));+ geometry.setIndex(new THREE39.BufferAttribute(new Uint32Array(mesh.triVerts), 1));if (uvs)- geometry.setAttribute("uv", new THREE38.BufferAttribute(uvs, 2));+ geometry.setAttribute("uv", new THREE39.BufferAttribute(uvs, 2));const out = opts.smooth ? geometry : geometry.toNonIndexed();out.computeVertexNormals();if (opts.smooth && uvs) {@@ -21168,7 +21623,7 @@ function firstMaterial(src) {if (!material && mesh.isMesh)material = Array.isArray(mesh.material) ? mesh.material[0] : mesh.material;});- return material ?? new THREE38.MeshStandardMaterial;+ return material ?? new THREE39.MeshStandardMaterial;}function outputMesh(result, name, parts, opts, context, isHull) {const materialized = materializeSolid(result);@@ -21227,7 +21682,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 THREE38.Mesh(geometry, context.preserve && !isHull && materials.length ? materials : firstMaterial(parts[0]));+ const output = new THREE39.Mesh(geometry, context.preserve && !isHull && materials.length ? materials : firstMaterial(parts[0]));output.name = `Mesh_${name}`;output.position.copy(context.frame.origin);return output;@@ -21636,7 +22091,7 @@ function smoothUnionSpheres(point, spheres, blend) {}// src/organic.ts-import * as THREE39 from "three";+import * as THREE40 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.`);@@ -21668,8 +22123,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 THREE39.Vector3(p[0], p[1], p[2]));- const curve = new THREE39.CatmullRomCurve3(vectors, closed);+ const vectors = controlPoints.map((p) => new THREE40.Vector3(p[0], p[1], p[2]));+ const curve = new THREE40.CatmullRomCurve3(vectors, closed);const points = curve.getPoints(spans * samplesPerSpan);if (closed)points.pop();@@ -21723,8 +22178,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 THREE39.Vector3(...axis);- const fwd = new THREE39.Vector3(...forward);+ const up = new THREE40.Vector3(...axis);+ const fwd = new THREE40.Vector3(...forward);if (up.lengthSq() < 0.000000000001 || fwd.lengthSq() < 0.000000000001)throw new Error("spiralPath axis and forward must be nonzero");up.normalize();@@ -21732,7 +22187,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 THREE39.Vector3().crossVectors(up, horiz).normalize();+ const right = new THREE40.Vector3().crossVectors(up, horiz).normalize();const out = [];for (let i = 0;i <= samples; i++) {const u = i / samples;@@ -22067,7 +22522,7 @@ var init_procedural_texture_v3 = __esm(() => {});// src/procedural-texture.ts-import * as THREE40 from "three";+import * as THREE41 from "three";function proceduralTextureSchemaVersion(input) {if (!input || typeof input !== "object" || Array.isArray(input))throw new ProceduralTextureError("proceduralTexture requires a plain JSON object.", "PROCEDURAL_TEXTURE_V3_CONTRACT");@@ -22088,14 +22543,14 @@ function proceduralTexture(spec) {if (proceduralTextureSchemaVersion(spec) === 3) {const compiled = compileProceduralTextureSpecV3(spec);const { width, height, usage, name } = compiled.spec;- const tex = new THREE40.DataTexture(compiled.pixels, width, height, THREE40.RGBAFormat, THREE40.UnsignedByteType);+ const tex = new THREE41.DataTexture(compiled.pixels, width, height, THREE41.RGBAFormat, THREE41.UnsignedByteType);if (name)tex.name = name;- tex.colorSpace = usage === "albedo" || usage === "emissive" ? THREE40.SRGBColorSpace : THREE40.NoColorSpace;- tex.wrapS = THREE40.RepeatWrapping;- tex.wrapT = THREE40.RepeatWrapping;- tex.minFilter = THREE40.LinearMipmapLinearFilter;- tex.magFilter = THREE40.LinearFilter;+ tex.colorSpace = usage === "albedo" || usage === "emissive" ? THREE41.SRGBColorSpace : THREE41.NoColorSpace;+ tex.wrapS = THREE41.RepeatWrapping;+ tex.wrapT = THREE41.RepeatWrapping;+ tex.minFilter = THREE41.LinearMipmapLinearFilter;+ tex.magFilter = THREE41.LinearFilter;tex.generateMipmaps = true;tex.needsUpdate = true;tex.userData["kilnProcedural"] = {@@ -22108,14 +22563,14 @@ function proceduralTexture(spec) {}const compiled = compileProceduralTextureSpecV2(spec);const { size, usage, name, layers } = compiled.spec;- const tex = new THREE40.DataTexture(compiled.pixels, size, size, THREE40.RGBAFormat, THREE40.UnsignedByteType);+ const tex = new THREE41.DataTexture(compiled.pixels, size, size, THREE41.RGBAFormat, THREE41.UnsignedByteType);if (name)tex.name = name;- tex.colorSpace = usage === "albedo" || usage === "emissive" ? THREE40.SRGBColorSpace : THREE40.NoColorSpace;- tex.wrapS = THREE40.RepeatWrapping;- tex.wrapT = THREE40.RepeatWrapping;- tex.minFilter = THREE40.LinearMipmapLinearFilter;- tex.magFilter = THREE40.LinearFilter;+ tex.colorSpace = usage === "albedo" || usage === "emissive" ? THREE41.SRGBColorSpace : THREE41.NoColorSpace;+ tex.wrapS = THREE41.RepeatWrapping;+ tex.wrapT = THREE41.RepeatWrapping;+ tex.minFilter = THREE41.LinearMipmapLinearFilter;+ tex.magFilter = THREE41.LinearFilter;tex.generateMipmaps = true;tex.needsUpdate = true;tex.userData["kilnProcedural"] = {@@ -22169,13 +22624,13 @@ function normalMapFromHeight(source, opts = {}) {out[o + 3] = 255;}}- const tex = new THREE40.DataTexture(out, width, height, THREE40.RGBAFormat, THREE40.UnsignedByteType);+ const tex = new THREE41.DataTexture(out, width, height, THREE41.RGBAFormat, THREE41.UnsignedByteType);tex.name = opts.name ?? (source.name ? `${source.name}_Normal` : "");- tex.colorSpace = THREE40.NoColorSpace;- tex.wrapS = THREE40.RepeatWrapping;- tex.wrapT = THREE40.RepeatWrapping;- tex.minFilter = THREE40.LinearMipmapLinearFilter;- tex.magFilter = THREE40.LinearFilter;+ tex.colorSpace = THREE41.NoColorSpace;+ tex.wrapS = THREE41.RepeatWrapping;+ tex.wrapT = THREE41.RepeatWrapping;+ tex.minFilter = THREE41.LinearMipmapLinearFilter;+ tex.magFilter = THREE41.LinearFilter;tex.generateMipmaps = true;tex.needsUpdate = true;return tex;@@ -22273,7 +22728,7 @@ var init_seeded_random = __esm(() => {});// src/textures.ts-import * as THREE41 from "three";+import * as THREE42 from "three";async function loadTexture(source, opts = {}) {let bytes;if (typeof source === "string") {@@ -22294,7 +22749,7 @@ async function loadTexture(source, opts = {}) {if (!meta.width || !meta.height) {throw new Error("loadTexture: could not read image dimensions");}- const tex = new THREE41.DataTexture(new Uint8Array(data), meta.width, meta.height, THREE41.RGBAFormat, THREE41.UnsignedByteType);+ const tex = new THREE42.DataTexture(new Uint8Array(data), meta.width, meta.height, THREE42.RGBAFormat, THREE42.UnsignedByteType);const usage = opts.usage ?? "albedo";const colorSpace = usage === "albedo" || usage === "emissive" ? "srgb" : "linear";let hasAlpha = false;@@ -22304,14 +22759,14 @@ async function loadTexture(source, opts = {}) {break;}}- tex.colorSpace = colorSpace === "srgb" ? THREE41.SRGBColorSpace : THREE41.NoColorSpace;+ tex.colorSpace = colorSpace === "srgb" ? THREE42.SRGBColorSpace : THREE42.NoColorSpace;if (opts.name)tex.name = opts.name;tex.needsUpdate = true;- tex.wrapS = THREE41.RepeatWrapping;- tex.wrapT = THREE41.RepeatWrapping;- tex.minFilter = THREE41.LinearMipmapLinearFilter;- tex.magFilter = THREE41.LinearFilter;+ tex.wrapS = THREE42.RepeatWrapping;+ tex.wrapT = THREE42.RepeatWrapping;+ tex.minFilter = THREE42.LinearMipmapLinearFilter;+ tex.magFilter = THREE42.LinearFilter;tex.generateMipmaps = true;tex.userData["encoded"] = {mime,@@ -22346,17 +22801,17 @@ function requireTextureUsage(texture, usage) {if (meta && meta.usage !== usage) {throw new TypeError(`Texture ${JSON.stringify(texture.name || "(unnamed)")} was loaded for ${meta.usage}, not ${usage}.`);}- texture.colorSpace = usage === "albedo" || usage === "emissive" ? THREE41.SRGBColorSpace : THREE41.NoColorSpace;+ texture.colorSpace = usage === "albedo" || usage === "emissive" ? THREE42.SRGBColorSpace : THREE42.NoColorSpace;}function pbrMaterial(opts = {}) {- const mat = new THREE41.MeshStandardMaterial;+ const mat = new THREE42.MeshStandardMaterial;const isTex = (v) => !!v?.isTexture;if (isTex(opts.albedo)) {requireTextureUsage(opts.albedo, "albedo");mat.map = opts.albedo;- mat.color = new THREE41.Color(16777215);+ mat.color = new THREE42.Color(16777215);} else if (opts.albedo !== undefined) {- mat.color = new THREE41.Color(opts.albedo);+ mat.color = new THREE42.Color(opts.albedo);}if (opts.normal) {requireTextureUsage(opts.normal, "normal");@@ -22394,9 +22849,9 @@ function pbrMaterial(opts = {}) {if (isTex(opts.emissive)) {requireTextureUsage(opts.emissive, "emissive");mat.emissiveMap = opts.emissive;- mat.emissive = new THREE41.Color(16777215);+ mat.emissive = new THREE42.Color(16777215);} else if (opts.emissive !== undefined) {- mat.emissive = new THREE41.Color(opts.emissive);+ mat.emissive = new THREE42.Color(opts.emissive);}if (opts.emissiveIntensity !== undefined) {mat.emissiveIntensity = opts.emissiveIntensity;@@ -22428,7 +22883,7 @@ function pbrMaterial(opts = {}) {mat.transparent = true;}if (opts.doubleSided)- mat.side = THREE41.DoubleSide;+ mat.side = THREE42.DoubleSide;mat.userData["kilnMaterial"] = {alphaMode,...alphaMode === "mask" ? { alphaCutoff: mat.alphaTest } : {},@@ -22723,7 +23178,7 @@ var init_texture_atlas_pixels = __esm(() => {});// src/uv-shapes.ts-import * as THREE42 from "three";+import * as THREE43 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.");@@ -22752,7 +23207,7 @@ function remapUV(geo, options = {}) {}const cloned = geo.clone();cloned.userData = structuredClone(geo.userData);- cloned.setAttribute("uv", new THREE42.Float32BufferAttribute(values, 2));+ cloned.setAttribute("uv", new THREE43.Float32BufferAttribute(values, 2));if ((scale[0] !== 1 || scale[1] !== 1) && cloned.hasAttribute("tangent")) {cloned.deleteAttribute("tangent");const previous = cloned.userData.kilnAttributeWarnings;@@ -22769,13 +23224,13 @@ function remapUV(geo, options = {}) {var init_uv_shapes = () => {};// src/texture-atlas.ts-import * as THREE43 from "three";+import * as THREE44 from "three";async function textureAtlas(input, options = {}) {const compiled = await compileTextureAtlasSpecV1(input, options);- const texture = new THREE43.DataTexture(compiled.pixels, compiled.spec.width, compiled.spec.height, THREE43.RGBAFormat, THREE43.UnsignedByteType);+ const texture = new THREE44.DataTexture(compiled.pixels, compiled.spec.width, compiled.spec.height, THREE44.RGBAFormat, THREE44.UnsignedByteType);texture.name = "Atlas";texture.flipY = false;- texture.colorSpace = compiled.spec.usage === "albedo" || compiled.spec.usage === "emissive" ? THREE43.SRGBColorSpace : THREE43.NoColorSpace;+ texture.colorSpace = compiled.spec.usage === "albedo" || compiled.spec.usage === "emissive" ? THREE44.SRGBColorSpace : THREE44.NoColorSpace;applyPortableSamplerV1(texture, compiled.spec.sampler);texture.userData.kilnAtlas = { spec: compiled.spec, manifest: compiled.manifest };texture.userData.kilnTexture = {@@ -22833,7 +23288,7 @@ function remapUVToAtlas(geometry, atlas, name, options) {bytes += buffer.byteLength;}} else {- bytes += attribute.array.byteLength * (attribute.constructor === THREE43.BufferAttribute || attribute.constructor === THREE43.InstancedBufferAttribute ? 1 : 2);+ bytes += attribute.array.byteLength * (attribute.constructor === THREE44.BufferAttribute || attribute.constructor === THREE44.InstancedBufferAttribute ? 1 : 2);}};for (const attr of Object.values(geometry.attributes))@@ -24990,7 +25445,7 @@ var init_material_resources = __esm(() => {});// src/material-recipe-runtime.ts-import * as THREE44 from "three";+import * as THREE45 from "three";async function applyMaterialRecipeV1(request, options = {}) {const resolved = resolveMaterialRecipeV1(request);const cache = options.cache ?? DEFAULT_APPROVED_TEXTURE_CACHE;@@ -25013,9 +25468,9 @@ async function applyMaterialRecipeV1(request, options = {}) {};const material = pbrMaterial(materialOptions);material.name = options.name ?? request.id;- material.color.setRGB(resolved.baseColorFactor[0], resolved.baseColorFactor[1], resolved.baseColorFactor[2], THREE44.LinearSRGBColorSpace);+ material.color.setRGB(resolved.baseColorFactor[0], resolved.baseColorFactor[1], resolved.baseColorFactor[2], THREE45.LinearSRGBColorSpace);material.opacity = resolved.baseColorFactor[3];- material.emissive.setRGB(resolved.emissiveFactor[0], resolved.emissiveFactor[1], resolved.emissiveFactor[2], THREE44.LinearSRGBColorSpace);+ material.emissive.setRGB(resolved.emissiveFactor[0], resolved.emissiveFactor[1], resolved.emissiveFactor[2], THREE45.LinearSRGBColorSpace);const resources = [...loaded.values()].map((entry) => entry.provenance).sort((a, b) => `${a.resourceId}:${a.usage}`.localeCompare(`${b.resourceId}:${b.usage}`));const provenance = {schemaVersion: 1,@@ -25451,7 +25906,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)@@ -25486,7 +25941,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))@@ -25598,7 +26053,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 () => {@@ -25630,7 +26085,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;@@ -25640,8 +26095,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);@@ -25676,11 +26131,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)))@@ -25716,7 +26171,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.");@@ -25757,15 +26212,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);@@ -25780,8 +26235,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();@@ -25837,7 +26292,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;@@ -25858,17 +26313,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)@@ -25900,16 +26355,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);@@ -25932,7 +26387,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);@@ -25951,7 +26406,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);@@ -25966,20 +26421,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);@@ -25996,7 +26451,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(",")}]).`);@@ -26004,7 +26459,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;@@ -26026,7 +26481,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);@@ -26034,14 +26489,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);@@ -26055,7 +26510,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;@@ -26071,12 +26526,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);@@ -26103,9 +26558,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;@@ -26120,7 +26575,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;@@ -26216,8 +26671,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;@@ -26248,17 +26703,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;@@ -26267,11 +26722,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];@@ -26287,7 +26742,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());@@ -26322,8 +26777,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)@@ -26331,7 +26786,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.");@@ -26341,19 +26796,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: [@@ -26393,7 +26848,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;@@ -26424,7 +26879,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, {@@ -26478,7 +26933,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;@@ -26508,7 +26963,7 @@ function requireColor(color, fn) {}function gameMaterial(color, options = {}) {requireColor(color, "gameMaterial");- const material = new THREE48.MeshStandardMaterial({+ const material = new THREE49.MeshStandardMaterial({color,metalness: options.metalness ?? 0,roughness: options.roughness ?? 0.8,@@ -26522,7 +26977,7 @@ function gameMaterial(color, options = {}) {}function basicMaterial(color, options = {}) {requireColor(color, "basicMaterial");- const material = new THREE48.MeshBasicMaterial({+ const material = new THREE49.MeshBasicMaterial({color,transparent: options.transparent ?? false,opacity: options.opacity ?? 1@@ -26533,13 +26988,13 @@ function basicMaterial(color, options = {}) {}function glassMaterial(color, options = {}) {requireColor(color, "glassMaterial");- const material = new THREE48.MeshStandardMaterial({+ const material = 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});if (options.name !== undefined)material.name = assertMaterialName(options.name, "glassMaterial");@@ -26547,7 +27002,7 @@ function glassMaterial(color, options = {}) {}function lambertMaterial(color, options = {}) {requireColor(color, "lambertMaterial");- const material = new THREE48.MeshLambertMaterial({+ const material = new THREE49.MeshLambertMaterial({color,flatShading: options.flatShading ?? true,emissive: options.emissive ?? 0@@ -26560,12 +27015,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) {@@ -26619,15 +27074,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);@@ -26637,7 +27092,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);@@ -26647,7 +27102,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())@@ -26660,7 +27115,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.");@@ -26674,12 +27129,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);@@ -26702,7 +27157,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;@@ -26779,12 +27234,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)@@ -27077,7 +27532,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};@@ -27220,7 +27675,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]);@@ -27338,10 +27793,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 = [];@@ -27365,7 +27820,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;@@ -27379,9 +27834,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;@@ -27702,7 +28157,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);@@ -29444,7 +29899,7 @@ var init_kit = __esm(() => {// src/texture-bake.tsimport { createHash as createHash5 } from "node:crypto";-import * as THREE50 from "three";+import * as THREE51 from "three";function readPixels(texture) {const image = texture.image;if (!image)@@ -29571,7 +30026,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)@@ -29654,10 +30109,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]);@@ -29677,7 +30132,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;@@ -29760,7 +30215,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)@@ -29922,7 +30377,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;@@ -29964,9 +30419,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,@@ -31229,7 +31684,7 @@ function prepareTriangleCoverage(ax, ay, bx, by, cx, cy, size) {}// src/views/raster.ts-import { Vector3 as Vector338 } from "three";+import { Vector3 as Vector339 } from "three";function orbitDir(azimuthDeg, elevationDeg) {const el = Math.min(MAX_ELEVATION_DEG, Math.max(MIN_ELEVATION_DEG, elevationDeg)) * Math.PI / 180;const az = azimuthDeg * Math.PI / 180;@@ -31253,7 +31708,7 @@ function updateSurfaceMatrices(root) {function surfaceVertexReader(mesh, position) {for (const bone of mesh.skeleton?.bones ?? [])bone.updateWorldMatrix?.(true, false);- const vertex = new Vector338;+ const vertex = new Vector339;if (mesh.getVertexPosition)return (index) => mesh.getVertexPosition(index, vertex);if (position.getX && position.getY && position.getZ)@@ -31530,7 +31985,7 @@ import {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 Vector340, Matrix4 as Matrix417, Euler as Euler5, Group as Group4 } from "three";function strict(value, keys, label) {for (const key of Object.keys(value))if (!keys.includes(key)) {@@ -31624,14 +32079,14 @@ function cameraFromBounds(bounds, dir, padding = 1, up, sceneBounds = bounds) {const z = vec(dir).normalize();if (!z.length())throw new Error("camera direction must be non-zero");- const hint = up ? vec(up) : Math.abs(z.y) > 0.99 ? new Vector339(0, 0, -1) : new Vector339(0, 1, 0);+ const hint = up ? vec(up) : Math.abs(z.y) > 0.99 ? new Vector340(0, 0, -1) : new Vector340(0, 1, 0);const x = hint.clone().cross(z).normalize();if (x.length() < 0.000000001)throw new Error("camera up must not be collinear with view");const y = z.clone().cross(x);let extent = 0.000001;for (let i = 0;i < 8; i++) {- const p = new Vector339((i & 1 ? bounds.max : bounds.min)[0], (i & 2 ? bounds.max : bounds.min)[1], (i & 4 ? bounds.max : bounds.min)[2]).sub(target);+ const p = new Vector340((i & 1 ? bounds.max : bounds.min)[0], (i & 2 ? bounds.max : bounds.min)[1], (i & 4 ? bounds.max : bounds.min)[2]).sub(target);extent = Math.max(extent, Math.abs(p.dot(x)), Math.abs(p.dot(y)));}const depthMin = bounds.min.map((v, i) => Math.min(v, sceneBounds.min[i]));@@ -31712,7 +32167,7 @@ function resolveAssetCamera(root, shot = {}) {if (relative !== "world") {const node = relative === "part" ? selected.node : rootNode;dir.transformDirection(node.matrixWorld);- up = tuple6(new Vector339(0, 1, 0).transformDirection(node.matrixWorld));+ up = tuple6(new Vector340(0, 1, 0).transformDirection(node.matrixWorld));}camera = cameraFromBounds(bounds, tuple6(dir), request.padding ?? 1.2, up, measureBounds(root));} else if (request.type === "explicit") {@@ -31759,7 +32214,7 @@ function resolveAssetCamera(root, shot = {}) {const position = vec(triple2(request.position, "position")).applyMatrix4(matrix);const target = request.target ? vec(triple2(request.target, "target")).applyMatrix4(matrix) : vec(bounds.min).add(vec(bounds.max)).multiplyScalar(0.5);const up = vec(triple2(request.up ?? [0, 1, 0], "up")).transformDirection(matrix);- const offset = vec(triple2(request.targetOffset ?? [0, 0, 0], "targetOffset")).applyMatrix4(matrix).sub(new Vector339().setFromMatrixPosition(matrix));+ const offset = vec(triple2(request.targetOffset ?? [0, 0, 0], "targetOffset")).applyMatrix4(matrix).sub(new Vector340().setFromMatrixPosition(matrix));const radius = vec(bounds.max).sub(vec(bounds.min)).length();camera = {version: "kiln.camera.v1",@@ -31872,11 +32327,11 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true, backdrop)}return result;};- const key = new Vector339(1.5, 2, 1).normalize();+ const key = new Vector340(1.5, 2, 1).normalize();const srgb = (n) => n <= 0.0031308 ? n * 12.92 : 1.055 * n ** (1 / 2.4) - 0.055;const ordered = compositingOrder(collectTriangles(root).tris, (px, py, pz) => camera.projection === "perspective" ? Math.hypot(px - position.x, py - position.y, pz - position.z) : (position.x - px) * z.x + (position.y - py) * z.y + (position.z - pz) * z.z);for (const tri of ordered) {- const world = [0, 1, 2].map((i) => new Vector339(tri.v[i * 3], tri.v[i * 3 + 1], tri.v[i * 3 + 2]));+ const world = [0, 1, 2].map((i) => new Vector340(tri.v[i * 3], tri.v[i * 3 + 1], tri.v[i * 3 + 2]));const normal = world[1].clone().sub(world[0]).cross(world[2].clone().sub(world[0])).normalize().multiplyScalar(tri.windingParity);const normalSign = visibleNormalSign(normal.dot(camera.projection === "perspective" ? position.clone().sub(world[0]) : z), tri.side, backfaceCull);if (normalSign === 0)@@ -31887,7 +32342,7 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true, backdrop)const color = tri.color.map((c) => Math.round(srgb(c * light) * 255));let polygon = world.map((p) => {const d = p.clone().sub(position);- return new Vector339(d.dot(x), d.dot(y), -d.dot(z));+ return new Vector340(d.dot(x), d.dot(y), -d.dot(z));});polygon = clip(clip(polygon, camera.near, true), camera.far, false);for (let t = 1;t < polygon.length - 1; t++) {@@ -31919,7 +32374,7 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true, backdrop)}return out;}-var vec = (a) => new Vector339(...a), tuple6 = (v) => [v.x || 0, v.y || 0, v.z || 0], KEY_HINTS;+var vec = (a) => new Vector340(...a), tuple6 = (v) => [v.x || 0, v.y || 0, v.z || 0], KEY_HINTS;var init_camera = __esm(() => {init_raster();init_background();@@ -32030,7 +32485,7 @@ import {PropertyBinding as PropertyBinding3,VectorKeyframeTrack as VectorKeyframeTrack2,Quaternion as Quaternion20,- Vector3 as Vector340,+ Vector3 as Vector341,InterpolateDiscrete as InterpolateDiscrete2,InterpolateLinear as InterpolateLinear2} from "three";@@ -32804,7 +33259,7 @@ var init_cli_output = () => {};// src/material-map-export-node.tsimport sharp from "sharp";-import * as THREE53 from "three";+import * as THREE54 from "three";var MATERIAL_MAP_EXPORT_LIMITS, PREVIEW_CAMERA, SRGB_TO_LINEAR;var init_material_map_export_node = __esm(() => {init_cli_output();@@ -33562,7 +34017,7 @@ var init_renderer_id = __esm(() => {});// src/views/scene-raster.ts-import * as THREE54 from "three";+import * as THREE55 from "three";var DEG2;var init_scene_raster = __esm(() => {init_evaluator();@@ -33574,18 +34029,18 @@ var init_scene_raster = __esm(() => {});// src/views/vehicle.ts-import * as THREE55 from "three";+import * as THREE56 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 THREE55.Box3;+ const bounds = new THREE56.Box3;let found = false;root.traverse((node) => {if (!hasRole2(node, "chassis"))return;node.traverse((part) => {- if (!(part instanceof THREE55.Mesh) || !(part.geometry instanceof THREE55.BufferGeometry))+ if (!(part instanceof THREE56.Mesh) || !(part.geometry instanceof THREE56.BufferGeometry))return;part.geometry.computeBoundingBox();const box = part.geometry.boundingBox;@@ -33595,7 +34050,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 THREE55.Vector3(x, y, z).applyMatrix4(matrix));+ bounds.expandByPoint(new THREE56.Vector3(x, y, z).applyMatrix4(matrix));found = true;}});@@ -33663,33 +34118,33 @@ function tagDiagnostic(node, role) {stampSemanticMetadataV1(node, { roles: [role] });}function rod(name, start, end, radius, color, role) {- const from = new THREE55.Vector3(...start);- const to = new THREE55.Vector3(...end);+ const from = new THREE56.Vector3(...start);+ const to = new THREE56.Vector3(...end);const direction = to.clone().sub(from);const length = direction.length();- 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 }));+ const geometry = length > 0.000000001 ? new THREE56.CylinderGeometry(radius, radius, length, 8) : new THREE56.SphereGeometry(radius, 8, 6);+ const result = new THREE56.Mesh(geometry, new THREE56.MeshBasicMaterial({ color }));result.name = name;result.position.copy(from).add(to).multiplyScalar(0.5);if (length > 0.000000001) {- result.quaternion.setFromUnitVectors(new THREE55.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));+ result.quaternion.setFromUnitVectors(new THREE56.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));}tagDiagnostic(result, role);return result;}function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnostics(root)) {- const overlay = new THREE55.Group;+ const overlay = new THREE56.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 THREE55.Group;+ const arrow = new THREE56.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 THREE55.Mesh(new THREE55.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE55.MeshBasicMaterial({ color: 16724804 }));+ const arrowHead = new THREE56.Mesh(new THREE56.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE56.MeshBasicMaterial({ color: 16724804 }));arrowHead.name = "Diagnostic_Forward_Head";arrowHead.position.set(descriptor.forwardArrow.end[0] - 0.12, 0, 0);- arrowHead.quaternion.setFromUnitVectors(new THREE55.Vector3(0, 1, 0), new THREE55.Vector3(1, 0, 0));+ arrowHead.quaternion.setFromUnitVectors(new THREE56.Vector3(0, 1, 0), new THREE56.Vector3(1, 0, 0));tagDiagnostic(arrowHead, "diagnostic.vehicle.forward");arrow.add(arrowHead);overlay.add(arrow);@@ -33697,18 +34152,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 THREE55.Mesh(new THREE55.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE55.MeshBasicMaterial({ color: 16763955 }));+ const ring = new THREE56.Mesh(new THREE56.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE56.MeshBasicMaterial({ color: 16763955 }));ring.name = `Diagnostic_Wheel_${wheel.id}`;ring.position.set(...wheel.center);- const axle = new THREE55.Vector3(...wheel.axle);+ const axle = new THREE56.Vector3(...wheel.axle);if (axle.lengthSq() > 0.000000000001) {- ring.quaternion.setFromUnitVectors(new THREE55.Vector3(0, 0, 1), axle.normalize());+ ring.quaternion.setFromUnitVectors(new THREE56.Vector3(0, 0, 1), axle.normalize());}tagDiagnostic(ring, `diagnostic.vehicle.wheel.${wheel.id}`);overlay.add(ring);}if (descriptor.chassisBox) {- const chassis = new THREE55.Group;+ const chassis = new THREE56.Group;chassis.name = "Diagnostic_ChassisBox";tagDiagnostic(chassis, "diagnostic.vehicle.chassis");const { min, max } = descriptor.chassisBox;@@ -33742,7 +34197,7 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnooverlay.add(chassis);}if (descriptor.supportPlaneY !== undefined) {- const plane = new THREE55.Group;+ const plane = new THREE56.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;@@ -34071,7 +34526,7 @@ var init_views = __esm(() => {});// src/views/character-capture.ts-import * as THREE56 from "three";+import * as THREE57 from "three";function drawLine2(rgb, width, height, from, to, color) {let x0 = Math.round(from[0]);let y0 = Math.round(from[1]);@@ -34108,22 +34563,22 @@ function drawCross(rgb, width, height, point, color, radius = 3) {}function projector(root, cameraId, size) {root.updateMatrixWorld(true);- const bounds = new THREE56.Box3().setFromObject(root);+ const bounds = new THREE57.Box3().setFromObject(root);if (bounds.isEmpty())- 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();+ bounds.set(new THREE57.Vector3(-0.5, 0, -0.5), new THREE57.Vector3(0.5, 1, 0.5));+ const center = bounds.getCenter(new THREE57.Vector3);+ const camera = cameraId === "front" ? new THREE57.Vector3(1, 0, 0) : new THREE57.Vector3(0, 0, 1);+ const upHint = new THREE57.Vector3(0, 1, 0);+ const xAxis = new THREE57.Vector3().crossVectors(upHint, camera).normalize();+ const yAxis = new THREE57.Vector3().crossVectors(camera, xAxis).normalize();let extent = 0.000001;for (let corner = 0;corner < 8; corner++) {- 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);+ const point = new THREE57.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 THREE56.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);+ const world = new THREE57.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);return [size / 2 + world.dot(xAxis) * scale, size / 2 - world.dot(yAxis) * scale];};}@@ -34249,7 +34704,7 @@ var init_character_capture = __esm(() => {});// src/render.ts-import * as THREE57 from "three";+import * as THREE58 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";@@ -34479,7 +34934,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache, authorExtras, atlas)} else if (stdMat.transparent) {mat.setAlphaMode("BLEND");}- if (stdMat.side === THREE57.DoubleSide) {+ if (stdMat.side === THREE58.DoubleSide) {mat.setDoubleSided(true);}if (stdMat.map) {@@ -34556,7 +35011,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache, authorExtras, atlas)} else if (common.transparent || (common.opacity ?? 1) < 1) {mat.setAlphaMode("BLEND");}- if (threeMat.side === THREE57.DoubleSide)+ if (threeMat.side === THREE58.DoubleSide)mat.setDoubleSided(true);if (common.map && !mat.getBaseColorTexture()) {const texture = bridgeTexture(doc, common.map, textureCache);@@ -34719,7 +35174,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 THREE57.PlaneGeometry(1, 1);+ const geometry = new THREE58.PlaneGeometry(1, 1);if (centerX !== 0.5 || centerY !== 0.5) {geometry.translate(0.5 - centerX, 0.5 - centerY, 0);}@@ -34743,9 +35198,9 @@ function animationInterpolation(track) {if (isCubicSplineTrack(track))return "CUBICSPLINE";const mode = track.getInterpolation();- if (mode === THREE57.InterpolateDiscrete)+ if (mode === THREE58.InterpolateDiscrete)return "STEP";- if (mode === THREE57.InterpolateLinear)+ if (mode === THREE58.InterpolateLinear)return "LINEAR";throw new Error(`Unsupported animation interpolation on ${track.name}; use LINEAR, STEP or CUBICSPLINE.`);}@@ -35309,8 +35764,8 @@ function collectMeshStats(root) {if (!Number.isFinite(box.min.x) || !Number.isFinite(box.max.x)) {return;}- const center = new THREE57.Vector3;- const size = new THREE57.Vector3;+ const center = new THREE58.Vector3;+ const size = new THREE58.Vector3;box.getCenter(center);box.getSize(size);out.push({@@ -35326,7 +35781,7 @@ function collectMeshStats(root) {return out;}function minimalGapVector(a, b) {- const v = new THREE57.Vector3;+ const v = new THREE58.Vector3;for (const axis of ["x", "y", "z"]) {if (a.min[axis] > b.max[axis])v[axis] = b.max[axis] - a.min[axis];@@ -35344,10 +35799,10 @@ function inspectSceneStructure(root, opts = {}) {return warnings;const cat = opts.category?.toLowerCase();if (cat === "vehicle" || cat === "weapon" || cat === "boat" || cat === "aircraft") {- const all = new THREE57.Box3;+ const all = new THREE58.Box3;for (const m of meshes)all.union(m.box);- const size = new THREE57.Vector3;+ const size = new THREE58.Vector3;all.getSize(size);if (cat === "aircraft") {if (size.y > size.x * 1.2) {@@ -35472,18 +35927,18 @@ var init_render = __esm(() => {engineIO = createGltfIO;ACCESSOR_TYPES = [TYPE_SCALAR, TYPE_VEC2, TYPE_VEC3, TYPE_VEC4];GLTF_MIN_FILTER = {- [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 };+ [THREE58.NearestFilter]: 9728,+ [THREE58.LinearFilter]: 9729,+ [THREE58.NearestMipmapNearestFilter]: 9984,+ [THREE58.LinearMipmapNearestFilter]: 9985,+ [THREE58.NearestMipmapLinearFilter]: 9986,+ [THREE58.LinearMipmapLinearFilter]: 9987+ };+ GLTF_MAG_FILTER = { [THREE58.NearestFilter]: 9728, [THREE58.LinearFilter]: 9729 };GLTF_WRAP = {- [THREE57.ClampToEdgeWrapping]: 33071,- [THREE57.MirroredRepeatWrapping]: 33648,- [THREE57.RepeatWrapping]: 10497+ [THREE58.ClampToEdgeWrapping]: 33071,+ [THREE58.MirroredRepeatWrapping]: 33648,+ [THREE58.RepeatWrapping]: 10497};REVIEW_CLIP_LIMITS = {clips: 32,diff --git a/dist/mcp-engine.mjs b/dist/mcp-engine.mjsindex 46355544..06950841 100644--- a/dist/mcp-engine.mjs+++ b/dist/mcp-engine.mjs@@ -18908,10 +18908,745 @@ var init_self_intersection = __esm(() => {});});-// src/sweep-analysis.ts+// src/geometry.tsimport * as THREE25 from "three";+function finiteArray(values, label, length) {+ const result = Array.from(values);+ if (length !== undefined && result.length !== length)+ throw new Error(`${label}: expected ${length} values, got ${result.length}`);+ if (!result.every((n) => Number.isFinite(Math.fround(n))))+ throw new AuthoringDiagnosticError("MESH_DATA_NONFINITE", `${label}: all values must be finite Float32 values`);+ return result;+}+function meshGeo(data) {+ const positions = finiteArray(data.positions, "meshGeo positions");+ if (positions.length < 9 || positions.length % 3)+ throw new Error("meshGeo positions: need at least three xyz vertices");+ const count = positions.length / 3;+ const geometry = new THREE25.BufferGeometry;+ geometry.setAttribute("position", new THREE25.Float32BufferAttribute(positions, 3));+ if (data.indices) {+ const indices = Array.from(data.indices);+ if (!indices.length || indices.length % 3)+ throw new Error("meshGeo indices: need complete triangles");+ if (!indices.every((i) => Number.isInteger(i) && i >= 0 && i < count))+ throw new Error("meshGeo index out of bounds or not an integer");+ geometry.setIndex(indices);+ } else if (count % 3)+ throw new Error("meshGeo: non-indexed positions must form complete triangles");+ if (data.normals) {+ const normals = finiteArray(data.normals, "meshGeo normals", count * 3);+ geometry.setAttribute("normal", new THREE25.Float32BufferAttribute(normals, 3));+ for (let i = 0;i < count; i++)+ if (Math.hypot(normals[i * 3], normals[i * 3 + 1], normals[i * 3 + 2]) === 0)+ throw new Error("meshGeo normals: zero-length normal");+ geometry.normalizeNormals();+ } else+ geometry.computeVertexNormals();+ if (data.uvs)+ geometry.setAttribute("uv", new THREE25.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 THREE25.Float32BufferAttribute(tangents, 4));+ }+ geometry.computeBoundingBox();+ geometry.computeBoundingSphere();+ return geometry;+}+function boundsScale(bounds) {+ const size = bounds.getSize(new THREE25.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 THREE25.Box3;+ const point = new THREE25.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 THREE25.Vector3 : bounds.min,+ scale: boundsScale(bounds)+ };+}+function positionTolerance(scale, supplied, relative) {+ if (supplied === undefined)+ return scale * relative;+ if (!Number.isFinite(supplied) || supplied <= 0)+ throw new Error("Geometry tolerance must be positive and finite");+ if (scale / supplied > Number.MAX_SAFE_INTEGER)+ throw new Error("Geometry tolerance is too small to resolve the position extent safely");+ return supplied;+}+function positionKey(point, origin, tolerance) {+ if (tolerance === 0)+ return point.toArray().join(",");+ return point.clone().sub(origin).toArray().map((x) => Math.round(x / tolerance)).join(",");+}+function geometryDiagnostics(geometry, tolerance) {+ const p = geometry.getAttribute("position");+ if (p?.itemSize !== 3)+ throw new Error("geometryDiagnostics requires xyz positions");+ const frame = positionFrame(p);+ const distance = positionTolerance(frame.scale, tolerance, 0.000001);+ const result = {+ tolerance: distance,+ toleranceMode: tolerance === undefined ? "relative" : "absolute",+ positionScale: frame.scale,+ vertices: p.count,+ triangles: 0,+ boundaryEdges: 0,+ nonManifoldEdges: 0,+ orientationConflicts: 0,+ degenerateTriangles: 0,+ collapsedByToleranceTriangles: 0,+ invalidIndices: 0,+ nonFiniteVertices: 0,+ solid: { closed: false, manifold: true, orientation: "mixed", signedVolume: 0 }+ };+ let signedVolume = 0;+ const pa = new THREE25.Vector3, pb = new THREE25.Vector3, pc = new THREE25.Vector3;+ const ids = [];+ const points = new Map;+ const finite = [];+ const point = new THREE25.Vector3;+ for (let i = 0;i < p.count; i++) {+ point.fromBufferAttribute(p, i);+ finite[i] = [point.x, point.y, point.z].every(Number.isFinite);+ if (!finite[i])+ result.nonFiniteVertices++;+ const key = finite[i] ? positionKey(point, frame.origin, distance) : `invalid:${i}`;+ if (!points.has(key))+ points.set(key, points.size);+ ids.push(points.get(key));+ }+ const indices = geometry.index ? Array.from(geometry.index.array) : Array.from({ length: p.count }, (_, i) => i);+ const edges = new Map;+ const a = new THREE25.Vector3, b = new THREE25.Vector3, c = new THREE25.Vector3;+ for (let i = 0;i < indices.length; i += 3) {+ result.triangles++;+ const triangle = indices.slice(i, i + 3);+ if (triangle.length !== 3 || triangle.some((n) => !Number.isInteger(n) || n < 0 || n >= p.count)) {+ result.invalidIndices++;+ continue;+ }+ const [ia, ib, ic] = triangle;+ if (!finite[ia] || !finite[ib] || !finite[ic])+ continue;+ pa.fromBufferAttribute(p, ia);+ pb.fromBufferAttribute(p, ib);+ pc.fromBufferAttribute(p, ic);+ signedVolume += pa.dot(pb.cross(pc)) / 6;+ a.fromBufferAttribute(p, ia);+ b.fromBufferAttribute(p, ib);+ c.fromBufferAttribute(p, ic);+ const scale = frame.scale || 1;+ b.sub(a).divideScalar(scale);+ c.sub(a).divideScalar(scale);+ if (b.cross(c).length() <= (distance / scale) ** 2)+ result.degenerateTriangles++;+ if (ids[ia] === ids[ib] || ids[ib] === ids[ic] || ids[ic] === ids[ia]) {+ result.collapsedByToleranceTriangles++;+ continue;+ }+ for (const [start, end] of [+ [ia, ib],+ [ib, ic],+ [ic, ia]+ ]) {+ const u = ids[start], v = ids[end];+ const key = u < v ? `${u}:${v}` : `${v}:${u}`;+ const edge = edges.get(key) ?? { count: 0, direction: 0 };+ edge.count++;+ edge.direction += u < v ? 1 : -1;+ edges.set(key, edge);+ }+ }+ for (const edge of edges.values()) {+ if (edge.count === 1)+ result.boundaryEdges++;+ else if (edge.count > 2)+ result.nonManifoldEdges++;+ else if (edge.direction !== 0)+ result.orientationConflicts++;+ }+ const volumeFloor = (frame.scale || 1) ** 3 * 0.000000000001;+ result.solid = {+ closed: result.boundaryEdges === 0 && edges.size > 0,+ manifold: result.nonManifoldEdges === 0,+ orientation: result.orientationConflicts > 0 || Math.abs(signedVolume) <= volumeFloor ? "mixed" : signedVolume > 0 ? "outward" : "inward",+ signedVolume: Object.is(signedVolume, -0) ? 0 : signedVolume+ };+ return result;+}+function parametricSurface(sample, options = {}) {+ const {+ u = [0, 1],+ v = [0, 1],+ uSegments: nu = 24,+ vSegments: nv = 24,+ periodicU = false,+ periodicV = false,+ orientation = "uv"+ } = options;+ for (const [name, n] of [+ ["uSegments", nu],+ ["vSegments", nv]+ ])+ if (!Number.isSafeInteger(n) || n < 1)+ throw new Error(`parametricSurface ${name} must be a positive integer`);+ const sampleCount = (nu + 1) * (nv + 1);+ if (!Number.isSafeInteger(sampleCount) || sampleCount > GEOMETRY_ALLOCATION_LIMITS.parametricSamples)+ throw new RangeError(`parametricSurface sample budget exceeded: requested ${sampleCount}, limit ${GEOMETRY_ALLOCATION_LIMITS.parametricSamples}. Reduce uSegments/vSegments or split the surface.`);+ for (const [name, range] of [+ ["u", u],+ ["v", v]+ ])+ if (range.length !== 2 || !range.every(Number.isFinite) || range[0] === range[1] || !Number.isFinite(range[1] - range[0]))+ throw new Error(`parametricSurface ${name} must be a finite nonzero domain`);+ if (orientation !== "uv" && orientation !== "vu")+ throw new Error("parametricSurface orientation must be uv or vu");+ const positions = [], uvs = [], indices = [];+ const sampledBounds = new THREE25.Box3;+ const sampledPoint = new THREE25.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);+ if (point.length !== 3 || !point.every(Number.isFinite))+ throw new Error(`parametricSurface: sample (${i},${j}) must return three finite coordinates`);+ positions.push(...point);+ sampledBounds.expandByPoint(sampledPoint.set(...point));+ uvs.push(i / nu, j / nv);+ }+ const groups = Array.from({ length: (nu + 1) * (nv + 1) }, (_, i) => i);+ const seamScale = boundsScale(sampledBounds);+ const find = (i) => {+ while (groups[i] !== i)+ i = groups[i];+ return i;+ };+ const join = (a, b, _label) => {+ const pa = positions.slice(a * 3, a * 3 + 3), pb = positions.slice(b * 3, b * 3 + 3);+ if (Math.hypot(...pa.map((x, k) => x - pb[k])) > seamScale * 0.000001)+ throw new AuthoringDiagnosticError("PARAMETRIC_PERIODIC_ENDPOINT");+ groups[find(b)] = find(a);+ for (let k = 0;k < 3; k++)+ positions[b * 3 + k] = positions[a * 3 + k];+ };+ if (periodicU)+ for (let j = 0;j <= nv; j++)+ join(j * (nu + 1), j * (nu + 1) + nu, "periodicU");+ if (periodicV)+ for (let i = 0;i <= nu; i++)+ join(i, nv * (nu + 1) + i, "periodicV");+ for (let j = 0;j < nv; j++)+ for (let i = 0;i < nu; i++) {+ const a = j * (nu + 1) + i, b = a + 1, c = a + nu + 1, d = c + 1;+ indices.push(...orientation === "uv" ? [a, b, c, b, d, c] : [a, c, b, b, c, d]);+ }+ const out = meshGeo({ positions, indices, uvs });+ if (periodicU || periodicV) {+ const normal = out.getAttribute("normal");+ const sums = new Map;+ for (let i = 0;i < normal.count; i++) {+ const id = find(i);+ const sum = sums.get(id) ?? new THREE25.Vector3;+ sum.add(new THREE25.Vector3().fromBufferAttribute(normal, i));+ sums.set(id, sum);+ }+ for (let i = 0;i < normal.count; i++) {+ const n = sums.get(find(i)).clone().normalize();+ normal.setXYZ(i, n.x, n.y, n.z);+ }+ }+ return out;+}+function creaseNormals(geometry, options = {}) {+ const angle = options.angle ?? 60;+ if (!Number.isFinite(angle) || angle < 0 || angle > 180)+ throw new Error("creaseNormals angle must be between 0 and 180 degrees");+ const out = geometry.index ? geometry.toNonIndexed() : geometry.clone();+ const position = out.getAttribute("position");+ if (position?.itemSize !== 3 || position.count % 3 !== 0)+ throw new Error("creaseNormals requires complete xyz triangles");+ const frame = positionFrame(position);+ const tolerance = positionTolerance(frame.scale, options.tolerance, 0.00000001);+ const scale = frame.scale || 1;+ const adjacent = new Map;+ const keys = [];+ const faces = [];+ for (let i = 0;i < position.count; i += 3) {+ const a = new THREE25.Vector3().fromBufferAttribute(position, i);+ const b = new THREE25.Vector3().fromBufferAttribute(position, i + 1);+ const c = new THREE25.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 THREE25.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);+ keys.push(key);+ const neighbors = adjacent.get(key) ?? new Set;+ neighbors.add(i / 3);+ adjacent.set(key, neighbors);+ }+ }+ const normals = new Float32Array(position.count * 3);+ const threshold = Math.cos(THREE25.MathUtils.degToRad(angle));+ for (let i = 0;i < position.count; i++) {+ const face = faces[Math.floor(i / 3)], sum = new THREE25.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 THREE25.BufferAttribute(normals, 3));+ out.deleteAttribute("tangent");+ out.computeBoundingBox();+ out.computeBoundingSphere();+ return out;+}+var init_geometry = __esm(() => {+ init_geometry_budget();+ init_authoring_diagnostic();+});++// src/qa/open-surface-penetration.ts+import * as THREE26 from "three";+function buildHierarchy(triangles) {+ const box = new THREE26.Box3;+ for (const triangle of triangles)+ box.union(triangle.box);+ if (triangles.length <= 4)+ return { box, triangles };+ const size = box.getSize(new THREE26.Vector3);+ const axis = size.x >= size.y && size.x >= size.z ? "x" : size.y >= size.z ? "y" : "z";+ const center = (triangle) => triangle.box.min[axis] / 2 + triangle.box.max[axis] / 2;+ const sorted = [...triangles].sort((a, b) => center(a) - center(b));+ const middle = Math.floor(sorted.length / 2);+ return {+ box,+ children: [buildHierarchy(sorted.slice(0, middle)), buildHierarchy(sorted.slice(middle))]+ };+}+function worldTriangles(mesh) {+ const geometry = mesh.geometry;+ const position = geometry.getAttribute("position");+ if (position?.itemSize !== 3)+ return null;+ const index = geometry.getIndex();+ const count = index ? index.count : position.count;+ if (count % 3 !== 0)+ return null;+ const triangles = [];+ const vertex = (at) => {+ const id = index ? index.getX(at) : at;+ if (!Number.isSafeInteger(id) || id < 0 || id >= position.count)+ return null;+ const point = new THREE26.Vector3().fromBufferAttribute(position, id).applyMatrix4(mesh.matrixWorld);+ return [point.x, point.y, point.z].every(Number.isFinite) ? point : null;+ };+ for (let i = 0;i < count; i += 3) {+ const a = vertex(i), b = vertex(i + 1), c = vertex(i + 2);+ if (!a || !b || !c)+ return null;+ const triangle = new THREE26.Triangle(a, b, c);+ triangles.push({ triangle, box: new THREE26.Box3().setFromPoints([a, b, c]) });+ }+ return triangles.length ? triangles : null;+}+function triangleCount2(geometry) {+ const index = geometry.getIndex();+ const position = geometry.getAttribute("position");+ if (!position)+ return 0;+ return Math.floor((index ? index.count : position.count) / 3);+}+function collectParts4(root, skipped) {+ const parts = [];+ root.updateWorldMatrix(true, true);+ root.traverseVisible((node) => {+ const mesh = node;+ if (!mesh.isMesh || !mesh.geometry)+ return;+ const name = mesh.name || "(unnamed mesh)";+ if (mesh.isInstancedMesh || mesh.isSkinnedMesh || Object.values(mesh.geometry.morphAttributes).some((targets) => targets.length)) {+ skipped.push({+ part: name,+ reason: "instancing, skin or morph deformation is unsupported by surface sampling"+ });+ return;+ }+ const total = mesh.geometry.index?.count ?? mesh.geometry.getAttribute("position")?.count ?? 0;+ const range = mesh.geometry.drawRange;+ if (range.start !== 0 || range.count < total) {+ skipped.push({+ part: name,+ reason: "partial triangle draw ranges are unsupported by surface sampling"+ });+ return;+ }+ const triangles = triangleCount2(mesh.geometry);+ if (triangles === 0)+ return;+ if (triangles > MAX_SURFACE_TRIANGLES) {+ skipped.push({+ part: name,+ reason: `${triangles} triangles exceeds the ${MAX_SURFACE_TRIANGLES}-triangle analysis budget`+ });+ return;+ }+ mesh.geometry.computeBoundingBox();+ const box = mesh.geometry.boundingBox.clone().applyMatrix4(mesh.matrixWorld);+ if (box.isEmpty())+ return;+ const determinant = mesh.matrixWorld.determinant();+ if (![...box.min, ...box.max].every(Number.isFinite) || !Number.isFinite(determinant)) {+ skipped.push({ part: name, reason: "non-finite transformed bounds cannot be measured" });+ return;+ }+ let diagnostics;+ try {+ diagnostics = geometryDiagnostics(mesh.geometry);+ } catch (error) {+ skipped.push({+ part: name,+ reason: `topology could not be analyzed (${error instanceof Error ? error.message : String(error)})`+ });+ return;+ }+ const closed = diagnostics.solid.closed && diagnostics.solid.manifold && diagnostics.solid.orientation !== "mixed";+ parts.push({ name, mesh, box, closed, lod: lodMembership(mesh) });+ });+ return parts;+}+function boxDistanceSquared(box, point) {+ const x = Math.max(box.min.x - point.x, 0, point.x - box.max.x);+ const y = Math.max(box.min.y - point.y, 0, point.y - box.max.y);+ const z = Math.max(box.min.z - point.z, 0, point.z - box.max.z);+ return x * x + y * y + z * z;+}+function boxOverlapRatio2(a, b) {+ const extent = (box) => (box.max.x - box.min.x) * (box.max.y - box.min.y) * (box.max.z - box.min.z);+ 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(extent(a), extent(b));+ return Number.isFinite(ratio) ? ratio : 0;+}++class Budget {+ limit;+ used = 0;+ exhausted = false;+ constructor(limit) {+ this.limit = limit;+ }+ spend() {+ if (this.used >= this.limit) {+ this.exhausted = true;+ return false;+ }+ this.used++;+ return true;+ }+}+function nearestDistance(root, point, budget) {+ let best = Infinity;+ const stack = [root];+ const scratch = new THREE26.Vector3;+ while (stack.length) {+ const node = stack.pop();+ if (boxDistanceSquared(node.box, point) >= best)+ continue;+ if ("triangles" in node) {+ for (const { triangle } of node.triangles) {+ if (!budget.spend())+ return null;+ const distance = point.distanceToSquared(triangle.closestPointToPoint(point, scratch));+ if (distance < best)+ best = distance;+ }+ } else+ stack.push(node.children[0], node.children[1]);+ }+ return Number.isFinite(best) ? Math.sqrt(best) : null;+}+function parity(root, point, direction, budget) {+ const ray = new THREE26.Ray(point, direction);+ const stack = [root];+ const hit = new THREE26.Vector3;+ const barycentric = new THREE26.Vector3;+ let crossings = 0;+ while (stack.length) {+ const node = stack.pop();+ if (!ray.intersectsBox(node.box))+ continue;+ if ("triangles" in node) {+ for (const { triangle } of node.triangles) {+ if (!budget.spend())+ return null;+ if (ray.intersectTriangle(triangle.a, triangle.b, triangle.c, false, hit) === null)+ continue;+ triangle.getBarycoord(hit, barycentric);+ if ([barycentric.x, barycentric.y, barycentric.z].some((v) => Math.abs(v) < PARITY_EPSILON))+ return null;+ crossings++;+ }+ } else+ stack.push(node.children[0], node.children[1]);+ }+ return crossings % 2 === 1;+}+function inside2(root, point, budget) {+ for (const direction of PARITY_DIRECTIONS) {+ const verdict = parity(root, point, direction, budget);+ if (verdict !== null)+ return verdict;+ if (budget.exhausted)+ return null;+ }+ return null;+}+function analyzeOpenSurfacePenetration(root, contactTolerance = OPEN_SURFACE_CONTACT_TOLERANCE) {+ const evidence = {+ schemaVersion: 1,+ source: "engine-scene-analysis",+ contactTolerance,+ openParts: 0,+ closedParts: 0,+ candidatePairs: 0,+ pairsTested: 0,+ pairsNotReached: 0,+ verticesUnresolved: 0,+ pairsLodAlternates: 0,+ truncated: false,+ skipped: [],+ penetrations: []+ };+ if (!(root instanceof THREE26.Object3D))+ return evidence;+ const parts = collectParts4(root, evidence.skipped);+ const open = parts.filter((part) => !part.closed);+ const closed = parts.filter((part) => part.closed);+ evidence.openParts = open.length;+ evidence.closedParts = closed.length;+ const candidates = [];+ let considered = 0;+ broadPhase:+ for (const surface of open) {+ for (const solid of closed) {+ if (considered++ === MAX_BROAD_PHASE_PAIRS2) {+ evidence.broadPhaseTruncated = true;+ break broadPhase;+ }+ if (!surface.box.intersectsBox(solid.box))+ continue;+ if (surface.lod && solid.lod && surface.lod.parent === solid.lod.parent && surface.lod.stem === solid.lod.stem && surface.lod.level !== solid.lod.level) {+ evidence.pairsLodAlternates++;+ continue;+ }+ candidates.push({+ open: surface,+ solid,+ overlap: boxOverlapRatio2(surface.box, solid.box),+ order: candidates.length+ });+ }+ }+ evidence.candidatePairs = candidates.length;+ evidence.truncated = evidence.broadPhaseTruncated === true;+ if (!candidates.length)+ return evidence;+ candidates.sort((x, y) => y.overlap - x.overlap || x.order - y.order);+ const budget = new Budget(MAX_WORK);+ const penetrations = [];+ for (const candidate of candidates) {+ if (budget.exhausted) {+ evidence.pairsNotReached++;+ continue;+ }+ if (!candidate.solid.hierarchy) {+ const triangles = worldTriangles(candidate.solid.mesh);+ if (!triangles) {+ evidence.skipped.push({+ part: candidate.solid.name,+ reason: "invalid or non-finite triangles cannot be indexed"+ });+ evidence.pairsNotReached++;+ continue;+ }+ candidate.solid.hierarchy = buildHierarchy(triangles);+ }+ const hierarchy = candidate.solid.hierarchy;+ const position = candidate.open.mesh.geometry.getAttribute("position");+ if (position?.itemSize !== 3) {+ evidence.skipped.push({+ part: candidate.open.name,+ reason: "open surfaces are sampled at their vertices and this part has none"+ });+ continue;+ }+ const matrix = candidate.open.mesh.matrixWorld;+ const limit = Math.min(position.count, MAX_SAMPLED_VERTICES);+ const vertex = new THREE26.Vector3;+ let depth = 0;+ let penetrating = 0;+ let tested = 0;+ let unresolved = 0;+ let partial = limit < position.count;+ for (let i = 0;i < limit; i++) {+ vertex.fromBufferAttribute(position, i).applyMatrix4(matrix);+ if (![vertex.x, vertex.y, vertex.z].every(Number.isFinite))+ continue;+ if (boxDistanceSquared(candidate.solid.box, vertex) > contactTolerance * contactTolerance) {+ tested++;+ continue;+ }+ const distance = nearestDistance(hierarchy, vertex, budget);+ if (distance === null) {+ partial = true;+ break;+ }+ tested++;+ if (distance <= contactTolerance)+ continue;+ const verdict = inside2(hierarchy, vertex, budget);+ if (verdict === null) {+ if (budget.exhausted) {+ partial = true;+ break;+ }+ unresolved++;+ continue;+ }+ if (!verdict)+ continue;+ penetrating++;+ if (distance > depth)+ depth = distance;+ }+ evidence.verticesUnresolved += unresolved;+ if (partial)+ evidence.pairsNotReached++;+ else+ evidence.pairsTested++;+ if (penetrating > 0)+ penetrations.push({+ open: candidate.open.name,+ solid: candidate.solid.name,+ depth: round2(depth),+ vertices: penetrating,+ tested+ });+ }+ evidence.truncated = evidence.truncated || evidence.pairsNotReached > 0;+ penetrations.sort((x, y) => y.depth - x.depth || `${x.open}:${x.solid}`.localeCompare(`${y.open}:${y.solid}`));+ evidence.penetrations = penetrations;+ return evidence;+}+function inspectOpenSurfacePenetration(evidence) {+ if (evidence?.schemaVersion !== 1)+ return [];+ const findings = evidence.penetrations.map((pair) => ({+ code: "GEO_OPEN_SURFACE_PENETRATION",+ disposition: "observe",+ dimension: "visualQuality",+ profile: "geometry.openSurfacePenetration",+ message: `Open surface ${JSON.stringify(pair.open)} reaches ${pair.depth.toFixed(4)} m inside solid ${JSON.stringify(pair.solid)}: ` + `${pair.vertices} of ${pair.tested} sampled ${pair.vertices === 1 ? "vertex lies" : "vertices lie"} deeper inside it than the ${evidence.contactTolerance} m contact tolerance.`,+ affected: { node: pair.open },+ measurement: {+ name: "openSurfacePenetrationDepth",+ actual: pair.depth,+ expected: evidence.contactTolerance,+ unit: "m",+ breakdown: { penetratingVertices: pair.vertices, sampledVertices: pair.tested }+ },+ repairText: "A positive here is not a defect. Most are intentional: a fitting set into a structural shell -- a lamp recess in a hull, a strut landing, a ridge into a cap -- puts shell vertices inside the solid by design, exactly as a bolt in a hole shares volume. Review the ones you did not intend, such as a cloth crossing a wall or a canopy pierced by a mast, and move the surface clear or cut it back to the solid. Vertices are the samples, so a solid thinner than this surface’s facet spacing can pass between two of them."+ }));+ const unresolved = evidence.verticesUnresolved ?? 0;+ if (evidence.truncated || unresolved > 0) {+ const clauses = [];+ if (evidence.truncated)+ clauses.push(`Sampled ${evidence.pairsTested} of ${evidence.broadPhaseTruncated ? "at least " : ""}${evidence.candidatePairs} overlapping open-surface and solid pairs; ` + `${evidence.pairsNotReached} were beyond the ${MAX_WORK}-test analysis budget.` + (evidence.broadPhaseTruncated ? ` Pair discovery stopped after ${MAX_BROAD_PHASE_PAIRS2} box comparisons.` : "") + " Unsampled pairs were not examined; the most overlapping bounding boxes were sampled first.");+ if (unresolved > 0)+ clauses.push(`${unresolved} ${unresolved === 1 ? "vertex" : "vertices"} further than the contact tolerance from a solid could not be resolved as inside or outside it, and ${unresolved === 1 ? "is" : "are"} counted as neither.`);+ findings.push({+ code: "GEO_OPEN_SURFACE_PENETRATION_TRUNCATED",+ disposition: "observe",+ dimension: "visualQuality",+ profile: "geometry.openSurfacePenetration",+ message: clauses.join(" "),+ measurement: {+ name: "openSurfacePairsSampled",+ actual: evidence.pairsTested,+ expected: evidence.candidatePairs,+ breakdown: {+ pairsNotReached: evidence.pairsNotReached,+ verticesUnresolved: unresolved+ }+ }+ });+ }+ if (evidence.skipped.length) {+ const byReason = new Map;+ for (const { part, reason } of evidence.skipped) {+ const parts = byReason.get(reason);+ if (parts)+ parts.push(part);+ else+ byReason.set(reason, [part]);+ }+ const reasons = [...byReason].map(([reason, parts]) => `${parts.length} because ${reason}: ${namedParts2(parts)}.`);+ const one = evidence.skipped.length === 1;+ findings.push({+ code: "GEO_OPEN_SURFACE_PENETRATION_UNMEASURED",+ disposition: "observe",+ dimension: "visualQuality",+ profile: "geometry.openSurfacePenetration",+ message: `${evidence.skipped.length} ${one ? "part was" : "parts were"} not sampled for open-surface penetration. ` + `${reasons.join(" ")} ${one ? "This part is" : "These parts are"} not certified clear of the solids around ${one ? "it" : "them"}.`+ });+ }+ return findings;+}+var OPEN_SURFACE_CONTACT_TOLERANCE = 0.005, MAX_SURFACE_TRIANGLES = 20000, MAX_SAMPLED_VERTICES = 20000, MAX_WORK = 250000, MAX_BROAD_PHASE_PAIRS2 = 250000, PARITY_DIRECTIONS, PARITY_EPSILON = 0.0000001, round2 = (value) => Number(value.toPrecision(9)), NAMES_SHOWN = 5, namedParts2 = (parts) => {+ const named = parts.slice(0, NAMES_SHOWN).map((part) => JSON.stringify(part));+ const more = parts.length > NAMES_SHOWN ? ` and ${parts.length - NAMES_SHOWN} more` : "";+ return `${named.join(", ")}${more}`;+}, OPEN_SURFACE_PENETRATION_QA_RULE;+var init_open_surface_penetration = __esm(() => {+ init_geometry();+ init_lod2();+ init_registry();+ PARITY_DIRECTIONS = Object.freeze([+ new THREE26.Vector3(1, 0, 0),+ new THREE26.Vector3(0.5773502691896258, 0.5773502691896258, 0.5773502691896258),+ new THREE26.Vector3(-0.2672612419124244, 0.5345224838248488, 0.8017837257372732)+ ]);+ OPEN_SURFACE_PENETRATION_QA_RULE = Object.freeze({+ id: "GEO_OPEN_SURFACE_PENETRATION",+ profile: "geometry.openSurfacePenetration",+ scope: { kind: "universal" },+ ruleClass: "heuristic",+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: "observe",+ evaluate(context) {+ return inspectOpenSurfacePenetration(analyzeOpenSurfacePenetration(context.scene));+ }+ });+});++// src/sweep-analysis.ts+import * as THREE27 from "three";function segmentHitsTriangle(a, b, tri, epsilon) {- const plane = new THREE25.Plane().setFromCoplanarPoints(tri.a, tri.b, tri.c);+ const plane = new THREE27.Plane().setFromCoplanarPoints(tri.a, tri.b, tri.c);if (plane.normal.lengthSq() === 0)return false;const da = plane.distanceToPoint(a), db = plane.distanceToPoint(b);@@ -18949,7 +19684,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 THREE25.Vector3).divideScalar(ring.length));+ const centers = rings.map((ring) => ring.reduce((sum, p) => sum.add(p), new THREE27.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);@@ -18963,17 +19698,17 @@ function recordSweepAnalysis(geometry, rings, profiles, closed) {const triangles = new Map;const faces = (index) => {if (!triangles.has(index))- triangles.set(index, THREE25.ShapeUtils.triangulateShape(profiles[index], []).map(([a, b, c]) => new THREE25.Triangle(rings[index][a], rings[index][b], rings[index][c])));+ triangles.set(index, THREE27.ShapeUtils.triangulateShape(profiles[index], []).map(([a, b, c]) => new THREE27.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 THREE25.Box3().setFromPoints(rings[i - 1]);- const boundsB = new THREE25.Box3().setFromPoints(rings[i]);+ const boundsA = new THREE27.Box3().setFromPoints(rings[i - 1]);+ const boundsB = new THREE27.Box3().setFromPoints(rings[i]);if (!boundsA.intersectsBox(boundsB)) {result.ringPairsChecked++;continue;}- const epsilon = Math.max(boundsA.getSize(new THREE25.Vector3).length(), boundsB.getSize(new THREE25.Vector3).length()) * 0.0000000001;+ const epsilon = Math.max(boundsA.getSize(new THREE27.Vector3).length(), boundsB.getSize(new THREE27.Vector3).length()) * 0.0000000001;let hit = false;pair:for (const [a, b] of [@@ -19005,10 +19740,10 @@ var init_sweep_analysis = __esm(() => {});// src/qa/sweep.ts-import { Object3D as Object3D13 } from "three";+import { Object3D as Object3D14 } from "three";function inspectSweepGeometry(scene) {const findings = [];- if (!(scene instanceof Object3D13))+ if (!(scene instanceof Object3D14))return findings;scene.traverseVisible((node) => {const geometry = node.geometry;@@ -19073,7 +19808,7 @@ var init_sweep = __esm(() => {});// src/qa/environment.ts-import * as THREE26 from "three";+import * as THREE28 from "three";function finding4(context, value) {return { ...value, profile: context.profile ?? "asset.requirements.v1" };}@@ -19092,11 +19827,11 @@ function nodePath3(root, node) {return names.reverse().join("/");}function transformedBox2(source, transform) {- const result = new THREE26.Box3;+ const result = new THREE28.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 THREE28.Vector3(x, y, z).applyMatrix4(transform));}}}@@ -19105,16 +19840,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 THREE26.Vector3;- const rotation = new THREE26.Quaternion;- const scale = new THREE26.Vector3;+ const position = new THREE28.Vector3;+ const rotation = new THREE28.Quaternion;+ const scale = new THREE28.Vector3;relative.decompose(position, rotation, scale);- const recomposed = new THREE26.Matrix4().compose(position, rotation, scale);+ const recomposed = new THREE28.Matrix4().compose(position, rotation, scale);const residual = Math.max(...relative.elements.map((component, index) => Math.abs(component - (recomposed.elements[index] ?? component))));if (residual > 0.00001)return;- const center = source.getCenter(new THREE26.Vector3).applyMatrix4(relative);- const sourceHalf = source.getSize(new THREE26.Vector3).multiplyScalar(0.5);+ const center = source.getCenter(new THREE28.Vector3).applyMatrix4(relative);+ const sourceHalf = source.getSize(new THREE28.Vector3).multiplyScalar(0.5);const halfExtents = [Math.abs(sourceHalf.x * scale.x),Math.abs(sourceHalf.y * scale.y),@@ -19129,30 +19864,30 @@ function orientedBoxFromLocalBounds(root, node, source, relative = root.matrixWohalfExtents});}-function collectParts4(root) {+function collectParts5(root) {root.updateWorldMatrix(true, true);const rootInverse = root.matrixWorld.clone().invert();const result = [];root.traverseVisible((node) => {const roles = rolesOf4(node);- const renderable = node instanceof THREE26.Mesh;+ const renderable = node instanceof THREE28.Mesh;let box;let orientedBox;let source;- if (renderable && node.geometry instanceof THREE26.BufferGeometry) {+ if (renderable && node.geometry instanceof THREE28.BufferGeometry) {node.geometry.computeBoundingBox();if (node.geometry.boundingBox) {source = node.geometry.boundingBox;}} else if (roles.length > 0) {- source = new THREE26.Box3(new THREE26.Vector3(-0.5, -0.5, -0.5), new THREE26.Vector3(0.5, 0.5, 0.5));+ source = new THREE28.Box3(new THREE28.Vector3(-0.5, -0.5, -0.5), new THREE28.Vector3(0.5, 0.5, 0.5));}const relative = rootInverse.clone().multiply(node.matrixWorld);- const count = node instanceof THREE26.InstancedMesh ? node.count : 1;+ const count = node instanceof THREE28.InstancedMesh ? node.count : 1;for (let index = 0;index < count; index++) {const transform = relative.clone();- if (node instanceof THREE26.InstancedMesh) {- const instance = new THREE26.Matrix4;+ if (node instanceof THREE28.InstancedMesh) {+ const instance = new THREE28.Matrix4;node.getMatrixAt(index, instance);transform.multiply(instance);}@@ -19183,9 +19918,9 @@ function resolveSocket(root, node, socket) {return;root.updateWorldMatrix(true, true);const rootInverse = root.matrixWorld.clone().invert();- const point = new THREE26.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);- const rootInverseQuaternion = root.getWorldQuaternion(new THREE26.Quaternion).invert();- const rotation = node.getWorldQuaternion(new THREE26.Quaternion).multiply(new THREE26.Quaternion(...frame.rotation)).premultiply(rootInverseQuaternion).normalize();+ const point = new THREE28.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);+ const rootInverseQuaternion = root.getWorldQuaternion(new THREE28.Quaternion).invert();+ const rotation = node.getWorldQuaternion(new THREE28.Quaternion).multiply(new THREE28.Quaternion(...frame.rotation)).premultiply(rootInverseQuaternion).normalize();return {id: socket.id,type: socket.type,@@ -19214,7 +19949,7 @@ function socketByType(sockets, type) {return sockets.find((socket) => socket.type === type);}function inspectPlacementSockets(context) {- if (!(context.scene instanceof THREE26.Object3D)) {+ if (!(context.scene instanceof THREE28.Object3D)) {return [];}const root = context.scene;@@ -19278,8 +20013,8 @@ function materialSignature(material) {function boundarySamples(root, axis, side, bins = 12) {root.updateWorldMatrix(true, true);const inverse = root.matrixWorld.clone().invert();- const localBounds = new THREE26.Box3;- for (const part of collectParts4(root))+ const localBounds = new THREE28.Box3;+ for (const part of collectParts5(root))if (part.renderable && part.box)localBounds.union(part.box);if (localBounds.isEmpty())@@ -19292,30 +20027,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 THREE26.Mesh) || !(node.geometry instanceof THREE26.BufferGeometry))+ if (!(node instanceof THREE28.Mesh) || !(node.geometry instanceof THREE28.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 THREE26.InstancedMesh ? node.count : 1;+ const count = node instanceof THREE28.InstancedMesh ? node.count : 1;for (let instanceIndex = 0;instanceIndex < count; instanceIndex++) {const transform = relative.clone();- if (node instanceof THREE26.InstancedMesh) {- const instance = new THREE26.Matrix4;+ if (node instanceof THREE28.InstancedMesh) {+ const instance = new THREE28.Matrix4;node.getMatrixAt(instanceIndex, instance);transform.multiply(instance);}- const normalMatrix = new THREE26.Matrix3().getNormalMatrix(transform);+ const normalMatrix = new THREE28.Matrix3().getNormalMatrix(transform);const material = materialSignature(node.material);for (let index = 0;index < positions.count; index++) {- const point = new THREE26.Vector3(positions.getX(index), positions.getY(index), positions.getZ(index)).applyMatrix4(transform);+ const point = new THREE28.Vector3(positions.getX(index), positions.getY(index), positions.getZ(index)).applyMatrix4(transform);if (Math.abs(point[axis] - edge) > band)continue;- const t = THREE26.MathUtils.clamp((point[crossAxis] - crossMin) / crossExtent, 0, 1);+ const t = THREE28.MathUtils.clamp((point[crossAxis] - crossMin) / crossExtent, 0, 1);const bin = Math.min(bins - 1, Math.floor(t * bins));- const normal = normals ? new THREE26.Vector3(normals.getX(index), normals.getY(index), normals.getZ(index)).applyMatrix3(normalMatrix).normalize() : new THREE26.Vector3(0, 1, 0);+ const normal = normals ? new THREE28.Vector3(normals.getX(index), normals.getY(index), normals.getZ(index)).applyMatrix3(normalMatrix).normalize() : new THREE28.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 });@@ -19338,7 +20073,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]) => THREE26.MathUtils.radToDeg(Math.acos(THREE26.MathUtils.clamp(a.normal.dot(b.normal), -1, 1))))) : 180;+ const maximumNormalDeltaDegrees = pairs.length ? Math.max(...pairs.map(([a, b]) => THREE28.MathUtils.radToDeg(Math.acos(THREE28.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`);@@ -19355,7 +20090,7 @@ function edgePairMeasurements(root, axis, sockets) {};}function inspectTileEdges(context) {- if (context.tileable !== true || !(context.scene instanceof THREE26.Object3D)) {+ if (context.tileable !== true || !(context.scene instanceof THREE28.Object3D)) {return [];}const root = context.scene;@@ -19438,11 +20173,11 @@ function isCorridor(part) {return part.roles.some((role) => /^environment\.(?:navigation\.)?corridor(?:\.|$)/.test(role));}function inspectNavigationClearance(context) {- if (context.navigable !== true || !(context.scene instanceof THREE26.Object3D)) {+ if (context.navigable !== true || !(context.scene instanceof THREE28.Object3D)) {return [];}const root = context.scene;- const parts = collectParts4(root);+ const parts = collectParts5(root);const corridors = parts.filter((part) => isCorridor(part));if (corridors.length === 0) {return [@@ -19568,11 +20303,11 @@ 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 THREE26.Object3D)) {+ if (context.groundPlaneY === undefined || !(context.scene instanceof THREE28.Object3D)) {return [];}const root = context.scene;- const parts = collectParts4(root).filter((part) => part.renderable && part.box);+ const parts = collectParts5(root).filter((part) => part.renderable && part.box);const findings = [];for (const part of parts) {const box = part.box;@@ -19615,7 +20350,7 @@ function inspectSpatialSupport(context) {}));}}- const size = box.getSize(new THREE26.Vector3);+ const size = box.getSize(new THREE28.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",@@ -20227,7 +20962,7 @@ var init_breadth2 = __esm(() => {});// src/qa/breadth-evidence.ts-import * as THREE27 from "three";+import * as THREE29 from "three";function record7(value) {return typeof value === "object" && value !== null && !Array.isArray(value);}@@ -20246,7 +20981,7 @@ function isAnimationClip(value) {function localRenderableBox(rootInverse, node) {if (isSpriteNode(node)) {const transform = rootInverse.clone().multiply(node.matrixWorld);- return new THREE27.Box3(new THREE27.Vector3(-0.5, -0.5, -0.0005), new THREE27.Vector3(0.5, 0.5, 0.0005)).applyMatrix4(transform);+ return new THREE29.Box3(new THREE29.Vector3(-0.5, -0.5, -0.0005), new THREE29.Vector3(0.5, 0.5, 0.0005)).applyMatrix4(transform);}if (!isMeshNode(node) || !node.geometry?.isBufferGeometry)return;@@ -20255,11 +20990,11 @@ function localRenderableBox(rootInverse, node) {if (!source || source.isEmpty())return;const transform = rootInverse.clone().multiply(node.matrixWorld);- const result = new THREE27.Box3;+ const result = new THREE29.Box3;for (const x of [source.min.x, source.max.x]) {for (const y of [source.min.y, source.max.y]) {for (const z of [source.min.z, source.max.z]) {- result.expandByPoint(new THREE27.Vector3(x, y, z).applyMatrix4(transform));+ result.expandByPoint(new THREE29.Vector3(x, y, z).applyMatrix4(transform));}}}@@ -20347,10 +21082,10 @@ function isEffectSurface(nodes) {function coverageRatio(boxes, overall) {if (boxes.length === 0 || overall.isEmpty())return 0;- const overallSize = overall.getSize(new THREE27.Vector3);+ const overallSize = overall.getSize(new THREE29.Vector3);const denominator = Math.max(0.000000001, overallSize.x * overallSize.y, overallSize.z * overallSize.y, overallSize.x * overallSize.z);const area = boxes.reduce((sum, box) => {- const size = box.getSize(new THREE27.Vector3);+ const size = box.getSize(new THREE29.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));@@ -20359,7 +21094,7 @@ function collectMaterialEvidence(root, intent) {root.updateWorldMatrix(true, true);const inverse = root.matrixWorld.clone().invert();const byMaterial = new Map;- const overall = new THREE27.Box3;+ const overall = new THREE29.Box3;root.traverseVisible((node) => {const box = localRenderableBox(inverse, node);if (!box || !isMeshNode(node) && !isSpriteNode(node))@@ -20384,7 +21119,7 @@ function collectMaterialEvidence(root, intent) {effectSurface: isEffectSurface(value.nodes),alphaMode: mode,alphaData: alphaData(material),- doubleSided: material.side === THREE27.DoubleSide,+ doubleSided: material.side === THREE29.DoubleSide,...mode === "mask" ? { alphaCutoff: standard.alphaTest ?? 0 } : {},screenAreaRatio: coverageRatio(value.boxes, overall),transparentLayers: mode === "blend" ? value.nodes.length : 0,@@ -20412,23 +21147,23 @@ function dominantGeometryAxis(root, mode) {const bounds = node.geometry.boundingBox;if (!bounds || bounds.isEmpty())return;- const size = bounds.getSize(new THREE27.Vector3);+ const size = bounds.getSize(new THREE29.Vector3);const axes = [- { score: size.x, direction: new THREE27.Vector3(1, 0, 0) },- { score: size.y, direction: new THREE27.Vector3(0, 1, 0) },- { score: size.z, direction: new THREE27.Vector3(0, 0, 1) }+ { score: size.x, direction: new THREE29.Vector3(1, 0, 0) },+ { score: size.y, direction: new THREE29.Vector3(0, 1, 0) },+ { score: size.z, direction: new THREE29.Vector3(0, 0, 1) }];const selected = axes.reduce((candidate, value) => mode === "length" ? value.score > candidate.score ? value : candidate : value.score < candidate.score ? value : candidate);const relative = inverse.clone().multiply(node.matrixWorld);const direction = selected.direction.transformDirection(relative);- const score = selected.score * node.getWorldScale(new THREE27.Vector3).length();+ const score = selected.score * node.getWorldScale(new THREE29.Vector3).length();if (!best || (mode === "length" ? score > best.score : score < best.score)) {best = { score, direction };}});if (best)return signedAxis(best.direction);- const overall = new THREE27.Box3;+ const overall = new THREE29.Box3;root.traverseVisible((node) => {const box = localRenderableBox(inverse, node);if (box)@@ -20436,8 +21171,8 @@ function dominantGeometryAxis(root, mode) {});if (overall.isEmpty())return "+X";- const size = overall.getSize(new THREE27.Vector3);- const vector = mode === "length" ? size.x >= size.y && size.x >= size.z ? new THREE27.Vector3(1, 0, 0) : size.y >= size.z ? new THREE27.Vector3(0, 1, 0) : new THREE27.Vector3(0, 0, 1) : size.x <= size.y && size.x <= size.z ? new THREE27.Vector3(1, 0, 0) : size.y <= size.z ? new THREE27.Vector3(0, 1, 0) : new THREE27.Vector3(0, 0, 1);+ const size = overall.getSize(new THREE29.Vector3);+ const vector = mode === "length" ? size.x >= size.y && size.x >= size.z ? new THREE29.Vector3(1, 0, 0) : size.y >= size.z ? new THREE29.Vector3(0, 1, 0) : new THREE29.Vector3(0, 0, 1) : size.x <= size.y && size.x <= size.z ? new THREE29.Vector3(1, 0, 0) : size.y <= size.z ? new THREE29.Vector3(0, 1, 0) : new THREE29.Vector3(0, 0, 1);return signedAxis(vector);}function analyzedFacing(root, intent) {@@ -20471,8 +21206,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 THREE27.Quaternion().fromArray(first);- const b = new THREE27.Quaternion().fromArray(last);+ const a = new THREE29.Quaternion().fromArray(first);+ const b = new THREE29.Quaternion().fromArray(last);if (a.lengthSq() === 0 || b.lengthSq() === 0)return false;return 1 - Math.abs(a.normalize().dot(b.normalize())) <= 0.000001;@@ -21208,16 +21943,16 @@ function evaluateValidationProfileDocument(profile, doc, options = {}) {measurement: { actual: null }}, "observe");} else if (outcome.failures.length > 0)- report("HOST_VALIDATION_ATTRIBUTE_GRADIENT", "gradient", `${where} ${check.gradient.attribute}[${check.gradient.component}] fails the ${outcome.failures.join(" and ")} test along local ${check.gradient.axis}: ${round2(outcome.fromMean)} to ${round2(outcome.toMean)}, expected ${check.gradient.from} to ${check.gradient.to} within ${check.gradient.tolerance}.`, {+ report("HOST_VALIDATION_ATTRIBUTE_GRADIENT", "gradient", `${where} ${check.gradient.attribute}[${check.gradient.component}] fails the ${outcome.failures.join(" and ")} test along local ${check.gradient.axis}: ${round3(outcome.fromMean)} to ${round3(outcome.toMean)}, expected ${check.gradient.from} to ${check.gradient.to} within ${check.gradient.tolerance}.`, {affected: { ...affected, attribute: check.gradient.attribute },measurement: {- actual: `${round2(outcome.fromMean)}..${round2(outcome.toMean)}`,+ actual: `${round3(outcome.fromMean)}..${round3(outcome.toMean)}`,expected: `${check.gradient.from}..${check.gradient.to}`,threshold: check.gradient.tolerance,breakdown: {- fromMean: round2(outcome.fromMean),- toMean: round2(outcome.toMean),- worstRegression: round2(outcome.worstRegression)+ fromMean: round3(outcome.fromMean),+ toMean: round3(outcome.toMean),+ worstRegression: round3(outcome.worstRegression)}}});@@ -21242,10 +21977,10 @@ function evaluateValidationProfileDocument(profile, doc, options = {}) {}const { tolerance } = check.range;if (accessor.getCount() > 0 && (min < check.range.min - tolerance || max > check.range.max + tolerance))- report("HOST_VALIDATION_ATTRIBUTE_RANGE", "range", `${where} ${check.range.attribute}[${check.range.component}] spans ${round2(min)}..${round2(max)}; the host allows ${check.range.min}..${check.range.max} within ${tolerance}.`, {+ report("HOST_VALIDATION_ATTRIBUTE_RANGE", "range", `${where} ${check.range.attribute}[${check.range.component}] spans ${round3(min)}..${round3(max)}; the host allows ${check.range.min}..${check.range.max} within ${tolerance}.`, {affected: { ...affected, attribute: check.range.attribute },measurement: {- actual: `${round2(min)}..${round2(max)}`,+ actual: `${round3(min)}..${round3(max)}`,expected: `${check.range.min}..${check.range.max}`,threshold: tolerance}@@ -21409,7 +22144,7 @@ async function evaluateValidationProfileGlb(profile, bytes, options = {}) {}return evaluateValidationProfileDocument(profile, doc, options);}-var HOST_VALIDATION_RULE_ID = "HOST_VALIDATION_PROFILE", MAX_VALIDATION_ATTRIBUTE_READS = 4000000, MAX_VALIDATION_FINDINGS_PER_CODE = 32, ENDPOINT_BAND = 0.05, GRADIENT_BINS = 16, MIN_AXIS_EXTENT = 0.000001, HOST_VALIDATION_QA_RULE, round2 = (value) => Math.round(value * 1e6) / 1e6, AXIS_INDEX;+var HOST_VALIDATION_RULE_ID = "HOST_VALIDATION_PROFILE", MAX_VALIDATION_ATTRIBUTE_READS = 4000000, MAX_VALIDATION_FINDINGS_PER_CODE = 32, ENDPOINT_BAND = 0.05, GRADIENT_BINS = 16, MIN_AXIS_EXTENT = 0.000001, HOST_VALIDATION_QA_RULE, round3 = (value) => Math.round(value * 1e6) / 1e6, AXIS_INDEX;var init_validation_profile2 = __esm(() => {init_gltf_io();init_delivery_inspect();@@ -21480,6 +22215,7 @@ var init_run = __esm(() => {init_part_connectivity();init_reference_comparison();init_self_intersection();+ init_open_surface_penetration();init_sweep();init_environment2();init_breadth2();@@ -21500,6 +22236,7 @@ var init_run = __esm(() => {...ENVIRONMENT_QA_RULES,...W7_BREADTH_QA_RULES,SELF_INTERSECTION_QA_RULE,+ OPEN_SURFACE_PENETRATION_QA_RULE,SWEEP_QA_RULE,PART_CONNECTIVITY_QA_RULE,REFERENCE_COMPARISON_QA_RULE,@@ -22112,6 +22849,13 @@ var init_requirements_applicability = __esm(() => {observation: true,kernel: "connectivity"},+ {+ id: "GEO_OPEN_SURFACE_PENETRATION",+ mode: "observe",+ keys: [],+ observation: true,+ kernel: "openSurface"+ },{ id: "REF_COMPARISON", mode: "observe", keys: [], observation: true },{ id: "SWEEP_SELF_INTERSECTION", mode: "observe", keys: [], observation: true, kernel: "sweep" },{ id: "HOST_VALIDATION_PROFILE", mode: "enforce", keys: ["validation"], kernel: "validation" }@@ -22270,7 +23014,7 @@ var init_rebuild_options = __esm(() => {});// src/qa/breadth-final.ts-import * as THREE28 from "three";+import * as THREE30 from "three";function bytesContainAscii(bytes, value) {const needle = new TextEncoder().encode(value);outer:@@ -22329,7 +23073,7 @@ function finalEffectAxis(nodes, mode) {if (!(semantic?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {continue;}- const matrix = new THREE28.Matrix4().fromArray(node.getWorldMatrix());+ const matrix = new THREE30.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() ?? []) {@@ -22339,9 +23083,9 @@ function finalEffectAxis(nodes, mode) {const min = position.getMin([]);const max = position.getMax([]);const axes = [- { score: (max[0] ?? 0) - (min[0] ?? 0), direction: new THREE28.Vector3(1, 0, 0) },- { score: (max[1] ?? 0) - (min[1] ?? 0), direction: new THREE28.Vector3(0, 1, 0) },- { score: (max[2] ?? 0) - (min[2] ?? 0), direction: new THREE28.Vector3(0, 0, 1) }+ { score: (max[0] ?? 0) - (min[0] ?? 0), direction: new THREE30.Vector3(1, 0, 0) },+ { score: (max[1] ?? 0) - (min[1] ?? 0), direction: new THREE30.Vector3(0, 1, 0) },+ { score: (max[2] ?? 0) - (min[2] ?? 0), direction: new THREE30.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 = {@@ -22584,13 +23328,13 @@ var init_breadth_final = __esm(() => {});// src/qa/requirements-run.ts-import { Object3D as Object3D15 } from "three";+import { Object3D as Object3D16 } 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"))+ if (!(scene instanceof Object3D16) || !sceneDecisions(context, policy).some((d) => d.ruleId === SELF_INTERSECTION_QA_RULE.id && d.mode !== "off"))return {};try {return { partPenetration: await analyzePartPenetration(scene) };@@ -22631,12 +23375,12 @@ function runRequirementsSceneQa(context, scene, clips, policy = {}, evidence = {};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 scopeObservation = scope?.state === "requested" && scene instanceof Object3D16 && 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) } : {}+ ...effects && scene instanceof Object3D16 && decisions.some((d) => d.ruleId.startsWith("VFX_") && d.mode !== "off") ? { vfxArtifact: analyzeVfxArtifactEvidenceV1(effects, scene, clips) } : {}}};const spatialInput = {@@ -22696,11 +23440,32 @@ function runRequirementsSceneQa(context, scene, clips, policy = {}, evidence = {}continue;}+ if (decision.ruleId === OPEN_SURFACE_PENETRATION_QA_RULE.id) {+ if (!(scene instanceof Object3D16))+ continue;+ const surfaces = analyzeOpenSurfacePenetration(scene);+ executedRules.push(decision.ruleId);+ findings.push(...inspectOpenSurfacePenetration(surfaces));+ Object.assign(geometryMetrics, {+ openSurfaceCoverage: surfaces.truncated || surfaces.skipped.length > 0 ? "partial" : "complete-surface-pairs",+ openSurfaceScope: "Visible static open surfaces sampled at their vertices against visible static closed solids, except alternates on different LOD levels; excludes open-vs-open pairs, motion, and any solid thinner than the sampled surface's facet spacing. Penetration within the contact tolerance is treated as intended contact, and penetration beyond it may still be intentional, as a fitting socketed into a shell is.",+ openSurfaceContactTolerance: surfaces.contactTolerance,+ openSurfaceOpenParts: surfaces.openParts,+ openSurfaceClosedParts: surfaces.closedParts,+ openSurfaceCandidatePairs: surfaces.candidatePairs,+ openSurfacePairsSampled: surfaces.pairsTested,+ openSurfacePairsNotReached: surfaces.pairsNotReached,+ openSurfaceVerticesUnresolved: surfaces.verticesUnresolved,+ openSurfaceLodAlternatePairs: surfaces.pairsLodAlternates,+ openSurfaceSkipped: surfaces.skipped.length+ });+ continue;+ }if (decision.ruleId === ASSET_SCOPE_QA_RULE.id && !scopeObservation)continue;if (decision.ruleId === HOST_VALIDATION_QA_RULE.id)continue;- if (decision.ruleId === PART_CONNECTIVITY_QA_RULE.id && !(scene instanceof Object3D15))+ if (decision.ruleId === PART_CONNECTIVITY_QA_RULE.id && !(scene instanceof Object3D16))continue;executedRules.push(decision.ruleId);if (decision.ruleId === PROP_EXACT_QA_RULE.id) {@@ -22846,6 +23611,7 @@ var init_requirements_run = __esm(() => {init_material();init_prop();init_part_connectivity();+ init_open_surface_penetration();init_sweep();init_self_intersection();init_vehicle2();@@ -22866,6 +23632,7 @@ var init_requirements_run = __esm(() => {PROP_ADVISORY_QA_RULE,PART_CONNECTIVITY_QA_RULE,SELF_INTERSECTION_QA_RULE,+ OPEN_SURFACE_PENETRATION_QA_RULE,SWEEP_QA_RULE,...VEHICLE_QA_RULES,...ARCHITECTURE_QA_RULES,@@ -22881,7 +23648,7 @@ var init_requirements_run = __esm(() => {});// src/qa/skin-integrity.ts-import * as THREE29 from "three";+import * as THREE31 from "three";function validAttribute(a, count, size) {if (!a || a.itemSize !== size || a.count !== count || !Number.isSafeInteger(count) || count < 1)return false;@@ -22928,9 +23695,9 @@ function inspectSkinIntegrity(root) {}while (chain.length) {const n = chain.pop();- const local = n.matrixAutoUpdate ? new THREE29.Matrix4().compose(n.position, n.quaternion, n.scale) : n.matrix.clone();+ const local = n.matrixAutoUpdate ? new THREE31.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 THREE29.Matrix4().multiplyMatrices(parent, local) : local;+ const value = n.matrixWorldAutoUpdate === false ? n.matrixWorld.clone() : parent ? new THREE31.Matrix4().multiplyMatrices(parent, local) : local;worlds.set(n, value);}return worlds.get(node);@@ -22980,7 +23747,7 @@ function inspectSkinIntegrity(root) {if (result.truncated)break;}- if (!finiteAffine(mesh.bindMatrix) || !Number.isFinite(mesh.bindMatrix.determinant()) || mesh.bindMatrix.determinant() === 0 || ![THREE29.AttachedBindMode, THREE29.DetachedBindMode].includes(mesh.bindMode)) {+ if (!finiteAffine(mesh.bindMatrix) || !Number.isFinite(mesh.bindMatrix.determinant()) || mesh.bindMatrix.determinant() === 0 || ![THREE31.AttachedBindMode, THREE31.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;@@ -23029,7 +23796,7 @@ function inspectSkinIntegrity(root) {add("SKIN_POSE_TRANSFORM", "Current mesh world transform must be finite and affine.");continue;}- const inverse = mesh.bindMode === THREE29.AttachedBindMode ? meshWorld.clone().invert() : mesh.bindMatrix.clone().invert();+ const inverse = mesh.bindMode === THREE31.AttachedBindMode ? meshWorld.clone().invert() : mesh.bindMatrix.clone().invert();const matrices = [];for (let joint = 0;joint < bones.length; joint++) {const boneWorld = world(bones[joint]);@@ -23037,13 +23804,13 @@ function inspectSkinIntegrity(root) {add("SKIN_POSE_TRANSFORM", `Current transform for joint ${joint} must be finite and affine.`, `joints[${joint}]`);break;}- matrices.push(new THREE29.Matrix4().multiplyMatrices(boneWorld, skeleton.boneInverses[joint]).multiply(mesh.bindMatrix));+ matrices.push(new THREE31.Matrix4().multiplyMatrices(boneWorld, skeleton.boneInverses[joint]).multiply(mesh.bindMatrix));}if (result.findings.length !== start)continue;- const base = new THREE29.Vector3, posed = new THREE29.Vector3, temp = new THREE29.Vector3, box = new THREE29.Box3;+ const base = new THREE31.Vector3, posed = new THREE31.Vector3, temp = new THREE31.Vector3, box = new THREE31.Box3;for (let vertex = 0;vertex < count; vertex++) {- THREE29.Mesh.prototype.getVertexPosition.call(mesh, vertex, base);+ THREE31.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);@@ -23108,7 +23875,7 @@ var init_material_export = __esm(() => {});// src/community-exporter.ts-import * as THREE30 from "three";+import * as THREE32 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) {@@ -23138,7 +23905,7 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, areturn found;const copy = cleanClone(source);normalizeTextureTransform(copy);- copy.source = new THREE30.TextureSource(source.image);+ copy.source = new THREE32.TextureSource(source.image);textures.set(source, copy);const bytes = source.userData["encoded"];if (bytes?.bytes) {@@ -23147,8 +23914,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 = THREE30.RGBAFormat;- copy.type = THREE30.UnsignedByteType;+ copy.format = THREE32.RGBAFormat;+ copy.type = THREE32.UnsignedByteType;})());}return copy;@@ -23165,7 +23932,7 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, aphysical.sheen = 1;}for (const [key, value] of Object.entries(copy)) {- if (value instanceof THREE30.Texture)+ if (value instanceof THREE32.Texture)copy[key] = texture(value);}materials.set(source, copy);@@ -23181,15 +23948,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 THREE30.Group;+ copy = new THREE32.Group;copy.copy(shadow, false);}if (source.isSprite) {const sprite = source;- const geometry = new THREE30.PlaneGeometry(1, 1);+ const geometry = new THREE32.PlaneGeometry(1, 1);geometry.translate(0.5 - sprite.center.x, 0.5 - sprite.center.y, 0);geometry.rotateZ(sprite.material.rotation);- const spriteMaterial = new THREE30.MeshBasicMaterial({+ const spriteMaterial = new THREE32.MeshBasicMaterial({name: sprite.material.name,color: sprite.material.color,opacity: sprite.material.opacity,@@ -23200,8 +23967,8 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, a});Object.assign(spriteMaterial.userData, authorExtras?.material(sprite.material));originalMaterials.set(spriteMaterial, sprite.material);- copy = new THREE30.Mesh(geometry, spriteMaterial);- THREE30.Object3D.prototype.copy.call(copy, shadow, false);+ copy = new THREE32.Mesh(geometry, spriteMaterial);+ THREE32.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];@@ -23265,8 +24032,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 THREE30.Texture().copy(map);- adapted.source = new THREE30.TextureSource(canvas);+ const adapted = new THREE32.Texture().copy(map);+ adapted.source = new THREE32.TextureSource(canvas);canvasInputs.set(map, adapted);const direct = directImages.get(map);if (direct)@@ -23275,7 +24042,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 THREE30.Texture && value.flipY && value.image?.data)+ if (value instanceof THREE32.Texture && value.flipY && value.image?.data)material[key] = canvasInput(value);}const standard = material;@@ -23297,8 +24064,8 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, a}cloned.tracks = cloned.tracks.filter((track) => {try {- const binding = THREE30.PropertyBinding.parseTrackName(track.name);- return ["position", "quaternion", "scale", "morphTargetInfluences"].includes(binding.propertyName) && THREE30.PropertyBinding.findNode(copy, binding.nodeName) !== null;+ const binding = THREE32.PropertyBinding.parseTrackName(track.name);+ return ["position", "quaternion", "scale", "morphTargetInfluences"].includes(binding.propertyName) && THREE32.PropertyBinding.findNode(copy, binding.nodeName) !== null;} catch {return false;}@@ -23493,7 +24260,7 @@ function applyIndexPolicy(doc, policy) {var init_index_policy = () => {};// src/surface-bake.ts-import * as THREE31 from "three";+import * as THREE33 from "three";function settings(value, label) {if (value === false)return;@@ -23535,13 +24302,13 @@ function drawnMeshes(root) {function weld(mesh) {const position = mesh.geometry.getAttribute("position");const world = [];- const box = new THREE31.Box3;+ const box = new THREE33.Box3;for (let i = 0;i < position.count; i++) {- const point = new THREE31.Vector3().fromBufferAttribute(position, i).applyMatrix4(mesh.matrixWorld);+ const point = new THREE33.Vector3().fromBufferAttribute(position, i).applyMatrix4(mesh.matrixWorld);world.push(point);box.expandByPoint(point);}- const size = box.isEmpty() ? 0 : box.getSize(new THREE31.Vector3).length();+ const size = box.isEmpty() ? 0 : box.getSize(new THREE33.Vector3).length();const tolerance = size > 0 ? size * 0.000001 : 0.000000001;const keys = new Map;const ids = new Int32Array(position.count);@@ -23575,7 +24342,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 THREE31.Vector3().subVectors(b, a).cross(new THREE31.Vector3().subVectors(c, a)).normalize());+ normals.push(new THREE33.Vector3().subVectors(b, a).cross(new THREE33.Vector3().subVectors(c, a)).normalize());}const edges = new Map;const neighbours = points.map(() => new Set);@@ -23594,7 +24361,7 @@ function bakeEdge(topology, thresholdDegrees, smoothing) {edges.set(key, list);}}- const threshold = THREE31.MathUtils.degToRad(thresholdDegrees);+ const threshold = THREE33.MathUtils.degToRad(thresholdDegrees);const weights = new Float64Array(points.length);for (const [key, incidences] of edges) {let weight;@@ -23604,10 +24371,10 @@ function bakeEdge(topology, thresholdDegrees, smoothing) {const [[f1], [f2, opposite2]] = incidences;const n1 = normals[f1];const n2 = normals[f2];- const angle = Math.acos(THREE31.MathUtils.clamp(n1.dot(n2), -1, 1));+ const angle = Math.acos(THREE33.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 THREE31.Vector3().subVectors(points[opposite2], points[u]).dot(n1) / scale;+ const side = new THREE33.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))@@ -23769,12 +24536,12 @@ function hemisphereDirections(count) {const phi = i * golden;const x = r * Math.cos(phi);const y = r * Math.sin(phi);- return new THREE31.Vector3(x, y, Math.sqrt(Math.max(0, 1 - x * x - y * y)));+ return new THREE33.Vector3(x, y, Math.sqrt(Math.max(0, 1 - x * x - y * y)));});}function occluderTriangles(occluders, bakedTier) {const values = [];- const point = new THREE31.Vector3;+ const point = new THREE33.Vector3;for (const mesh of drawnMeshes(occluders)) {if (!drawn(mesh, null))continue;@@ -23838,12 +24605,12 @@ function bakeSurfaceAttributes(target, options = {}) {let entry = bvhs.get(key);if (!entry) {const triangles = occluderTriangles(occluders, tier);- const box = new THREE31.Box3;+ const box = new THREE33.Box3;for (let i = 0;i < triangles.length; i += 3)- box.expandByPoint(new THREE31.Vector3(triangles[i], triangles[i + 1], triangles[i + 2]));+ box.expandByPoint(new THREE33.Vector3(triangles[i], triangles[i + 1], triangles[i + 2]));entry = {bvh: new TriangleBvh(triangles),- diagonal: box.isEmpty() ? 0 : box.getSize(new THREE31.Vector3).length()+ diagonal: box.isEmpty() ? 0 : box.getSize(new THREE33.Vector3).length()};bvhs.set(key, entry);}@@ -23860,27 +24627,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] = THREE31.MathUtils.clamp(welded[topology.ids[i]], 0, 1);- geometry.setAttribute("_edge", new THREE31.BufferAttribute(values, 1));+ values[i] = THREE33.MathUtils.clamp(welded[topology.ids[i]], 0, 1);+ geometry.setAttribute("_edge", new THREE33.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 THREE31.Vector3);+ const normals = topology.points.map(() => new THREE33.Vector3);const { points, triangles } = topology;for (let t = 0;t < triangles.length; t += 3) {const a = points[triangles[t]];- const face = new THREE31.Vector3().subVectors(points[triangles[t + 1]], a).cross(new THREE31.Vector3().subVectors(points[triangles[t + 2]], a));+ const face = new THREE33.Vector3().subVectors(points[triangles[t + 1]], a).cross(new THREE33.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 THREE31.Vector3;- const bitangent = new THREE31.Vector3;- const origin = new THREE31.Vector3;- const direction = new THREE31.Vector3;+ const tangent = new THREE33.Vector3;+ const bitangent = new THREE33.Vector3;+ const origin = new THREE33.Vector3;+ const direction = new THREE33.Vector3;points.forEach((point, id) => {const normal = normals[id];if (normal.lengthSq() === 0) {@@ -23902,8 +24669,8 @@ function bakeSurfaceAttributes(target, options = {}) {});const values = new Float32Array(sourceCount);for (let i = 0;i < sourceCount; i++)- values[i] = THREE31.MathUtils.clamp(exposure[topology.ids[i]], 0, 1);- geometry.setAttribute("_cavity", new THREE31.BufferAttribute(values, 1));+ values[i] = THREE33.MathUtils.clamp(exposure[topology.ids[i]], 0, 1);+ geometry.setAttribute("_cavity", new THREE33.BufferAttribute(values, 1));record._CAVITY = { rays, radius };}geometry.userData = { ...geometry.userData, [SURFACE_BAKE_KEY]: record };@@ -23923,7 +24690,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 = THREE31.MathUtils.clamp((x - edge0) / (edge1 - edge0), 0, 1);+ const t = THREE33.MathUtils.clamp((x - edge0) / (edge1 - edge0), 0, 1);return t * t * (3 - 2 * t);};var init_surface_bake = __esm(() => {@@ -23936,318 +24703,6 @@ var init_surface_bake = __esm(() => {});});-// src/geometry.ts-import * as THREE32 from "three";-function finiteArray(values, label, length) {- const result = Array.from(values);- if (length !== undefined && result.length !== length)- throw new Error(`${label}: expected ${length} values, got ${result.length}`);- if (!result.every((n) => Number.isFinite(Math.fround(n))))- throw new AuthoringDiagnosticError("MESH_DATA_NONFINITE", `${label}: all values must be finite Float32 values`);- return result;-}-function meshGeo(data) {- const positions = finiteArray(data.positions, "meshGeo positions");- if (positions.length < 9 || positions.length % 3)- throw new Error("meshGeo positions: need at least three xyz vertices");- const count = positions.length / 3;- const geometry = new 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)- throw new Error("meshGeo indices: need complete triangles");- if (!indices.every((i) => Number.isInteger(i) && i >= 0 && i < count))- throw new Error("meshGeo index out of bounds or not an integer");- geometry.setIndex(indices);- } else if (count % 3)- throw new Error("meshGeo: non-indexed positions must form complete triangles");- if (data.normals) {- const normals = finiteArray(data.normals, "meshGeo normals", count * 3);- geometry.setAttribute("normal", new 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");- geometry.normalizeNormals();- } else- geometry.computeVertexNormals();- if (data.uvs)- 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 THREE32.Float32BufferAttribute(tangents, 4));- }- geometry.computeBoundingBox();- geometry.computeBoundingSphere();- return geometry;-}-function boundsScale(bounds) {- 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 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 THREE32.Vector3 : bounds.min,- scale: boundsScale(bounds)- };-}-function positionTolerance(scale, supplied, relative) {- if (supplied === undefined)- return scale * relative;- if (!Number.isFinite(supplied) || supplied <= 0)- throw new Error("Geometry tolerance must be positive and finite");- if (scale / supplied > Number.MAX_SAFE_INTEGER)- throw new Error("Geometry tolerance is too small to resolve the position extent safely");- return supplied;-}-function positionKey(point, origin, tolerance) {- if (tolerance === 0)- return point.toArray().join(",");- return point.clone().sub(origin).toArray().map((x) => Math.round(x / tolerance)).join(",");-}-function geometryDiagnostics(geometry, tolerance) {- const p = geometry.getAttribute("position");- if (p?.itemSize !== 3)- throw new Error("geometryDiagnostics requires xyz positions");- const frame = positionFrame(p);- const distance = positionTolerance(frame.scale, tolerance, 0.000001);- const result = {- tolerance: distance,- toleranceMode: tolerance === undefined ? "relative" : "absolute",- positionScale: frame.scale,- vertices: p.count,- triangles: 0,- boundaryEdges: 0,- nonManifoldEdges: 0,- orientationConflicts: 0,- degenerateTriangles: 0,- collapsedByToleranceTriangles: 0,- invalidIndices: 0,- nonFiniteVertices: 0,- solid: { closed: false, manifold: true, orientation: "mixed", signedVolume: 0 }- };- let signedVolume = 0;- const pa = new THREE32.Vector3, pb = new THREE32.Vector3, pc = new THREE32.Vector3;- const ids = [];- const points = new Map;- const finite = [];- 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);- if (!finite[i])- result.nonFiniteVertices++;- const key = finite[i] ? positionKey(point, frame.origin, distance) : `invalid:${i}`;- if (!points.has(key))- points.set(key, points.size);- ids.push(points.get(key));- }- const indices = geometry.index ? Array.from(geometry.index.array) : Array.from({ length: p.count }, (_, i) => i);- const edges = new Map;- const a = new 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);- if (triangle.length !== 3 || triangle.some((n) => !Number.isInteger(n) || n < 0 || n >= p.count)) {- result.invalidIndices++;- continue;- }- const [ia, ib, ic] = triangle;- if (!finite[ia] || !finite[ib] || !finite[ic])- continue;- pa.fromBufferAttribute(p, ia);- pb.fromBufferAttribute(p, ib);- pc.fromBufferAttribute(p, ic);- signedVolume += pa.dot(pb.cross(pc)) / 6;- a.fromBufferAttribute(p, ia);- b.fromBufferAttribute(p, ib);- c.fromBufferAttribute(p, ic);- const scale = frame.scale || 1;- b.sub(a).divideScalar(scale);- c.sub(a).divideScalar(scale);- if (b.cross(c).length() <= (distance / scale) ** 2)- result.degenerateTriangles++;- if (ids[ia] === ids[ib] || ids[ib] === ids[ic] || ids[ic] === ids[ia]) {- result.collapsedByToleranceTriangles++;- continue;- }- for (const [start, end] of [- [ia, ib],- [ib, ic],- [ic, ia]- ]) {- const u = ids[start], v = ids[end];- const key = u < v ? `${u}:${v}` : `${v}:${u}`;- const edge = edges.get(key) ?? { count: 0, direction: 0 };- edge.count++;- edge.direction += u < v ? 1 : -1;- edges.set(key, edge);- }- }- for (const edge of edges.values()) {- if (edge.count === 1)- result.boundaryEdges++;- else if (edge.count > 2)- result.nonManifoldEdges++;- else if (edge.direction !== 0)- result.orientationConflicts++;- }- const volumeFloor = (frame.scale || 1) ** 3 * 0.000000000001;- result.solid = {- closed: result.boundaryEdges === 0 && edges.size > 0,- manifold: result.nonManifoldEdges === 0,- orientation: result.orientationConflicts > 0 || Math.abs(signedVolume) <= volumeFloor ? "mixed" : signedVolume > 0 ? "outward" : "inward",- signedVolume: Object.is(signedVolume, -0) ? 0 : signedVolume- };- return result;-}-function parametricSurface(sample, options = {}) {- const {- u = [0, 1],- v = [0, 1],- uSegments: nu = 24,- vSegments: nv = 24,- periodicU = false,- periodicV = false,- orientation = "uv"- } = options;- for (const [name, n] of [- ["uSegments", nu],- ["vSegments", nv]- ])- if (!Number.isSafeInteger(n) || n < 1)- throw new Error(`parametricSurface ${name} must be a positive integer`);- const sampleCount = (nu + 1) * (nv + 1);- if (!Number.isSafeInteger(sampleCount) || sampleCount > GEOMETRY_ALLOCATION_LIMITS.parametricSamples)- throw new RangeError(`parametricSurface sample budget exceeded: requested ${sampleCount}, limit ${GEOMETRY_ALLOCATION_LIMITS.parametricSamples}. Reduce uSegments/vSegments or split the surface.`);- for (const [name, range] of [- ["u", u],- ["v", v]- ])- if (range.length !== 2 || !range.every(Number.isFinite) || range[0] === range[1] || !Number.isFinite(range[1] - range[0]))- throw new Error(`parametricSurface ${name} must be a finite nonzero domain`);- if (orientation !== "uv" && orientation !== "vu")- throw new Error("parametricSurface orientation must be uv or vu");- const positions = [], uvs = [], indices = [];- 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);- if (point.length !== 3 || !point.every(Number.isFinite))- throw new Error(`parametricSurface: sample (${i},${j}) must return three finite coordinates`);- positions.push(...point);- sampledBounds.expandByPoint(sampledPoint.set(...point));- uvs.push(i / nu, j / nv);- }- const groups = Array.from({ length: (nu + 1) * (nv + 1) }, (_, i) => i);- const seamScale = boundsScale(sampledBounds);- const find = (i) => {- while (groups[i] !== i)- i = groups[i];- return i;- };- const join = (a, b, _label) => {- const pa = positions.slice(a * 3, a * 3 + 3), pb = positions.slice(b * 3, b * 3 + 3);- if (Math.hypot(...pa.map((x, k) => x - pb[k])) > seamScale * 0.000001)- throw new AuthoringDiagnosticError("PARAMETRIC_PERIODIC_ENDPOINT");- groups[find(b)] = find(a);- for (let k = 0;k < 3; k++)- positions[b * 3 + k] = positions[a * 3 + k];- };- if (periodicU)- for (let j = 0;j <= nv; j++)- join(j * (nu + 1), j * (nu + 1) + nu, "periodicU");- if (periodicV)- for (let i = 0;i <= nu; i++)- join(i, nv * (nu + 1) + i, "periodicV");- for (let j = 0;j < nv; j++)- for (let i = 0;i < nu; i++) {- const a = j * (nu + 1) + i, b = a + 1, c = a + nu + 1, d = c + 1;- indices.push(...orientation === "uv" ? [a, b, c, b, d, c] : [a, c, b, b, c, d]);- }- const out = meshGeo({ positions, indices, uvs });- if (periodicU || periodicV) {- const normal = out.getAttribute("normal");- const sums = new Map;- for (let i = 0;i < normal.count; i++) {- const id = find(i);- const sum = sums.get(id) ?? new THREE32.Vector3;- sum.add(new THREE32.Vector3().fromBufferAttribute(normal, i));- sums.set(id, sum);- }- for (let i = 0;i < normal.count; i++) {- const n = sums.get(find(i)).clone().normalize();- normal.setXYZ(i, n.x, n.y, n.z);- }- }- return out;-}-function creaseNormals(geometry, options = {}) {- const angle = options.angle ?? 60;- if (!Number.isFinite(angle) || angle < 0 || angle > 180)- throw new Error("creaseNormals angle must be between 0 and 180 degrees");- const out = geometry.index ? geometry.toNonIndexed() : geometry.clone();- const position = out.getAttribute("position");- if (position?.itemSize !== 3 || position.count % 3 !== 0)- throw new Error("creaseNormals requires complete xyz triangles");- const frame = positionFrame(position);- const tolerance = positionTolerance(frame.scale, options.tolerance, 0.00000001);- const scale = frame.scale || 1;- const adjacent = new Map;- const keys = [];- const faces = [];- for (let i = 0;i < position.count; i += 3) {- 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 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);- keys.push(key);- const neighbors = adjacent.get(key) ?? new Set;- neighbors.add(i / 3);- adjacent.set(key, neighbors);- }- }- const normals = new Float32Array(position.count * 3);- const threshold = Math.cos(THREE32.MathUtils.degToRad(angle));- for (let i = 0;i < position.count; i++) {- 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 THREE32.BufferAttribute(normals, 3));- out.deleteAttribute("tangent");- out.computeBoundingBox();- out.computeBoundingSphere();- return out;-}-var init_geometry = __esm(() => {- init_geometry_budget();- init_authoring_diagnostic();-});-// src/require-solid.tsfunction requireSolid(part) {if (part?.isObject3D !== true)@@ -24835,16 +25290,16 @@ function buildWallPanels(length, height, thickness, apertures) {}// src/assembly-transform.ts-import * as THREE33 from "three";+import * as THREE34 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 THREE33.Vector3, quaternion = new THREE33.Quaternion, scale = new THREE33.Vector3;+ const position = new THREE34.Vector3, quaternion = new THREE34.Quaternion, scale = new THREE34.Vector3;matrix.decompose(position, quaternion, scale);- const rebuilt = new THREE33.Matrix4().compose(position, quaternion, scale);+ const rebuilt = new THREE34.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 };@@ -24852,7 +25307,7 @@ function checkedTrs(matrix, label) {var init_assembly_transform = () => {};// src/assembly.ts-import * as THREE34 from "three";+import * as THREE35 from "three";function jsonData(value, label, ancestors = new Set) {if (value === null || typeof value === "string" || typeof value === "boolean")return;@@ -24899,7 +25354,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 THREE34.Matrix4().compose(node.position, node.quaternion, node.scale) : node.matrix.clone();+ return node.matrixAutoUpdate ? new THREE35.Matrix4().compose(node.position, node.quaternion, node.scale) : node.matrix.clone();}function worldMatrix2(node) {const chain = [], seen = new Set;@@ -24909,7 +25364,7 @@ function worldMatrix2(node) {seen.add(cursor);chain.push(cursor);}- const result = new THREE34.Matrix4;+ const result = new THREE35.Matrix4;for (const entry of chain.reverse())result.multiply(localMatrix(entry));return result;@@ -24925,7 +25380,7 @@ function census(root) {const stack = [root];while (stack.length) {const node = stack.pop();- if (!(node instanceof THREE34.Object3D) || ![THREE34.Object3D, THREE34.Group, THREE34.Mesh].includes(node.constructor))+ if (!(node instanceof THREE35.Object3D) || ![THREE35.Object3D, THREE35.Group, THREE35.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.");@@ -24941,21 +25396,21 @@ function census(root) {checkedTrs(matrix, node.name || "unnamed node");nodes.push(node);matrices.set(node, matrix);- 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)+ if (node.onBeforeRender !== THREE35.Object3D.prototype.onBeforeRender || node.onAfterRender !== THREE35.Object3D.prototype.onAfterRender || node.onBeforeShadow !== THREE35.Object3D.prototype.onBeforeShadow || node.onAfterShadow !== THREE35.Object3D.prototype.onAfterShadow)throw new Error("Custom node render callbacks are unsupported in assembly replication.");- if (node instanceof THREE34.Mesh) {- if (!(node.geometry instanceof THREE34.BufferGeometry) || node.geometry instanceof THREE34.InstancedBufferGeometry)+ if (node instanceof THREE35.Mesh) {+ if (!(node.geometry instanceof THREE35.BufferGeometry) || node.geometry instanceof THREE35.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 THREE34.Material)))+ if (materials.length === 0 || materials.some((material) => !(material instanceof THREE35.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 THREE34.AnimationClip)))+ if (!Array.isArray(node.animations) || node.animations.some((clip) => !(clip instanceof THREE35.AnimationClip)))throw new Error("Assembly node animations must contain AnimationClip instances.");if (node.userData[KILN_SEMANTIC_EXTRAS_KEY] !== undefined) {const metadata = readSemanticMetadataV1(node);@@ -24996,11 +25451,11 @@ function describeAssembly(root, options = {}) {const state = census(root), roles = new Map;const frames = [], sockets = [], joints = [], materials = [];const relative = new Map;- const bounds = new THREE34.Box3, point = new THREE34.Vector3;+ const bounds = new THREE35.Box3, point = new THREE35.Vector3;let positionSamples = 0;for (const [index, node] of state.nodes.entries()) {const nodeId = `n${index}`;- const matrix = node === root ? new THREE34.Matrix4 : relative.get(node.parent).clone().multiply(state.matrices.get(node));+ const matrix = node === root ? new THREE35.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);@@ -25022,7 +25477,7 @@ function describeAssembly(root, options = {}) {for (const role of metadata?.roles ?? [])addIndex(roles, role, node);for (const frame of metadata?.frames ?? []) {- const local = new THREE34.Matrix4().compose(new THREE34.Vector3(...frame.translation), new THREE34.Quaternion(...frame.rotation), new THREE34.Vector3(1, 1, 1));+ const local = new THREE35.Matrix4().compose(new THREE35.Vector3(...frame.translation), new THREE35.Quaternion(...frame.rotation), new THREE35.Vector3(1, 1, 1));frames.push({node,nodeId,@@ -25032,7 +25487,7 @@ function describeAssembly(root, options = {}) {}for (const socket of metadata?.sockets ?? [])sockets.push({ node, nodeId, socket: structuredClone(socket) });- if (!(node instanceof THREE34.Mesh))+ if (!(node instanceof THREE35.Mesh))continue;for (const [materialIndex, material] of (Array.isArray(node.material) ? node.material : [node.material]).entries())materials.push({ node, nodeId, index: materialIndex, material });@@ -25067,7 +25522,7 @@ function describeAssembly(root, options = {}) {space: "root-local",min: bounds.min.toArray(),max: bounds.max.toArray(),- size: bounds.getSize(new THREE34.Vector3).toArray()+ size: bounds.getSize(new THREE35.Vector3).toArray()},clips,ownership: {@@ -25106,7 +25561,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 THREE34.Object3D))+ if (options.parent !== undefined && !(options.parent instanceof THREE35.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))@@ -25139,16 +25594,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 THREE34.Mesh) {+ if (node instanceof THREE35.Mesh) {if (options.geometry === "copy") {jsonData(node.geometry.userData, `${node.name} geometry`);- if (node.geometry.clone !== THREE34.BufferGeometry.prototype.clone || !threeConstructors.has(node.geometry.constructor))+ if (node.geometry.clone !== THREE35.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 !== 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)+ if (material.onBeforeCompile !== THREE35.Material.prototype.onBeforeCompile || material.onBeforeRender !== THREE35.Material.prototype.onBeforeRender || material.clone !== THREE35.Material.prototype.clone || !threeConstructors.has(material.constructor) || material.customProgramCacheKey !== THREE35.Material.prototype.customProgramCacheKey || material instanceof THREE35.ShaderMaterial)throw new Error("Copying custom/shader materials is unsupported; explicit sharing preserves their existing implementation.");}}@@ -25236,9 +25691,9 @@ function replicateAssembly(source, options) {const trackTargets = new Map;const animatedNodes = new Set;for (const clip of fresh.clips) {- if (!(clip instanceof THREE34.AnimationClip))+ if (!(clip instanceof THREE35.AnimationClip))throw new Error("Assembly clips must be AnimationClip instances.");- if (clip.blendMode !== THREE34.NormalAnimationBlendMode)+ if (clip.blendMode !== THREE35.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")@@ -25265,7 +25720,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 THREE34.Matrix4;+ const parentWorld = options.parent ? worldMatrix2(options.parent) : new THREE35.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));@@ -25306,7 +25761,7 @@ function replicateAssembly(source, options) {return materials.get(material);};for (const node of state.nodes) {- const copy = node instanceof THREE34.Mesh ? new THREE34.Mesh(node.geometry, node.material) : node instanceof THREE34.Group ? new THREE34.Group : new THREE34.Object3D;+ const copy = node instanceof THREE35.Mesh ? new THREE35.Mesh(node.geometry, node.material) : node instanceof THREE35.Group ? new THREE35.Group : new THREE35.Object3D;copy.copy(node, false);copy.name = names.get(node);copy.animations = [];@@ -25319,7 +25774,7 @@ function replicateAssembly(source, options) {}copy.matrix.copy(matrix);copy.matrixWorldNeedsUpdate = true;- if (node instanceof THREE34.Mesh && copy instanceof THREE34.Mesh) {+ if (node instanceof THREE35.Mesh && copy instanceof THREE35.Mesh) {if (options.geometry === "copy") {if (!geometries.has(node.geometry))geometries.set(node.geometry, node.geometry.clone());@@ -25384,7 +25839,7 @@ var init_assembly = __esm(() => {KILN_CHARACTER_JOINT_EXTRAS_KEY,KILN_CHARACTER_RIG_EXTRAS_KEY]);- threeConstructors = new Set(Object.values(THREE34));+ threeConstructors = new Set(Object.values(THREE35));});// src/palette-check.ts@@ -25507,7 +25962,7 @@ var init_palette_check = __esm(() => {});// src/animation-cubic.ts-import * as THREE35 from "three";+import * as THREE36 from "three";function useCubicSpline(track) {track.createInterpolant = cubicSplineFactory;return track;@@ -25515,7 +25970,7 @@ function useCubicSpline(track) {var CubicSplineInterpolant, CubicSplineQuaternionInterpolant, cubicSplineFactory;var init_animation_cubic = __esm(() => {init_animation_spline();- CubicSplineInterpolant = class CubicSplineInterpolant extends THREE35.Interpolant {+ CubicSplineInterpolant = class CubicSplineInterpolant extends THREE36.Interpolant {copySampleValue_(index) {const result = this.resultBuffer;const size = this.valueSize;@@ -25543,7 +25998,7 @@ var init_animation_cubic = __esm(() => {});// src/architecture.ts-import * as THREE36 from "three";+import * as THREE37 from "three";function positive4(value, name) {if (!Number.isFinite(value) || value <= 0)throw new RangeError(`${name} must be finite and > 0`);@@ -25608,17 +26063,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 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 downhill = profile.ridgeAxis === "x" ? new THREE37.Vector3(0, -verticalRun, sideSign * horizontalRun).normalize() : new THREE37.Vector3(sideSign * horizontalRun, -verticalRun, 0).normalize();+ const tangent = profile.ridgeAxis === "x" ? new THREE37.Vector3(sideSign, 0, 0) : new THREE37.Vector3(0, 0, -sideSign);const normal = downhill.clone().cross(tangent).normalize();- const localToRoof = new THREE36.Matrix4().makeBasis(tangent, normal, downhill);+ const localToRoof = new THREE37.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 THREE36.Vector3(x, 0, z).applyMatrix4(world());+ const point = (x, z) => new THREE37.Vector3(x, 0, z).applyMatrix4(world());return {side,ridgeAxis: profile.ridgeAxis,@@ -25628,13 +26083,13 @@ function buildFace(roofRoot, profile, sideSign) {return world();},get ridgeTangent() {- return direction(new THREE36.Vector3(1, 0, 0));+ return direction(new THREE37.Vector3(1, 0, 0));},get downhillDirection() {- return direction(new THREE36.Vector3(0, 0, 1));+ return direction(new THREE37.Vector3(0, 0, 1));},get outwardNormal() {- return direction(new THREE36.Vector3(0, 1, 0));+ return direction(new THREE37.Vector3(0, 1, 0));},get ridgeStart() {return point(-alongRidge / 2, 0);@@ -25652,17 +26107,17 @@ function buildFace(roofRoot, profile, sideSign) {};}function buildRoof(name, material, profile, parent) {- const root = new THREE36.Object3D;+ const root = new THREE37.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 THREE36.BoxGeometry(face.dimensions.alongRidge, profile.thickness, face.dimensions.downhill);- const mesh = new THREE36.Mesh(geometry, material);+ const geometry = new THREE37.BoxGeometry(face.dimensions.alongRidge, profile.thickness, face.dimensions.downhill);+ const mesh = new THREE37.Mesh(geometry, material);mesh.name = `Mesh_${name}_${face.side}`;- const center = new THREE36.Matrix4().makeTranslation(0, -profile.thickness / 2, face.dimensions.downhill / 2);+ const center = new THREE37.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)], [@@ -25732,7 +26187,7 @@ function createGableEndPanel(name, material, options) {const ridgeAxis = options.ridgeAxis ?? "x";const side = options.side ?? "positive";const half = span / 2;- const shape = new THREE36.Shape;+ const shape = new THREE37.Shape;shape.moveTo(-half, 0);shape.lineTo(half, 0);shape.lineTo(0, rise);@@ -25751,7 +26206,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 THREE36.Path;+ const hole = new THREE37.Path;hole.moveTo(left, bottom);hole.lineTo(left, top);hole.lineTo(right, top);@@ -25759,7 +26214,7 @@ function createGableEndPanel(name, material, options) {hole.closePath();shape.holes.push(hole);}- const geometry = new THREE36.ExtrudeGeometry(shape, {+ const geometry = new THREE37.ExtrudeGeometry(shape, {depth: thickness,bevelEnabled: false,steps: 1@@ -25768,7 +26223,7 @@ function createGableEndPanel(name, material, options) {if (ridgeAxis === "x")geometry.rotateY(-Math.PI / 2);geometry.computeVertexNormals();- const root = new THREE36.Mesh(geometry, material);+ const root = new THREE37.Mesh(geometry, material);root.name = `Mesh_${name}`;stampSemanticMetadataV1(root, roleMetadata([`roof.gable.${side}`], [relationship("adjacent-to", "roof.slope.positive"),@@ -25784,7 +26239,7 @@ function createGableEndPanel(name, material, options) {}]));const markers = normalized.map((opening, index) => {- const marker = new THREE36.Object3D;+ const marker = new THREE37.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);@@ -25804,7 +26259,7 @@ function wallNeighbors(wall) {}function createShellWall(name, wall, material, length, height, thickness, openings) {const axis = wallRunAxis(wall);- const root = new THREE36.Object3D;+ const root = new THREE37.Object3D;root.name = `${name}_Wall_${wall}`;const neighbors = wallNeighbors(wall);stampSemanticMetadataV1(root, roleMetadata([`wall.${wall}`], [@@ -25816,8 +26271,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 THREE36.BoxGeometry(hi - lo, y1 - y0, thickness) : new THREE36.BoxGeometry(thickness, y1 - y0, hi - lo);- const mesh = new THREE36.Mesh(geometry, material);+ const geometry = axis === "x" ? new THREE37.BoxGeometry(hi - lo, y1 - y0, thickness) : new THREE37.BoxGeometry(thickness, y1 - y0, hi - lo);+ const mesh = new THREE37.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);@@ -25834,7 +26289,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 THREE36.Object3D;+ const marker = new THREE37.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);@@ -25857,7 +26312,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 THREE36.Object3D;+ const root = new THREE37.Object3D;root.name = name;stampSemanticMetadataV1(root, roleMetadata(["architecture.shell.gable"], [relationship("contains", "floor"), relationship("contains", "roof.assembly")]));const wallSpecs = {@@ -25875,7 +26330,7 @@ function createGableShell(name, materials, options) {walls[wall] = built.root;openingMarkers.push(...built.openings);}- const floor = new THREE36.Mesh(new THREE36.BoxGeometry(spanX, floorThickness, spanZ), materials.floor ?? materials.wall);+ const floor = new THREE37.Mesh(new THREE37.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}`))));@@ -25990,13 +26445,13 @@ function createRoofSurfaceLayout(name, material, options) {assertDimension("createRoofSurfaceLayout generated width", spec.width);assertDimension("createRoofSurfaceLayout generated length", spec.length);}- const root = new THREE36.Object3D;+ const root = new THREE37.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 THREE36.Mesh(new THREE36.BoxGeometry(spec.width, thickness, spec.length), material);+ const mesh = new THREE37.Mesh(new THREE37.BoxGeometry(spec.width, thickness, spec.length), material);mesh.name = `Mesh_${name}_${index + 1}`;- const local = new THREE36.Matrix4().makeTranslation(spec.x, thickness / 2 + 0.002, spec.z);+ const local = new THREE37.Matrix4().makeTranslation(spec.x, thickness / 2 + 0.002, spec.z);setTransform(mesh, faceToRoot.clone().multiply(local));root.add(mesh);return mesh;@@ -26013,7 +26468,7 @@ var init_architecture2 = __esm(() => {});// src/gears.ts-import * as THREE37 from "three";+import * as THREE38 from "three";function gearGeo(opts = {}) {const {teeth = 12,@@ -26112,8 +26567,8 @@ function gearGeo(opts = {}) {indices.push(tA, bA, bB);indices.push(tA, bB, tB);}- const geo = new THREE37.BufferGeometry;- geo.setAttribute("position", new THREE37.Float32BufferAttribute(positions, 3));+ const geo = new THREE38.BufferGeometry;+ geo.setAttribute("position", new THREE38.Float32BufferAttribute(positions, 3));geo.setIndex(indices);const nonIndexed = geo.toNonIndexed();nonIndexed.computeVertexNormals();@@ -26198,8 +26653,8 @@ function bladeGeo(opts = {}) {indices.push(count + i, tip, count + j);}}- const geo = new THREE37.BufferGeometry;- geo.setAttribute("position", new THREE37.Float32BufferAttribute(positions, 3));+ const geo = new THREE38.BufferGeometry;+ geo.setAttribute("position", new THREE38.Float32BufferAttribute(positions, 3));geo.setIndex(indices);const nonIndexed = geo.toNonIndexed();nonIndexed.computeVertexNormals();@@ -26211,7 +26666,7 @@ var init_gears = __esm(() => {});// src/ops.ts-import * as THREE38 from "three";+import * as THREE39 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) {@@ -26245,9 +26700,9 @@ function arrayLinear(namePrefix, source, count, offset, parent) {}function degreesOf(euler) {return [- THREE38.MathUtils.radToDeg(euler.x),- THREE38.MathUtils.radToDeg(euler.y),- THREE38.MathUtils.radToDeg(euler.z)+ THREE39.MathUtils.radToDeg(euler.x),+ THREE39.MathUtils.radToDeg(euler.y),+ THREE39.MathUtils.radToDeg(euler.z)];}function arrayRadial(namePrefix, source, count, axis = "y", parent, center, options = {}) {@@ -26260,12 +26715,12 @@ function arrayRadial(namePrefix, source, count, axis = "y", parent, center, optiif (center)assertFiniteTriple("arrayRadial center", center);const out = [];- const pivot = center ? new THREE38.Vector3(...center) : new THREE38.Vector3;+ const pivot = center ? new THREE39.Vector3(...center) : new THREE39.Vector3;const basePos = source.position.clone().sub(pivot);- 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 axisVec = axis === "x" ? new THREE39.Vector3(1, 0, 0) : axis === "z" ? new THREE39.Vector3(0, 0, 1) : new THREE39.Vector3(0, 1, 0);const positions = [];for (let i = 1;i < count; i++) {- const position = basePos.clone().applyMatrix4(new THREE38.Matrix4().makeRotationAxis(axisVec, i / count * Math.PI * 2)).add(pivot);+ const position = basePos.clone().applyMatrix4(new THREE39.Matrix4().makeRotationAxis(axisVec, i / count * Math.PI * 2)).add(pivot);assertFiniteTriple("arrayRadial resulting position", position.toArray());positions.push(position);}@@ -26304,7 +26759,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 THREE38.Vector3(...up);+ const upVector = new THREE39.Vector3(...up);if (upVector.lengthSq() === 0)throw new RangeError(`${name} up must not be zero.`);upVector.normalize();@@ -26343,13 +26798,13 @@ function repeatAlongCurve(source, points, options) {segment++;while (segment < points.length - 2 && cumulative[segment + 1] === cumulative[segment])segment++;- const a = new THREE38.Vector3(...points[segment]);- const b = new THREE38.Vector3(...points[segment + 1]);+ const a = new THREE39.Vector3(...points[segment]);+ const b = new THREE39.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 = THREE38.MathUtils.lerp(scale[0], scale[1], t);- const rotation = new THREE38.Matrix4;+ const k = THREE39.MathUtils.lerp(scale[0], scale[1], t);+ const rotation = new THREE39.Matrix4;let angle = 0;if (align === "tangent") {const tangent = b.clone().sub(a).normalize();@@ -26357,17 +26812,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 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 = new THREE39.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 THREE38.Vector3().crossVectors(tangent, side));- angle = THREE38.MathUtils.degToRad(THREE38.MathUtils.lerp(twist[0], twist[1], t));+ rotation.makeBasis(tangent, side, new THREE39.Vector3().crossVectors(tangent, side));+ angle = THREE39.MathUtils.degToRad(THREE39.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 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));+ turned.multiply(new THREE39.Matrix4().makeRotationX(angle + extra));+ const matrix = new THREE39.Matrix4().makeTranslation(position.x, position.y, position.z).multiply(turned).multiply(new THREE39.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 });@@ -26399,9 +26854,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 THREE38.BufferGeometry;- const vector = new THREE38.Vector3;- const normalMatrix = new THREE38.Matrix3;+ const merged = new THREE39.BufferGeometry;+ const vector = new THREE39.Vector3;+ const normalMatrix = new THREE39.Matrix3;for (const [key, attribute] of Object.entries(geometry.attributes)) {const size = attribute.itemSize;const transformed = key === "position" || key === "normal" || key === "tangent";@@ -26425,13 +26880,13 @@ function repeatAlongCurve(source, points, options) {}}}- merged.setAttribute(key, new THREE38.BufferAttribute(out, size, transformed ? false : attribute.normalized));+ merged.setAttribute(key, new THREE39.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 THREE38.BufferAttribute(along, 1));+ merged.setAttribute("_along", new THREE39.BufferAttribute(along, 1));}const index = geometry.getIndex();if (index) {@@ -26439,7 +26894,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 THREE38.BufferAttribute(indices, 1));+ merged.setIndex(new THREE39.BufferAttribute(indices, 1));}merged.computeBoundingBox();merged.computeBoundingSphere();@@ -26448,15 +26903,15 @@ function repeatAlongCurve(source, points, options) {function mirror(name, source, axis, parent) {if (source.matrixAutoUpdate)source.updateMatrix();- const reflected = new THREE38.Matrix4().makeScale(axis === "x" ? -1 : 1, axis === "y" ? -1 : 1, axis === "z" ? -1 : 1).multiply(source.matrix);+ const reflected = new THREE39.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 THREE38.Vector3;- const quaternion = new THREE38.Quaternion;- const scale = new THREE38.Vector3;+ const position = new THREE39.Vector3;+ const quaternion = new THREE39.Quaternion;+ const scale = new THREE39.Vector3;reflected.decompose(position, quaternion, scale);- const recomposed = new THREE38.Matrix4().compose(position, quaternion, scale);+ const recomposed = new THREE39.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.`);}@@ -26472,13 +26927,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 THREE38.BufferGeometry;+ const stripped = new THREE39.BufferGeometry;const pos = geometry.getAttribute("position");if (!pos)return geometry;- stripped.setAttribute("position", new THREE38.BufferAttribute(new Float32Array(pos.array), pos.itemSize, pos.normalized));+ stripped.setAttribute("position", new THREE39.BufferAttribute(new Float32Array(pos.array), pos.itemSize, pos.normalized));if (geometry.index) {- stripped.setIndex(new THREE38.BufferAttribute(new Uint32Array(geometry.index.array), 1));+ stripped.setIndex(new THREE39.BufferAttribute(new Uint32Array(geometry.index.array), 1));}return threeMergeVertices(stripped, tolerance);}@@ -26513,8 +26968,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 THREE38.Vector3);- const extent = prepared.boundingBox.getSize(new THREE38.Vector3);+ const center = prepared.boundingBox.getCenter(new THREE39.Vector3);+ const extent = prepared.boundingBox.getSize(new THREE39.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))@@ -26544,13 +26999,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 THREE38.BufferAttribute(values, 1));+ input.setAttribute(lane, new THREE39.BufferAttribute(values, 1));lanes.push(lane);}input.deleteAttribute(name);fourthComponents.push({ name, lanes });} else- input.setAttribute(name, new THREE38.BufferAttribute(decoded, components));+ input.setAttribute(name, new THREE39.BufferAttribute(decoded, components));}for (const targets of Object.values(input.morphAttributes))for (let target = 0;target < targets.length; target++) {@@ -26559,7 +27014,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 THREE38.BufferAttribute(decoded, 3);+ targets[target] = new THREE39.BufferAttribute(decoded, 3);}if (preserveUV)subOpts.uvSmooth = false;@@ -26573,7 +27028,7 @@ function subdivide(geometry, iterations = 1, opts = {}) {values[i * 4 + component] = lane.getX(i);output.deleteAttribute(lanes[component]);}- output.setAttribute(name, new THREE38.BufferAttribute(values, 4));+ output.setAttribute(name, new THREE39.BufferAttribute(values, 4));}output.scale(1 / normalizationScale, 1 / normalizationScale, 1 / normalizationScale).translate(center.x, center.y, center.z);output.userData = structuredClone(geometry.userData);@@ -26638,9 +27093,9 @@ function assertTubeRadius(radius) {}function curveToMesh(points, radius, tubularSegments = 32, radialSegments = 8, closed = false) {assertTubeRadius(radius);- 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);+ const vectors = points.map((p) => new THREE39.Vector3(p[0], p[1], p[2]));+ const curve = new THREE39.CatmullRomCurve3(vectors, closed);+ return new THREE39.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);}function normalizeSurfaceNormals(geo) {const normal = geo.getAttribute("normal");@@ -26671,15 +27126,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 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]);+ const points2d = profile.map((p) => new THREE39.Vector2(p[0], p[1]));+ const geo = normalizeSurfaceNormals(new THREE39.LatheGeometry(points2d, segments, 0, angle));+ const n = new THREE39.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 THREE38.Quaternion().setFromUnitVectors(new THREE38.Vector3(0, 1, 0), n);+ const q = new THREE39.Quaternion().setFromUnitVectors(new THREE39.Vector3(0, 1, 0), n);geo.applyQuaternion(q);}return geo;@@ -26695,9 +27150,9 @@ function pipeAlongPath(points, radius, options = {}) {const smoothed = [];smoothed.push(points[0]);for (let i = 1;i < points.length - 1; i++) {- const prev = new THREE38.Vector3(...points[i - 1]);- const cur = new THREE38.Vector3(...points[i]);- const next = new THREE38.Vector3(...points[i + 1]);+ const prev = new THREE39.Vector3(...points[i - 1]);+ const cur = new THREE39.Vector3(...points[i]);+ const next = new THREE39.Vector3(...points[i + 1]);const inDir = cur.clone().sub(prev);const outDir = next.clone().sub(cur);const inLen = inDir.length();@@ -26715,12 +27170,12 @@ function pipeAlongPath(points, radius, options = {}) {return curveToMesh(pathPoints, radius, tubularSegments, radialSegments, closed);}function bezierCurve(controlPoints, samples = 32) {- const vecs = controlPoints.map((p) => new THREE38.Vector3(p[0], p[1], p[2]));+ const vecs = controlPoints.map((p) => new THREE39.Vector3(p[0], p[1], p[2]));let curve;if (vecs.length === 3) {- curve = new THREE38.QuadraticBezierCurve3(vecs[0], vecs[1], vecs[2]);+ curve = new THREE39.QuadraticBezierCurve3(vecs[0], vecs[1], vecs[2]);} else if (vecs.length === 4) {- curve = new THREE38.CubicBezierCurve3(vecs[0], vecs[1], vecs[2], vecs[3]);+ curve = new THREE39.CubicBezierCurve3(vecs[0], vecs[1], vecs[2], vecs[3]);} else {throw new Error(`bezierCurve: need 3 or 4 control points, got ${vecs.length}`);}@@ -26733,20 +27188,20 @@ var init_ops = __esm(() => {});// src/deformation-normals.ts-import * as THREE39 from "three";+import * as THREE40 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 THREE39.Box3().setFromBufferAttribute(attribute);+ const box = new THREE40.Box3().setFromBufferAttribute(attribute);return {- center: box.getCenter(new THREE39.Vector3),- size: box.getSize(new THREE39.Vector3).length() || 1+ center: box.getCenter(new THREE40.Vector3),+ size: box.getSize(new THREE40.Vector3).length() || 1};};const before = bounds(original), after = bounds(position);- const point = new THREE39.Vector3, normal = new THREE39.Vector3;+ const point = new THREE40.Vector3, normal = new THREE40.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(",");@@ -26769,7 +27224,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 THREE39.Vector3, b = new THREE39.Vector3, c = new THREE39.Vector3;+ const a = new THREE40.Vector3, b = new THREE40.Vector3, c = new THREE40.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;@@ -26790,17 +27245,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 THREE39.BufferAttribute(normals, 3));+ output.setAttribute("normal", new THREE40.BufferAttribute(normals, 3));}var init_deformation_normals = () => {};// src/deform.ts-import * as THREE40 from "three";+import * as THREE41 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 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));+ return new THREE41.Matrix4().compose(new THREE41.Vector3(...origin), new THREE41.Quaternion().setFromEuler(new THREE41.Euler(...rotation.map(THREE41.MathUtils.degToRad), "XYZ")), new THREE41.Vector3(1, 1, 1));}function deform(geometry, options, map) {const source = geometry.getAttribute("position");@@ -26827,7 +27282,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 THREE40.Vector3().fromBufferAttribute(source, i).applyMatrix4(inverse));+ const points = Array.from({ length: source.count }, (_, i) => new THREE41.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;@@ -26850,7 +27305,7 @@ function deform(geometry, options, map) {const point = points[i];if (point.y < low - epsilon || point.y > high + epsilon)continue;- const t = length > 0 ? THREE40.MathUtils.clamp((point.y - low) / length, 0, 1) : 0;+ const t = length > 0 ? THREE41.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");@@ -26884,31 +27339,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 THREE40.Vector3(0, 1, 0), THREE40.MathUtils.degToRad(options.angle) * t));+ return deform(geometry, options, (p, t) => p.applyAxisAngle(new THREE41.Vector3(0, 1, 0), THREE41.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 = THREE40.MathUtils.degToRad(options.angle);+ const angle = THREE41.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 THREE40.Vector3(radius - (radius - p.x) * Math.cos(theta), low + (radius - p.x) * Math.sin(theta), p.z);+ return new THREE41.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 * THREE40.MathUtils.lerp(start[0], end[0], t), p.y, p.z * THREE40.MathUtils.lerp(start[1], end[1], t)));+ return deform(geometry, options, (p, t) => p.set(p.x * THREE41.MathUtils.lerp(start[0], end[0], t), p.y, p.z * THREE41.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 THREE40.Vector3(...delta));+ return p.add(new THREE41.Vector3(...delta));});}var init_deform = __esm(() => {@@ -26916,7 +27371,7 @@ var init_deform = __esm(() => {});// src/sweep.ts-import * as THREE41 from "three";+import * as THREE42 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.`);@@ -26924,9 +27379,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 THREE41.Vector2(...p));- const bounds = new THREE41.Box2().setFromPoints(points);- const extent = bounds.getSize(new THREE41.Vector2).length();+ const points = profile.map((p) => new THREE42.Vector2(...p));+ const bounds = new THREE42.Box2().setFromPoints(points);+ const extent = bounds.getSize(new THREE42.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));@@ -26949,7 +27404,7 @@ function profilePoints(profile) {throw new Error("profile self-intersects or touches itself");}}- const area = THREE41.ShapeUtils.area(normalized);+ const area = THREE42.ShapeUtils.area(normalized);if (Math.abs(area) < 0.000000000001)throw new Error("profile area must be nonzero");if (area < 0)@@ -26963,11 +27418,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 THREE41.MathUtils.radToDeg(angle) > creaseAngle + CREASE_TOLERANCE_DEGREES;+ return THREE42.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 THREE41.Vector3).multiplyScalar(1 / n));+ const centers = rings.map((r) => r.reduce((sum, p) => sum.add(p), new THREE42.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]));@@ -27027,13 +27482,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 THREE41.Box2().setFromPoints(profile);- const size = bounds.getSize(new THREE41.Vector2);+ const bounds = new THREE42.Box2().setFromPoints(profile);+ const size = bounds.getSize(new THREE42.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 THREE41.ShapeUtils.triangulateShape(profile, [])) {+ for (const tri of THREE42.ShapeUtils.triangulateShape(profile, [])) {if (station === 0)indices.push(...tri.map((j) => start + j));else@@ -27046,7 +27501,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 THREE41.Vector3().fromBufferAttribute(normal, a).add(new THREE41.Vector3().fromBufferAttribute(normal, b)).normalize();+ const sum = new THREE42.Vector3().fromBufferAttribute(normal, a).add(new THREE42.Vector3().fromBufferAttribute(normal, b)).normalize();normal.setXYZ(a, sum.x, sum.y, sum.z);normal.setXYZ(b, sum.x, sum.y, sum.z);};@@ -27084,8 +27539,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 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 rings = profiles.map((profile, i) => profile.map((p) => new THREE42.Vector3(p.x, 0, p.y).applyMatrix4(frames[i])));+ const out = buildLoft(rings, profiles, false, loftCapEnds(options.cap), new THREE42.Vector3(0, 1, 0).transformDirection(frames[0]));const analysis = recordSweepAnalysis(out, rings, profiles, false);out.userData.kilnGeometryWarnings = analysis.complete ? [] : [{@@ -27108,8 +27563,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 THREE41.Vector3(...p));- const pathExtent = new THREE41.Box3().setFromPoints(stations).getSize(new THREE41.Vector3).length();+ const stations = path.map((p) => new THREE42.Vector3(...p));+ const pathExtent = new THREE42.Box3().setFromPoints(stations).getSize(new THREE42.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;@@ -27150,7 +27605,7 @@ function sweepProfile(profile, path, options = {}) {});return incoming.clone().add(outgoing).normalize();});- 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 up = options.up ? new THREE42.Vector3(...options.up) : Math.abs(tangents[0].z) < 0.9 ? new THREE42.Vector3(0, 0, 1) : new THREE42.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");@@ -27167,7 +27622,7 @@ function sweepProfile(profile, path, options = {}) {}const distances = [0];for (let i = 1;i < stations.length; i++) {- z = z.clone().applyQuaternion(new THREE41.Quaternion().setFromUnitVectors(tangents[i - 1], tangents[i]));+ z = z.clone().applyQuaternion(new THREE42.Quaternion().setFromUnitVectors(tangents[i - 1], tangents[i]));normals.push(z);distances.push(distances[i - 1] + stations[i].distanceTo(stations[i - 1]));}@@ -27177,7 +27632,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 + THREE41.MathUtils.degToRad(twist)) * t);+ const axisZ = normals[i].clone().applyAxisAngle(tangent, (correction + THREE42.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]));});@@ -27202,7 +27657,7 @@ var init_sweep2 = __esm(() => {});// src/simplify.ts-import * as THREE42 from "three";+import * as THREE43 from "three";function loadSimplifier() {simplifierReady ??= import("meshoptimizer/simplifier").then(async ({ MeshoptSimplifier }) => {await MeshoptSimplifier.ready;@@ -27224,7 +27679,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 THREE42.BufferAttribute(values, attribute.itemSize, attribute.normalized);+ const out = new THREE43.BufferAttribute(values, attribute.itemSize, attribute.normalized);out.name = attribute.name;return out;}@@ -27509,14 +27964,14 @@ async function simplifyGeometry(geometry, options) {indexValues[i] = remap[w];}const sources = Uint32Array.from(used, (w) => representative[w]);- const out = new THREE42.BufferGeometry;+ const out = new THREE43.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 THREE42.BufferAttribute(outPosition, 3);+ const attr = new THREE43.BufferAttribute(outPosition, 3);attr.name = attribute.name;out.setAttribute(name, attr);} else@@ -27525,7 +27980,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 THREE42.BufferAttribute(indexValues, 1));+ out.setIndex(new THREE43.BufferAttribute(indexValues, 1));for (const group of outGroups)out.addGroup(group.start, group.count, group.materialIndex);out.computeBoundingBox();@@ -27580,7 +28035,7 @@ var init_simplify = __esm(() => {});// src/solids.ts-import * as THREE43 from "three";+import * as THREE44 from "three";async function getManifoldModule() {if (_module)return _module;@@ -27610,10 +28065,10 @@ function computationFrame(parts) {meshes.push(mesh);});}- const origin = meshes.length ? new THREE43.Vector3().setFromMatrixPosition(meshes[0].matrixWorld) : new THREE43.Vector3;+ const origin = meshes.length ? new THREE44.Vector3().setFromMatrixPosition(meshes[0].matrixWorld) : new THREE44.Vector3;const matrices = new Map;- const bounds = new THREE43.Box3;- const point = new THREE43.Vector3;+ const bounds = new THREE44.Box3;+ const point = new THREE44.Vector3;for (const mesh of meshes) {const matrix = mesh.matrixWorld.clone();matrix.elements[12] -= origin.x;@@ -27630,11 +28085,11 @@ function computationFrame(parts) {bounds.expandByPoint(point);}}- const size = bounds.getSize(new THREE43.Vector3);+ const size = bounds.getSize(new THREE44.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 THREE43.Vector3), scale: scale || 1, matrices };+ return { origin, center: bounds.getCenter(new THREE44.Vector3), scale: scale || 1, matrices };}function retainNotes(target, notes) {if (!Array.isArray(notes))@@ -27714,7 +28169,7 @@ function threeToManifold(src, mod, label, context) {elsecontext.missingUV.add(mesh.name || label);}- const point = new THREE43.Vector3;+ const point = new THREE44.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))))@@ -27857,11 +28312,11 @@ function solidMeshToGeometry({ mesh, collapsed }, opts = {}) {if (uvs)uvs.set(mesh.vertProperties.subarray(i + 3, i + 5), v * 2);}- const geometry = new THREE43.BufferGeometry;- geometry.setAttribute("position", new THREE43.BufferAttribute(positions, 3));- geometry.setIndex(new THREE43.BufferAttribute(new Uint32Array(mesh.triVerts), 1));+ const geometry = new THREE44.BufferGeometry;+ geometry.setAttribute("position", new THREE44.BufferAttribute(positions, 3));+ geometry.setIndex(new THREE44.BufferAttribute(new Uint32Array(mesh.triVerts), 1));if (uvs)- geometry.setAttribute("uv", new THREE43.BufferAttribute(uvs, 2));+ geometry.setAttribute("uv", new THREE44.BufferAttribute(uvs, 2));const out = opts.smooth ? geometry : geometry.toNonIndexed();out.computeVertexNormals();if (opts.smooth && uvs) {@@ -27892,7 +28347,7 @@ function firstMaterial(src) {if (!material && mesh.isMesh)material = Array.isArray(mesh.material) ? mesh.material[0] : mesh.material;});- return material ?? new THREE43.MeshStandardMaterial;+ return material ?? new THREE44.MeshStandardMaterial;}function outputMesh(result, name, parts, opts, context, isHull) {const materialized = materializeSolid(result);@@ -27951,7 +28406,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 THREE43.Mesh(geometry, context.preserve && !isHull && materials.length ? materials : firstMaterial(parts[0]));+ const output = new THREE44.Mesh(geometry, context.preserve && !isHull && materials.length ? materials : firstMaterial(parts[0]));output.name = `Mesh_${name}`;output.position.copy(context.frame.origin);return output;@@ -28360,7 +28815,7 @@ function smoothUnionSpheres(point, spheres, blend) {}// src/organic.ts-import * as THREE44 from "three";+import * as THREE45 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.`);@@ -28392,8 +28847,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 THREE44.Vector3(p[0], p[1], p[2]));- const curve = new THREE44.CatmullRomCurve3(vectors, closed);+ const vectors = controlPoints.map((p) => new THREE45.Vector3(p[0], p[1], p[2]));+ const curve = new THREE45.CatmullRomCurve3(vectors, closed);const points = curve.getPoints(spans * samplesPerSpan);if (closed)points.pop();@@ -28447,8 +28902,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 THREE44.Vector3(...axis);- const fwd = new THREE44.Vector3(...forward);+ const up = new THREE45.Vector3(...axis);+ const fwd = new THREE45.Vector3(...forward);if (up.lengthSq() < 0.000000000001 || fwd.lengthSq() < 0.000000000001)throw new Error("spiralPath axis and forward must be nonzero");up.normalize();@@ -28456,7 +28911,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 THREE44.Vector3().crossVectors(up, horiz).normalize();+ const right = new THREE45.Vector3().crossVectors(up, horiz).normalize();const out = [];for (let i = 0;i <= samples; i++) {const u = i / samples;@@ -28570,7 +29025,7 @@ var init_seeded_random = __esm(() => {});// src/uv-shapes.ts-import * as THREE45 from "three";+import * as THREE46 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.");@@ -28599,7 +29054,7 @@ function remapUV(geo, options = {}) {}const cloned = geo.clone();cloned.userData = structuredClone(geo.userData);- cloned.setAttribute("uv", new THREE45.Float32BufferAttribute(values, 2));+ cloned.setAttribute("uv", new THREE46.Float32BufferAttribute(values, 2));if ((scale[0] !== 1 || scale[1] !== 1) && cloned.hasAttribute("tangent")) {cloned.deleteAttribute("tangent");const previous = cloned.userData.kilnAttributeWarnings;@@ -28616,13 +29071,13 @@ function remapUV(geo, options = {}) {var init_uv_shapes = () => {};// src/texture-atlas.ts-import * as THREE46 from "three";+import * as THREE47 from "three";async function textureAtlas(input, options = {}) {const compiled = await compileTextureAtlasSpecV1(input, options);- const texture = new THREE46.DataTexture(compiled.pixels, compiled.spec.width, compiled.spec.height, THREE46.RGBAFormat, THREE46.UnsignedByteType);+ const texture = new THREE47.DataTexture(compiled.pixels, compiled.spec.width, compiled.spec.height, THREE47.RGBAFormat, THREE47.UnsignedByteType);texture.name = "Atlas";texture.flipY = false;- texture.colorSpace = compiled.spec.usage === "albedo" || compiled.spec.usage === "emissive" ? THREE46.SRGBColorSpace : THREE46.NoColorSpace;+ texture.colorSpace = compiled.spec.usage === "albedo" || compiled.spec.usage === "emissive" ? THREE47.SRGBColorSpace : THREE47.NoColorSpace;applyPortableSamplerV1(texture, compiled.spec.sampler);texture.userData.kilnAtlas = { spec: compiled.spec, manifest: compiled.manifest };texture.userData.kilnTexture = {@@ -28680,7 +29135,7 @@ function remapUVToAtlas(geometry, atlas, name, options) {bytes += buffer.byteLength;}} else {- bytes += attribute.array.byteLength * (attribute.constructor === THREE46.BufferAttribute || attribute.constructor === THREE46.InstancedBufferAttribute ? 1 : 2);+ bytes += attribute.array.byteLength * (attribute.constructor === THREE47.BufferAttribute || attribute.constructor === THREE47.InstancedBufferAttribute ? 1 : 2);}};for (const attr of Object.values(geometry.attributes))@@ -28905,7 +29360,7 @@ var init_portable_material_runtime = __esm(() => {});// src/uv-data.ts-import * as THREE47 from "three";+import * as THREE48 from "three";function validateAtlasRemap(mesh, inputIndex, sourceCount) {const count = mesh.vertexCount;if (!Number.isSafeInteger(count) || count < 1 || count > GEOMETRY_ALLOCATION_LIMITS.unwrapVertices)@@ -28940,7 +29395,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 THREE47.Float16BufferAttribute(array, attribute.itemSize, attribute.normalized) : new THREE47.BufferAttribute(array, attribute.itemSize, attribute.normalized);+ const output = attribute.isFloat16BufferAttribute ? new THREE48.Float16BufferAttribute(array, attribute.itemSize, attribute.normalized) : new THREE48.BufferAttribute(array, attribute.itemSize, attribute.normalized);output.name = attribute.name;output.setUsage(interleaved(attribute) ? attribute.data.usage : attribute.usage);if (!interleaved(attribute))@@ -29052,7 +29507,7 @@ var init_uv_data = __esm(() => {});// src/uv.ts-import * as THREE48 from "three";+import * as THREE49 from "three";async function getXatlas() {if (!_xatlasReady) {_xatlasReady = (async () => {@@ -29084,7 +29539,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 THREE48.BufferGeometry;+ const out = new THREE49.BufferGeometry;for (const [name, attribute] of Object.entries(geometry.attributes)) {if (name === "uv" || name === "tangent" || name === "normal" && !prepared.useNormals)continue;@@ -29094,8 +29549,8 @@ async function autoUnwrap(geometry, opts = {}) {out.morphAttributes[name] = targets.map((attribute) => remapUnwrapAttribute(attribute, remap.oldIndexes));}out.morphTargetsRelative = geometry.morphTargetsRelative;- out.setIndex(new THREE48.BufferAttribute(new Uint32Array(remap.index), 1));- out.setAttribute("uv", new THREE48.BufferAttribute(new Float32Array(remap.uv), 2));+ out.setIndex(new THREE49.BufferAttribute(new Uint32Array(remap.index), 1));+ out.setAttribute("uv", new THREE49.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);@@ -29130,11 +29585,11 @@ function repairZeroNormals(geo) {if (broken.size === 0)return;const acc = new Float32Array(normal.count * 3);- 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;+ const a = new THREE49.Vector3;+ const b = new THREE49.Vector3;+ const c = new THREE49.Vector3;+ const face = new THREE49.Vector3;+ const edge = new THREE49.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)))@@ -29170,7 +29625,7 @@ var init_uv = __esm(() => {});// src/uv-project.ts-import * as THREE49 from "three";+import * as THREE50 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.");@@ -29211,15 +29666,15 @@ function projectUV(geometry, options) {throw new Error("projectUV: index contains an invalid vertex reference.");}const points = [];- const bounds = new THREE49.Box3;+ const bounds = new THREE50.Box3;for (let i = 0;i < positions.count; i++) {- const point = new THREE49.Vector3().fromBufferAttribute(positions, i).applyMatrix4(inverse);+ const point = new THREE50.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 THREE49.Vector3);+ const extent = bounds.getSize(new THREE50.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);@@ -29234,8 +29689,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 THREE49.Vector3;- const edge = new THREE49.Vector3;+ const normal = new THREE50.Vector3;+ const edge = new THREE50.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();@@ -29291,7 +29746,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 THREE49.Float32BufferAttribute(outputUVs, 2));+ out.setAttribute("uv", new THREE50.Float32BufferAttribute(outputUVs, 2));if (out.hasAttribute("tangent")) {out.deleteAttribute("tangent");const previous = out.userData.kilnAttributeWarnings;@@ -29312,17 +29767,17 @@ var init_uv_project = __esm(() => {});// src/primitives.ts-import * as THREE50 from "three";+import * as THREE51 from "three";function vectorToTuple(v) {return [v.x, v.y, v.z];}function createRoot(name) {- const root = new THREE50.Object3D;+ const root = new THREE51.Object3D;root.name = name;return root;}function createPivot(name, position = [0, 0, 0], parent) {- const pivot = new THREE50.Object3D;+ const pivot = new THREE51.Object3D;pivot.name = `Joint_${name}`;pivot.position.set(...position);if (parent)@@ -29354,16 +29809,16 @@ function assertPartArgs(name, geometry2, material) {}function createPart(name, geometry2, material, options = {}) {assertPartArgs(name, geometry2, material);- const mesh = new THREE50.Mesh(geometry2, material);+ const mesh = new THREE51.Mesh(geometry2, material);mesh.name = `Mesh_${name}`;if (options.position)mesh.position.set(...options.position);if (options.rotation)- mesh.rotation.set(THREE50.MathUtils.degToRad(options.rotation[0]), THREE50.MathUtils.degToRad(options.rotation[1]), THREE50.MathUtils.degToRad(options.rotation[2]));+ mesh.rotation.set(THREE51.MathUtils.degToRad(options.rotation[0]), THREE51.MathUtils.degToRad(options.rotation[1]), THREE51.MathUtils.degToRad(options.rotation[2]));if (options.scale)mesh.scale.set(...options.scale);if (options.pivot) {- const pivot = new THREE50.Object3D;+ const pivot = new THREE51.Object3D;pivot.name = `Joint_${name}`;pivot.add(mesh);mesh.position.set(0, 0, 0);@@ -29386,7 +29841,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 THREE50.CapsuleGeometry(radius, height, 2, segments);+ return new THREE51.CapsuleGeometry(radius, height, 2, segments);}function capsuleXGeo(radius, length, segments = 6) {const geo = capsuleGeo(radius, length, segments);@@ -29405,7 +29860,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 THREE50.CylinderGeometry(radiusTop, radiusBottom, height, segments);+ return new THREE51.CylinderGeometry(radiusTop, radiusBottom, height, segments);}function cylinderXGeo(radiusTop, radiusBottom, length, segments = 8) {const geo = cylinderGeo(radiusTop, radiusBottom, length, segments);@@ -29420,20 +29875,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 THREE50.BoxGeometry(width, height, depth);+ return new THREE51.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 THREE50.SphereGeometry(radius, widthSegments, heightSegments);+ return new THREE51.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 THREE50.ConeGeometry(radius, height, segments);+ return new THREE51.ConeGeometry(radius, height, segments);}function coneXGeo(radius, length, segments = 8) {const geo = coneGeo(radius, length, segments);@@ -29450,7 +29905,7 @@ function cylinderOnAxis(center, normal, radiusBottom, height, options = {}) {const segments = options.segments ?? 8;assertFiniteTriple("cylinderOnAxis center", center);assertFiniteTriple("cylinderOnAxis normal", normal);- const n = new THREE50.Vector3(normal[0], normal[1], normal[2]);+ const n = new THREE51.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(",")}]).`);@@ -29458,7 +29913,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 THREE50.Quaternion().setFromUnitVectors(new THREE50.Vector3(0, 1, 0), n);+ const q = new THREE51.Quaternion().setFromUnitVectors(new THREE51.Vector3(0, 1, 0), n);geo.applyQuaternion(q);geo.translate(center[0], center[1], center[2]);return geo;@@ -29480,7 +29935,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 THREE50.TorusGeometry(radius, tube, radialSegments, tubularSegments);+ return new THREE51.TorusGeometry(radius, tube, radialSegments, tubularSegments);}function planeGeo(width, height, widthSegments = 1, heightSegments = 1) {assertDimension("planeGeo width", width);@@ -29488,14 +29943,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 THREE50.PlaneGeometry(width, height, widthSegments, heightSegments);+ return new THREE51.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 THREE50.BoxGeometry(width, height, d);+ return new THREE51.BoxGeometry(width, height, d);}function validateCardFrame(name, width, height, yPivot) {assertDimension(`${name} width`, width);@@ -29509,7 +29964,7 @@ function foliageCardGeo(opts = {}) {const h = opts.height ?? 1;const yPivot = opts.yPivot ?? 0;validateCardFrame("foliageCardGeo", w, h, yPivot);- const geom = new THREE50.PlaneGeometry(w, h);+ const geom = new THREE51.PlaneGeometry(w, h);geom.translate(0, h * (0.5 - yPivot), 0);geom.userData["kilnGeometryRole"] = "foliageCard";return geom;@@ -29525,12 +29980,12 @@ function crossedQuadsGeo(opts = {}) {const geometries = [];for (let i = 0;i < planes; i++) {const angle = i / planes * Math.PI;- const quad = new THREE50.PlaneGeometry(w, h);+ const quad = new THREE51.PlaneGeometry(w, h);quad.translate(0, h * (0.5 - yPivot), 0);quad.rotateY(angle);geometries.push(quad);}- const out = new THREE50.BufferGeometry;+ const out = new THREE51.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);@@ -29557,9 +30012,9 @@ function crossedQuadsGeo(opts = {}) {}vOffset += p.count;}- 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.setAttribute("position", new THREE51.BufferAttribute(positions, 3));+ out.setAttribute("normal", new THREE51.BufferAttribute(normals, 3));+ out.setAttribute("uv", new THREE51.BufferAttribute(uvs, 2));out.setIndex(indices);out.userData["kilnGeometryRole"] = "foliageCard";return out;@@ -29574,7 +30029,7 @@ function octaGridPlane(opts) {const h = opts.height ?? 1;const yPivot = opts.yPivot ?? 0;validateCardFrame("octaGridPlane", w, h, yPivot);- const geom = new THREE50.PlaneGeometry(w, h);+ const geom = new THREE51.PlaneGeometry(w, h);geom.translate(0, h * (0.5 - yPivot), 0);const uv = geom.attributes.uv;const du = 1 / opts.tilesX;@@ -29670,8 +30125,8 @@ function wingGeo(options = {}) {7,6];- const geo = new THREE50.BufferGeometry;- geo.setAttribute("position", new THREE50.BufferAttribute(vertices, 3));+ const geo = new THREE51.BufferGeometry;+ geo.setAttribute("position", new THREE51.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;@@ -29702,17 +30157,17 @@ function createWingPair(name, material, options) {};}function beamBetween(name, start, end, radius, material, options = {}) {- const a = new THREE50.Vector3(...start);- const b = new THREE50.Vector3(...end);+ const a = new THREE51.Vector3(...start);+ const b = new THREE51.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 THREE50.Mesh(cylinderGeo(radius, radius, length, options.segments ?? 8), material);+ const mesh = new THREE51.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 THREE50.Vector3(0, 1, 0), direction.normalize());+ mesh.quaternion.setFromUnitVectors(new THREE51.Vector3(0, 1, 0), direction.normalize());if (options.parent)options.parent.add(mesh);return mesh;@@ -29721,11 +30176,11 @@ function snapTo(part, host, options = {}) {const overlap = options.overlap ?? 0.02;part.updateWorldMatrix(true, true);host.updateWorldMatrix(true, true);- const a = new THREE50.Box3().setFromObject(part);- const b = new THREE50.Box3().setFromObject(host);+ const a = new THREE51.Box3().setFromObject(part);+ const b = new THREE51.Box3().setFromObject(host);if (a.isEmpty() || b.isEmpty())return part;- const delta = new THREE50.Vector3;+ const delta = new THREE51.Vector3;for (const axis of ["x", "y", "z"]) {if (a.min[axis] > b.max[axis])delta[axis] = b.max[axis] - a.min[axis];@@ -29741,7 +30196,7 @@ function snapTo(part, host, options = {}) {delta[dominant] = -overlap;const parent = part.parent;if (parent) {- const p0 = new THREE50.Vector3;+ const p0 = new THREE51.Vector3;part.getWorldPosition(p0);const p1 = p0.clone().add(delta);const l0 = parent.worldToLocal(p0.clone());@@ -29776,8 +30231,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 THREE50.Vector3;- const topVec = new THREE50.Vector3(...top).sub(new THREE50.Vector3(...bottom));+ const bottomVec = new THREE51.Vector3;+ const topVec = new THREE51.Vector3(...top).sub(new THREE51.Vector3(...bottom));const length = Math.hypot(topVec.x, topVec.y, topVec.z);assertDimension("createLadder endpoint distance", length);if (length <= 0.0001)@@ -29785,7 +30240,7 @@ function createLadder(name, options) {const along = topVec.clone().divideScalar(length);if (widthDirection !== undefined)assertFiniteTriple("createLadder widthDirection", widthDirection);- let across = widthDirection ? new THREE50.Vector3(...widthDirection) : widthAxis === "x" ? new THREE50.Vector3(1, 0, 0) : new THREE50.Vector3(0, 0, 1);+ let across = widthDirection ? new THREE51.Vector3(...widthDirection) : widthAxis === "x" ? new THREE51.Vector3(1, 0, 0) : new THREE51.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.");@@ -29795,19 +30250,19 @@ function createLadder(name, options) {if (widthDirection)throw new RangeError("createLadder widthDirection must not be parallel to the endpoints.");const axes = [- new THREE50.Vector3(1, 0, 0),- new THREE50.Vector3(0, 1, 0),- new THREE50.Vector3(0, 0, 1)+ new THREE51.Vector3(1, 0, 0),+ new THREE51.Vector3(0, 1, 0),+ new THREE51.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 THREE50.Object3D;+ const root = new THREE51.Object3D;root.name = name;root.position.set(...bottom);- const rotation = new THREE50.Quaternion().setFromRotationMatrix(new THREE50.Matrix4().makeBasis(across, along, across.clone().cross(along))).toArray();+ const rotation = new THREE51.Quaternion().setFromRotationMatrix(new THREE51.Matrix4().makeBasis(across, along, across.clone().cross(along))).toArray();stampSemanticMetadataV1(root, {roles: ["ladder"],frames: [@@ -29847,7 +30302,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 THREE50.Object3D;+ const group = new THREE51.Object3D;group.name = name;const panel = (suffix, lenStart, lenEnd, yLo, yHi) => {const segLen = lenEnd - lenStart;@@ -29878,7 +30333,7 @@ function room(name, material, options = {}) {parent} = options;const openings = options.openings ?? [{ wall: "front", kind: "door" }];- const root = new THREE50.Object3D;+ const root = new THREE51.Object3D;root.name = name;const wall = (suffix, len, axis, pos, which) => {const w = wallWithOpening(`${name}_Wall${suffix}`, material, {@@ -29932,7 +30387,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 THREE50.Object3D;+ const root = new THREE51.Object3D;root.name = name;const stepRise = totalRise / steps;const stepRun = totalRun / steps;@@ -29962,7 +30417,7 @@ function requireColor(color, fn) {}function gameMaterial(color, options = {}) {requireColor(color, "gameMaterial");- const material = new THREE50.MeshStandardMaterial({+ const material = new THREE51.MeshStandardMaterial({color,metalness: options.metalness ?? 0,roughness: options.roughness ?? 0.8,@@ -29976,7 +30431,7 @@ function gameMaterial(color, options = {}) {}function basicMaterial(color, options = {}) {requireColor(color, "basicMaterial");- const material = new THREE50.MeshBasicMaterial({+ const material = new THREE51.MeshBasicMaterial({color,transparent: options.transparent ?? false,opacity: options.opacity ?? 1@@ -29987,13 +30442,13 @@ function basicMaterial(color, options = {}) {}function glassMaterial(color, options = {}) {requireColor(color, "glassMaterial");- const material = new THREE50.MeshStandardMaterial({+ const material = new THREE51.MeshStandardMaterial({color,transparent: true,opacity: options.opacity ?? 0.35,roughness: options.roughness ?? 0.1,metalness: options.metalness ?? 0,- side: THREE50.DoubleSide+ side: THREE51.DoubleSide});if (options.name !== undefined)material.name = assertMaterialName(options.name, "glassMaterial");@@ -30001,7 +30456,7 @@ function glassMaterial(color, options = {}) {}function lambertMaterial(color, options = {}) {requireColor(color, "lambertMaterial");- const material = new THREE50.MeshLambertMaterial({+ const material = new THREE51.MeshLambertMaterial({color,flatShading: options.flatShading ?? true,emissive: options.emissive ?? 0@@ -30014,12 +30469,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" ? THREE50.InterpolateDiscrete : THREE50.InterpolateLinear;+ return mode === "STEP" ? THREE51.InterpolateDiscrete : THREE51.InterpolateLinear;}function interpolatedTrack(Type, name, times, values, interpolation) {if (!isCubicInterpolation(interpolation))return new Type(name, times, values, threeInterpolation(interpolation));- const quaternion = Type === THREE50.QuaternionKeyframeTrack;+ const quaternion = Type === THREE51.QuaternionKeyframeTrack;return useCubicSpline(new Type(name, times, cubicSplineValues(times, values, quaternion ? 4 : 3, interpolation, quaternion)));}function animationNumber(value, label) {@@ -30073,15 +30528,15 @@ function rotationTrack(jointName, keyframes, interpolation) {animationKeys(jointName, keyframes, "rotation", interpolation);const times = [];const values = [];- const euler = new THREE50.Euler;- const quat = new THREE50.Quaternion;+ const euler = new THREE51.Euler;+ const quat = new THREE51.Quaternion;for (const kf of keyframes) {times.push(kf.time);- euler.set(THREE50.MathUtils.degToRad(kf.rotation[0]), THREE50.MathUtils.degToRad(kf.rotation[1]), THREE50.MathUtils.degToRad(kf.rotation[2]));+ euler.set(THREE51.MathUtils.degToRad(kf.rotation[0]), THREE51.MathUtils.degToRad(kf.rotation[1]), THREE51.MathUtils.degToRad(kf.rotation[2]));quat.setFromEuler(euler);values.push(quat.x, quat.y, quat.z, quat.w);}- return interpolatedTrack(THREE50.QuaternionKeyframeTrack, `${jointName}.quaternion`, times, values, interpolation);+ return interpolatedTrack(THREE51.QuaternionKeyframeTrack, `${jointName}.quaternion`, times, values, interpolation);}function positionTrack(jointName, keyframes, interpolation) {animationKeys(jointName, keyframes, "position", interpolation);@@ -30091,7 +30546,7 @@ function positionTrack(jointName, keyframes, interpolation) {times.push(kf.time);values.push(...kf.position);}- return interpolatedTrack(THREE50.VectorKeyframeTrack, `${jointName}.position`, times, values, interpolation);+ return interpolatedTrack(THREE51.VectorKeyframeTrack, `${jointName}.position`, times, values, interpolation);}function scaleTrack(jointName, keyframes, interpolation) {animationKeys(jointName, keyframes, "scale", interpolation);@@ -30101,7 +30556,7 @@ function scaleTrack(jointName, keyframes, interpolation) {times.push(kf.time);values.push(...kf.scale);}- return interpolatedTrack(THREE50.VectorKeyframeTrack, `${jointName}.scale`, times, values, interpolation);+ return interpolatedTrack(THREE51.VectorKeyframeTrack, `${jointName}.scale`, times, values, interpolation);}function createClip(name, duration, tracks, options) {if (typeof name !== "string" || !name.trim())@@ -30114,7 +30569,7 @@ function createClip(name, duration, tracks, options) {const loop = clipLoopOption(options);const names = new Set;for (const track of tracks) {- if (!(track instanceof THREE50.KeyframeTrack))+ if (!(track instanceof THREE51.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.");@@ -30128,12 +30583,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 ? THREE50.QuaternionKeyframeTrack : THREE50.VectorKeyframeTrack;+ const Type = quaternion ? THREE51.QuaternionKeyframeTrack : THREE51.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 !== THREE50.InterpolateLinear && mode !== THREE50.InterpolateDiscrete) {+ if (!cubic && mode !== THREE51.InterpolateLinear && mode !== THREE51.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);@@ -30156,7 +30611,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 THREE50.AnimationClip(name, duration, tracks);+ const clip = new THREE51.AnimationClip(name, duration, tracks);if (loop !== undefined)clip.userData.kilnLoopIntent = loop ? "loop" : "once";return clip;@@ -30233,12 +30688,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 THREE50.Mesh(sourceMesh.geometry, sourceMesh.material);+ const mesh = new THREE51.Mesh(sourceMesh.geometry, sourceMesh.material);mesh.name = `Mesh_${name}`;if (options.position)mesh.position.set(...options.position);if (options.rotation)- mesh.rotation.set(THREE50.MathUtils.degToRad(options.rotation[0]), THREE50.MathUtils.degToRad(options.rotation[1]), THREE50.MathUtils.degToRad(options.rotation[2]));+ mesh.rotation.set(THREE51.MathUtils.degToRad(options.rotation[0]), THREE51.MathUtils.degToRad(options.rotation[1]), THREE51.MathUtils.degToRad(options.rotation[2]));if (options.scale)mesh.scale.set(...options.scale);if (options.parent)@@ -30531,7 +30986,7 @@ function buildSandboxGlobals(usage, options = {}) {getJointNames: wrap("getJointNames", getJointNames),materialBudgetAdvisory: wrap("materialBudgetAdvisory", materialBudgetAdvisory),seededRandom: wrap("seededRandom", seededRandom),- THREE: THREE50,+ THREE: THREE51,Math,console: options.console ?? console};@@ -30660,7 +31115,7 @@ import {PropertyType as PropertyType5} from "@gltf-transform/core";import { createTransform, dequantizePrimitive, joinPrimitives } from "@gltf-transform/functions";-import * as THREE51 from "three";+import * as THREE52 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]);@@ -30778,10 +31233,10 @@ function reverseWinding(prim) {}}function bake(prim, matrix) {- const linear = new THREE51.Matrix3().setFromMatrix4(matrix);- const normalMatrix = new THREE51.Matrix3().getNormalMatrix(matrix);+ const linear = new THREE52.Matrix3().setFromMatrix4(matrix);+ const normalMatrix = new THREE52.Matrix3().getNormalMatrix(matrix);const mirrored = matrix.determinant() < 0;- const v = new THREE51.Vector3;+ const v = new THREE52.Vector3;const each = (semantic, apply) => {const attribute = prim.getAttribute(semantic);const element = [];@@ -30805,7 +31260,7 @@ function destinationOf(entries) {let best = Infinity;let bestScale = Infinity;for (const { node } of entries) {- const linear = new THREE51.Matrix3().setFromMatrix4(worldOf(node));+ const linear = new THREE52.Matrix3().setFromMatrix4(worldOf(node));const norm = Math.hypot(...linear.elements);const inverseNorm = Math.hypot(...linear.clone().invert().elements);const condition = norm * inverseNorm;@@ -30819,9 +31274,9 @@ function destinationOf(entries) {return chosen;}function checkPositionPrecision(input, output, sourceWorld, destinationWorld, reversed) {- const expected = new THREE51.Vector3;- const actual = new THREE51.Vector3;- const bounds = new THREE51.Box3;+ const expected = new THREE52.Vector3;+ const actual = new THREE52.Vector3;+ const bounds = new THREE52.Box3;const element = [];let error = 0;let magnitude = 0;@@ -31142,7 +31597,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 THREE51.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 THREE52.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);@@ -33682,7 +34137,7 @@ var init_kit = __esm(() => {// src/texture-bake.tsimport { createHash as createHash12 } from "node:crypto";-import * as THREE52 from "three";+import * as THREE53 from "three";function readPixels(texture) {const image = texture.image;if (!image)@@ -33809,7 +34264,7 @@ async function bakeSceneTextures(root, warnings) {mime: "image/png",bytes};- const colorSpace = entry.texture.colorSpace === THREE52.SRGBColorSpace ? "srgb" : "linear";+ const colorSpace = entry.texture.colorSpace === THREE53.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)@@ -33892,10 +34347,10 @@ function computeTangentBasis(geometry) {}}const out = new Float32Array(vertexCount * 4);- const n = new THREE52.Vector3;- const t = new THREE52.Vector3;- const tmp = new THREE52.Vector3;- const tmp2 = new THREE52.Vector3;+ const n = new THREE53.Vector3;+ const t = new THREE53.Vector3;+ const tmp = new THREE53.Vector3;+ const tmp2 = new THREE53.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]);@@ -33915,7 +34370,7 @@ function computeTangentBasis(geometry) {out[v * 4 + 2] = tmp.z;out[v * 4 + 3] = w;}- geometry.setAttribute("tangent", new THREE52.BufferAttribute(out, 4));+ geometry.setAttribute("tangent", new THREE53.BufferAttribute(out, 4));}function ensureNormalMapTangents(root, warnings) {let count = 0;@@ -34033,7 +34488,7 @@ var init_exporter_node = __esm(() => {});// src/views/character.ts-import * as THREE53 from "three";+import * as THREE54 from "three";function rounded(value) {const result = Math.round(value * 1e9) / 1e9;return Object.is(result, -0) ? 0 : result;@@ -34075,9 +34530,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 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 position = new THREE54.Vector3().setFromMatrixPosition(relative);+ const forward = new THREE54.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);+ const bend = new THREE54.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);const chainId = chainIdFor(joint.descriptor, descriptorByRole);return {role: joint.descriptor.role,@@ -35462,7 +35917,7 @@ function prepareTriangleCoverage(ax, ay, bx, by, cx, cy, size) {}// src/views/raster.ts-import { Vector3 as Vector338 } from "three";+import { Vector3 as Vector339 } from "three";function orbitDir(azimuthDeg, elevationDeg) {const el = Math.min(MAX_ELEVATION_DEG, Math.max(MIN_ELEVATION_DEG, elevationDeg)) * Math.PI / 180;const az = azimuthDeg * Math.PI / 180;@@ -35497,7 +35952,7 @@ function updateSurfaceMatrices(root) {function surfaceVertexReader(mesh, position) {for (const bone of mesh.skeleton?.bones ?? [])bone.updateWorldMatrix?.(true, false);- const vertex = new Vector338;+ const vertex = new Vector339;if (mesh.getVertexPosition)return (index) => mesh.getVertexPosition(index, vertex);if (position.getX && position.getY && position.getZ)@@ -35907,7 +36362,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 Group5 } from "three";+import { Vector3 as Vector340, 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)) {@@ -36001,14 +36456,14 @@ function cameraFromBounds(bounds, dir, padding = 1, up, sceneBounds = bounds) {const z = vec(dir).normalize();if (!z.length())throw new Error("camera direction must be non-zero");- const hint = up ? vec(up) : Math.abs(z.y) > 0.99 ? new Vector339(0, 0, -1) : new Vector339(0, 1, 0);+ const hint = up ? vec(up) : Math.abs(z.y) > 0.99 ? new Vector340(0, 0, -1) : new Vector340(0, 1, 0);const x = hint.clone().cross(z).normalize();if (x.length() < 0.000000001)throw new Error("camera up must not be collinear with view");const y = z.clone().cross(x);let extent = 0.000001;for (let i = 0;i < 8; i++) {- const p = new Vector339((i & 1 ? bounds.max : bounds.min)[0], (i & 2 ? bounds.max : bounds.min)[1], (i & 4 ? bounds.max : bounds.min)[2]).sub(target);+ const p = new Vector340((i & 1 ? bounds.max : bounds.min)[0], (i & 2 ? bounds.max : bounds.min)[1], (i & 4 ? bounds.max : bounds.min)[2]).sub(target);extent = Math.max(extent, Math.abs(p.dot(x)), Math.abs(p.dot(y)));}const depthMin = bounds.min.map((v, i) => Math.min(v, sceneBounds.min[i]));@@ -36089,7 +36544,7 @@ function resolveAssetCamera(root, shot = {}) {if (relative !== "world") {const node = relative === "part" ? selected.node : rootNode;dir.transformDirection(node.matrixWorld);- up = tuple6(new Vector339(0, 1, 0).transformDirection(node.matrixWorld));+ up = tuple6(new Vector340(0, 1, 0).transformDirection(node.matrixWorld));}camera = cameraFromBounds(bounds, tuple6(dir), request.padding ?? 1.2, up, measureBounds(root));} else if (request.type === "explicit") {@@ -36136,7 +36591,7 @@ function resolveAssetCamera(root, shot = {}) {const position = vec(triple2(request.position, "position")).applyMatrix4(matrix);const target = request.target ? vec(triple2(request.target, "target")).applyMatrix4(matrix) : vec(bounds.min).add(vec(bounds.max)).multiplyScalar(0.5);const up = vec(triple2(request.up ?? [0, 1, 0], "up")).transformDirection(matrix);- const offset = vec(triple2(request.targetOffset ?? [0, 0, 0], "targetOffset")).applyMatrix4(matrix).sub(new Vector339().setFromMatrixPosition(matrix));+ const offset = vec(triple2(request.targetOffset ?? [0, 0, 0], "targetOffset")).applyMatrix4(matrix).sub(new Vector340().setFromMatrixPosition(matrix));const radius = vec(bounds.max).sub(vec(bounds.min)).length();camera = {version: "kiln.camera.v1",@@ -36265,11 +36720,11 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true, backdrop)}return result;};- const key = new Vector339(1.5, 2, 1).normalize();+ const key = new Vector340(1.5, 2, 1).normalize();const srgb = (n) => n <= 0.0031308 ? n * 12.92 : 1.055 * n ** (1 / 2.4) - 0.055;const ordered = compositingOrder(collectTriangles(root).tris, (px, py, pz) => camera.projection === "perspective" ? Math.hypot(px - position.x, py - position.y, pz - position.z) : (position.x - px) * z.x + (position.y - py) * z.y + (position.z - pz) * z.z);for (const tri of ordered) {- const world = [0, 1, 2].map((i) => new Vector339(tri.v[i * 3], tri.v[i * 3 + 1], tri.v[i * 3 + 2]));+ const world = [0, 1, 2].map((i) => new Vector340(tri.v[i * 3], tri.v[i * 3 + 1], tri.v[i * 3 + 2]));const normal = world[1].clone().sub(world[0]).cross(world[2].clone().sub(world[0])).normalize().multiplyScalar(tri.windingParity);const normalSign = visibleNormalSign(normal.dot(camera.projection === "perspective" ? position.clone().sub(world[0]) : z), tri.side, backfaceCull);if (normalSign === 0)@@ -36280,7 +36735,7 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true, backdrop)const color = tri.color.map((c) => Math.round(srgb(c * light) * 255));let polygon = world.map((p) => {const d = p.clone().sub(position);- return new Vector339(d.dot(x), d.dot(y), -d.dot(z));+ return new Vector340(d.dot(x), d.dot(y), -d.dot(z));});polygon = clip(clip(polygon, camera.near, true), camera.far, false);for (let t = 1;t < polygon.length - 1; t++) {@@ -36312,7 +36767,7 @@ function rasterizeCamera(root, input, size = 384, backfaceCull = true, backdrop)}return out;}-var vec = (a) => new Vector339(...a), tuple6 = (v) => [v.x || 0, v.y || 0, v.z || 0], KEY_HINTS;+var vec = (a) => new Vector340(...a), tuple6 = (v) => [v.x || 0, v.y || 0, v.z || 0], KEY_HINTS;var init_camera = __esm(() => {init_raster();init_background();@@ -37083,7 +37538,7 @@ import {PropertyBinding as PropertyBinding3,VectorKeyframeTrack as VectorKeyframeTrack2,Quaternion as Quaternion20,- Vector3 as Vector340,+ Vector3 as Vector341,InterpolateDiscrete as InterpolateDiscrete2,InterpolateLinear as InterpolateLinear2} from "three";@@ -37267,7 +37722,7 @@ function instanceMatrices(node) {translations?.getElement(index, translation);rotations?.getElement(index, rotation);scales?.getElement(index, scale);- const local = new Matrix418().compose(new Vector340(translations ? translation[0] : 0, translations ? translation[1] : 0, translations ? translation[2] : 0), new Quaternion20(rotations ? rotation[0] : 0, rotations ? rotation[1] : 0, rotations ? rotation[2] : 0, rotations ? rotation[3] : 1).normalize(), new Vector340(scales ? scale[0] : 1, scales ? scale[1] : 1, scales ? scale[2] : 1));+ const local = new Matrix418().compose(new Vector341(translations ? translation[0] : 0, translations ? translation[1] : 0, translations ? translation[2] : 0), new Quaternion20(rotations ? rotation[0] : 0, rotations ? rotation[1] : 0, rotations ? rotation[2] : 0, rotations ? rotation[3] : 1).normalize(), new Vector341(scales ? scale[0] : 1, scales ? scale[1] : 1, scales ? scale[2] : 1));matrices.push(world.clone().multiply(local));}return { matrices, count };@@ -37374,7 +37829,7 @@ function localInstanceMatrices(node) {translations?.getElement(index, translation);rotations?.getElement(index, rotation);scales?.getElement(index, scale);- return new Matrix418().compose(new Vector340(...translations ? translation.slice(0, 3) : [0, 0, 0]), new Quaternion20(...rotations ? rotation.slice(0, 4) : [0, 0, 0, 1]).normalize(), new Vector340(...scales ? scale.slice(0, 3) : [1, 1, 1]));+ return new Matrix418().compose(new Vector341(...translations ? translation.slice(0, 3) : [0, 0, 0]), new Quaternion20(...rotations ? rotation.slice(0, 4) : [0, 0, 0, 1]).normalize(), new Vector341(...scales ? scale.slice(0, 3) : [1, 1, 1]));});}async function loadGlbReviewScene(bytes) {@@ -37972,7 +38427,7 @@ var init_renderer_id = __esm(() => {});// src/views/scene-raster.ts-import * as THREE54 from "three";+import * as THREE55 from "three";var DEG2;var init_scene_raster = __esm(() => {init_evaluator();@@ -37984,18 +38439,18 @@ var init_scene_raster = __esm(() => {});// src/views/vehicle.ts-import * as THREE55 from "three";+import * as THREE56 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 THREE55.Box3;+ const bounds = new THREE56.Box3;let found = false;root.traverse((node) => {if (!hasRole2(node, "chassis"))return;node.traverse((part) => {- if (!(part instanceof THREE55.Mesh) || !(part.geometry instanceof THREE55.BufferGeometry))+ if (!(part instanceof THREE56.Mesh) || !(part.geometry instanceof THREE56.BufferGeometry))return;part.geometry.computeBoundingBox();const box = part.geometry.boundingBox;@@ -38005,7 +38460,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 THREE55.Vector3(x, y, z).applyMatrix4(matrix));+ bounds.expandByPoint(new THREE56.Vector3(x, y, z).applyMatrix4(matrix));found = true;}});@@ -38073,33 +38528,33 @@ function tagDiagnostic(node, role) {stampSemanticMetadataV1(node, { roles: [role] });}function rod(name, start, end, radius, color, role) {- const from = new THREE55.Vector3(...start);- const to = new THREE55.Vector3(...end);+ const from = new THREE56.Vector3(...start);+ const to = new THREE56.Vector3(...end);const direction = to.clone().sub(from);const length = direction.length();- 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 }));+ const geometry = length > 0.000000001 ? new THREE56.CylinderGeometry(radius, radius, length, 8) : new THREE56.SphereGeometry(radius, 8, 6);+ const result = new THREE56.Mesh(geometry, new THREE56.MeshBasicMaterial({ color }));result.name = name;result.position.copy(from).add(to).multiplyScalar(0.5);if (length > 0.000000001) {- result.quaternion.setFromUnitVectors(new THREE55.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));+ result.quaternion.setFromUnitVectors(new THREE56.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));}tagDiagnostic(result, role);return result;}function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnostics(root)) {- const overlay = new THREE55.Group;+ const overlay = new THREE56.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 THREE55.Group;+ const arrow = new THREE56.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 THREE55.Mesh(new THREE55.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE55.MeshBasicMaterial({ color: 16724804 }));+ const arrowHead = new THREE56.Mesh(new THREE56.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE56.MeshBasicMaterial({ color: 16724804 }));arrowHead.name = "Diagnostic_Forward_Head";arrowHead.position.set(descriptor.forwardArrow.end[0] - 0.12, 0, 0);- arrowHead.quaternion.setFromUnitVectors(new THREE55.Vector3(0, 1, 0), new THREE55.Vector3(1, 0, 0));+ arrowHead.quaternion.setFromUnitVectors(new THREE56.Vector3(0, 1, 0), new THREE56.Vector3(1, 0, 0));tagDiagnostic(arrowHead, "diagnostic.vehicle.forward");arrow.add(arrowHead);overlay.add(arrow);@@ -38107,18 +38562,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 THREE55.Mesh(new THREE55.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE55.MeshBasicMaterial({ color: 16763955 }));+ const ring = new THREE56.Mesh(new THREE56.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE56.MeshBasicMaterial({ color: 16763955 }));ring.name = `Diagnostic_Wheel_${wheel.id}`;ring.position.set(...wheel.center);- const axle = new THREE55.Vector3(...wheel.axle);+ const axle = new THREE56.Vector3(...wheel.axle);if (axle.lengthSq() > 0.000000000001) {- ring.quaternion.setFromUnitVectors(new THREE55.Vector3(0, 0, 1), axle.normalize());+ ring.quaternion.setFromUnitVectors(new THREE56.Vector3(0, 0, 1), axle.normalize());}tagDiagnostic(ring, `diagnostic.vehicle.wheel.${wheel.id}`);overlay.add(ring);}if (descriptor.chassisBox) {- const chassis = new THREE55.Group;+ const chassis = new THREE56.Group;chassis.name = "Diagnostic_ChassisBox";tagDiagnostic(chassis, "diagnostic.vehicle.chassis");const { min, max } = descriptor.chassisBox;@@ -38152,7 +38607,7 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnooverlay.add(chassis);}if (descriptor.supportPlaneY !== undefined) {- const plane = new THREE55.Group;+ const plane = new THREE56.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;@@ -38750,7 +39205,7 @@ var init_views = __esm(() => {});// src/views/character-capture.ts-import * as THREE56 from "three";+import * as THREE57 from "three";function drawLine2(rgb, width, height, from, to, color) {let x0 = Math.round(from[0]);let y0 = Math.round(from[1]);@@ -38787,22 +39242,22 @@ function drawCross(rgb, width, height, point, color, radius = 3) {}function projector(root, cameraId, size) {root.updateMatrixWorld(true);- const bounds = new THREE56.Box3().setFromObject(root);+ const bounds = new THREE57.Box3().setFromObject(root);if (bounds.isEmpty())- 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();+ bounds.set(new THREE57.Vector3(-0.5, 0, -0.5), new THREE57.Vector3(0.5, 1, 0.5));+ const center = bounds.getCenter(new THREE57.Vector3);+ const camera = cameraId === "front" ? new THREE57.Vector3(1, 0, 0) : new THREE57.Vector3(0, 0, 1);+ const upHint = new THREE57.Vector3(0, 1, 0);+ const xAxis = new THREE57.Vector3().crossVectors(upHint, camera).normalize();+ const yAxis = new THREE57.Vector3().crossVectors(camera, xAxis).normalize();let extent = 0.000001;for (let corner = 0;corner < 8; corner++) {- 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);+ const point = new THREE57.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 THREE56.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);+ const world = new THREE57.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);return [size / 2 + world.dot(xAxis) * scale, size / 2 - world.dot(yAxis) * scale];};}@@ -38928,7 +39383,7 @@ var init_character_capture = __esm(() => {});// src/render.ts-import * as THREE57 from "three";+import * as THREE58 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";@@ -39158,7 +39613,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache, authorExtras, atlas)} else if (stdMat.transparent) {mat.setAlphaMode("BLEND");}- if (stdMat.side === THREE57.DoubleSide) {+ if (stdMat.side === THREE58.DoubleSide) {mat.setDoubleSided(true);}if (stdMat.map) {@@ -39235,7 +39690,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache, authorExtras, atlas)} else if (common.transparent || (common.opacity ?? 1) < 1) {mat.setAlphaMode("BLEND");}- if (threeMat.side === THREE57.DoubleSide)+ if (threeMat.side === THREE58.DoubleSide)mat.setDoubleSided(true);if (common.map && !mat.getBaseColorTexture()) {const texture = bridgeTexture(doc, common.map, textureCache);@@ -39398,7 +39853,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 THREE57.PlaneGeometry(1, 1);+ const geometry = new THREE58.PlaneGeometry(1, 1);if (centerX !== 0.5 || centerY !== 0.5) {geometry.translate(0.5 - centerX, 0.5 - centerY, 0);}@@ -39422,9 +39877,9 @@ function animationInterpolation(track) {if (isCubicSplineTrack(track))return "CUBICSPLINE";const mode = track.getInterpolation();- if (mode === THREE57.InterpolateDiscrete)+ if (mode === THREE58.InterpolateDiscrete)return "STEP";- if (mode === THREE57.InterpolateLinear)+ if (mode === THREE58.InterpolateLinear)return "LINEAR";throw new Error(`Unsupported animation interpolation on ${track.name}; use LINEAR, STEP or CUBICSPLINE.`);}@@ -39998,8 +40453,8 @@ function collectMeshStats(root) {if (!Number.isFinite(box.min.x) || !Number.isFinite(box.max.x)) {return;}- const center = new THREE57.Vector3;- const size = new THREE57.Vector3;+ const center = new THREE58.Vector3;+ const size = new THREE58.Vector3;box.getCenter(center);box.getSize(size);out.push({@@ -40015,7 +40470,7 @@ function collectMeshStats(root) {return out;}function minimalGapVector(a, b) {- const v = new THREE57.Vector3;+ const v = new THREE58.Vector3;for (const axis of ["x", "y", "z"]) {if (a.min[axis] > b.max[axis])v[axis] = b.max[axis] - a.min[axis];@@ -40033,10 +40488,10 @@ function inspectSceneStructure(root, opts = {}) {return warnings;const cat = opts.category?.toLowerCase();if (cat === "vehicle" || cat === "weapon" || cat === "boat" || cat === "aircraft") {- const all = new THREE57.Box3;+ const all = new THREE58.Box3;for (const m of meshes)all.union(m.box);- const size = new THREE57.Vector3;+ const size = new THREE58.Vector3;all.getSize(size);if (cat === "aircraft") {if (size.y > size.x * 1.2) {@@ -40161,18 +40616,18 @@ var init_render = __esm(() => {engineIO = createGltfIO;ACCESSOR_TYPES = [TYPE_SCALAR, TYPE_VEC2, TYPE_VEC3, TYPE_VEC4];GLTF_MIN_FILTER = {- [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 };+ [THREE58.NearestFilter]: 9728,+ [THREE58.LinearFilter]: 9729,+ [THREE58.NearestMipmapNearestFilter]: 9984,+ [THREE58.LinearMipmapNearestFilter]: 9985,+ [THREE58.NearestMipmapLinearFilter]: 9986,+ [THREE58.LinearMipmapLinearFilter]: 9987+ };+ GLTF_MAG_FILTER = { [THREE58.NearestFilter]: 9728, [THREE58.LinearFilter]: 9729 };GLTF_WRAP = {- [THREE57.ClampToEdgeWrapping]: 33071,- [THREE57.MirroredRepeatWrapping]: 33648,- [THREE57.RepeatWrapping]: 10497+ [THREE58.ClampToEdgeWrapping]: 33071,+ [THREE58.MirroredRepeatWrapping]: 33648,+ [THREE58.RepeatWrapping]: 10497};REVIEW_CLIP_LIMITS2 = {clips: 32,@@ -41261,12 +41716,12 @@ var exports_part_placement = {};__export(exports_part_placement, {createPartPlacementReader: () => createPartPlacementReader});-import * as THREE58 from "three";+import * as THREE59 from "three";function createPartPlacementReader(root) {const bounds = createPartBoundsReader(root);- const position = new THREE58.Vector3;- const quaternion = new THREE58.Quaternion;- const scale = new THREE58.Vector3;+ const position = new THREE59.Vector3;+ const quaternion = new THREE59.Quaternion;+ const scale = new THREE59.Vector3;return (node) => {node.matrixWorld.decompose(position, quaternion, scale);const box = bounds(node);@@ -41279,10 +41734,10 @@ function createPartPlacementReader(root) {};};}-var round3 = (value) => {+var round4 = (value) => {const rounded = Math.round(value * 1e6) / 1e6;return rounded === 0 ? 0 : rounded;-}, rounded2 = (values) => values.map(round3);+}, rounded2 = (values) => values.map(round4);var init_part_placement = __esm(() => {init_raster();});@@ -41417,13 +41872,13 @@ var init_inspect = __esm(() => {});// src/views/measurement.ts-import { Box3 as Box326, Vector3 as Vector345 } from "three";+import { Box3 as Box327, Vector3 as Vector346 } from "three";function describeSubjectFrame(root, subject) {const selected = selectCameraSubject(root, subject);selected.node.updateWorldMatrix(true, true);const matrix = selected.node.matrixWorld;- const bounds = new Box326().setFromObject(selected.node);- const local = new Box326;+ const bounds = new Box327().setFromObject(selected.node);+ const local = new Box327;const invertible = matrix.determinant() !== 0;const inverse = matrix.clone().invert();selected.node.traverse((node) => {@@ -41434,10 +41889,10 @@ function describeSubjectFrame(root, subject) {if (!attr)return;for (let i = 0;i < attr.count; i++)- local.expandByPoint(new Vector345().fromBufferAttribute(attr, i).applyMatrix4(mesh.matrixWorld).applyMatrix4(inverse));+ local.expandByPoint(new Vector346().fromBufferAttribute(attr, i).applyMatrix4(mesh.matrixWorld).applyMatrix4(inverse));});const box = (b) => b.isEmpty() ? null : { min: b.min.toArray(), max: b.max.toArray() };- const axis = (i) => new Vector345().setFromMatrixColumn(matrix, i).normalize().toArray();+ const axis = (i) => new Vector346().setFromMatrixColumn(matrix, i).normalize().toArray();return {path: selected.path,name: selected.name,@@ -41447,7 +41902,7 @@ function describeSubjectFrame(root, subject) {invertible,worldMatrix: matrix.toArray(),axes: { frame: "world", x: axis(0), y: axis(1), z: axis(2) },- origin: new Vector345().setFromMatrixPosition(matrix).toArray()+ origin: new Vector346().setFromMatrixPosition(matrix).toArray()};}function measureAttachment(root, input) {@@ -41460,7 +41915,7 @@ function measureAttachment(root, input) {return {path: selected.path,local: [...local],- world: new Vector345(...local).applyMatrix4(selected.node.matrixWorld).toArray()+ world: new Vector346(...local).applyMatrix4(selected.node.matrixWorld).toArray()};};const from = endpoint(input.from), to = endpoint(input.to);@@ -41470,7 +41925,7 @@ function measureAttachment(root, input) {method: "straight-line anchor distance",from,to,- distance: new Vector345(...from.world).distanceTo(new Vector345(...to.world))+ distance: new Vector346(...from.world).distanceTo(new Vector346(...to.world))};}var init_measurement = __esm(() => {@@ -41482,7 +41937,7 @@ import {PropertyType as PropertyType6} from "@gltf-transform/core";import { ALL_EXTENSIONS as ALL_EXTENSIONS2 } from "@gltf-transform/extensions";-import { Box3 as Box327, Matrix4 as Matrix419, Quaternion as Quaternion23, Vector3 as Vector346 } from "three";+import { Box3 as Box328, Matrix4 as Matrix419, Quaternion as Quaternion23, Vector3 as Vector347 } from "three";async function accessorFingerprint(accessor) {const array = accessor?.getArray();if (!accessor || !array)@@ -41501,7 +41956,7 @@ function bounds(box) {return box.isEmpty() ? null : {min: box.min.toArray(),max: box.max.toArray(),- size: box.getSize(new Vector346).toArray()+ size: box.getSize(new Vector347).toArray()};}async function digest8(bytes) {@@ -41517,7 +41972,7 @@ function placements(node) {const rotation = instances.getAttribute("ROTATION");const scale = instances.getAttribute("SCALE");const count = translation?.getCount() ?? rotation?.getCount() ?? scale?.getCount() ?? 1;- return Array.from({ length: count }, (_, i) => world.clone().multiply(new Matrix419().compose(new Vector346().fromArray(translation?.getElement(i, []) ?? [0, 0, 0]), new Quaternion23().fromArray(rotation?.getElement(i, []) ?? [0, 0, 0, 1]), new Vector346().fromArray(scale?.getElement(i, []) ?? [1, 1, 1]))));+ return Array.from({ length: count }, (_, i) => world.clone().multiply(new Matrix419().compose(new Vector347().fromArray(translation?.getElement(i, []) ?? [0, 0, 0]), new Quaternion23().fromArray(rotation?.getElement(i, []) ?? [0, 0, 0, 1]), new Vector347().fromArray(scale?.getElement(i, []) ?? [1, 1, 1]))));}function triangleCorners(mode, count) {const corners = [];@@ -41584,7 +42039,7 @@ async function drawnGeometryDigests(doc) {}const data = new Float32Array(triangles * RECORD);const others = [];- const point = new Vector346;+ const point = new Vector347;const element = [0, 0, 0];const texcoord = [0, 0];const corner = new Float32Array(15);@@ -41667,7 +42122,7 @@ async function revisionTotals(doc) {const { vertices, geometry, uv } = await drawnGeometryDigests(doc);const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];const drawnBounds = scene ? drawnSceneBounds(scene) : null;- const box = drawnBounds && [...drawnBounds.min, ...drawnBounds.max].every(Number.isFinite) ? new Box327(new Vector346(...drawnBounds.min), new Vector346(...drawnBounds.max)) : new Box327;+ const box = drawnBounds && [...drawnBounds.min, ...drawnBounds.max].every(Number.isFinite) ? new Box328(new Vector347(...drawnBounds.min), new Vector347(...drawnBounds.max)) : new Box328;return {triangles: metrics.triangles,vertices,@@ -41742,7 +42197,7 @@ async function snapshot3(bytes) {if (depth > 128)throw new Error("Revision comparison hierarchy exceeds 128 levels.");const names = new Set;- const combined = new Box327;+ const combined = new Box328;const placed = siblings.flatMap((node) => [{ node, drawn: true },...lowerLevels(node).map((level) => ({ node: level, drawn: false }))@@ -41759,7 +42214,7 @@ async function snapshot3(bytes) {if (node.listExtensions().some((extension) => extension.extensionName !== MSFT_LOD && extension.extensionName !== "KHR_node_visibility") || mesh?.listExtensions().length)throw new Error("Revision comparison does not support node/mesh extensions (including instancing).");const primitives = mesh?.listPrimitives() ?? [];- const own = new Box327;+ const own = new Box328;const matrix = parentWorld.clone().multiply(new Matrix419().fromArray(node.getMatrix()));if (matrix.elements.some((value) => !Number.isFinite(value)))throw new Error("Revision comparison requires finite transforms.");@@ -41780,7 +42235,7 @@ async function snapshot3(bytes) {if (!Number.isInteger(vertex) || vertex < 0 || vertex >= position.getCount())throw new Error("Revision comparison found an invalid vertex index.");position.getElement(vertex, element);- const point = new Vector346(...element).applyMatrix4(matrix);+ const point = new Vector347(...element).applyMatrix4(matrix);if (point.toArray().some((value) => !Number.isFinite(value)))throw new Error("Revision comparison requires finite positions.");own.expandByPoint(point);@@ -41980,20 +42435,20 @@ var init_revision_comparison = __esm(() => {// src/views/surface-distance.tsimport {- Box3 as Box328,+ Box3 as Box329,Matrix4 as Matrix420,- Ray as Ray2,- Triangle as Triangle2,- Vector3 as Vector347+ Ray as Ray3,+ Triangle as Triangle3,+ Vector3 as Vector348} from "three";function hierarchy(triangles) {- const box = new Box328;+ const box = new Box329;for (const triangle of triangles)box.union(triangle.box);const count = triangles.length;if (count <= 4)return { box, count, triangles };- const size = box.getSize(new Vector347);+ const size = box.getSize(new Vector348);const axis = size.x >= size.y && size.x >= size.z ? "x" : size.y >= size.z ? "y" : "z";const center = (triangle) => triangle.box.min[axis] / 2 + triangle.box.max[axis] / 2;triangles.sort((a, b) => center(a) - center(b));@@ -42004,7 +42459,7 @@ function hierarchy(triangles) {children: [hierarchy(triangles.slice(0, middle)), hierarchy(triangles.slice(middle))]};}-function boxDistanceSquared(a, b) {+function boxDistanceSquared2(a, b) {const x = Math.max(0, a.min.x - b.max.x, b.min.x - a.max.x);const y = Math.max(0, a.min.y - b.max.y, b.min.y - a.max.y);const z = Math.max(0, a.min.z - b.max.z, b.min.z - a.max.z);@@ -42012,7 +42467,7 @@ function boxDistanceSquared(a, b) {}function collect(node, paths) {const triangles = [];- const bounds = new Box328;+ const bounds = new Box329;node.updateWorldMatrix(true, true);node.traverseVisible((child) => {const mesh = child;@@ -42045,13 +42500,13 @@ function collect(node, paths) {const id = index ? index.getX(i + offset) : i + offset;if (!Number.isSafeInteger(id) || id < 0 || id >= position.count)throw new Error("Surface distance encountered an invalid triangle index.");- const point = new Vector347().fromBufferAttribute(position, id).applyMatrix4(matrix);+ const point = new Vector348().fromBufferAttribute(position, id).applyMatrix4(matrix);if (![point.x, point.y, point.z].every(Number.isFinite))throw new Error("Surface distance encountered a non-finite world position.");return point;};- const triangle = new Triangle2(vertex(0), vertex(1), vertex(2));- const box = new Box328().setFromPoints([triangle.a, triangle.b, triangle.c]);+ const triangle = new Triangle3(vertex(0), vertex(1), vertex(2));+ const box = new Box329().setFromPoints([triangle.a, triangle.b, triangle.c]);bounds.union(box);triangles.push({triangle,@@ -42104,10 +42559,10 @@ function trianglePair(a, b) {const av = [a.a, a.b, a.c], bv = [b.a, b.b, b.c];if (b.getArea() > 0)for (const p of av)- record(p, b.closestPointToPoint(p, new Vector347));+ record(p, b.closestPointToPoint(p, new Vector348));if (a.getArea() > 0)for (const q of bv)- record(a.closestPointToPoint(q, new Vector347), q);+ record(a.closestPointToPoint(q, new Vector348), q);for (let i = 0;i < 3; i++) {const p = av[i], q = av[(i + 1) % 3];for (let j = 0;j < 3; j++)@@ -42120,9 +42575,9 @@ function trianglePair(a, b) {const length = delta.length();if (length === 0)continue;- const hit = new Ray2(origin, delta.divideScalar(length)).intersectTriangle(target.a, target.b, target.c, false, new Vector347);+ const hit = new Ray3(origin, delta.divideScalar(length)).intersectTriangle(target.a, target.b, target.c, false, new Vector348);if (hit && origin.distanceTo(hit) <= length) {- const onFace = target.closestPointToPoint(hit, new Vector347);+ const onFace = target.closestPointToPoint(hit, new Vector348);if (vertices === av)record(hit, onFace);else@@ -42156,7 +42611,7 @@ function measureSurfaceDistance(root, input) {});const finish = (complete) => {const upper = Number.isFinite(best) ? Math.sqrt(best) : null;- const lower = complete ? upper : Math.sqrt(boxDistanceSquared(a.bounds, b.bounds));+ const lower = complete ? upper : Math.sqrt(boxDistanceSquared2(a.bounds, b.bounds));if (!Number.isFinite(lower))throw new Error("Surface distance exceeds the finite numeric range.");return {@@ -42170,7 +42625,7 @@ function measureSurfaceDistance(root, input) {bounds: { lower, upper },closest,pairsVisited: visited,- reason: complete ? null : `Search budget ${MAX_WORK} reached (hierarchy and triangle pairs); select smaller parts. Upper bound is the closest pair found, not a completed minimum.`,+ reason: complete ? null : `Search budget ${MAX_WORK2} reached (hierarchy and triangle pairs); select smaller parts. Upper bound is the closest pair found, not a completed minimum.`,limitations: LIMITATIONS};};@@ -42178,25 +42633,25 @@ function measureSurfaceDistance(root, input) {{a: hierarchy(a.triangles),b: hierarchy(b.triangles),- lower: boxDistanceSquared(a.bounds, b.bounds)+ lower: boxDistanceSquared2(a.bounds, b.bounds)}];while (pending.length) {const current = pending.pop();if (current.lower >= best)continue;- if (work === MAX_WORK)+ if (work === MAX_WORK2)return finish(false);work++;const { a: x, b: y } = current;if ("triangles" in x && "triangles" in y) {for (const left of x.triangles)for (const right of y.triangles) {- if (work === MAX_WORK)+ if (work === MAX_WORK2)return finish(false);work++;visited++;- if (boxDistanceSquared(left.box, right.box) >= best)+ if (boxDistanceSquared2(left.box, right.box) >= best)continue;const candidate = trianglePair(left.triangle, right.triangle);if (candidate.squared < best) {@@ -42213,7 +42668,7 @@ function measureSurfaceDistance(root, input) {}));const next = pairs.map((pair) => ({...pair,- lower: boxDistanceSquared(pair.a.box, pair.b.box)+ lower: boxDistanceSquared2(pair.a.box, pair.b.box)}));if (next[0].lower <= next[1].lower)pending.push(next[1], next[0]);@@ -42276,7 +42731,7 @@ function measureSurfacePairs(root, pairs) {results};}-var MAX_TRIANGLES = 20000, MAX_WORK = 250000, LIMITATIONS = "Unsigned distance between tessellated surfaces in the exported rest pose. Zero means touching or crossing surfaces; positive distance does not exclude containment. Does not establish solid clearance, attachment strength, motion, or alpha/displacement appearance.";+var MAX_TRIANGLES = 20000, MAX_WORK2 = 250000, LIMITATIONS = "Unsigned distance between tessellated surfaces in the exported rest pose. Zero means touching or crossing surfaces; positive distance does not exclude containment. Does not establish solid clearance, attachment strength, motion, or alpha/displacement appearance.";var init_surface_distance = __esm(() => {init_camera();});@@ -42288,7 +42743,7 @@ __export(exports_draw_diagnostics, {});import { Primitive as Primitive3 } from "@gltf-transform/core";import { cloneDocument as cloneDocument2 } from "@gltf-transform/functions";-import * as THREE59 from "three";+import * as THREE60 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)@@ -42341,7 +42796,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 THREE59.Vector3).length(), b.bounds.getSize(new THREE59.Vector3).length(), 0.000000000001) * 0.000001;+ const tolerance = Math.max(a.bounds.getSize(new THREE60.Vector3).length(), b.bounds.getSize(new THREE60.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);@@ -42383,7 +42838,7 @@ function observe(uses) {unexaminedPrimitiveUses++;continue;}- const matrix = new THREE59.Matrix4().fromArray(node.getWorldMatrix());+ const matrix = new THREE60.Matrix4().fromArray(node.getWorldMatrix());if (primitive.getAttribute("TANGENT") && matrix.determinant() < 0)mirrored.set(part.id, part);const position = primitive.getAttribute("POSITION");@@ -42397,14 +42852,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 THREE59.Vector3().fromArray(position.getElement(indices ? indices.getScalar(start + j) : start + j, [])).applyMatrix4(matrix));+ const points = [0, 1, 2].map((j) => new THREE60.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 THREE59.Box3().setFromPoints(points),+ bounds: new THREE60.Box3().setFromPoints(points),part});}@@ -47828,6 +48283,7 @@ define2("markOpenShell", {semantics: ["QA reports a marked part that cannot be built as a closed solid as GEO_PART_SELF_INTERSECTION_ACKNOWLEDGED with the reason, instead of GEO_PART_SELF_INTERSECTION_UNMEASURED.","Overlapping pairs with the marked part stay unmeasured and are counted; overlap there is not ruled out. Overlap between other parts is still measured and reported.",+ "Volume stays unmeasured, but GEO_OPEN_SURFACE_PENETRATION separately samples an open surface against the closed solids it meets and reports how far inside one it reaches.","A marked part that builds as a closed solid is measured like any other part. A part skipped for its size, draw range, instancing or invalid indices is still reported as unmeasured.","Both exporters write the mark as the node extras kilnOpenShell: { schemaVersion: 1, reason }; import restores it to userData.","Invalid arguments, or a kilnOpenShell value this helper did not write, are an OPEN_SHELL build error."@@ -52580,7 +53036,7 @@ init_render();init_requirements_context();init_evaluator();init_material_resources();-import * as THREE60 from "three";+import * as THREE61 from "three";// src/render-route.tsvar GPU_SERVES = new Set([@@ -53165,8 +53621,8 @@ function collectSceneMetrics(root) {let meshes = 0;const materialSet = new Set;let lowestPart;- const box = new THREE60.Box3;- const point = new THREE60.Vector3;+ const box = new THREE61.Box3;+ const point = new THREE61.Vector3;root.updateWorldMatrix(true, true);root.traverseVisible((node) => {const n = node;@@ -53182,7 +53638,7 @@ function collectSceneMetrics(root) {const mesh = node;const position = mesh.geometry.getAttribute("position");const index = mesh.geometry.index;- const mb = new THREE60.Box3;+ const mb = new THREE61.Box3;if (position) {for (let i = 0;i < (index?.count ?? position.count); i++) {point.fromBufferAttribute(position, index ? index.getX(i) : i);@@ -53197,7 +53653,7 @@ function collectSceneMetrics(root) {});let bbox;if (!box.isEmpty()) {- const size = new THREE60.Vector3;+ const size = new THREE61.Vector3;box.getSize(size);bbox = {min: [box.min.x, box.min.y, box.min.z],diff --git a/skills/kiln-qa-asset/SKILL.md b/skills/kiln-qa-asset/SKILL.mdindex 7dbf18d7..d2a3ca75 100644--- a/skills/kiln-qa-asset/SKILL.md+++ b/skills/kiln-qa-asset/SKILL.md@@ -40,6 +40,26 @@ not a clean result. Closed components are unioned before measuring overlap;unsupported inward shells or component budgets remain unmeasured. Hidden subtreesare excluded from category QA, while `hiddenNodes` accounts for their triangles.+An open surface has no volume, so the overlap observer can never measure it. A separate+observation does: `GEO_OPEN_SURFACE_PENETRATION` samples each open surface's vertices+against the closed solids it meets and reports how far inside one it reaches, naming both+parts and the depth in metres. Penetration at or below the 0.005 m contact tolerance is+treated as intended contact, so a cloth resting on a seat or tucked flush against a panel+stays silent; a cloth crossing a wall or pierced by a mast does not. This is deliberately+far tighter than the 0.02 m adjacency tolerance the floating-part and connectivity checks+share, because a surface two centimetres inside a cushion, a canopy panel or a wall cap is+already visibly wrong.++A positive is a measurement, not a verdict, and most are intentional. Open surfaces in real+assets are usually structural shells -- hulls, roofs, canopies, ribs -- and a fitting+socketed into a shell puts shell vertices inside the solid by design, exactly as a bolt in a+hole shares volume with it. Read these the way you read the part-overlap observations: group+them by code, then review the pairs you did not intend. Vertices are the samples, so a solid+thinner than the surface's own facet spacing can pass between two of them: `_TRUNCATED`+reports pairs left for budget and vertices whose side could not be settled, and `_UNMEASURED`+names parts that were not sampled at all. A clean result here is not a fit audit, and it says+nothing about open surfaces meeting each other.+`SWEEP_SELF_INTERSECTION` observes tight station curvature or intersectingconsecutive rings in a sweep/loft. Inspect the station and radius evidence. A`_PARTIAL` finding or `_UNCHECKED` warning means the bounded local analysis did notdiff --git a/src/discovery/helper-contracts.ts b/src/discovery/helper-contracts.tsindex 56274fbe..b17cfd4a 100644--- a/src/discovery/helper-contracts.ts+++ b/src/discovery/helper-contracts.ts@@ -1190,6 +1190,7 @@ define(semantics: ['QA reports a marked part that cannot be built as a closed solid as GEO_PART_SELF_INTERSECTION_ACKNOWLEDGED with the reason, instead of GEO_PART_SELF_INTERSECTION_UNMEASURED.','Overlapping pairs with the marked part stay unmeasured and are counted; overlap there is not ruled out. Overlap between other parts is still measured and reported.',+ 'Volume stays unmeasured, but GEO_OPEN_SURFACE_PENETRATION separately samples an open surface against the closed solids it meets and reports how far inside one it reaches.','A marked part that builds as a closed solid is measured like any other part. A part skipped for its size, draw range, instancing or invalid indices is still reported as unmeasured.','Both exporters write the mark as the node extras kilnOpenShell: { schemaVersion: 1, reason }; import restores it to userData.','Invalid arguments, or a kilnOpenShell value this helper did not write, are an OPEN_SHELL build error.',diff --git a/src/qa/open-surface-penetration.test.ts b/src/qa/open-surface-penetration.test.tsnew file mode 100644index 00000000..221a9175--- /dev/null+++ b/src/qa/open-surface-penetration.test.ts@@ -0,0 +1,351 @@+/**+ * #277 — open surfaces measured against closed solids.+ *+ * The difficulty is the same as T4.1's and sharper: a cloth has no volume, so+ * the boolean pass cannot measure it at all, and the true negatives are the+ * whole problem. A throw resting on a seat, a canopy touching its mast and a+ * cloth deliberately sunk a millimetre or two to hide a seam are all correct+ * geometry. Every one has a fixture here beside the true positives.+ */++import { describe, expect, test } from 'bun:test';+import * as THREE from 'three';+import {+ analyzeOpenSurfacePenetration,+ inspectOpenSurfacePenetration,+ OPEN_SURFACE_CONTACT_TOLERANCE,+ OPEN_SURFACE_PENETRATION_QA_RULE,+} from './open-surface-penetration';+import { analyzePartPenetration } from './self-intersection';+import { EXTERNAL_SUPPORT_TOLERANCE } from '../external-support';+import { createAssetIntentV1 } from '../contracts';+import { markOpenShell } from '../open-shell';++function solid(name: string, size: [number, number, number], at: [number, number, number]) {+ const mesh = new THREE.Mesh(new THREE.BoxGeometry(...size));+ mesh.name = name;+ mesh.position.set(...at);+ return mesh;+}++/** An open surface: one plane, no thickness, no volume. */+function cloth(+ name: string,+ size: [number, number],+ at: [number, number, number],+ rotationX = -Math.PI / 2,+ segments = 8,+) {+ const mesh = new THREE.Mesh(new THREE.PlaneGeometry(size[0], size[1], segments, segments));+ mesh.name = name;+ mesh.rotation.x = rotationX;+ mesh.position.set(...at);+ return mesh;+}++function sceneOf(...nodes: THREE.Object3D[]): THREE.Object3D {+ const root = new THREE.Object3D();+ root.name = 'Asset';+ for (const node of nodes) root.add(node);+ return root;+}++describe('true positives — an open surface inside a closed solid', () => {+ test('a cloth running through a wall names both parts and the depth', () => {+ const evidence = analyzeOpenSurfacePenetration(+ sceneOf(+ solid('Mesh_CurvedWall', [2, 1.4, 0.12], [0, 0.7, 0.4]),+ cloth('Mesh_ThrowBlanket', [1, 1], [0, 0.7, 0.4], 0),+ ),+ );+ expect(evidence.penetrations).toHaveLength(1);+ const [pair] = evidence.penetrations;+ expect(pair!.open).toBe('Mesh_ThrowBlanket');+ expect(pair!.solid).toBe('Mesh_CurvedWall');+ // The cloth sits on the wall's mid-plane, so the nearest face is half its thickness away.+ expect(pair!.depth).toBeCloseTo(0.06, 4);+ const [finding] = inspectOpenSurfacePenetration(evidence);+ expect(finding!.code).toBe('GEO_OPEN_SURFACE_PENETRATION');+ expect(finding!.message).toContain('Mesh_ThrowBlanket');+ expect(finding!.message).toContain('Mesh_CurvedWall');+ expect(finding!.message).toContain('0.0600');+ });++ test('a canopy pierced by one mast is reported from a single penetrating vertex', () => {+ const evidence = analyzeOpenSurfacePenetration(+ sceneOf(+ solid('Mesh_Mast', [0.06, 2, 0.06], [0, 1, 0]),+ cloth('Mesh_Canopy', [1.2, 1.2], [0, 1, 0]),+ ),+ );+ expect(evidence.penetrations).toHaveLength(1);+ expect(evidence.penetrations[0]!.vertices).toBe(1);+ expect(evidence.penetrations[0]!.depth).toBeCloseTo(0.03, 4);+ });+});++describe('true negatives — correct geometry that must stay silent', () => {+ test('a cloth resting exactly on a seat top is contact, not penetration', () => {+ const evidence = analyzeOpenSurfacePenetration(+ sceneOf(+ solid('Mesh_Seat', [1, 0.4, 1], [0, 0.2, 0]),+ cloth('Mesh_Throw', [0.8, 0.8], [0, 0.4, 0]),+ ),+ );+ expect(evidence.candidatePairs).toBe(1);+ expect(evidence.penetrations).toEqual([]);+ expect(inspectOpenSurfacePenetration(evidence)).toEqual([]);+ });++ test('a cloth sunk inside the contact tolerance to hide a seam stays silent', () => {+ const sunk = OPEN_SURFACE_CONTACT_TOLERANCE / 2;+ const evidence = analyzeOpenSurfacePenetration(+ sceneOf(+ solid('Mesh_Cushion', [1, 0.4, 1], [0, 0.2, 0]),+ cloth('Mesh_Throw', [0.8, 0.8], [0, 0.4 - sunk, 0]),+ ),+ );+ expect(evidence.penetrations).toEqual([]);+ });++ test('a cloth clear above a seat is neither contact nor penetration', () => {+ const evidence = analyzeOpenSurfacePenetration(+ sceneOf(+ solid('Mesh_Seat', [1, 0.4, 1], [0, 0.2, 0]),+ cloth('Mesh_Throw', [0.8, 0.8], [0, 0.45, 0]),+ ),+ );+ expect(evidence.candidatePairs).toBe(0);+ expect(evidence.penetrations).toEqual([]);+ });++ test('two closed solids are left to the boolean pass', () => {+ const evidence = analyzeOpenSurfacePenetration(+ sceneOf(solid('Mesh_A', [1, 1, 1], [0, 0, 0]), solid('Mesh_B', [1, 1, 1], [0.5, 0, 0])),+ );+ expect(evidence.openParts).toBe(0);+ expect(evidence.candidatePairs).toBe(0);+ expect(evidence.penetrations).toEqual([]);+ });+});++describe('composed modules', () => {+ test('a cloth from one module through a wall in another is reported', () => {+ const seating = new THREE.Group();+ seating.name = 'SeatingModule';+ seating.add(solid('Mesh_Bench', [1.2, 0.4, 0.5], [0, 0.2, 0]));+ seating.add(cloth('Mesh_ThrowBlanket', [1, 1], [0, 0.7, 0.4], 0));+ const structure = new THREE.Group();+ structure.name = 'StructureModule';+ structure.add(solid('Mesh_CurvedWall', [2, 1.4, 0.12], [0, 0.7, 0.4]));+ const evidence = analyzeOpenSurfacePenetration(sceneOf(seating, structure));+ expect(evidence.penetrations.map((pair) => [pair.open, pair.solid])).toEqual([+ ['Mesh_ThrowBlanket', 'Mesh_CurvedWall'],+ ]);+ });+});++describe('the tolerance regime', () => {+ test('penetration uses its own tolerance, not the 2 cm adjacency tolerance', () => {+ expect(OPEN_SURFACE_CONTACT_TOLERANCE).toBeLessThan(EXTERNAL_SUPPORT_TOLERANCE);+ expect(EXTERNAL_SUPPORT_TOLERANCE).toBe(0.02);+ });++ test('a cloth 1 cm inside a 3 cm panel is reported, where a 2 cm tolerance would hide it', () => {+ // The panel's mid-plane is 15 mm from either face, so a cloth on it reads 15 mm:+ // under the adjacency tolerance, over this pass's.+ const evidence = analyzeOpenSurfacePenetration(+ sceneOf(+ solid('Mesh_WallCap', [1.5, 0.4, 0.03], [0, 0.5, 0]),+ cloth('Mesh_Throw', [0.6, 0.3], [0, 0.5, 0], 0),+ ),+ );+ expect(evidence.penetrations).toHaveLength(1);+ expect(evidence.penetrations[0]!.depth).toBeCloseTo(0.015, 4);+ expect(evidence.penetrations[0]!.depth).toBeLessThan(EXTERNAL_SUPPORT_TOLERANCE);+ });++ test('an explicit tolerance widens intended contact without changing the measurement', () => {+ const build = () =>+ sceneOf(+ solid('Mesh_Cushion', [1, 0.4, 1], [0, 0.2, 0]),+ cloth('Mesh_Throw', [0.8, 0.8], [0, 0.39, 0]),+ );+ expect(analyzeOpenSurfacePenetration(build()).penetrations).toHaveLength(1);+ expect(analyzeOpenSurfacePenetration(build(), 0.02).penetrations).toEqual([]);+ });+});++describe('coverage this pass does not claim', () => {+ test('a marked open shell is measured here, which the volume pass says it cannot be', async () => {+ const throwBlanket = cloth('Mesh_ThrowBlanket', [1, 1], [0, 0.7, 0.4], 0);+ markOpenShell(throwBlanket, 'a single-sided wool throw');+ const scene = sceneOf(solid('Mesh_CurvedWall', [2, 1.4, 0.12], [0, 0.7, 0.4]), throwBlanket);+ // The volume pass can only acknowledge the mark; this one takes the measurement.+ const volume = await analyzePartPenetration(scene);+ expect(volume.penetrations).toEqual([]);+ expect(volume.acknowledged?.map((part) => part.part)).toEqual(['Mesh_ThrowBlanket']);+ expect(analyzeOpenSurfacePenetration(scene).penetrations).toHaveLength(1);+ });++ test('a solid thinner than the surface facet spacing passes between vertices unreported', () => {+ // One quad, 1 m across, and a 2 cm post through its middle: no vertex is inside.+ const evidence = analyzeOpenSurfacePenetration(+ sceneOf(+ solid('Mesh_Post', [0.02, 2, 0.02], [0, 1, 0]),+ cloth('Mesh_Canopy', [1, 1], [0, 1, 0], -Math.PI / 2, 1),+ ),+ );+ expect(evidence.candidatePairs).toBe(1);+ expect(evidence.penetrations).toEqual([]);+ });++ test('LOD alternates are not compared', () => {+ const low = new THREE.Group();+ low.name = 'Awning_LOD1';+ low.add(cloth('Mesh_AwningCloth', [1, 1], [0, 0.7, 0.4], 0));+ const high = new THREE.Group();+ high.name = 'Awning_LOD0';+ high.add(solid('Mesh_AwningFrame', [2, 1.4, 0.12], [0, 0.7, 0.4]));+ const evidence = analyzeOpenSurfacePenetration(sceneOf(low, high));+ expect(evidence.pairsLodAlternates).toBe(1);+ expect(evidence.candidatePairs).toBe(0);+ expect(evidence.penetrations).toEqual([]);+ });++ test('an instanced part is named as unmeasured rather than dropped', () => {+ const instanced = new THREE.InstancedMesh(new THREE.BoxGeometry(1, 1, 1), undefined, 2);+ instanced.name = 'Mesh_Pebbles';+ const evidence = analyzeOpenSurfacePenetration(+ sceneOf(instanced, cloth('Mesh_Throw', [1, 1], [0, 0, 0])),+ );+ expect(evidence.skipped.map((part) => part.part)).toEqual(['Mesh_Pebbles']);+ const codes = inspectOpenSurfacePenetration(evidence).map((finding) => finding.code);+ expect(codes).toContain('GEO_OPEN_SURFACE_PENETRATION_UNMEASURED');+ });++ test('a non-Object3D scene yields an empty measurement, never a clean pass claim', () => {+ const evidence = analyzeOpenSurfacePenetration(undefined);+ expect(evidence.openParts).toBe(0);+ expect(evidence.closedParts).toBe(0);+ expect(inspectOpenSurfacePenetration(evidence)).toEqual([]);+ });+});++describe('determinism and wiring', () => {+ test('the same scene yields the same evidence', () => {+ const build = () =>+ sceneOf(+ solid('Mesh_CurvedWall', [2, 1.4, 0.12], [0, 0.7, 0.4]),+ solid('Mesh_Mast', [0.06, 2, 0.06], [0.4, 1, 0.4]),+ cloth('Mesh_ThrowBlanket', [1.4, 1.4], [0, 0.7, 0.4], 0),+ );+ const first = analyzeOpenSurfacePenetration(build());+ expect(JSON.stringify(analyzeOpenSurfacePenetration(build()))).toBe(JSON.stringify(first));+ expect(first.penetrations.map((pair) => pair.solid)).toEqual(['Mesh_CurvedWall']);+ });++ test('the rule takes its own measurement from the scene', () => {+ const findings = OPEN_SURFACE_PENETRATION_QA_RULE.evaluate({+ intent: createAssetIntentV1({ category: 'prop' }),+ scene: sceneOf(+ solid('Mesh_CurvedWall', [2, 1.4, 0.12], [0, 0.7, 0.4]),+ cloth('Mesh_ThrowBlanket', [1, 1], [0, 0.7, 0.4], 0),+ ),+ });+ expect(findings.map((finding) => finding.code)).toEqual(['GEO_OPEN_SURFACE_PENETRATION']);+ expect(findings[0]!.disposition).toBe('observe');+ expect(findings[0]!.dimension).toBe('visualQuality');+ });+});++describe('reported coverage', () => {+ const base = {+ schemaVersion: 1 as const,+ source: 'engine-scene-analysis' as const,+ contactTolerance: OPEN_SURFACE_CONTACT_TOLERANCE,+ openParts: 2,+ closedParts: 2,+ candidatePairs: 4,+ pairsTested: 1,+ pairsNotReached: 3,+ pairsLodAlternates: 0,+ verticesUnresolved: 0,+ truncated: true,+ skipped: [],+ penetrations: [],+ };++ test('a budget shortfall names the pairs it did not sample', () => {+ const [finding] = inspectOpenSurfacePenetration(base);+ expect(finding!.code).toBe('GEO_OPEN_SURFACE_PENETRATION_TRUNCATED');+ expect(finding!.message).toContain('Sampled 1 of 4');+ expect(finding!.message).not.toContain('could not be resolved');+ expect(finding!.measurement!.breakdown).toEqual({+ pairsNotReached: 3,+ verticesUnresolved: 0,+ });+ });++ test('unresolved vertices are reported apart from the budget, not as skipped work', () => {+ const [finding] = inspectOpenSurfacePenetration({+ ...base,+ pairsTested: 4,+ pairsNotReached: 0,+ truncated: false,+ verticesUnresolved: 2,+ });+ expect(finding!.code).toBe('GEO_OPEN_SURFACE_PENETRATION_TRUNCATED');+ expect(finding!.message).not.toContain('analysis budget');+ expect(finding!.message).toContain('2 vertices');+ expect(finding!.message).toContain('counted as neither');+ });++ test('complete coverage reports nothing', () => {+ expect(+ inspectOpenSurfacePenetration({+ ...base,+ pairsTested: 4,+ pairsNotReached: 0,+ truncated: false,+ }),+ ).toEqual([]);+ });+});++describe('a positive is a measurement, not a verdict', () => {+ /**+ * Measured over the 86 shipped examples, 916 findings across 51 of them, against+ * 3,575 from the part-volume pass across all 86. The dominant real case is not+ * cloth: it is a fitting socketed into a structural shell, which is correct+ * geometry and is still reported, exactly as the volume pass reports a bolt in a+ * hole. This fixture pins that, so the pass is never mistaken for a defect gate.+ */+ test('a fitting socketed into a hull shell is reported, like a bolt in a hole', () => {+ // An open hull panel with a lamp recess set into it: the recess is meant to be there.+ const hull = cloth('Mesh_HullPanel', [2, 1.2], [0, 0.6, 0], 0, 12);+ const recess = solid('Mesh_LampRecess', [0.12, 0.12, 0.2], [0, 0.6, 0]);+ const evidence = analyzeOpenSurfacePenetration(sceneOf(recess, hull));+ expect(evidence.penetrations).toHaveLength(1);+ const [finding] = inspectOpenSurfacePenetration(evidence);+ expect(finding!.disposition).toBe('observe');+ expect(finding!.repairText).toContain('not a defect');+ expect(finding!.repairText).toContain('a bolt in a hole');+ });++ test('the finding carries the depth as a measurement against the tolerance', () => {+ const evidence = analyzeOpenSurfacePenetration(+ sceneOf(+ solid('Mesh_CurvedWall', [2, 1.4, 0.12], [0, 0.7, 0.4]),+ cloth('Mesh_ThrowBlanket', [1, 1], [0, 0.7, 0.4], 0),+ ),+ );+ const [finding] = inspectOpenSurfacePenetration(evidence);+ expect(finding!.measurement).toMatchObject({+ name: 'openSurfacePenetrationDepth',+ expected: OPEN_SURFACE_CONTACT_TOLERANCE,+ unit: 'm',+ });+ expect(finding!.measurement!.actual).toBeCloseTo(0.06, 4);+ });+});diff --git a/src/qa/open-surface-penetration.ts b/src/qa/open-surface-penetration.tsnew file mode 100644index 00000000..3cee054b--- /dev/null+++ b/src/qa/open-surface-penetration.ts@@ -0,0 +1,697 @@+/**+ * Open surfaces measured against closed solids — #277+ *+ * ## The gap this fills+ *+ * The part-volume pass (`self-intersection.ts`) measures shared volume, so it+ * can only compare parts it can build as closed solids. A cloth, a canopy sheet+ * or an ivy card encloses no volume at all, so every pair containing one is+ * reported as unmeasured — `GEO_PART_SELF_INTERSECTION_UNMEASURED`, or+ * `GEO_PART_SELF_INTERSECTION_ACKNOWLEDGED` when the author marked the shell+ * open. Both findings say plainly that overlap there is not ruled out.+ *+ * That leaves the author with one signal for two opposite situations. A throw+ * resting on a seat and a throw running through a wall produce the same+ * sentence. This pass answers the question the volume pass states it cannot:+ * how far does an open surface reach inside a closed neighbour.+ *+ * ## Depth before sign+ *+ * The measurement is a per-vertex distance to the solid's surface, and the sign+ * — inside or outside — comes from ray parity against the same watertight+ * triangles. The order matters:+ *+ * 1. Distance first. A vertex within {@link OPEN_SURFACE_CONTACT_TOLERANCE} of+ * the surface is **contact**, and no sign is claimed for it.+ * 2. Sign only beyond the tolerance, where parity is well away from its+ * degenerate regime.+ *+ * A cloth authored exactly flush on a seat has every vertex on the surface,+ * which is precisely where a parity ray is ambiguous — it grazes the face it+ * starts on. Testing distance first removes that whole class: those vertices+ * never reach the ray. The flush case is silent because it is contact, not+ * because the measurement failed.+ *+ * ## The tolerance is not the adjacency tolerance+ *+ * `FLOATING_EXPAND` and `EXTERNAL_SUPPORT_TOLERANCE` are both 2 cm, and both+ * answer a gross question: did the author forget to attach this part at all.+ * Penetration is a different regime and needs its own, much smaller number —+ * see {@link OPEN_SURFACE_CONTACT_TOLERANCE} for the measurements it was chosen+ * from. Reusing 2 cm here would let a cloth sink 2 cm into a cushion, a canopy+ * panel or a wall cap unreported, and those are exactly the parts an open+ * surface meets.+ *+ * ## Bounded time+ *+ * One deterministic triangle hierarchy per closed solid, built at most once and+ * reused across every open surface that meets it. Vertices are tested in buffer+ * order against a shared work budget; pairs are visited deepest box overlap+ * first, so the likeliest penetration is measured before the budget runs out.+ * Whatever the budget leaves is counted and reported, never silently dropped.+ *+ * ## A positive is not a defect+ *+ * Measured over the 86 shipped examples: 916 findings across 51 of them, against+ * 3,575 from the part-volume pass across all 86. So this sits well inside the+ * established register of that surface, and for the same reason. Open surfaces in+ * real assets are mostly structural shells — hulls, roofs, canopies, ribs — and a+ * fitting socketed into a shell puts shell vertices inside the solid by design,+ * exactly as a bolt in a hole shares volume with it. The finding is an `observe`+ * measurement the author adjudicates, and the output boundary groups repeated+ * findings by code so the count does not drown the report.+ *+ * ## What it does not see+ *+ * Vertices are the samples, so a solid thinner than the open surface's own+ * facet spacing can pass between two vertices that are both outside it. A+ * coarse drape over a thin rail reads clean for the same reason it should: its+ * vertices lie on or outside the rail, and only the interpolated facet cuts the+ * corner. Instanced, skinned and morph-deformed parts are not sampled.+ */++import * as THREE from 'three';+import { geometryDiagnostics } from '../geometry';+import { lodMembership } from './lod';+import { KILN_ENGINE_QA_OWNER, type QaRule } from './registry';+import type { QaContext, QaFinding } from './types';++/**+ * Penetration at or below this depth is treated as intended contact, in metres.+ *+ * Chosen from measured fixtures rather than from the adjacency tolerance:+ *+ * | geometry | depth |+ * |-------------------------------------------|---------|+ * | cloth flush on a seat top | 0 mm |+ * | cloth sunk to hide a seam | 1–3 mm |+ * | cloth 2 mm into a wall (invisible) | 2 mm |+ * | canopy pierced by a 6 cm mast | 30 mm |+ * | cloth running through a 12 cm wall | 60 mm |+ *+ * 5 mm sits an order of magnitude below the defects and above the authoring+ * slop, so both sides keep real margin. It is absolute rather than relative to+ * either part: the quantity is how deep a surface disappears into a solid,+ * which reads the same on a bench and on a building, and scaling it to the open+ * surface would let a 20 m banner hide 10 cm of penetration.+ */+export const OPEN_SURFACE_CONTACT_TOLERANCE = 0.005;+/** Above this, one part stops being bounded-time to sample or to index. */+export const MAX_SURFACE_TRIANGLES = 20000;+/** Vertices sampled per open surface, in buffer order. */+export const MAX_SAMPLED_VERTICES = 20000;+/** Triangle tests shared by every distance and parity query in one analysis. */+export const MAX_WORK = 250_000;+/** Bound pair discovery even when many boxes overlap. */+export const MAX_BROAD_PHASE_PAIRS = 250_000;++export interface OpenSurfacePenetrationPairV1 {+ /** The open surface's part name. */+ open: string;+ /** The closed solid it reaches inside. */+ solid: string;+ /** Deepest distance from the solid's surface to a penetrating vertex, in metres. */+ depth: number;+ /** Vertices measured inside the solid beyond the contact tolerance. */+ vertices: number;+ /** Vertices of the open surface sampled against this solid. */+ tested: number;+}++export interface OpenSurfacePenetrationEvidenceV1 {+ schemaVersion: 1;+ source: 'engine-scene-analysis';+ /** Contact tolerance the analysis ran with, in metres. */+ contactTolerance: number;+ /** Eligible open-surface parts collected. */+ openParts: number;+ /** Eligible closed-solid parts collected. */+ closedParts: number;+ /**+ * Open/closed pairs whose world boxes overlap, excluding LOD alternates; a+ * lower bound when `broadPhaseTruncated` is true.+ */+ candidatePairs: number;+ /** Pair discovery itself exhausted its budget; later pairs were not considered. */+ broadPhaseTruncated?: boolean;+ /** Pairs sampled to completion. */+ pairsTested: number;+ /** Candidate pairs left unsampled, or sampled only in part, by the work budget. */+ pairsNotReached: number;+ /**+ * Vertices whose side of a surface no parity direction could settle. Counted as+ * neither inside nor outside, and kept apart from the budget: an unresolved vertex+ * is a numeric limit, not work left undone.+ */+ verticesUnresolved: number;+ /** Overlapping pairs on different LOD levels: alternates, deliberately not compared. */+ pairsLodAlternates: number;+ /** True when pair discovery or the work budget left geometry unexamined. */+ truncated: boolean;+ /** Parts skipped, with the reason — never silently dropped. */+ skipped: { part: string; reason: string }[];+ /** Pairs whose depth exceeds the contact tolerance, deepest first. */+ penetrations: OpenSurfacePenetrationPairV1[];+}++interface SurfaceTriangle {+ triangle: THREE.Triangle;+ box: THREE.Box3;+}++type Hierarchy = { box: THREE.Box3 } & (+ | { triangles: SurfaceTriangle[] }+ | { children: [Hierarchy, Hierarchy] }+);++interface AnalyzedPart {+ name: string;+ mesh: THREE.Mesh;+ box: THREE.Box3;+ closed: boolean;+ lod: ReturnType<typeof lodMembership>;+ /** Built on first use and reused; closed parts only. */+ hierarchy?: Hierarchy;+}++/** Balanced and deterministic: the same scene yields the same tree on every run. */+function buildHierarchy(triangles: SurfaceTriangle[]): Hierarchy {+ const box = new THREE.Box3();+ for (const triangle of triangles) box.union(triangle.box);+ if (triangles.length <= 4) return { box, triangles };+ const size = box.getSize(new THREE.Vector3());+ const axis = size.x >= size.y && size.x >= size.z ? 'x' : size.y >= size.z ? 'y' : 'z';+ const center = (triangle: SurfaceTriangle) =>+ triangle.box.min[axis] / 2 + triangle.box.max[axis] / 2;+ // Sorting a copy keeps the caller's traversal order, and the source geometry, untouched.+ const sorted = [...triangles].sort((a, b) => center(a) - center(b));+ const middle = Math.floor(sorted.length / 2);+ return {+ box,+ children: [buildHierarchy(sorted.slice(0, middle)), buildHierarchy(sorted.slice(middle))],+ };+}++function worldTriangles(mesh: THREE.Mesh): SurfaceTriangle[] | null {+ const geometry = mesh.geometry;+ const position = geometry.getAttribute('position') as THREE.BufferAttribute | undefined;+ if (position?.itemSize !== 3) return null;+ const index = geometry.getIndex();+ const count = index ? index.count : position.count;+ if (count % 3 !== 0) return null;+ const triangles: SurfaceTriangle[] = [];+ const vertex = (at: number) => {+ const id = index ? index.getX(at) : at;+ if (!Number.isSafeInteger(id) || id < 0 || id >= position.count) return null;+ const point = new THREE.Vector3()+ .fromBufferAttribute(position, id)+ .applyMatrix4(mesh.matrixWorld);+ return [point.x, point.y, point.z].every(Number.isFinite) ? point : null;+ };+ for (let i = 0; i < count; i += 3) {+ const a = vertex(i),+ b = vertex(i + 1),+ c = vertex(i + 2);+ if (!a || !b || !c) return null;+ const triangle = new THREE.Triangle(a, b, c);+ triangles.push({ triangle, box: new THREE.Box3().setFromPoints([a, b, c]) });+ }+ return triangles.length ? triangles : null;+}++function triangleCount(geometry: THREE.BufferGeometry): number {+ const index = geometry.getIndex();+ const position = geometry.getAttribute('position');+ if (!position) return 0;+ return Math.floor((index ? index.count : position.count) / 3);+}++/**+ * Split the visible meshes into open surfaces and closed solids.+ *+ * `geometryDiagnostics` answers this from quantized edge topology alone, with no+ * boolean and no WASM, so the whole pass stays synchronous and a QA rule can+ * take the measurement itself.+ */+function collectParts(+ root: THREE.Object3D,+ skipped: OpenSurfacePenetrationEvidenceV1['skipped'],+): AnalyzedPart[] {+ const parts: AnalyzedPart[] = [];+ root.updateWorldMatrix(true, true);+ root.traverseVisible((node) => {+ const mesh = node as THREE.Mesh;+ if (!mesh.isMesh || !mesh.geometry) return;+ const name = mesh.name || '(unnamed mesh)';+ if (+ (mesh as THREE.InstancedMesh).isInstancedMesh ||+ (mesh as THREE.SkinnedMesh).isSkinnedMesh ||+ Object.values(mesh.geometry.morphAttributes).some((targets) => targets.length)+ ) {+ skipped.push({+ part: name,+ reason: 'instancing, skin or morph deformation is unsupported by surface sampling',+ });+ return;+ }+ const total = mesh.geometry.index?.count ?? mesh.geometry.getAttribute('position')?.count ?? 0;+ const range = mesh.geometry.drawRange;+ if (range.start !== 0 || range.count < total) {+ skipped.push({+ part: name,+ reason: 'partial triangle draw ranges are unsupported by surface sampling',+ });+ return;+ }+ const triangles = triangleCount(mesh.geometry);+ if (triangles === 0) return;+ if (triangles > MAX_SURFACE_TRIANGLES) {+ skipped.push({+ part: name,+ reason: `${triangles} triangles exceeds the ${MAX_SURFACE_TRIANGLES}-triangle analysis budget`,+ });+ return;+ }+ // Bounds belong to this mesh, never its child meshes (which are independent parts).+ mesh.geometry.computeBoundingBox();+ const box = mesh.geometry.boundingBox!.clone().applyMatrix4(mesh.matrixWorld);+ if (box.isEmpty()) return;+ const determinant = mesh.matrixWorld.determinant();+ if (![...box.min, ...box.max].every(Number.isFinite) || !Number.isFinite(determinant)) {+ skipped.push({ part: name, reason: 'non-finite transformed bounds cannot be measured' });+ return;+ }+ let diagnostics: ReturnType<typeof geometryDiagnostics>;+ try {+ diagnostics = geometryDiagnostics(mesh.geometry);+ } catch (error) {+ skipped.push({+ part: name,+ reason: `topology could not be analyzed (${error instanceof Error ? error.message : String(error)})`,+ });+ return;+ }+ // A watertight, orientable shell is a solid a ray can be counted against.+ // Anything else — a sheet, a card, a shell with a hole — is an open surface.+ const closed =+ diagnostics.solid.closed &&+ diagnostics.solid.manifold &&+ diagnostics.solid.orientation !== 'mixed';+ parts.push({ name, mesh, box, closed, lod: lodMembership(mesh) });+ });+ return parts;+}++function boxDistanceSquared(box: THREE.Box3, point: THREE.Vector3): number {+ const x = Math.max(box.min.x - point.x, 0, point.x - box.max.x);+ const y = Math.max(box.min.y - point.y, 0, point.y - box.max.y);+ const z = Math.max(box.min.z - point.z, 0, point.z - box.max.z);+ return x * x + y * y + z * z;+}++/** Shared box volume over the smaller box's volume, 0..1; 0 for flat boxes. */+function boxOverlapRatio(a: THREE.Box3, b: THREE.Box3): number {+ const extent = (box: THREE.Box3) =>+ (box.max.x - box.min.x) * (box.max.y - box.min.y) * (box.max.z - box.min.z);+ 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(extent(a), extent(b));+ return Number.isFinite(ratio) ? ratio : 0;+}++/** A work meter every query draws on, so one analysis has one bounded cost. */+class Budget {+ private used = 0;+ exhausted = false;+ constructor(private readonly limit: number) {}+ spend(): boolean {+ if (this.used >= this.limit) {+ this.exhausted = true;+ return false;+ }+ this.used++;+ return true;+ }+}++/** Nearest distance from `point` to the indexed surface; null when the budget runs out. */+function nearestDistance(root: Hierarchy, point: THREE.Vector3, budget: Budget): number | null {+ let best = Infinity;+ const stack: Hierarchy[] = [root];+ const scratch = new THREE.Vector3();+ while (stack.length) {+ const node = stack.pop()!;+ if (boxDistanceSquared(node.box, point) >= best) continue;+ if ('triangles' in node) {+ for (const { triangle } of node.triangles) {+ if (!budget.spend()) return null;+ const distance = point.distanceToSquared(triangle.closestPointToPoint(point, scratch));+ if (distance < best) best = distance;+ }+ } else stack.push(node.children[0], node.children[1]);+ }+ return Number.isFinite(best) ? Math.sqrt(best) : null;+}++/**+ * Three fixed directions, tried in order. A ray that grazes a triangle edge+ * cannot be counted, so an ambiguous direction is abandoned for the next rather+ * than guessed at; the set is fixed so the verdict never varies between runs.+ */+const PARITY_DIRECTIONS: readonly THREE.Vector3[] = Object.freeze([+ new THREE.Vector3(1, 0, 0),+ new THREE.Vector3(0.5773502691896258, 0.5773502691896258, 0.5773502691896258),+ new THREE.Vector3(-0.2672612419124244, 0.5345224838248488, 0.8017837257372732),+]);+/** Barycentric margin below which a hit sits on an edge and the count is unreliable. */+const PARITY_EPSILON = 1e-7;++/** Crossing parity along one direction: true inside, false outside, null ambiguous. */+function parity(+ root: Hierarchy,+ point: THREE.Vector3,+ direction: THREE.Vector3,+ budget: Budget,+): boolean | null {+ const ray = new THREE.Ray(point, direction);+ const stack: Hierarchy[] = [root];+ const hit = new THREE.Vector3();+ const barycentric = new THREE.Vector3();+ let crossings = 0;+ while (stack.length) {+ const node = stack.pop()!;+ if (!ray.intersectsBox(node.box)) continue;+ if ('triangles' in node) {+ for (const { triangle } of node.triangles) {+ if (!budget.spend()) return null;+ if (ray.intersectTriangle(triangle.a, triangle.b, triangle.c, false, hit) === null)+ continue;+ triangle.getBarycoord(hit, barycentric);+ if ([barycentric.x, barycentric.y, barycentric.z].some((v) => Math.abs(v) < PARITY_EPSILON))+ return null;+ crossings++;+ }+ } else stack.push(node.children[0], node.children[1]);+ }+ return crossings % 2 === 1;+}++function inside(root: Hierarchy, point: THREE.Vector3, budget: Budget): boolean | null {+ for (const direction of PARITY_DIRECTIONS) {+ const verdict = parity(root, point, direction, budget);+ if (verdict !== null) return verdict;+ if (budget.exhausted) return null;+ }+ return null;+}++/** Fixed precision so a report is byte-comparable across runs. */+const round = (value: number): number => Number(value.toPrecision(9));++/**+ * Measure how far every open surface reaches inside every closed solid it meets.+ *+ * Synchronous by construction: the open/closed split comes from edge topology+ * and the depth from triangle queries, so no WASM solid is built and the rule+ * takes its own measurement instead of waiting on a derived-evidence pre-pass.+ */+export function analyzeOpenSurfacePenetration(+ root: unknown,+ contactTolerance: number = OPEN_SURFACE_CONTACT_TOLERANCE,+): OpenSurfacePenetrationEvidenceV1 {+ const evidence: OpenSurfacePenetrationEvidenceV1 = {+ schemaVersion: 1,+ source: 'engine-scene-analysis',+ contactTolerance,+ openParts: 0,+ closedParts: 0,+ candidatePairs: 0,+ pairsTested: 0,+ pairsNotReached: 0,+ verticesUnresolved: 0,+ pairsLodAlternates: 0,+ truncated: false,+ skipped: [],+ penetrations: [],+ };+ if (!(root instanceof THREE.Object3D)) return evidence;+ const parts = collectParts(root, evidence.skipped);+ const open = parts.filter((part) => !part.closed);+ const closed = parts.filter((part) => part.closed);+ evidence.openParts = open.length;+ evidence.closedParts = closed.length;++ const candidates: {+ open: AnalyzedPart;+ solid: AnalyzedPart;+ overlap: number;+ order: number;+ }[] = [];+ let considered = 0;+ broadPhase: for (const surface of open) {+ for (const solid of closed) {+ if (considered++ === MAX_BROAD_PHASE_PAIRS) {+ evidence.broadPhaseTruncated = true;+ break broadPhase;+ }+ // Contact within the tolerance is not penetration, so only boxes that+ // already overlap can hold a vertex deeper than it.+ if (!surface.box.intersectsBox(solid.box)) continue;+ if (+ surface.lod &&+ solid.lod &&+ surface.lod.parent === solid.lod.parent &&+ surface.lod.stem === solid.lod.stem &&+ surface.lod.level !== solid.lod.level+ ) {+ evidence.pairsLodAlternates++;+ continue;+ }+ candidates.push({+ open: surface,+ solid,+ overlap: boxOverlapRatio(surface.box, solid.box),+ order: candidates.length,+ });+ }+ }+ evidence.candidatePairs = candidates.length;+ evidence.truncated = evidence.broadPhaseTruncated === true;+ if (!candidates.length) return evidence;++ // Deepest box overlap first: a surface buried in a solid's box is the likeliest+ // real penetration, a grazing contact the least. Equal overlaps keep collection+ // order through an explicit key rather than relying on the sort being stable.+ candidates.sort((x, y) => y.overlap - x.overlap || x.order - y.order);++ const budget = new Budget(MAX_WORK);+ const penetrations: OpenSurfacePenetrationPairV1[] = [];+ for (const candidate of candidates) {+ if (budget.exhausted) {+ evidence.pairsNotReached++;+ continue;+ }+ if (!candidate.solid.hierarchy) {+ const triangles = worldTriangles(candidate.solid.mesh);+ if (!triangles) {+ evidence.skipped.push({+ part: candidate.solid.name,+ reason: 'invalid or non-finite triangles cannot be indexed',+ });+ evidence.pairsNotReached++;+ continue;+ }+ candidate.solid.hierarchy = buildHierarchy(triangles);+ }+ const hierarchy = candidate.solid.hierarchy;+ const position = candidate.open.mesh.geometry.getAttribute('position') as+ | THREE.BufferAttribute+ | undefined;+ if (position?.itemSize !== 3) {+ evidence.skipped.push({+ part: candidate.open.name,+ reason: 'open surfaces are sampled at their vertices and this part has none',+ });+ continue;+ }+ const matrix = candidate.open.mesh.matrixWorld;+ const limit = Math.min(position.count, MAX_SAMPLED_VERTICES);+ const vertex = new THREE.Vector3();+ let depth = 0;+ let penetrating = 0;+ let tested = 0;+ let unresolved = 0;+ let partial = limit < position.count;+ for (let i = 0; i < limit; i++) {+ vertex.fromBufferAttribute(position, i).applyMatrix4(matrix);+ if (![vertex.x, vertex.y, vertex.z].every(Number.isFinite)) continue;+ // Outside the solid's own box, the nearest surface is at least a box+ // distance away, so a cheap reject stands in for the whole query.+ if (boxDistanceSquared(candidate.solid.box, vertex) > contactTolerance * contactTolerance) {+ tested++;+ continue;+ }+ const distance = nearestDistance(hierarchy, vertex, budget);+ if (distance === null) {+ partial = true;+ break;+ }+ tested++;+ // Depth before sign: within the tolerance this is contact either way, and+ // a parity ray starting on the surface it would count is ambiguous.+ if (distance <= contactTolerance) continue;+ const verdict = inside(hierarchy, vertex, budget);+ if (verdict === null) {+ if (budget.exhausted) {+ partial = true;+ break;+ }+ // No direction settled this vertex. That is a numeric limit, not work the+ // budget skipped, so it is counted on its own and claimed neither way.+ unresolved++;+ continue;+ }+ if (!verdict) continue;+ penetrating++;+ if (distance > depth) depth = distance;+ }+ evidence.verticesUnresolved += unresolved;+ if (partial) evidence.pairsNotReached++;+ else evidence.pairsTested++;+ if (penetrating > 0)+ penetrations.push({+ open: candidate.open.name,+ solid: candidate.solid.name,+ depth: round(depth),+ vertices: penetrating,+ tested,+ });+ }+ evidence.truncated = evidence.truncated || evidence.pairsNotReached > 0;+ // Deepest first, then by name so equal-depth pairs keep a stable order.+ penetrations.sort(+ (x, y) => y.depth - x.depth || `${x.open}:${x.solid}`.localeCompare(`${y.open}:${y.solid}`),+ );+ evidence.penetrations = penetrations;+ return evidence;+}++// -----------------------------------------------------------------------------+// The rule+// -----------------------------------------------------------------------------++/** Names listed per skipped reason; the count covers the rest. */+const NAMES_SHOWN = 5;++const namedParts = (parts: readonly string[]): string => {+ const named = parts.slice(0, NAMES_SHOWN).map((part) => JSON.stringify(part));+ const more = parts.length > NAMES_SHOWN ? ` and ${parts.length - NAMES_SHOWN} more` : '';+ return `${named.join(', ')}${more}`;+};++/** Shared observation kernel; the measurement is derived by the engine, never asset metadata. */+export function inspectOpenSurfacePenetration(+ evidence?: OpenSurfacePenetrationEvidenceV1,+): readonly QaFinding[] {+ if (evidence?.schemaVersion !== 1) return [];+ const findings: QaFinding[] = evidence.penetrations.map((pair) => ({+ code: 'GEO_OPEN_SURFACE_PENETRATION',+ disposition: 'observe' as const,+ dimension: 'visualQuality' as const,+ profile: 'geometry.openSurfacePenetration',+ message:+ `Open surface ${JSON.stringify(pair.open)} reaches ${pair.depth.toFixed(4)} m inside solid ${JSON.stringify(pair.solid)}: ` ++ `${pair.vertices} of ${pair.tested} sampled ${pair.vertices === 1 ? 'vertex lies' : 'vertices lie'} deeper inside it than the ${evidence.contactTolerance} m contact tolerance.`,+ affected: { node: pair.open },+ measurement: {+ name: 'openSurfacePenetrationDepth',+ actual: pair.depth,+ expected: evidence.contactTolerance,+ unit: 'm',+ breakdown: { penetratingVertices: pair.vertices, sampledVertices: pair.tested },+ },+ repairText:+ 'A positive here is not a defect. Most are intentional: a fitting set into a structural shell -- a lamp recess in a hull, a strut landing, a ridge into a cap -- puts shell vertices inside the solid by design, exactly as a bolt in a hole shares volume. Review the ones you did not intend, such as a cloth crossing a wall or a canopy pierced by a mast, and move the surface clear or cut it back to the solid. Vertices are the samples, so a solid thinner than this surface’s facet spacing can pass between two of them.',+ }));++ const unresolved = evidence.verticesUnresolved ?? 0;+ if (evidence.truncated || unresolved > 0) {+ const clauses: string[] = [];+ if (evidence.truncated)+ clauses.push(+ `Sampled ${evidence.pairsTested} of ${evidence.broadPhaseTruncated ? 'at least ' : ''}${evidence.candidatePairs} overlapping open-surface and solid pairs; ` ++ `${evidence.pairsNotReached} were beyond the ${MAX_WORK}-test analysis budget.` ++ (evidence.broadPhaseTruncated+ ? ` Pair discovery stopped after ${MAX_BROAD_PHASE_PAIRS} box comparisons.`+ : '') ++ ' Unsampled pairs were not examined; the most overlapping bounding boxes were sampled first.',+ );+ if (unresolved > 0)+ clauses.push(+ `${unresolved} ${unresolved === 1 ? 'vertex' : 'vertices'} further than the contact tolerance from a solid could not be resolved as inside or outside it, and ${unresolved === 1 ? 'is' : 'are'} counted as neither.`,+ );+ findings.push({+ code: 'GEO_OPEN_SURFACE_PENETRATION_TRUNCATED',+ disposition: 'observe' as const,+ dimension: 'visualQuality' as const,+ profile: 'geometry.openSurfacePenetration',+ message: clauses.join(' '),+ measurement: {+ name: 'openSurfacePairsSampled',+ actual: evidence.pairsTested,+ expected: evidence.candidatePairs,+ breakdown: {+ pairsNotReached: evidence.pairsNotReached,+ verticesUnresolved: unresolved,+ },+ },+ });+ }++ if (evidence.skipped.length) {+ // One line per reason: an asset with forty instanced parts needs the reason once.+ const byReason = new Map<string, string[]>();+ for (const { part, reason } of evidence.skipped) {+ const parts = byReason.get(reason);+ if (parts) parts.push(part);+ else byReason.set(reason, [part]);+ }+ const reasons = [...byReason].map(+ ([reason, parts]) => `${parts.length} because ${reason}: ${namedParts(parts)}.`,+ );+ const one = evidence.skipped.length === 1;+ findings.push({+ code: 'GEO_OPEN_SURFACE_PENETRATION_UNMEASURED',+ disposition: 'observe' as const,+ dimension: 'visualQuality' as const,+ profile: 'geometry.openSurfacePenetration',+ message:+ `${evidence.skipped.length} ${one ? 'part was' : 'parts were'} not sampled for open-surface penetration. ` ++ `${reasons.join(' ')} ${one ? 'This part is' : 'These parts are'} not certified clear of the solids around ${one ? 'it' : 'them'}.`,+ });+ }++ return findings;+}++/**+ * Report open surfaces that reach inside closed solids.+ *+ * `heuristic`, not `exact`, even though the depth is measured rather than+ * inferred: in this registry `exact` is a promotion contract that demands+ * `enforce` with frozen conformance evidence, and this rule has none yet.+ * Reclassify when a fixture set is frozen and promoted, never before.+ */+export const OPEN_SURFACE_PENETRATION_QA_RULE: QaRule = Object.freeze({+ id: 'GEO_OPEN_SURFACE_PENETRATION',+ profile: 'geometry.openSurfacePenetration',+ scope: { kind: 'universal' as const },+ ruleClass: 'heuristic',+ owner: KILN_ENGINE_QA_OWNER,+ defaultMode: 'observe',+ evaluate(context: QaContext): readonly QaFinding[] {+ return inspectOpenSurfacePenetration(analyzeOpenSurfacePenetration(context.scene));+ },+});diff --git a/src/qa/registry.test.ts b/src/qa/registry.test.tsindex 3e248b67..d2a2e042 100644--- a/src/qa/registry.test.ts+++ b/src/qa/registry.test.ts@@ -792,9 +792,10 @@ describe('QaRegistry', () => {test('publishes a stable auditable state and owner for every checked-in rule', () => {const decisions = DETERMINISTIC_QA_REGISTRY.describePolicy();// 27 -> 28 with the approved bounded sweep/loft observation, 28 -> 29 with the host- // validation profile (#208). The count means a rule can never join the deterministic- // registry without someone noticing.- expect(decisions).toHaveLength(29);+ // validation profile (#208), 29 -> 30 with the open-surface penetration observation+ // (#277). The count means a rule can never join the deterministic registry without+ // someone noticing.+ expect(decisions).toHaveLength(30);expect(decisions.filter((item) => item.ruleClass === 'exact')diff --git a/src/qa/requirements-applicability.test.ts b/src/qa/requirements-applicability.test.tsindex 1d1d732f..baaf2898 100644--- a/src/qa/requirements-applicability.test.ts+++ b/src/qa/requirements-applicability.test.ts@@ -5,11 +5,11 @@ import {REQUIREMENTS_RULE_MAP,resolveRequirementsApplicability,} from './requirements-applicability';-test('the migration map covers each of the 29 actual registered rules and preserves modes', () => {+test('the migration map covers each of the 30 actual registered rules and preserves modes', () => {const rules = DETERMINISTIC_QA_REGISTRY.list();- expect(rules).toHaveLength(29);- expect(REQUIREMENTS_RULE_MAP).toHaveLength(29);- expect(new Set(REQUIREMENTS_RULE_MAP.map((rule) => rule.id)).size).toBe(29);+ expect(rules).toHaveLength(30);+ expect(REQUIREMENTS_RULE_MAP).toHaveLength(30);+ expect(new Set(REQUIREMENTS_RULE_MAP.map((rule) => rule.id)).size).toBe(30);expect(REQUIREMENTS_RULE_MAP.map((rule) => [rule.id, rule.mode]).sort()).toEqual(rules.map((rule) => [rule.id, rule.defaultMode]).sort(),);@@ -21,7 +21,7 @@ test('labels never select a domain and empty requirements do not imply prop or g);expect(labeled).toEqual(neutral);expect(neutral.unevaluatedRequirements).toEqual([]);- expect(neutral.rules.filter((rule) => rule.status === 'evaluate')).toHaveLength(10);+ expect(neutral.rules.filter((rule) => rule.status === 'evaluate')).toHaveLength(11);expect(neutral.rules.find((rule) => rule.id === 'GEO_PART_SELF_INTERSECTION')).toMatchObject({mode: 'observe',status: 'evaluate',diff --git a/src/qa/requirements-applicability.ts b/src/qa/requirements-applicability.tsindex e49437a8..845e0037 100644--- a/src/qa/requirements-applicability.ts+++ b/src/qa/requirements-applicability.ts@@ -18,6 +18,7 @@ interface RuleMapping {| 'scope'| 'connectivity'| 'partVolume'+ | 'openSurface'| 'sweep'| 'rig'| 'validation';@@ -95,6 +96,13 @@ export const REQUIREMENTS_RULE_MAP: readonly RuleMapping[] = [observation: true,kernel: 'connectivity',},+ {+ id: 'GEO_OPEN_SURFACE_PENETRATION',+ mode: 'observe',+ keys: [],+ observation: true,+ kernel: 'openSurface',+ },{ id: 'REF_COMPARISON', mode: 'observe', keys: [], observation: true },{ id: 'SWEEP_SELF_INTERSECTION', mode: 'observe', keys: [], observation: true, kernel: 'sweep' },// Host-bound final-GLB profile (#208); evaluated by appendRequirementsFinalQa only.diff --git a/src/qa/requirements-placement.test.ts b/src/qa/requirements-placement.test.tsindex 69c92dda..2ce42ec2 100644--- a/src/qa/requirements-placement.test.ts+++ b/src/qa/requirements-placement.test.ts@@ -162,6 +162,7 @@ test('unrequested placement has no promotion decision; requested placement retaibyRule: {GEO_PART_CONNECTIVITY: 'observe' as const,GEO_PART_SELF_INTERSECTION: 'observe' as const,+ GEO_OPEN_SURFACE_PENETRATION: 'observe' as const,SWEEP_SELF_INTERSECTION: 'observe' as const,},};diff --git a/src/qa/requirements-run.ts b/src/qa/requirements-run.tsindex 5dd25332..9c309bb4 100644--- a/src/qa/requirements-run.ts+++ b/src/qa/requirements-run.ts@@ -25,6 +25,11 @@ import {PROP_ADVISORY_QA_RULE,} from './prop';import { inspectPartConnectivity, PART_CONNECTIVITY_QA_RULE } from './part-connectivity';+import {+ analyzeOpenSurfacePenetration,+ inspectOpenSurfacePenetration,+ OPEN_SURFACE_PENETRATION_QA_RULE,+} from './open-surface-penetration';import { inspectSweepGeometry, SWEEP_QA_RULE } from './sweep';import {analyzePartPenetration,@@ -66,6 +71,7 @@ const registry = new QaRegistry([PROP_ADVISORY_QA_RULE,PART_CONNECTIVITY_QA_RULE,SELF_INTERSECTION_QA_RULE,+ OPEN_SURFACE_PENETRATION_QA_RULE,SWEEP_QA_RULE,...VEHICLE_QA_RULES,...ARCHITECTURE_QA_RULES,@@ -256,6 +262,30 @@ export function runRequirementsSceneQa(}continue;}+ if (decision.ruleId === OPEN_SURFACE_PENETRATION_QA_RULE.id) {+ if (!(scene instanceof Object3D)) continue;+ // Open surfaces enclose no volume, so the boolean pass cannot measure them.+ // This one samples their vertices against the solids they meet (#277).+ const surfaces = analyzeOpenSurfacePenetration(scene);+ executedRules.push(decision.ruleId);+ findings.push(...inspectOpenSurfacePenetration(surfaces));+ Object.assign(geometryMetrics, {+ openSurfaceCoverage:+ surfaces.truncated || surfaces.skipped.length > 0 ? 'partial' : 'complete-surface-pairs',+ openSurfaceScope:+ "Visible static open surfaces sampled at their vertices against visible static closed solids, except alternates on different LOD levels; excludes open-vs-open pairs, motion, and any solid thinner than the sampled surface's facet spacing. Penetration within the contact tolerance is treated as intended contact, and penetration beyond it may still be intentional, as a fitting socketed into a shell is.",+ openSurfaceContactTolerance: surfaces.contactTolerance,+ openSurfaceOpenParts: surfaces.openParts,+ openSurfaceClosedParts: surfaces.closedParts,+ openSurfaceCandidatePairs: surfaces.candidatePairs,+ openSurfacePairsSampled: surfaces.pairsTested,+ openSurfacePairsNotReached: surfaces.pairsNotReached,+ openSurfaceVerticesUnresolved: surfaces.verticesUnresolved,+ openSurfaceLodAlternatePairs: surfaces.pairsLodAlternates,+ openSurfaceSkipped: surfaces.skipped.length,+ });+ continue;+ }if (decision.ruleId === ASSET_SCOPE_QA_RULE.id && !scopeObservation) continue;// Only the final GLB shows the destination's primitives; appendRequirementsFinalQa runs it.if (decision.ruleId === HOST_VALIDATION_QA_RULE.id) continue;diff --git a/src/qa/run.ts b/src/qa/run.tsindex 8a0ab26c..61eb86f7 100644--- a/src/qa/run.ts+++ b/src/qa/run.ts@@ -14,6 +14,7 @@ import {type ReferenceComparisonEvidenceV1,} from './reference-comparison';import { SELF_INTERSECTION_QA_RULE } from './self-intersection';+import { OPEN_SURFACE_PENETRATION_QA_RULE } from './open-surface-penetration';import { SWEEP_QA_RULE } from './sweep';import { ENVIRONMENT_QA_RULES } from './environment';import { W7_BREADTH_QA_RULES } from './breadth';@@ -44,6 +45,7 @@ export const DETERMINISTIC_QA_REGISTRY = new QaRegistry([...ENVIRONMENT_QA_RULES,...W7_BREADTH_QA_RULES,SELF_INTERSECTION_QA_RULE,+ OPEN_SURFACE_PENETRATION_QA_RULE,SWEEP_QA_RULE,PART_CONNECTIVITY_QA_RULE,REFERENCE_COMPARISON_QA_RULE,