3D engine that AI agents drive
Add bounded BVH contact and closed-solid queries
Nguyen Xuan An9151d545557b
diff --git a/.gitignore b/.gitignoreindex 1df87459..31603e70 100644--- a/.gitignore+++ b/.gitignore@@ -14,6 +14,8 @@ public/physics.mdpublic/export-glb.mdpublic/sculpt.mdpublic/surface.md+public/mesh-query.md+public/primitives.mdartifacts/.env.env.*diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 80702479..6f86d786 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,8 @@## Unreleased+- Add owned, bounded BVH mesh queries for static surface contact, ray hits and validated closed-solid containment.+- Close primitive seams exactly in Float32 and validate detail counts before geometry allocation.- Add retained scene hierarchy, pivots and atomic reparenting with world pose preservation.- Add bounded lathe, extrusion with holes and bevels, and curve tube modeling through an optional addon.- Add a lantern modeling study with textured materials, orbit controls and PNG capture.diff --git a/README.md b/README.mdindex b10b0181..94f6caed 100644--- a/README.md+++ b/README.md@@ -173,6 +173,11 @@ The source [GLB exporter](docs/export-glb.md) preserves opaque vertex colors, UVSource-only [sculpt brushes](docs/sculpt.md) apply bounded inflation, directional displacement and neighborhood smoothing through serializable strokes.The [surface patch addon](docs/surface.md) clips a badge onto a curved mesh with geometric clearance and follows its retained rigid transform.++Source-only [mesh queries](docs/mesh-query.md) use owned BVH indices to detect boundary contact, ray hits and containment between validated closed solids.+Surface contact does not measure penetration depth or diagnose z-fighting. Queries accept static geometry and explicit affine transforms.+The [primitive contract](docs/primitives.md) defines bounded subdivision counts and exact seam closure for mesh validation.+The trailer's rigid actor joints now use authored clips, with attached headwear and hands moving together.The [optional asset addon](docs/gltf.md) loads glTF/GLB meshes, base-color textures, opaque vertex colors and rigid node animation.diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.mdindex f57ea6bf..90b9f306 100644--- a/THIRD-PARTY-NOTICES.md+++ b/THIRD-PARTY-NOTICES.md@@ -20,6 +20,30 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INTHE SOFTWARE.+## three-mesh-bvh 0.9.16 (optional mesh query addon)++MIT License++Copyright (c) 2018 Garrett Johnson++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+THE SOFTWARE.+## highlight.js 11.12.0 (website syntax highlighting)BSD 3-Clause Licensediff --git a/docs/mesh-query.md b/docs/mesh-query.mdnew file mode 100644index 00000000..34724d8b--- /dev/null+++ b/docs/mesh-query.md@@ -0,0 +1,158 @@+# Static mesh queries++Use mesh queries to find contacts between triangle surfaces or containment between validated closed solids.+These CPU queries accept static geometry and explicit affine matrices.+They do not measure penetration depth, correct collisions, or diagnose depth-buffer artifacts.++```js+import { createMeshQueryIndex, createMeshPairQuery } from '67js/addons/mesh-query';++const outer = createMeshQueryIndex(outerGeometry, { solid: true });+const inner = createMeshQueryIndex(innerGeometry, { solid: true });+const query = createMeshPairQuery(outer, inner, { mode: 'closed-solids' });+const result = query.evaluate(outerMatrix, innerMatrix);+const hit = inner.raycast(innerMatrix, {+ origin: [0, 0, 4],+ direction: [0, 0, -1],+ maxDistance: 10,+});++outer.dispose();+inner.dispose();+```++## Owned geometry and budgets++`createMeshQueryIndex(geometry, options)` copies `geometry.positions` and `geometry.indices` once.+Positions must use nonempty `Float32Array` XYZ triples.+Indices must use nonempty `Uint32Array` triangle triples.+All positions must remain finite, and every index must reference an existing vertex.+UVs, colors, normals, and materials do not affect the queries.++The constructor rejects skin attributes and morph targets.+The caller must provide geometry that matches the visible static surface.+Shader displacement and procedural materials can change that surface without changing its triangle buffers.+Build another index after any geometry edit.+Source edits after construction do not change the copied query surface.++| Option | Default | Accepted range |+| --- | --- | --- |+| `maxVertices` | 250000 | Integer from 1 through 1000000 |+| `maxTriangles` | 250000 | Integer from 1 through 1000000 |+| `memoryBudgetMiB` | 64 | Number greater than 0 through 1024 |+| `solid` | false | Boolean |+| `maxValidationPairs` | 2000000 | Integer from 1 through 100000000 |++The constructor checks counts, triangle quality, and an allocation estimate before creating the copied buffers and BVH.+The estimate reserves 24 bytes per vertex and 128 bytes per triangle for surface indices.+Solid validation reserves 152 bytes per vertex and 512 bytes per triangle.+JavaScript object overhead and temporary library allocations vary between runtimes.+`memoryBudgetMiB` limits this estimate, not the total process memory.++`index.info` contains frozen `vertexCount`, `triangleCount`, and `estimatedBytes` fields.+`index.memoryPlan` also contains `reservedBytes`, `memoryBudgetMiB`, and `validationPairs`.+Neither field exposes geometry buffers or library objects.+`dispose()` releases the owned geometry and BVH references.+Repeated disposal succeeds, but subsequent queries throw.++## Surface and solid results++`createMeshPairQuery(indexA, indexB, options)` accepts `mode` and `maxTriangleTests`.+The default mode is `surfaces`.+The triangle budget defaults to 2000000 and accepts integers from 1 through 100000000.+Each evaluation returns a fresh serializable object.++| `kind` | `solidRelation` | Meaning |+| --- | --- | --- |+| `surface-intersection` | `not-tested` | Surface mode found touching, crossing, or coplanar triangles |+| `surface-disjoint` | `not-tested` | Surface mode found no boundary contact |+| `surface-intersection` | `boundaries-intersect` | Closed-solid mode found boundary contact |+| `contained` | `a-in-b` | Solid A lies inside solid B without boundary contact |+| `contained` | `b-in-a` | Solid B lies inside solid A without boundary contact |+| `separate` | `outside` | Closed-solid mode found neither contact nor containment |++`triangles` contains the first contacting pair of original triangle indices, or `null`.+`triangleTests` counts actual triangle callbacks, including containment rays.+`rayAttempts` counts containment ray directions, including rejected grazing directions.+The traversal order determines the first pair, so the result does not identify every contact.+Exhausting a budget throws instead of returning a disjoint result.+Errors leave the index usable for another evaluation.++Surface contact alone does not establish volume penetration.+Two closed solids can touch at a face, edge, or vertex without overlapping interiors.+Two surfaces can remain disjoint while one closed solid contains another.+Depth-buffer fighting also depends on the camera, projection, and renderer precision.++## Closed-solid validation++Both indices must use `solid: true` for `closed-solids` queries.+Validation welds exactly equal position triples, including duplicates at UV seams.+It does not merge approximately equal positions.+Every welded edge must have two oppositely directed faces.+The boundary must remain connected, and each vertex link must form one cycle.+This contract accepts one boundary component, including a torus, but rejects separate shells and cavity boundaries.++A BVH self-cast checks actual candidate triangle pairs within `maxValidationPairs`.+Adjacent triangles can meet along their shared edge or vertex.+Overlapping adjacent faces and intersections beyond those shared features cause an error.+Open boundaries, duplicate faces, disconnected shells, and self-crossing surfaces also cause an error.++After excluding boundary contact, the query tests a boundary vertex from each solid against the other solid.+It tries six fixed ray directions and requires two unambiguous directions to agree.+Hits near triangle edges, vertices, or the ray origin cause a retry.+Coplanar grazing also causes a retry.+Conflicting witnesses or exhausted retries throw an indeterminate-containment error.+The query never counts raw duplicate edge hits as reliable parity evidence.++## Matrices and numerical limits++Each query matrix must contain 16 finite, Float32-representable components in column-major order.+The query rounds those components to Float32 before evaluation.+The last row must equal `[0, 0, 0, 1]`, and the matrix must remain nonsingular.+Reflections, nonuniform scales, rotations, and shear are supported.+Each evaluation uses only the supplied matrices, so arbitrary forward and backward animation seeks give the same result.++The index normalizes its copied positions into a private Double-precision frame.+Matrix inversion and relative transforms also use Double precision.+Original triangle indices remain unchanged through an indirect BVH.+This permits very small and very large finite source meshes without Float32 cross-product overflow.++Triangles must have a normalized minimum altitude greater than `1e-8`.+Pair evaluation requires each relative mesh extent to stay within `1e6` normalized units.+Its transformed minimum altitude must remain greater than `1e-8` in the other normalized frame.+World bounds must remain finite in Float32, and triangle altitudes must exceed a conservative world precision margin.+The margin uses an inverse-matrix norm and approximately four Float32 units at the largest world coordinate.+Large translations can therefore reject a small mesh even when every individual input remains finite.++Intersection and ambiguity tests use numerical tolerances rather than exact arithmetic predicates.+The ambiguity tolerance is `1e-9` in the normalized frame.+The API rejects unsupported precision domains instead of promising reliable results for arbitrarily thin or collapsed geometry.++## Rays++`index.raycast(matrix, { origin, direction, maxDistance })` accepts world-space origin and direction triples.+Their components must remain finite and representable in Float32.+The direction must remain nonzero after Float32 rounding.+`maxDistance` defaults to infinity and must remain nonnegative.+The normalized local ray origin must remain within `1e6` units.++A miss returns `null`.+A hit returns `{ point, distance, triangle, barycentric }`.+`point` and `distance` use world coordinates.+`triangle` identifies the original triangle, and `barycentric` follows its three original index entries.+Rays test both triangle sides.+Ray hits can land on edges, so a single public ray hit does not establish solid containment.++## Design choice and references++Two designs were considered: explicit owned indices with matrix arguments, and an implicit scene cache borrowing mutable geometry buffers.+The explicit design gives the caller control over rebuilds, disposal, budgets, and animation evaluation.+It avoids hidden invalidation rules and prevents source edits from changing a query midway through evaluation.+Fresh results also avoid partially updated output objects after validation fails.++The implementation reuses maintained triangle intersection, BVH traversal, and ray methods from [three-mesh-bvh 0.9.16](https://github.com/gkjohnson/three-mesh-bvh/releases/tag/v0.9.16).+The library documents local coordinate frames, indirect indices, and query methods in its [API reference](https://github.com/gkjohnson/three-mesh-bvh/blob/v0.9.16/API.md).+It does not supply the closed-manifold validation and containment contract described here.+Those checks remain part of this module.++These APIs are available in the current source build. The published npm version can lag behind it.diff --git a/docs/primitives.md b/docs/primitives.mdnew file mode 100644index 00000000..0b34704b--- /dev/null+++ b/docs/primitives.md@@ -0,0 +1,41 @@+# Primitive shape and resource bounds++These constructor guards and exact closed seams are available in the current source, after published version 0.3.3.++```js+import { box, sphere, cylinder, torus } from '@codepawlhq/67js';++const shell = box(0.15, 7);+const eye = sphere(64, 40);+const wheel = cylinder(80, 0.025, 6);+const rim = torus(0.045, 96, 24);+```++All generators return local Float32 positions and unit normals with Uint32 triangle indices. Use part matrices to position and scale instances.++| Constructor | Shape | Input bounds |+| --- | --- | --- |+| `box(bevel = 0.08, subdivisions = 6)` | Cube with each axis from -0.5 to 0.5. | Bevel from 0 to 0.5. Subdivisions from 1 to 128. |+| `sphere(segments = 64, rings = 40)` | Unit-radius sphere. | Segments from 3 to 2048. Rings from 2 to 2048. |+| `cylinder(segments = 80, bevel = 0.025, bevelSegments = 6)` | Y-axis cylinder with radius 1 and height 1. | Segments from 3 to 2048. Bevel from 0 to 0.5. Bevel segments from 1 to 128. |+| `torus(tubeRadius = 0.08, segments = 96, sides = 24, arc = 2π, start = 0)` | XY torus with major radius 1. Partial arcs have end caps. | Positive tube radius. Segments from 3 to 2048. Sides from 3 to 128. Arc within (0, 2π]. Start uses radians. |++Counts must be integers. Numeric parameters must remain finite in Float32. Positive tube radius and arc cannot underflow to zero. Positive bevel values also reject Float32 underflow.++Each constructor checks its vertex reservation before sampling, with a fixed limit of one million vertices. This prevents uncontrolled loops and allocations from malformed detail counts. Temporary JavaScript arrays, indices and renderer allocations require additional memory. The limit does not guarantee a total browser memory ceiling.++## Closed seams++Full turns sample their final position at the same angle as the first position. Sphere poles have exactly zero radial coordinates. This removes tiny trigonometric gaps at duplicated seam vertices while retaining separate UV coordinates.++Exact Float32 position welding finds paired, oppositely oriented edges on the tested sphere, torus, cylinder and rounded-box fixtures. The legacy rounded-coordinate topology check remains covered separately.++The seam fix changes 884 position or normal components in the WALL·E fixture by at most `2.56e-16`. Triangle indices and instance matrices remain unchanged. Native GPU images at 960 × 540 and 540 × 960 have identical pixels before and after the change.++`scripts/smoke-primitive-seams.mjs` rebuilds its baseline from Git commit `61a0102` and requires that commit in local history. Its images and measurements go to `artifacts/`.++## Geometry limits++High sampling density cannot recover details smaller than local Float32 precision. Keep geometry near its origin and apply world placement through matrices.++Primitive construction does not perform Boolean operations, sculpting, collision resolution or general manifold certification. Large torus tube radii can create self-intersections. Thin partial arcs or extreme proportions need validation before use as solids.diff --git a/package-lock.json b/package-lock.jsonindex 5dfd4739..1fd6a028 100644--- a/package-lock.json+++ b/package-lock.json@@ -17,6 +17,7 @@"react": "19.3.0","react-dom": "19.3.0","three": "0.186.1",+ "three-mesh-bvh": "0.9.16","vite": "8.3.4","wrangler": "4.149.0"},@@ -2726,6 +2727,16 @@"dev": true,"license": "MIT"},+ "node_modules/three-mesh-bvh": {+ "version": "0.9.16",+ "resolved": "https://registry.npmjs.org/three-mesh-bvh/-/three-mesh-bvh-0.9.16.tgz",+ "integrity": "sha512-2RK+5MJOaiHJhopURn2CUkOHiF3tFloD0uZBfhebV0CKB7mgVLpWUWaDpOyhNJRDkKKe7x4rRfTHZ32GwpXdkw==",+ "dev": true,+ "license": "MIT",+ "peerDependencies": {+ "three": ">= 0.159.0"+ }+ },"node_modules/tinyglobby": {"version": "0.2.17","resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",diff --git a/package.json b/package.jsonindex b2e07c88..d62d0500 100644--- a/package.json+++ b/package.json@@ -37,7 +37,9 @@"docs/gltf-morph.md","docs/export-glb.md","docs/sculpt.md",- "docs/surface.md"+ "docs/surface.md",+ "docs/mesh-query.md",+ "docs/primitives.md"],"main": "./build/67.module.js","module": "./build/67.module.js",@@ -52,6 +54,7 @@"./addons/modeling": "./build/modeling.js","./addons/sculpt": "./build/sculpt.js","./addons/surface": "./build/surface.js",+ "./addons/mesh-query": "./build/mesh-query.js","./addons/physics": "./build/physics.js","./package.json": "./package.json"},@@ -92,6 +95,7 @@"react": "19.3.0","react-dom": "19.3.0","three": "0.186.1",+ "three-mesh-bvh": "0.9.16","vite": "8.3.4","wrangler": "4.149.0"}diff --git a/public/llms.txt b/public/llms.txtindex b03bb187..14e228ea 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -89,6 +89,12 @@ Source-only `addons/surface` creates projector-clipped curved patches. Read `docShare the target's retained matrix to follow rigid motion. Skin, morph, assembly and procedural targets reject rather than returning stale patches.Surface clearance prevents overlapping layers in this workflow. It does not detect general mesh penetration or provide whole-object shrinkwrap.+Source-only `addons/mesh-query` owns copied static geometry in disposable BVH indices. Read `docs/mesh-query.md` before querying.+Use `solid: true` indices and `mode: 'closed-solids'` to distinguish boundary contact, containment and separation.+Surface contact does not prove volume penetration or identify z-fighting. Never substitute surface-only results for containment.+Pass current affine matrices explicitly, rebuild after geometry edits, and preserve budget/precision errors instead of treating them as misses.+Read `docs/primitives.md` for subdivision bounds and exact seam closure. Skin, morph and shader-deformed surfaces require geometry matching the visible pose.+GLB support excludes transparent and double-sided materials and compressed geometry. Unsupported features require visible errors.The optional GLB decoder uses Three.js GLTFLoader. The renderer remains 67.js.diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjsindex 6e5607ca..95b84054 100644--- a/scripts/prepare-release.mjs+++ b/scripts/prepare-release.mjs@@ -35,7 +35,7 @@ await copyFile(resolve(root, 'build-browser/67.module.js'), resolve(releases, meawait copyFile(resolve(root, 'CHANGELOG.md'), resolve(root, 'public/changelog.md'));await copyFile(resolve(root, 'docs/guide.md'), resolve(root, 'public/guide.md'));await copyFile(resolve(root, 'docs/gltf.md'), resolve(root, 'public/gltf.md'));-for (const name of ['gltf-morph.md', 'morph-targets.md', 'skinning.md', 'physics.md', 'export-glb.md', 'sculpt.md', 'surface.md']) {+for (const name of ['gltf-morph.md', 'morph-targets.md', 'skinning.md', 'physics.md', 'export-glb.md', 'sculpt.md', 'surface.md', 'mesh-query.md', 'primitives.md']) {await copyFile(resolve(root, 'docs', name), resolve(root, 'public', name));}diff --git a/scripts/smoke-mesh-query.mjs b/scripts/smoke-mesh-query.mjsnew file mode 100644index 00000000..4e6e7f56--- /dev/null+++ b/scripts/smoke-mesh-query.mjs@@ -0,0 +1,105 @@+import assert from 'node:assert/strict';+import { mkdir, writeFile } from 'node:fs/promises';+import { constants, setPriority } from 'node:os';+import { chromium } from 'playwright';++setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+await mkdir('artifacts', { recursive: true });+const width = Number(process.argv[2] ?? 960);+const height = Number(process.argv[3] ?? 540);+const browser = await chromium.launch({+ executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe',+ headless: true,+ args: ['--enable-webgl', '--ignore-gpu-blocklist'],+});+try {+ const page = await browser.newPage({ viewport: { width, height } });+ const errors = [];+ page.on('pageerror', error => errors.push(error.message));+ await page.route('**/mesh-query-smoke.html', route => route.fulfill({+ contentType: 'text/html', body: `<canvas style="width:${width}px;height:${height}px;display:block"></canvas>`,+ }));+ await page.goto('http://127.0.0.1:5173/mesh-query-smoke.html');+ const report = await page.evaluate(async () => {+ const { Renderer67, box, cylinder, createAnimationClip, createAnimationPlayer, fitPerspectiveDistance } = await import('/build/67.module.js');+ const { createMeshQueryIndex, createMeshPairQuery } = await import('/build/mesh-query.js');+ const identity = () => new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);+ const geometry = box(0);+ const firstIndex = createMeshQueryIndex(geometry, { solid: true });+ const secondIndex = createMeshQueryIndex(geometry, { solid: true });+ const query = createMeshPairQuery(firstIndex, secondIndex, { mode: 'closed-solids' });+ const outerMatrix = identity();+ outerMatrix[0] = outerMatrix[5] = outerMatrix[10] = 4;+ const inner = { name: 'Inner', geometry, matrix: identity(), material: { color: [0.03, 0.5, 0.28], metallic: 0.15, roughness: 0.3, emission: 0 }, castShadow: false };+ const retainedMatrix = inner.matrix;+ const parts = [inner];+ const beam = cylinder(12, 0, 1);+ for (let axis = 0; axis < 3; axis++) {+ for (const firstSide of [-2, 2]) {+ for (const secondSide of [-2, 2]) {+ const matrix = identity();+ const radius = 0.035;+ if (axis === 0) matrix.set([0, -radius, 0, 0, 4, 0, 0, 0, 0, 0, radius, 0, 0, firstSide, secondSide, 1]);+ if (axis === 1) matrix.set([radius, 0, 0, 0, 0, 4, 0, 0, 0, 0, radius, 0, firstSide, 0, secondSide, 1]);+ if (axis === 2) matrix.set([radius, 0, 0, 0, 0, 0, 4, 0, 0, -radius, 0, 0, firstSide, secondSide, 0, 1]);+ parts.push({ name: `Boundary ${axis} ${firstSide} ${secondSide}`, geometry: beam, matrix,+ material: { color: [0.06, 0.15, 0.23], metallic: 0.3, roughness: 0.35, emission: 0 }, castShadow: false });+ }+ }+ }+ const player = createAnimationPlayer(createAnimationClip({ duration: 2, tracks: [{+ target: 'Inner', property: 'translation', keyframes: [+ { time: 0, value: [0, 0, 0] }, { time: 1, value: [2, 0, 0] }, { time: 2, value: [4.5, 0, 0] },+ ],+ }] }), parts);+ const canvas = document.querySelector('canvas');+ const camera = { eye: [7, 5, 10], target: [1.25, 0, 0], fov: 44 };+ const fitted = fitPerspectiveDistance({ minimum: [-2.1, -2.1, -2.1], maximum: [5.1, 2.1, 2.1] }, camera, canvas.clientWidth / canvas.clientHeight);+ const originalDistance = Math.hypot(...camera.eye.map((value, axis) => value - camera.target[axis]));+ camera.eye = camera.eye.map((value, axis) => camera.target[axis] + (value - camera.target[axis]) * fitted / originalDistance);+ const renderer = new Renderer67(canvas, parts, {+ world: true, ground: false, samples: 2, pixelRatio: 1, hdr: true, memoryBudgetMiB: 96,+ environment: { keyIntensity: 0.8, fillIntensity: 0.5, ambientIntensity: 0.4 },+ });+ function draw(time) {+ player.apply(time);+ const result = query.evaluate(outerMatrix, inner.matrix);+ inner.material.color = time === 0 ? [0.03, 0.5, 0.28] : time === 1 ? [1, 0.3, 0.02] : [0.13, 0.3, 0.85];+ renderer.updateParts(parts);+ renderer.render({ ...camera, time: 0, effects: { grain: 0, bloom: { strength: 0 } } });+ const context = renderer.context;+ const pixels = new Uint8Array(canvas.width * canvas.height * 4);+ context.readPixels(0, 0, canvas.width, canvas.height, context.RGBA, context.UNSIGNED_BYTE, pixels);+ return { time, result, pixels, image: canvas.toDataURL('image/png'), glError: context.getError() };+ }+ const results = [draw(0), draw(1), draw(2)];+ const reverse = draw(0);+ const replayExact = results[0].pixels.every((value, index) => value === reverse.pixels[index]);+ const rayHit = firstIndex.raycast(outerMatrix, { origin: [0.2, 0.3, 6], direction: [0, 0, -1], maxDistance: 10 });+ const context = renderer.context;+ const info = context.getExtension('WEBGL_debug_renderer_info');+ const gpu = info ? context.getParameter(info.UNMASKED_RENDERER_WEBGL) : 'unavailable';+ renderer.dispose();+ firstIndex.dispose();+ secondIndex.dispose();+ return { results: results.map(({ pixels, ...result }) => result), replayExact,+ retainedMatrix: inner.matrix === retainedMatrix, rayHit, gpu, reverseGlError: reverse.glError };+ });+ for (const result of report.results) {+ await writeFile(`artifacts/mesh-query-${result.time}-${width}x${height}.png`, Buffer.from(result.image.split(',')[1], 'base64'));+ delete result.image;+ assert.equal(result.glError, 0);+ }+ await writeFile(`artifacts/mesh-query-${width}x${height}.json`, JSON.stringify(report, null, 2));+ console.log(JSON.stringify(report, null, 2));+ assert.deepEqual(errors, []);+ assert.equal(report.replayExact, true);+ assert.equal(report.retainedMatrix, true);+ assert.equal(report.reverseGlError, 0);+ assert.equal(report.results[0].result.kind, 'contained');+ assert.equal(report.results[1].result.kind, 'surface-intersection');+ assert.equal(report.results[2].result.kind, 'separate');+ assert.ok(Math.abs(report.rayHit.distance - 4) < 1e-6);+} finally {+ await browser.close();+}diff --git a/scripts/smoke-package.mjs b/scripts/smoke-package.mjsindex 02a5a314..271d39ab 100644--- a/scripts/smoke-package.mjs+++ b/scripts/smoke-package.mjs@@ -39,6 +39,7 @@ import { createCanvas2D } from '67js/addons/canvas2d';import { parseGltf } from '67js/addons/gltf';import { sculptGeometry } from '67js/addons/sculpt';import { createSurfacePatch } from '67js/addons/surface';+import { createMeshQueryIndex, createMeshPairQuery } from '67js/addons/mesh-query';import { createPhysicsScene, planPhysicsScene } from '67js/addons/physics';assert.equal(VERSION, '${metadata.version}');assert.equal(typeof Renderer67, 'function');@@ -73,6 +74,20 @@ assert.notDeepEqual(sculptOutput.positions, sculptSource.positions);const packedPatch = createSurfacePatch({ geometry: sculptSource }, { position: [0, 0, 0.5], size: [0.3, 0.3, 0.1] });assert.ok(packedPatch.indices.length > 0);assert.ok(packedPatch.positions.some((value, index) => index % 3 === 2 && value > 0.5));+const queryGeometry = box(0);+const solidIndex = createMeshQueryIndex(queryGeometry, { solid: true });+const queryMatrix = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);+const outerMatrix = queryMatrix.slice();+outerMatrix[0] = outerMatrix[5] = outerMatrix[10] = 4;+const solidQuery = createMeshPairQuery(solidIndex, solidIndex, { mode: 'closed-solids' });+assert.equal(solidQuery.evaluate(outerMatrix, queryMatrix).solidRelation, 'b-in-a');+queryMatrix[12] = 2;+assert.equal(solidQuery.evaluate(outerMatrix, queryMatrix).kind, 'surface-intersection');+queryMatrix[12] = 4;+assert.equal(solidQuery.evaluate(outerMatrix, queryMatrix).kind, 'separate');+const queryHit = solidIndex.raycast(outerMatrix, { origin: [0.2, 0.3, 6], direction: [0, 0, -1] });+assert.ok(Math.abs(queryHit.distance - 4) < 1e-6);+solidIndex.dispose();const parts = createModel();assert.equal(parts.length, 574);assert.ok(parts.every(part => assemblyOffset(part, 1).some(value => value !== 0)));diff --git a/scripts/smoke-primitive-seams.mjs b/scripts/smoke-primitive-seams.mjsnew file mode 100644index 00000000..396d6eb9--- /dev/null+++ b/scripts/smoke-primitive-seams.mjs@@ -0,0 +1,104 @@+import assert from 'node:assert/strict';+import { mkdir, writeFile } from 'node:fs/promises';+import { constants, setPriority } from 'node:os';+import { spawnSync } from 'node:child_process';+import { chromium } from 'playwright';++setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+await mkdir('artifacts', { recursive: true });+const baselineCommit = '61a01023c753b6c58cade24cb9c8c0b32e249f62';+function baselineSource(path) {+ const result = spawnSync('git', ['show', `${baselineCommit}:${path}`], { windowsHide: true, encoding: 'utf8' });+ assert.equal(result.status, 0, `Baseline history is required for this comparison: ${result.stderr}`);+ return result.stdout;+}+await writeFile('artifacts/geometry-before-mesh-query.mjs', baselineSource('src/geometry.js'));+await writeFile('artifacts/model-before-mesh-query.mjs', baselineSource('src/model.js')+ .replace("'./geometry.js'", "'./geometry-before-mesh-query.mjs'")+ .replace("'./assembly.js'", "'/src/assembly.js'"));+const width = Number(process.argv[2] ?? 960);+const height = Number(process.argv[3] ?? 540);+const browser = await chromium.launch({+ executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe', headless: true,+ args: ['--enable-webgl', '--ignore-gpu-blocklist'],+});+try {+ const page = await browser.newPage({ viewport: { width, height } });+ const errors = [];+ page.on('pageerror', error => errors.push(error.message));+ await page.route('**/primitive-seams-smoke.html', route => route.fulfill({+ contentType: 'text/html', body: `<canvas style="width:${width}px;height:${height}px;display:block"></canvas>`,+ }));+ await page.goto('http://127.0.0.1:5173/primitive-seams-smoke.html');+ const report = await page.evaluate(async () => {+ const { Renderer67, fitPerspectiveDistance } = await import('/src/index.js');+ const { createModel } = await import('/src/model.js');+ const { createModel: createBefore } = await import('/artifacts/model-before-mesh-query.mjs');+ const before = createBefore();+ const after = createModel();+ let maximumGeometryDifference = 0;+ let changedGeometryComponents = 0;+ let indicesUnchanged = true;+ const oldMeshes = [...new Set(before.map(part => part.geometry))];+ const newMeshes = [...new Set(after.map(part => part.geometry))];+ for (let index = 0; index < oldMeshes.length; index++) {+ for (const field of ['positions', 'normals']) {+ oldMeshes[index][field].forEach((value, offset) => {+ const difference = Math.abs(value - newMeshes[index][field][offset]);+ maximumGeometryDifference = Math.max(maximumGeometryDifference, difference);+ if (difference > 0) changedGeometryComponents++;+ });+ }+ indicesUnchanged &&= oldMeshes[index].indices.every((value, offset) => value === newMeshes[index].indices[offset]);+ }+ const canvas = document.querySelector('canvas');+ const camera = { eye: [4, 3, 6], target: [0, 1.45, 0], fov: 35 };+ if (canvas.clientWidth < canvas.clientHeight) {+ const distance = fitPerspectiveDistance({ minimum: [-1.4, 0, -1], maximum: [1.4, 3, 1] }, camera, canvas.clientWidth / canvas.clientHeight);+ const original = Math.hypot(...camera.eye.map((value, axis) => value - camera.target[axis]));+ camera.eye = camera.eye.map((value, axis) => camera.target[axis] + (value - camera.target[axis]) * distance / original);+ }+ function draw(parts) {+ const renderer = new Renderer67(canvas, parts, {+ world: true, ground: false, transparent: true, hdr: true, samples: 2, pixelRatio: 1, memoryBudgetMiB: 128,+ });+ renderer.render({ ...camera, time: 0, effects: { grain: 0, bloom: { strength: 0 } } });+ const context = renderer.context;+ const pixels = new Uint8Array(canvas.width * canvas.height * 4);+ context.readPixels(0, 0, canvas.width, canvas.height, context.RGBA, context.UNSIGNED_BYTE, pixels);+ const info = context.getExtension('WEBGL_debug_renderer_info');+ const result = { pixels, image: canvas.toDataURL('image/png'), error: context.getError(), memory: renderer.memoryPlan,+ gpu: info ? context.getParameter(info.UNMASKED_RENDERER_WEBGL) : 'unavailable' };+ renderer.dispose();+ return result;+ }+ const original = draw(before);+ const current = draw(after);+ let maximumPixelDifference = 0;+ let changedPixelChannels = 0;+ original.pixels.forEach((value, offset) => {+ const difference = Math.abs(value - current.pixels[offset]);+ maximumPixelDifference = Math.max(maximumPixelDifference, difference);+ if (difference) changedPixelChannels++;+ });+ return { partCount: after.length, geometryCount: newMeshes.length, maximumGeometryDifference, changedGeometryComponents,+ indicesUnchanged, transformsUnchanged: before.every((part, index) => part.matrix.every((value, offset) => value === after[index].matrix[offset])),+ maximumPixelDifference, changedPixelChannels, sourceGlError: original.error, currentGlError: current.error,+ memory: current.memory, gpu: current.gpu, beforeImage: original.image, afterImage: current.image };+ });+ for (const name of ['before', 'after']) {+ await writeFile(`artifacts/primitive-seams-${name}-${width}x${height}.png`, Buffer.from(report[`${name}Image`].split(',')[1], 'base64'));+ delete report[`${name}Image`];+ }+ await writeFile(`artifacts/primitive-seams-${width}x${height}.json`, JSON.stringify(report, null, 2));+ console.log(JSON.stringify(report, null, 2));+ assert.deepEqual(errors, []);+ assert.equal(report.sourceGlError, 0);+ assert.equal(report.currentGlError, 0);+ assert.equal(report.indicesUnchanged, true);+ assert.equal(report.transformsUnchanged, true);+ assert.ok(report.maximumGeometryDifference < 1e-12);+ assert.equal(report.maximumPixelDifference, 0);+} finally {+ await browser.close();+}diff --git a/scripts/smoke-surface-sculpt.mjs b/scripts/smoke-surface-sculpt.mjsindex eb9a14f2..0dd3a63c 100644--- a/scripts/smoke-surface-sculpt.mjs+++ b/scripts/smoke-surface-sculpt.mjs@@ -65,7 +65,7 @@ try {if (entry.patch) parts.push({ name: 'Badge', geometry: entry.patch, matrix, material: orange, castShadow: false });const renderer = new Renderer67(canvas, parts, {world: true, ground: false, samples: 2, pixelRatio: 1, hdr: true, memoryBudgetMiB: 96,- environment: { keyStrength: 0.8, fillStrength: 0.5, ambientStrength: 0.4 },+ environment: { keyIntensity: 0.8, fillIntensity: 0.5, ambientIntensity: 0.4 },});function draw(time) {const angle = Math.sin(time) * 0.25;diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.mdindex 8c344847..767ab49d 100644--- a/skills/build-67js-scene/SKILL.md+++ b/skills/build-67js-scene/SKILL.md@@ -26,6 +26,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.- A GLB asset viewer uses the optional `src/gltf.js` addon and `src/asset-viewer.js`.- Static brush sculpting uses optional `src/sculpt.js` and the checkout's `docs/sculpt.md`.- A curved surface badge uses optional `src/surface.js` and the checkout's `docs/surface.md`.+- Static contact, ray hits or closed-solid containment use optional `src/mesh-query.js` and the checkout's `docs/mesh-query.md`.- An image or video export uses `render-67js-media`.Read [scene-contract.md](references/scene-contract.md) before creating parts or changing materials.diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.mdindex 1e99ca62..beae5306 100644--- a/skills/build-67js-scene/references/scene-contract.md+++ b/skills/build-67js-scene/references/scene-contract.md@@ -115,6 +115,11 @@ Static `sculptGeometry` strokes return new geometry before renderer upload. Read`createSurfacePatch` clips a curved overlay with target-local clearance. Read `docs/surface.md` and share the target's retained matrix.It rejects skin, morph, assembly and procedural targets. It does not detect arbitrary mesh penetration or provide animated shrinkwrap.+Static `createMeshQueryIndex` copies geometry into an owned disposable BVH. Read `docs/mesh-query.md` for numerical and work limits.+Pass current affine matrices to `createMeshPairQuery(...).evaluate()`; rebuild indices after editing geometry.+Closed-solid containment requires two `solid: true` indices. Surface contact does not prove volume penetration or z-fighting.+Use `docs/primitives.md` for exact seam closure and preallocation bounds. Preserve indeterminate and budget errors rather than reporting a miss.+`cameraView('front' | 'right' | 'top')` returns an orthographic camera with the correct up vector.`fitOrthographicHeight(bounds, view, aspect)` frames both model width and height.The `unlit` tag and a front orthographic camera produce flat XY geometry.diff --git a/src/geometry.js b/src/geometry.jsindex 1580b2cd..c07ecb29 100644--- a/src/geometry.js+++ b/src/geometry.js@@ -1,4 +1,27 @@const FULL_TURN = Math.PI * 2;+const MAX_PRIMITIVE_VERTICES = 1_000_000;++function integer(value, minimum, maximum, name) {+ if (!Number.isInteger(value) || value < minimum || value > maximum) {+ throw new RangeError(`${name} must be an integer from ${minimum} to ${maximum}.`);+ }+}++function finiteFloat(value, name) {+ if (!Number.isFinite(value) || !Number.isFinite(Math.fround(value))) {+ throw new TypeError(`${name} must be a finite Float32 value.`);+ }+}++function primitiveBudget(vertices) {+ if (vertices > MAX_PRIMITIVE_VERTICES) {+ throw new RangeError('Primitive exceeds one million vertices. Reduce segments or subdivisions.');+ }+}++function periodicAngle(fraction) {+ return fraction === 1 ? 0 : fraction * FULL_TURN;+}function geometry(positions, normals, indices) {return {@@ -49,10 +72,14 @@ function surface(columns, rows, sample) {}export function sphere(segments = 64, rings = 40) {+ integer(segments, 3, 2048, 'segments');+ integer(rings, 2, 2048, 'rings');+ primitiveBudget((segments + 1) * (rings + 1));const result = surface(segments, rings, (longitude, latitude) => {- const angle = longitude * FULL_TURN;+ const angle = periodicAngle(longitude);const elevation = latitude * Math.PI;- const position = [Math.sin(elevation) * Math.cos(angle), Math.cos(elevation), Math.sin(elevation) * Math.sin(angle)];+ const radial = latitude === 0 || latitude === 1 ? 0 : Math.sin(elevation);+ const position = [radial * Math.cos(angle), Math.cos(elevation), radial * Math.sin(angle)];return { position, normal: position };});return result;@@ -60,16 +87,26 @@ export function sphere(segments = 64, rings = 40) {// The torus lies in XY, facing +Z. Partial arcs are useful for interrupted armor rings.export function torus(tubeRadius = 0.08, segments = 96, sides = 24, arc = FULL_TURN, start = 0) {+ finiteFloat(tubeRadius, 'tubeRadius');+ finiteFloat(arc, 'arc');+ finiteFloat(start, 'start');+ if (Math.fround(tubeRadius) <= 0 || Math.fround(arc) <= 0 || arc > FULL_TURN) {+ throw new RangeError('tubeRadius must remain positive at Float32 precision and arc must be within (0, 2PI].');+ }+ integer(segments, 3, 2048, 'segments');+ integer(sides, 3, 128, 'sides');+ primitiveBudget((segments + 1) * (sides + 1) + (arc === FULL_TURN ? 0 : 2 * (sides + 2)));+ start %= FULL_TURN;const body = surface(segments, sides, (along, around) => {- const angle = start + along * arc;- const tubeAngle = around * FULL_TURN;+ const angle = start + (arc === FULL_TURN && along === 1 ? 0 : along * arc);+ const tubeAngle = periodicAngle(around);const radial = 1 + tubeRadius * Math.cos(tubeAngle);return {position: [radial * Math.cos(angle), radial * Math.sin(angle), tubeRadius * Math.sin(tubeAngle)],normal: [Math.cos(angle) * Math.cos(tubeAngle), Math.sin(angle) * Math.cos(tubeAngle), Math.sin(tubeAngle)],};});- if (Math.abs(arc - FULL_TURN) < 1e-8) return body;+ if (arc === FULL_TURN) return body;const positions = [...body.positions];const normals = [...body.normals];const indices = [...body.indices];@@ -83,7 +120,7 @@ export function torus(tubeRadius = 0.08, segments = 96, sides = 24, arc = FULL_Tnormals.push(...normal);uvs.push(0.5, 0.5);for (let index = 0; index <= sides; index++) {- const tubeAngle = index / sides * FULL_TURN;+ const tubeAngle = periodicAngle(index / sides);const radial = 1 + tubeRadius * Math.cos(tubeAngle);positions.push(radial * Math.cos(angle), radial * Math.sin(angle), tubeRadius * Math.sin(tubeAngle));normals.push(...normal);@@ -98,6 +135,13 @@ export function torus(tubeRadius = 0.08, segments = 96, sides = 24, arc = FULL_T}export function cylinder(segments = 80, bevel = 0.025, bevelSegments = 6) {+ integer(segments, 3, 2048, 'segments');+ integer(bevelSegments, 1, 128, 'bevelSegments');+ finiteFloat(bevel, 'bevel');+ if (bevel < 0 || bevel > 0.5 || bevel > 0 && Math.fround(bevel) === 0) {+ throw new RangeError('Cylinder bevel must be within zero and 0.5 without Float32 underflow.');+ }+ primitiveBudget((segments + 1) * 2 * (bevelSegments + 1) + 2 * (segments + 2));const profile = [];for (let index = 0; index <= bevelSegments; index++) {const angle = -Math.PI / 2 + index / bevelSegments * Math.PI / 2;@@ -108,7 +152,7 @@ export function cylinder(segments = 80, bevel = 0.025, bevelSegments = 6) {profile.push({ radius: 1 - bevel + bevel * Math.cos(angle), height: 0.5 - bevel + bevel * Math.sin(angle), radialNormal: Math.cos(angle), verticalNormal: Math.sin(angle) });}const wall = surface(segments, profile.length - 1, (along, height) => {- const angle = along * FULL_TURN;+ const angle = periodicAngle(along);const ring = profile[Math.round(height * (profile.length - 1))];return {position: [ring.radius * Math.cos(angle), ring.height, ring.radius * Math.sin(angle)],@@ -123,7 +167,7 @@ export function cylinder(segments = 80, bevel = 0.025, bevelSegments = 6) {positions.push(0, sign * 0.5, 0);normals.push(0, sign, 0);for (let index = 0; index <= segments; index++) {- const angle = index / segments * FULL_TURN;+ const angle = periodicAngle(index / segments);positions.push((1 - bevel) * Math.cos(angle), sign * 0.5, (1 - bevel) * Math.sin(angle));normals.push(0, sign, 0);}@@ -136,6 +180,12 @@ export function cylinder(segments = 80, bevel = 0.025, bevelSegments = 6) {}export function box(bevel = 0.08, subdivisions = 6) {+ finiteFloat(bevel, 'bevel');+ if (bevel < 0 || bevel > 0.5 || bevel > 0 && Math.fround(bevel) === 0) {+ throw new RangeError('Box bevel must be within zero and 0.5 without Float32 underflow.');+ }+ integer(subdivisions, 1, 128, 'subdivisions');+ primitiveBudget(bevel === 0 ? 24 : 6 * (2 * subdivisions + 2) ** 2);const positions = [];const normals = [];const indices = [];diff --git a/src/mesh-query.js b/src/mesh-query.jsnew file mode 100644index 00000000..12368ccb--- /dev/null+++ b/src/mesh-query.js@@ -0,0 +1,418 @@+import { Box3, BufferAttribute, BufferGeometry, DoubleSide, Line3, Matrix4, Ray, Triangle, Vector3 } from 'three';+import { MeshBVH, SAH } from 'three-mesh-bvh';++const records = new WeakMap();+const EPSILON = 1e-9;+const INDEX_OPTIONS = new Set(['maxTriangles', 'maxVertices', 'memoryBudgetMiB', 'solid', 'maxValidationPairs']);+const PAIR_OPTIONS = new Set(['mode', 'maxTriangleTests']);+const DIRECTIONS = [[0, 0, 1], [1, 0.41421356237, 0.73205080757], [0.61803398875, 1, 0.27182818285], [0.17320508075, 0.44721359550, 1], [-1, 0.31622776602, 0.14142135624], [0.22360679775, -1, 0.70710678118]];++function optionsObject(options, fields) {+ if (!options || typeof options !== 'object' || Array.isArray(options)) throw new TypeError('Query options require an object.');+ for (const field of Object.keys(options)) if (!fields.has(field)) throw new TypeError(`Unsupported query option ${field}.`);+}++function integer(value, maximum, label) {+ if (!Number.isSafeInteger(value) || value < 1 || value > maximum) throw new RangeError(`${label} requires an integer within one and ${maximum}.`);+ return value;+}++function budget(maximum, label) {+ let tests = 0;+ return {+ charge() {+ tests++;+ if (tests > maximum) throw new RangeError(`${label} exhausted. Raise the query budget or reduce geometry detail.`);+ },+ get tests() { return tests; },+ };+}++function live(index) {+ const record = records.get(index);+ if (!record) throw new TypeError('Use an index from createMeshQueryIndex().');+ if (record.disposed) throw new Error('Mesh query index was disposed. Create a new index.');+ return record;+}++// BVH callbacks must unwind normally: the maintained cast stores module-global traversal state.+function cast(first, second, transform, counter, visitor) {+ let failure;+ const intersected = first.bvh.bvhcast(second.bvh, transform, {+ intersectsTriangles(firstTriangle, secondTriangle, firstIndex, secondIndex) {+ try {+ counter.charge();+ return visitor(firstTriangle, secondTriangle, first.bvh.resolveTriangleIndex(firstIndex), second.bvh.resolveTriangleIndex(secondIndex));+ } catch (error) {+ failure = error;+ return true;+ }+ },+ });+ if (failure) throw failure;+ return intersected;+}++function validateGeometry(geometry, maxVertices, maxTriangles) {+ if (!geometry || typeof geometry !== 'object') throw new TypeError('Mesh queries require geometry.');+ if (geometry.skinIndices !== undefined || geometry.skinWeights !== undefined || geometry.morphTargets !== undefined) {+ throw new RangeError('Mesh queries require static geometry without skinning or morph targets.');+ }+ const positions = geometry.positions;+ const indices = geometry.indices;+ if (!(positions instanceof Float32Array) || positions.length === 0 || positions.length % 3 !== 0) throw new TypeError('Query positions require nonempty Float32 XYZ vertices.');+ if (!(indices instanceof Uint32Array) || indices.length === 0 || indices.length % 3 !== 0) throw new TypeError('Query indices require nonempty Uint32 triangles.');+ if (positions.length / 3 > maxVertices || indices.length / 3 > maxTriangles) throw new RangeError('Geometry exceeds maxVertices or maxTriangles.');+ const bounds = new Box3();+ const point = new Vector3();+ for (let offset = 0; offset < positions.length; offset += 3) {+ point.fromArray(positions, offset);+ if (![point.x, point.y, point.z].every(Number.isFinite)) throw new RangeError('Query positions must remain finite.');+ bounds.expandByPoint(point);+ }+ for (const index of indices) if (index >= positions.length / 3) throw new RangeError('Query index exceeds the vertex count.');+ const center = bounds.getCenter(new Vector3());+ const extent = bounds.getSize(new Vector3());+ const scale = Math.max(extent.x, extent.y, extent.z);+ if (scale === 0) throw new RangeError('Query geometry has no drawable extent.');+ const first = new Vector3();+ const second = new Vector3();+ const third = new Vector3();+ const cross = new Vector3();+ let minimumAltitude = Infinity;+ for (let offset = 0; offset < indices.length; offset += 3) {+ first.fromArray(positions, indices[offset] * 3);+ second.fromArray(positions, indices[offset + 1] * 3).sub(first).multiplyScalar(1 / scale);+ third.fromArray(positions, indices[offset + 2] * 3).sub(first).multiplyScalar(1 / scale);+ const longest = Math.max(second.length(), third.length(), first.subVectors(second, third).length());+ cross.crossVectors(second, third);+ const altitude = Math.hypot(cross.x, cross.y, cross.z) / longest;+ if (!Number.isFinite(altitude) || altitude <= 1e-8) throw new RangeError('Query triangle is degenerate or below the normalized precision domain.');+ minimumAltitude = Math.min(minimumAltitude, altitude);+ }+ return { center, scale, minimumAltitude, vertexCount: positions.length / 3, triangleCount: indices.length / 3 };+}++function topology(geometry) {+ const vertexIds = new Uint32Array(geometry.positions.length / 3);+ const vertices = new Map();+ for (let vertex = 0; vertex < vertexIds.length; vertex++) {+ const offset = vertex * 3;+ const key = Array.from(geometry.positions.subarray(offset, offset + 3), value => value === 0 ? 0 : value).join(',');+ if (!vertices.has(key)) vertices.set(key, vertices.size);+ vertexIds[vertex] = vertices.get(key);+ }+ const triangles = Uint32Array.from(geometry.indices, index => vertexIds[index]);+ const edges = new Map();+ const neighbors = Array.from({ length: triangles.length / 3 }, () => []);+ const incident = Array.from({ length: vertices.size }, () => []);+ for (let face = 0; face < triangles.length / 3; face++) {+ const ids = Array.from(triangles.subarray(face * 3, face * 3 + 3));+ for (let corner = 0; corner < 3; corner++) {+ const first = ids[corner];+ const second = ids[(corner + 1) % 3];+ incident[first].push(face);+ const key = `${Math.min(first, second)}:${Math.max(first, second)}`;+ if (!edges.has(key)) edges.set(key, []);+ edges.get(key).push({ first, second, face });+ }+ }+ for (const adjacent of edges.values()) {+ if (adjacent.length !== 2 || adjacent[0].first !== adjacent[1].second || adjacent[0].second !== adjacent[1].first) {+ throw new RangeError('Solid geometry requires closed oriented manifold edges after exact position welding.');+ }+ neighbors[adjacent[0].face].push(adjacent[1].face);+ neighbors[adjacent[1].face].push(adjacent[0].face);+ }+ const visited = new Set([0]);+ const stack = [0];+ while (stack.length) {+ for (const neighbor of neighbors[stack.pop()]) if (!visited.has(neighbor)) {+ visited.add(neighbor);+ stack.push(neighbor);+ }+ }+ if (visited.size !== triangles.length / 3) throw new RangeError('Solid geometry requires one connected boundary.');+ for (let vertex = 0; vertex < incident.length; vertex++) {+ if (incident[vertex].length === 0) continue;+ const links = new Map();+ for (const face of incident[vertex]) {+ const other = Array.from(triangles.subarray(face * 3, face * 3 + 3)).filter(index => index !== vertex);+ for (let side = 0; side < 2; side++) {+ if (!links.has(other[side])) links.set(other[side], []);+ links.get(other[side]).push(other[1 - side]);+ }+ }+ if (Array.from(links.values()).some(link => link.length !== 2)) throw new RangeError('Solid geometry requires manifold vertex links.');+ const reached = new Set();+ const pending = [links.keys().next().value];+ while (pending.length) {+ const current = pending.pop();+ if (reached.has(current)) continue;+ reached.add(current);+ pending.push(...links.get(current));+ }+ if (reached.size !== links.size) throw new RangeError('Solid geometry requires a single cycle at each vertex link.');+ }+ return triangles;+}++function coneContains(origin, first, second, point, normal) {+ const edgeA = first.clone().sub(origin);+ const edgeB = second.clone().sub(origin);+ const direction = point.clone().sub(origin);+ const cross = new Vector3();+ const denominator = cross.crossVectors(edgeA, edgeB).dot(normal);+ const firstWeight = cross.crossVectors(direction, edgeB).dot(normal) / denominator;+ const secondWeight = cross.crossVectors(edgeA, direction).dot(normal) / denominator;+ return firstWeight >= -EPSILON && secondWeight >= -EPSILON;+}++function validateSelfIntersections(record, welded, maximum) {+ const counter = budget(maximum, 'maxValidationPairs');+ const segment = new Line3();+ cast(record, record, new Matrix4(), counter, (first, second, firstId, secondId) => {+ if (firstId >= secondId) return false;+ if (!first.intersectsTriangle(second, segment, true)) return false;+ const firstIds = Array.from(welded.subarray(firstId * 3, firstId * 3 + 3));+ const secondIds = Array.from(welded.subarray(secondId * 3, secondId * 3 + 3));+ const shared = firstIds.filter(index => secondIds.includes(index));+ if (shared.length === 0 || shared.length === 3) throw new RangeError('Solid boundary intersects itself.');+ const firstPoints = [first.a, first.b, first.c];+ const secondPoints = [second.a, second.b, second.c];+ const firstNormal = first.getNormal(new Vector3());+ const secondNormal = second.getNormal(new Vector3());+ const coplanar = new Vector3().crossVectors(firstNormal, secondNormal).length() <= EPSILON;+ if (shared.length === 2) {+ if (coplanar) {+ const origin = firstPoints[firstIds.indexOf(shared[0])];+ const edge = firstPoints[firstIds.indexOf(shared[1])].clone().sub(origin);+ const firstTip = firstPoints[firstIds.findIndex(index => !shared.includes(index))].clone().sub(origin);+ const secondTip = secondPoints[secondIds.findIndex(index => !shared.includes(index))].clone().sub(origin);+ const firstSide = new Vector3().crossVectors(edge, firstTip).dot(firstNormal);+ const secondSide = new Vector3().crossVectors(edge, secondTip).dot(firstNormal);+ if (firstSide * secondSide >= 0) throw new RangeError('Solid adjacent faces overlap or have ambiguous coplanar sides.');+ }+ return false;+ }+ const origin = firstPoints[firstIds.indexOf(shared[0])];+ if (!coplanar) {+ if (segment.start.distanceTo(origin) > EPSILON || segment.end.distanceTo(origin) > EPSILON) throw new RangeError('Solid faces intersect beyond their shared vertex.');+ return false;+ }+ const firstOther = firstPoints.filter((point, index) => firstIds[index] !== shared[0]);+ const secondOther = secondPoints.filter((point, index) => secondIds[index] !== shared[0]);+ if (secondOther.some(point => coneContains(origin, ...firstOther, point, firstNormal)) || firstOther.some(point => coneContains(origin, ...secondOther, point, secondNormal))) {+ throw new RangeError('Solid coplanar faces intersect beyond their shared vertex.');+ }+ return false;+ });+ return counter.tests;+}++function matrixState(record, values) {+ if ((!Array.isArray(values) && !ArrayBuffer.isView(values)) || values.length !== 16) throw new TypeError('Query matrix requires 16 affine components.');+ const elements = Array.from(values, value => {+ if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isFinite(Math.fround(value))) throw new RangeError('Query matrix requires finite Float32 components.');+ return Math.fround(value);+ });+ if (elements[3] !== 0 || elements[7] !== 0 || elements[11] !== 0 || elements[15] !== 1) throw new RangeError('Query matrix must be affine.');+ const matrix = new Matrix4().fromArray(elements).multiply(record.normalization);+ const determinant = matrix.determinant();+ if (!Number.isFinite(determinant) || determinant === 0) throw new RangeError('Query matrix must be nonsingular.');+ const inverse = matrix.clone().invert();+ if (!inverse.elements.every(Number.isFinite)) throw new RangeError('Query matrix inverse exceeds the precision domain.');+ const bounds = record.bounds.clone().applyMatrix4(matrix);+ const coordinates = [...bounds.min.toArray(), ...bounds.max.toArray()];+ if (!coordinates.every(value => Number.isFinite(value) && Number.isFinite(Math.fround(value)))) throw new RangeError('Query world coordinates exceed finite Float32 bounds.');+ const inverseNorm = Math.hypot(...[0, 1, 2, 4, 5, 6, 8, 9, 10].map(index => inverse.elements[index]));+ const resolution = Math.max(...coordinates.map(Math.abs)) * 2 ** -21 + 2 ** -149;+ if (record.minimumAltitude / inverseNorm <= resolution) throw new RangeError('Query transformed triangles collapse within the Float32 precision domain.');+ return { matrix, inverse, bounds };+}++function relativeState(second, transform) {+ const inverse = transform.clone().invert();+ const inverseNorm = Math.hypot(...[0, 1, 2, 4, 5, 6, 8, 9, 10].map(index => inverse.elements[index]));+ const bounds = second.bounds.clone().applyMatrix4(transform);+ const maximum = Math.max(...bounds.min.toArray().map(Math.abs), ...bounds.max.toArray().map(Math.abs));+ if (!Number.isFinite(maximum) || maximum > 1e6 || second.minimumAltitude / inverseNorm <= 1e-8) {+ throw new RangeError('Relative mesh transform exceeds the normalized triangle precision domain.');+ }+}++function containment(record, point, counter) {+ if (!record.bounds.containsPoint(point)) return { inside: false, attempts: 0 };+ let previous;+ let accepted = 0;+ let attempts = 0;+ for (const direction of DIRECTIONS) {+ attempts++;+ const ray = new Ray(point, new Vector3(...direction).normalize());+ const hit = new Vector3();+ const weights = new Vector3();+ const normal = new Vector3();+ let count = 0;+ let ambiguous = false;+ let failure;+ record.bvh.shapecast({+ intersectsBounds: bounds => ray.intersectsBox(bounds),+ intersectsTriangle(triangle) {+ try {+ counter.charge();+ triangle.getNormal(normal);+ if (Math.abs(normal.dot(ray.direction)) <= EPSILON && Math.abs(normal.dot(point.clone().sub(triangle.a))) <= EPSILON) {+ ambiguous = true;+ return true;+ }+ if (!ray.intersectTriangle(triangle.a, triangle.b, triangle.c, false, hit)) return false;+ triangle.getBarycoord(hit, weights);+ if (hit.distanceTo(point) <= EPSILON || Math.min(weights.x, weights.y, weights.z) <= EPSILON) {+ ambiguous = true;+ return true;+ }+ count++;+ return false;+ } catch (error) {+ failure = error;+ return true;+ }+ },+ });+ if (failure) throw failure;+ if (ambiguous) continue;+ const inside = count % 2 === 1;+ if (accepted && previous !== inside) throw new RangeError('Solid containment has inconsistent ray witnesses.');+ previous = inside;+ accepted++;+ if (accepted === 2) return { inside, attempts };+ }+ throw new RangeError('Solid containment is indeterminate after bounded ray retries.');+}++/** Copies static geometry into a private normalized BVH. Returned handles expose no Three.js objects. */+export function createMeshQueryIndex(geometry, options = {}) {+ optionsObject(options, INDEX_OPTIONS);+ const maxTriangles = integer(options.maxTriangles ?? 250_000, 1_000_000, 'maxTriangles');+ const maxVertices = integer(options.maxVertices ?? 250_000, 1_000_000, 'maxVertices');+ const maxValidationPairs = integer(options.maxValidationPairs ?? 2_000_000, 100_000_000, 'maxValidationPairs');+ const solid = options.solid ?? false;+ if (typeof solid !== 'boolean') throw new TypeError('solid must be boolean.');+ const memoryBudgetMiB = options.memoryBudgetMiB ?? 64;+ if (!Number.isFinite(memoryBudgetMiB) || memoryBudgetMiB <= 0 || memoryBudgetMiB > 1024) throw new RangeError('memoryBudgetMiB must be within zero and 1024.');+ const metadata = validateGeometry(geometry, maxVertices, maxTriangles);+ const reservedBytes = metadata.vertexCount * (solid ? 152 : 24) + metadata.triangleCount * (solid ? 512 : 128);+ if (reservedBytes > memoryBudgetMiB * 1024 * 1024) throw new RangeError('Mesh query allocation estimate exceeds memoryBudgetMiB.');+ const welded = solid ? topology(geometry) : null;+ const source = new BufferGeometry();+ const positions = new Float64Array(geometry.positions.length);+ for (let offset = 0; offset < positions.length; offset += 3) {+ for (let axis = 0; axis < 3; axis++) positions[offset + axis] = (geometry.positions[offset + axis] - metadata.center.getComponent(axis)) / metadata.scale;+ }+ source.setAttribute('position', new BufferAttribute(positions, 3));+ source.setIndex(new BufferAttribute(new Uint32Array(geometry.indices), 1));+ const normalization = new Matrix4().makeScale(metadata.scale, metadata.scale, metadata.scale).setPosition(metadata.center);+ const record = { ...metadata, normalization, geometry: source, bounds: new Box3().setFromBufferAttribute(source.attributes.position), bvh: null, disposed: false, solid };+ try {+ record.bvh = new MeshBVH(source, { indirect: true, strategy: SAH, maxDepth: 64, targetLeafSize: 8, verbose: false });+ const validationPairs = solid ? validateSelfIntersections(record, welded, maxValidationPairs) : 0;+ const memoryPlan = Object.freeze({ reservedBytes, memoryBudgetMiB, vertexCount: metadata.vertexCount, triangleCount: metadata.triangleCount, validationPairs });+ const handle = Object.freeze({+ solid,+ memoryPlan,+ info: Object.freeze({ vertexCount: metadata.vertexCount, triangleCount: metadata.triangleCount, estimatedBytes: reservedBytes }),+ raycast(matrix, ray) {+ const current = live(handle);+ const state = matrixState(current, matrix);+ if (!ray || typeof ray !== 'object') throw new TypeError('ray requires origin and direction.');+ const read = field => {+ const input = ray[field];+ if ((!Array.isArray(input) && !ArrayBuffer.isView(input)) || input.length !== 3 || !Array.from(input).every(value => typeof value === 'number' && Number.isFinite(value) && Number.isFinite(Math.fround(value)))) throw new TypeError(`Ray ${field} requires three finite Float32 values.`);+ return new Vector3(...Array.from(input, Math.fround));+ };+ const origin = read('origin');+ const direction = read('direction');+ if (direction.length() === 0) throw new RangeError('Ray direction must be nonzero.');+ const maximum = ray.maxDistance ?? Infinity;+ if ((maximum !== Infinity && !Number.isFinite(maximum)) || maximum < 0) throw new RangeError('Ray maxDistance must be nonnegative.');+ const localRay = new Ray(origin.clone(), direction.normalize()).applyMatrix4(state.inverse);+ if (Math.max(...localRay.origin.toArray().map(Math.abs)) > 1e6) throw new RangeError('Ray origin exceeds the normalized query precision domain.');+ const result = current.bvh.raycastFirst(localRay, DoubleSide);+ if (!result) return null;+ const worldPoint = result.point.clone().applyMatrix4(state.matrix);+ const distance = worldPoint.distanceTo(origin);+ if (!Number.isFinite(distance) || !worldPoint.toArray().every(value => Number.isFinite(Math.fround(value)))) throw new RangeError('Ray hit exceeds finite world coordinates.');+ if (distance > maximum) return null;+ const triangle = result.faceIndex;+ const positions = current.geometry.attributes.position;+ const ids = current.geometry.index;+ const first = new Vector3().fromBufferAttribute(positions, ids.getX(triangle * 3));+ const second = new Vector3().fromBufferAttribute(positions, ids.getX(triangle * 3 + 1));+ const third = new Vector3().fromBufferAttribute(positions, ids.getX(triangle * 3 + 2));+ const weights = new Triangle(first, second, third).getBarycoord(result.point, new Vector3());+ if (!weights || !weights.toArray().every(Number.isFinite)) throw new RangeError('Ray barycentric coordinates exceed the query precision domain.');+ return { point: worldPoint.toArray(), distance, triangle, barycentric: weights.toArray() };+ },+ dispose() {+ if (record.disposed) return;+ record.disposed = true;+ record.geometry.dispose();+ record.geometry = null;+ record.bvh = null;+ },+ });+ records.set(handle, record);+ return handle;+ } catch (error) {+ source.dispose();+ throw error;+ }+}++/** Surface contacts are not proof of volume penetration. Closed solids additionally test containment. */+export function createMeshPairQuery(indexA, indexB, options = {}) {+ optionsObject(options, PAIR_OPTIONS);+ const first = live(indexA);+ const second = live(indexB);+ const mode = options.mode ?? 'surfaces';+ if (mode !== 'surfaces' && mode !== 'closed-solids') throw new RangeError('Query mode must be surfaces or closed-solids.');+ if (mode === 'closed-solids' && (!first.solid || !second.solid)) throw new RangeError('Closed-solid queries require two validated solid indices.');+ const maximum = integer(options.maxTriangleTests ?? 2_000_000, 100_000_000, 'maxTriangleTests');+ return Object.freeze({+ evaluate(matrixA, matrixB) {+ const currentA = live(indexA);+ const currentB = live(indexB);+ const stateA = matrixState(currentA, matrixA);+ const stateB = matrixState(currentB, matrixB);+ const result = { kind: mode === 'surfaces' ? 'surface-disjoint' : 'separate', solidRelation: mode === 'surfaces' ? 'not-tested' : 'outside', triangles: null, triangleTests: 0, rayAttempts: 0 };+ if (!stateA.bounds.intersectsBox(stateB.bounds)) return result;+ const relativeB = stateA.inverse.clone().multiply(stateB.matrix);+ const relativeA = stateB.inverse.clone().multiply(stateA.matrix);+ relativeState(currentB, relativeB);+ relativeState(currentA, relativeA);+ const counter = budget(maximum, 'maxTriangleTests');+ const contact = cast(currentA, currentB, relativeB, counter, (firstTriangle, secondTriangle, firstId, secondId) => {+ if (!firstTriangle.intersectsTriangle(secondTriangle)) return false;+ result.triangles = [firstId, secondId];+ return true;+ });+ if (contact) {+ result.kind = 'surface-intersection';+ result.solidRelation = mode === 'surfaces' ? 'not-tested' : 'boundaries-intersect';+ } else if (mode === 'closed-solids') {+ const pointA = new Vector3().fromBufferAttribute(currentA.geometry.attributes.position, currentA.geometry.index.getX(0)).applyMatrix4(relativeA);+ const pointB = new Vector3().fromBufferAttribute(currentB.geometry.attributes.position, currentB.geometry.index.getX(0)).applyMatrix4(relativeB);+ const firstInside = containment(currentB, pointA, counter);+ const secondInside = containment(currentA, pointB, counter);+ result.rayAttempts = firstInside.attempts + secondInside.attempts;+ if (firstInside.inside && secondInside.inside) throw new RangeError('Solid containment witnesses are inconsistent.');+ if (firstInside.inside || secondInside.inside) {+ result.kind = 'contained';+ result.solidRelation = firstInside.inside ? 'a-in-b' : 'b-in-a';+ }+ }+ result.triangleTests = counter.tests;+ return result;+ },+ });+}diff --git a/tests/mesh-query.test.js b/tests/mesh-query.test.jsnew file mode 100644index 00000000..f08b0bcd--- /dev/null+++ b/tests/mesh-query.test.js@@ -0,0 +1,223 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { BoxGeometry, Matrix4 } from 'three';+import { createMeshQueryIndex, createMeshPairQuery } from '../src/mesh-query.js';+import { sphere, torus, cylinder, box as beveledBox } from '../src/geometry.js';++const identity = new Matrix4().toArray();+const translated = (x, y = 0, z = 0) => new Matrix4().makeTranslation(x, y, z).toArray();++function box(size = 1) {+ const source = new BoxGeometry(size, size, size);+ const geometry = { positions: new Float32Array(source.attributes.position.array), indices: new Uint32Array(source.index.array), uvs: new Float32Array(source.attributes.uv.array) };+ source.dispose();+ return geometry;+}++function solid(size = 1) {+ return createMeshQueryIndex(box(size), { solid: true });+}++function joined(first, second, shift) {+ const positions = new Float32Array(first.positions.length + second.positions.length);+ positions.set(first.positions);+ positions.set(second.positions, first.positions.length);+ for (let offset = first.positions.length; offset < positions.length; offset += 3) positions[offset] += shift;+ const indices = new Uint32Array(first.indices.length + second.indices.length);+ indices.set(first.indices);+ indices.set(Array.from(second.indices, index => index + first.positions.length / 3), first.indices.length);+ return { positions, indices };+}++test('closed boxes distinguish containment in both directions, crossings, contact, and separation', () => {+ const outer = solid(4);+ const inner = solid();+ const query = createMeshPairQuery(outer, inner, { mode: 'closed-solids' });+ const contained = query.evaluate(identity, identity);+ assert.equal(contained.kind, 'contained');+ assert.equal(contained.solidRelation, 'b-in-a');+ assert.ok(contained.rayAttempts > 2, 'axis ray grazes a box diagonal and is retried');+ assert.equal(createMeshPairQuery(inner, outer, { mode: 'closed-solids' }).evaluate(identity, identity).solidRelation, 'a-in-b');+ for (const offset of [2, 2.5]) {+ const contact = query.evaluate(identity, translated(offset));+ assert.equal(contact.kind, 'surface-intersection');+ assert.equal(contact.solidRelation, 'boundaries-intersect');+ assert.equal(contact.triangles.length, 2);+ }+ assert.deepEqual(query.evaluate(identity, translated(10)), { kind: 'separate', solidRelation: 'outside', triangles: null, triangleTests: 0, rayAttempts: 0 });+ const repeated = query.evaluate(identity, identity);+ assert.deepEqual(repeated, contained);+ assert.notEqual(repeated, contained);+ outer.dispose();+ inner.dispose();+});++test('surface mode supports open triangles, including coplanar contact, without a containment claim', () => {+ const triangle = { positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]), indices: new Uint32Array([0, 1, 2]) };+ const first = createMeshQueryIndex(triangle);+ const second = createMeshQueryIndex(triangle);+ const query = createMeshPairQuery(first, second);+ assert.equal(query.evaluate(identity, translated(0.2, 0.2)).kind, 'surface-intersection');+ assert.equal(query.evaluate(identity, translated(0, 0, 1)).kind, 'surface-disjoint');+ assert.equal(query.evaluate(identity, identity).solidRelation, 'not-tested');+ assert.throws(() => createMeshPairQuery(first, second, { mode: 'closed-solids' }), /validated solid/);+ first.dispose();+ second.dispose();+});++test('ray hits retain original triangle IDs and barycentric coordinates across affine transforms', () => {+ const geometry = box();+ const index = createMeshQueryIndex(geometry, { solid: true });+ const hit = index.raycast(identity, { origin: [0.1, 0.2, 2], direction: [0, 0, -3] });+ assert.ok(Math.abs(hit.distance - 1.5) < 1e-8);+ assert.ok(Math.abs(hit.point[2] - 0.5) < 1e-8);+ assert.ok(Math.abs(hit.barycentric.reduce((sum, value) => sum + value, 0) - 1) < 1e-8);+ for (let axis = 0; axis < 3; axis++) {+ const coordinate = hit.barycentric.reduce((sum, weight, corner) => sum + weight * geometry.positions[geometry.indices[hit.triangle * 3 + corner] * 3 + axis], 0);+ assert.ok(Math.abs(coordinate - hit.point[axis]) < 1e-8);+ }+ assert.equal(index.raycast(identity, { origin: [0, 0, 2], direction: [0, 0, -1], maxDistance: 1 }), null);+ const affine = new Matrix4().makeScale(-2, 3, 0.5);+ affine.elements[4] = 0.4;+ affine.setPosition(2, -1, 4);+ const transformed = index.raycast(affine.toArray(), { origin: [2, -1, 6], direction: [0, 0, -1] });+ assert.deepEqual(transformed.point, [2, -1, 4.25]);+ assert.equal(transformed.distance, 1.75);+ assert.equal(index.info.vertexCount, 24);+ assert.equal(index.info.triangleCount, 12);+ assert.ok(Object.isFrozen(index.info));+ index.dispose();+});++test('closed queries accept reflected, rotated, nonuniform, and sheared affine transforms', () => {+ const outer = solid(4);+ const inner = solid();+ const query = createMeshPairQuery(outer, inner, { mode: 'closed-solids' });+ const matrix = new Matrix4().makeRotationY(0.4).multiply(new Matrix4().makeScale(-2, 0.5, 1.4));+ matrix.elements[4] += 0.3;+ matrix.setPosition(3, -2, 1);+ assert.equal(query.evaluate(matrix.toArray(), matrix.toArray()).solidRelation, 'b-in-a');+ assert.equal(query.evaluate(identity, identity).solidRelation, 'b-in-a');+ outer.dispose();+ inner.dispose();+});++test('exact position welding handles UV seams and leaves source arrays untouched and uncoupled', () => {+ const geometry = box();+ const positionStorage = new Float32Array(geometry.positions.length + 6);+ positionStorage.set(geometry.positions, 3);+ const indexStorage = new Uint32Array(geometry.indices.length + 4);+ indexStorage.set(geometry.indices, 2);+ geometry.positions = positionStorage.subarray(3, -3);+ geometry.indices = indexStorage.subarray(2, -2);+ const positions = new Float32Array(geometry.positions);+ const indices = new Uint32Array(geometry.indices);+ const index = createMeshQueryIndex(geometry, { solid: true });+ assert.deepEqual(geometry.positions, positions);+ assert.deepEqual(geometry.indices, indices);+ geometry.positions.fill(100);+ geometry.indices.fill(0);+ assert.equal(index.raycast(identity, { origin: [0, 0, 2], direction: [0, 0, -1] }).point[2], 0.5);+ index.dispose();+ index.dispose();+ assert.throws(() => index.raycast(identity, { origin: [0, 0, 2], direction: [0, 0, -1] }), /disposed/);+ assert.throws(() => createMeshPairQuery(index, index), /disposed/);+});++test('solid preflight rejects open, unoriented, nonmanifold, disconnected and self-crossing boundaries', () => {+ const open = box();+ open.indices = open.indices.slice(3);+ assert.throws(() => createMeshQueryIndex(open, { solid: true }), /manifold edges/);+ const reversed = box();+ [reversed.indices[0], reversed.indices[1]] = [reversed.indices[1], reversed.indices[0]];+ assert.throws(() => createMeshQueryIndex(reversed, { solid: true }), /manifold edges/);+ const duplicate = box();+ duplicate.indices = new Uint32Array([...duplicate.indices, ...duplicate.indices.slice(0, 3)]);+ assert.throws(() => createMeshQueryIndex(duplicate, { solid: true }), /manifold edges/);+ assert.throws(() => createMeshQueryIndex(joined(box(), box(), 3), { solid: true }), /connected boundary/);+ const folded = box();+ for (let offset = 0; offset < folded.positions.length; offset += 3) {+ if (folded.positions[offset] === 0.5 && folded.positions[offset + 1] === 0.5 && folded.positions[offset + 2] === 0.5) folded.positions.set([-1, -1, -1], offset);+ }+ assert.throws(() => createMeshQueryIndex(folded, { solid: true }), /intersect|overlap/);+ const valid = solid();+ valid.dispose();+});++test('budget failures unwind BVH callbacks and leave subsequent queries usable', () => {+ assert.throws(() => createMeshQueryIndex(box(), { solid: true, maxValidationPairs: 1 }), /maxValidationPairs exhausted/);+ const outer = solid(4);+ const inner = solid();+ assert.throws(() => createMeshPairQuery(outer, inner, { mode: 'closed-solids', maxTriangleTests: 1 }).evaluate(identity, identity), /maxTriangleTests exhausted/);+ const surfaces = createMeshPairQuery(outer, inner).evaluate(identity, identity);+ assert.equal(surfaces.kind, 'surface-disjoint');+ assert.throws(() => createMeshPairQuery(outer, inner, { mode: 'closed-solids', maxTriangleTests: surfaces.triangleTests + 1 }).evaluate(identity, identity), /maxTriangleTests exhausted/);+ assert.equal(createMeshPairQuery(outer, inner, { mode: 'closed-solids' }).evaluate(identity, identity).kind, 'contained');+ outer.dispose();+ inner.dispose();+});++test('closed built-in curved primitives retain seams and distinguish the torus hole from its solid interior', () => {+ for (const geometry of [sphere(12, 8), torus(0.2, 12, 8), cylinder(12, 0.025, 2), beveledBox(0.08, 2)]) {+ const index = createMeshQueryIndex(geometry, { solid: true });+ assert.ok(index.memoryPlan.validationPairs > 0);+ index.dispose();+ }+ const ring = createMeshQueryIndex(torus(0.2, 12, 8), { solid: true });+ const small = createMeshQueryIndex(sphere(12, 8), { solid: true });+ const query = createMeshPairQuery(ring, small, { mode: 'closed-solids' });+ const inHole = new Matrix4().makeScale(0.05, 0.05, 0.05);+ assert.equal(query.evaluate(identity, inHole.toArray()).kind, 'separate');+ const inTube = inHole.clone().setPosition(1, 0, 0);+ assert.equal(query.evaluate(identity, inTube.toArray()).solidRelation, 'b-in-a');+ ring.dispose();+ small.dispose();+});++test('closed topology rejects a pinched vertex even when all welded edges remain manifold', () => {+ const geometry = torus(0.2, 12, 8);+ const first = geometry.positions.slice(0, 3);+ const opposite = geometry.positions.slice(6 * 3, 6 * 3 + 3);+ for (let offset = 0; offset < geometry.positions.length; offset += 3) {+ if (geometry.positions[offset] === opposite[0] && geometry.positions[offset + 1] === opposite[1] && geometry.positions[offset + 2] === opposite[2]) geometry.positions.set(first, offset);+ }+ assert.throws(() => createMeshQueryIndex(geometry, { solid: true }), /vertex link/);+});++test('input and allocation limits reject before building, including malformed deformation and triangles', () => {+ for (const options of [{ maxTriangles: 1 }, { maxVertices: 2 }, { memoryBudgetMiB: 0.0001 }, { maxValidationPairs: 0 }, { solid: 1 }, { unknown: 1 }]) assert.throws(() => createMeshQueryIndex(box(), options));+ for (const field of ['skinIndices', 'skinWeights', 'morphTargets']) assert.throws(() => createMeshQueryIndex({ ...box(), [field]: [] }), /static geometry/);+ assert.throws(() => createMeshQueryIndex({ ...box(), indices: new Uint16Array([0, 1, 2]) }), /Uint32/);+ const invalid = box();+ invalid.positions[0] = Infinity;+ assert.throws(() => createMeshQueryIndex(invalid), /finite/);+ const outOfRange = box();+ outOfRange.indices[0] = 1000;+ assert.throws(() => createMeshQueryIndex(outOfRange), /vertex count/);+ const degenerate = box();+ degenerate.indices[0] = degenerate.indices[1];+ assert.throws(() => createMeshQueryIndex(degenerate), /degenerate/);+ assert.throws(() => createMeshPairQuery({}, {}), /createMeshQueryIndex/);+});++test('numeric domains normalize tiny and huge meshes but reject singular, overflow and collapsed poses', () => {+ for (const size of [1e-30, 1e30]) {+ const outer = solid(size * 4);+ const inner = solid(size);+ assert.equal(createMeshPairQuery(outer, inner, { mode: 'closed-solids' }).evaluate(identity, identity).kind, 'contained');+ outer.dispose();+ inner.dispose();+ }+ const index = solid();+ const query = createMeshPairQuery(index, index);+ for (const matrix of [new Matrix4().makeScale(0, 1, 1), new Matrix4().makeScale(1e-50, 1, 1), new Matrix4().makeTranslation(1e20, 0, 0), new Matrix4().makeScale(3e38, 3e38, 3e38)]) assert.throws(() => query.evaluate(identity, matrix.toArray()), /singular|collapse|precision|Float32/);+ const perspective = identity.slice();+ perspective[3] = 1;+ assert.throws(() => query.evaluate(identity, perspective), /affine/);+ const nonfinite = identity.slice();+ nonfinite[0] = NaN;+ assert.throws(() => query.evaluate(nonfinite, identity), /finite Float32/);+ assert.throws(() => index.raycast(identity, { origin: [0, 0, 2], direction: [0, 0, 0] }), /nonzero/);+ assert.throws(() => index.raycast(identity, { origin: [0, 0, 1e8], direction: [0, 0, -1] }), /precision domain/);+ index.dispose();+});diff --git a/tests/model.test.js b/tests/model.test.jsindex 817d24c6..df588a50 100644--- a/tests/model.test.js+++ b/tests/model.test.js@@ -2,6 +2,52 @@ import assert from 'node:assert/strict';import test from 'node:test';import { createHash } from 'node:crypto';import { box, cylinder, sphere, torus } from '../src/geometry.js';++test('closed primitives have exact Float32 seams and oppositely oriented paired edges', () => {+ for (const [name, mesh] of [+ ['sphere', sphere(16, 12)], ['torus', torus(0.08, 16, 8)],+ ['cylinder', cylinder(16, 0.025, 3)], ['box', box()],+ ]) {+ const vertices = new Map();+ const welded = [];+ for (let offset = 0; offset < mesh.positions.length; offset += 3) {+ const key = mesh.positions.subarray(offset, offset + 3).join(',');+ if (!vertices.has(key)) vertices.set(key, vertices.size);+ welded.push(vertices.get(key));+ }+ const edges = new Map();+ for (let offset = 0; offset < mesh.indices.length; offset += 3) {+ const triangle = Array.from(mesh.indices.subarray(offset, offset + 3), index => welded[index]);+ assert.equal(new Set(triangle).size, 3, name);+ for (let corner = 0; corner < 3; corner++) {+ const first = triangle[corner];+ const second = triangle[(corner + 1) % 3];+ const key = `${Math.min(first, second)}:${Math.max(first, second)}`;+ const edge = edges.get(key) ?? { count: 0, direction: 0 };+ edge.count++;+ edge.direction += first < second ? 1 : -1;+ edges.set(key, edge);+ }+ }+ assert.ok([...edges.values()].every(edge => edge.count === 2 && edge.direction === 0), `${name} has exact closed, oriented edges.`);+ }+});++test('primitive validation rejects unsafe allocations and invalid shapes before sampling', () => {+ assert.throws(() => sphere(2048, 2048), /million vertices/);+ assert.throws(() => sphere(Infinity, 40), /segments/);+ assert.throws(() => sphere(64, 0), /rings/);+ assert.throws(() => torus(1e-50), /positive/);+ assert.throws(() => torus(0.1, 16, 8, 0), /arc/);+ assert.throws(() => torus(0.1, 16, 8, 1e-50), /arc/);+ assert.throws(() => torus(0.1, 16, 8, Math.PI * 3), /arc/);+ assert.throws(() => torus(0.1, 16, 8, Math.PI, NaN), /Float32/);+ assert.throws(() => cylinder(16, 0.6), /bevel/);+ assert.throws(() => cylinder(16, 0.025, 0), /bevelSegments/);+ assert.throws(() => box(-0.1), /bevel/);+ assert.throws(() => box(1e-50), /underflow/);+ assert.throws(() => box(0.08, 1000000), /subdivisions/);+});import { createModel } from '../src/model.js';test('sphere UVs preserve separate seam coordinates and cover every vertex', () => {@@ -173,7 +219,7 @@ test('model respects the renderer contract, instancing and authored bounds', ()console.log(JSON.stringify({ parts: parts.length, geometries: geometries.size, triangleCount, meshBytes, sections: sections.size, bounds: { minimum, maximum }, expandedBounds: { minimum: expandedMinimum, maximum: expandedMaximum } }));});-test('detail metadata preserves the assembled WALL-E appearance byte for byte', () => {+test('assembled WALL-E geometry and instance snapshot stays stable after exact seam closure', () => {const parts = createModel();const hash = createHash('sha256');for (const part of parts) {@@ -185,5 +231,5 @@ test('detail metadata preserves the assembled WALL-E appearance byte for byte',}}assert.equal(parts.length, 574);- assert.equal(hash.digest('hex'), '8dc74e090405d078bdde805232da69fd5a5ed20431544d53eb30968e03d9da91');+ assert.equal(hash.digest('hex'), 'e9479c0c3061a32645e5510346e964be9ac8505135c7342a83295f7373d894b0');});diff --git a/vite.lib.config.js b/vite.lib.config.jsindex d8976f0c..ea9552b2 100644--- a/vite.lib.config.js+++ b/vite.lib.config.js@@ -21,6 +21,7 @@ export default defineConfig({modeling: 'src/modeling.js',sculpt: 'src/sculpt.js',surface: 'src/surface.js',+ 'mesh-query': 'src/mesh-query.js',physics: 'src/physics.js',},formats: ['es'],