Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add vehicle kit addon: path-driven wheel spin, steering, roll, pitch and ground following

Nguyen Xuan Anc3c4de1874ee
diff --git a/.gitignore b/.gitignore
index 4278ef3c..4f69fd34 100644
--- a/.gitignore
+++ b/.gitignore
@@ -18,6 +18,7 @@ public/mesh-query.md
public/primitives.md
public/shrinkwrap.md
public/spume.md
+public/vehicle.md
public/scene-graph.md
public/modeling.md
public/animation-curves.md
diff --git a/README.md b/README.md
index 1fef3b72..e524b170 100644
--- a/README.md
+++ b/README.md
@@ -211,6 +211,8 @@ Compatible results can become relative GPU morph targets, so animation reuses th
The source [Spume addon](docs/spume.md) plays back liquid baked by the [Spume](https://github.com/codepawl/spume) GPU solver, with whitewater, through `renderer.replaceParts`.
The solver runs offline; the browser only reads the compact cache.
+The source [vehicle addon](docs/vehicle.md) drives wheeled vehicles along a path deterministically: wheel spin, steering, body roll and pitch, and ground following, for parts, scene-graph nodes or imported GLBs.
+
The current source adds [surface attachments](docs/surface-attachment.md) for rigid accessories following a selected triangle through morphing and skinning.
The retained frame uses world-space clearance and samples three bound vertices without rebuilding a BVH every frame.
This addon is available from version `0.4.1`. It does not certify clearance over an accessory's entire footprint.
diff --git a/docs/guide.md b/docs/guide.md
index 1a12525c..ed83297e 100644
--- a/docs/guide.md
+++ b/docs/guide.md
@@ -174,6 +174,18 @@ Patches and shrinkwrap are static operations. They do not follow skin or morph d
The [Spume contract](/spume.md) covers the cache format, whitewater options, placement and measured cost.
The scene must stay rigid and untextured while frames are replaced.
+## Wheeled vehicles
+
+`67js/addons/vehicle` is in the current source and not yet published. It drives a car or truck along a path with deterministic, physics-free animation.
+
+1. Describe the vehicle with `createVehicleRig({ parts })`; wheels are found by name and geometry. Check `rig.wheels` or `findWheelCandidates(names)`.
+2. Build a drive with `driveAlongPath(rig, points, { cruiseSpeed, groundHeight })`.
+3. Each frame, call `applyVehiclePoseToParts(rig, drive.sample(seconds))` and then `renderer.updateParts(parts)`.
+
+Wheel spin, front-wheel steering, roll, pitch and ground following come from the path.
+Scene-graph nodes and imported GLBs use `applyVehiclePoseToSceneGraph` and `applyVehiclePoseToAsset`.
+The [vehicle contract](/vehicle.md) lists conventions, options and limits.
+
## Retained surface attachments
`createSurfaceAttachment` is introduced in `0.4.1`. Published npm `0.4.0` does not include this addon.
diff --git a/docs/vehicle.md b/docs/vehicle.md
new file mode 100644
index 00000000..85980acc
--- /dev/null
+++ b/docs/vehicle.md
@@ -0,0 +1,111 @@
+# Vehicle kit
+
+`67js/addons/vehicle` is in the current source and not yet published.
+It animates a wheeled vehicle along a path without physics.
+Sampling the same time always returns the same pose, so frames can be rendered in any order.
+
+```js
+import { createVehicleRig, driveAlongPath, applyVehiclePoseToParts } from '67js/addons/vehicle';
+
+const rig = createVehicleRig({ parts: vehicleParts }); // wheels found by name and geometry
+const drive = driveAlongPath(rig, [[0, 0, -20], [5, 0, 0], [0, 0, 20]], {
+ cruiseSpeed: 9,
+ acceleration: 3,
+ braking: 4,
+ maxLateralAcceleration: 5,
+ groundHeight: (x, z) => terrainHeight(x, z),
+});
+
+const pose = drive.sample(seconds);
+applyVehiclePoseToParts(rig, pose);
+renderer.updateParts(allParts);
+```
+
+## Conventions
+
+- Metres, +Y up, right-handed. Angles are radians.
+- The model's forward axis is `+z` unless `forwardAxis` is `'+x'`, `'-x'` or `'-z'`.
+ Left is `up x forward`, so left is `+x` when forward is `+z`.
+- The rig builds a local frame on the ground under the centroid of the wheel centers, then moves the whole model with it.
+ The model can sit anywhere in its own space; poses are relative to its authored rest position.
+- `pose.heading` is yaw about +Y, zero when facing +z. `pitch` is positive nose up. `roll` is positive when the left side rises (leaning right), which is what a left turn produces.
+- Steering is positive toward the left.
+
+## Describing the vehicle
+
+`createVehicleRig({ parts | graph | asset, body, wheels, forwardAxis, wheelbase, maxSteerAngle })` takes exactly one source.
+
+| Source | Moved through | Wheel and body references |
+| --- | --- | --- |
+| `parts` | `part.matrix` | part objects, names or indices |
+| `graph` | `node.localMatrix` of a scene graph | node names |
+| `asset` | node overrides of a `loadGltf` asset | node labels or ids such as `node-3` |
+
+| Option | Default | Meaning |
+| --- | --- | --- |
+| `wheels` | `'auto'` | `'auto'` or an array of `{ id, part \| node \| targets, side, axle, radius, center, steerable, spinSign }` |
+| `body` | everything that is not a wheel (roots for graphs and assets) | Array of parts or nodes that move rigidly |
+| `forwardAxis` | `'+z'` | Model forward direction |
+| `wheelbase` | measured front axle to rear axle | Metres, needed when the axles cannot be measured |
+| `maxSteerAngle` | 35 degrees | Clamp for the steering angle |
+
+Per wheel: `side` is `left`, `right` or `center`, `axle` is `front` or `rear`; both are inferred from position when omitted.
+`steerable` defaults to the front axle.
+`radius` and `center` are measured from the geometry bounds when omitted.
+`spinSign: -1` fixes a wheel whose model axis is mirrored.
+A wheel can list several parts (tire, hub, bolts); they all spin and steer together.
+
+### Automatic wheels
+
+`'auto'` matches wheel, tire/tyre, rim and hub names (`Wheel.001`, `FrontLeftWheel`, `tire_FR`, `RL_tyre`).
+It reads corners from `FL FR RL RR`, `front/rear/back` and `left/right`, groups pieces of one corner, and attaches unnamed pieces that sit inside a wheel.
+Names with steering, spare, fender, arch, brake, caliper, cover or similar words are rejected.
+Check what was decided before trusting it:
+
+```js
+findWheelCandidates(names); // { wheels: [{ name, kind, axle, side, corner }], rejected: [{ name, reason }] }
+rig.wheels; // id, side, axle, radius, steerable, entries
+rig.rejectedNames; // wheel-like names that were not treated as wheels
+```
+
+## Driving
+
+`driveAlongPath(rig, path, options)` returns `{ sample(seconds), duration, length, rig }`.
+
+The path is an array of `[x, y, z]` points (smoothed with a centripetal spline) or a camera path object, whose eye track is followed.
+Speed is arc-length based. Give exactly one of:
+
+| Option | Meaning |
+| --- | --- |
+| `speed` | Constant metres per second, no ramp |
+| `cruiseSpeed` | Profile with `acceleration` (3), `braking` (4), `startSpeed` (0), `endSpeed` (0) and `maxLateralAcceleration` (unlimited) |
+
+Other options: `startTime`, `groundHeight(x, z)`, `maxSteerAngle`, `rollGain` (0.012 rad per m/s2), `pitchGain` (0.012), `bounceFrequency` (1.6 Hz), `dampingRatio` (0.45), `suspensionTravel` (0.2 m), `pathSamples` (400, for camera paths).
+
+`sample(seconds)` returns `{ time, distance, speed, position, heading, pitch, roll, steerAngle, wheels: [{ id, spinAngle, steerAngle, suspensionOffset }] }`.
+
+- Wheel spin is `distance / radius`; inside wheels in a corner turn slower by their lateral offset times the heading change.
+- Steering uses a bicycle model: `atan(wheelbase * curvature)`, clamped.
+- Roll follows lateral acceleration and pitch follows longitudinal acceleration through a spring and damper. The response is integrated at a fixed step when the drive is created, so sampling order does not matter.
+- With `groundHeight`, the body height and its slope pitch and roll are fitted to the ground under the four wheels, and each wheel gets a `suspensionOffset` so it touches the ground. Without it, height and slope come from the path.
+- The vehicle holds the end of the path with zero speed. Use `cruiseSpeed` for a natural stop; a constant `speed` stops instantly and the body pitches accordingly.
+
+## Applying a pose
+
+| Function | Effect |
+| --- | --- |
+| `applyVehiclePoseToParts(rig, pose)` | Writes `part.matrix`; then call `renderer.updateParts` |
+| `applyVehiclePoseToSceneGraph(rig, pose, graph)` | Writes node `localMatrix`, calls `graph.update()` and returns `graph.parts` |
+| `createVehicleNodeOverrides(rig, pose)` | Returns `nodeOverrides` (translation, rotation, scale) for `asset.stagePose` |
+| `applyVehiclePoseToAsset(rig, pose, asset)` | Stages the overrides and commits them |
+
+For imported GLBs, wheel and body nodes must be editable (positive translation, rotation, scale), and children of a moved node follow it.
+Skinned vehicles are not driven by this addon.
+
+## Limits
+
+- Kinematic only: no collisions, tire slip, jumps or reversing. Heading follows the path tangent.
+- Ground is sampled under the wheels as a plane fit, so sharp bumps narrower than the wheelbase show as suspension offsets, clamped to `suspensionTravel`.
+- All steerable wheels share one angle; there is no Ackermann split.
+- Nodes with a nonzero scene-graph `pivot` are rejected.
+- Wheel radius from geometry assumes the wheel is round in the plane across its axle.
diff --git a/package.json b/package.json
index 6b3e12a7..e2ee638b 100644
--- a/package.json
+++ b/package.json
@@ -42,6 +42,7 @@
"docs/mesh-query.md",
"docs/primitives.md",
"docs/shrinkwrap.md",
+ "docs/vehicle.md",
"docs/surface-attachment.md",
"docs/agent-scene.md",
"docs/mcp.md",
@@ -76,6 +77,7 @@
"./addons/surface-attachment": "./build/surface-attachment.js",
"./addons/physics": "./build/physics.js",
"./addons/spume": "./build/spume.js",
+ "./addons/vehicle": "./build/vehicle.js",
"./addons/agent-scene": "./build/agent-scene.js",
"./addons/agent-asset": "./build/agent-asset.js",
"./package.json": "./package.json"
diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjs
index 2bf49817..15929f0a 100644
--- a/scripts/prepare-release.mjs
+++ b/scripts/prepare-release.mjs
@@ -40,6 +40,7 @@ const sourceDocuments = [
'scene-graph.md', 'modeling.md', 'animation-curves.md', 'animation-mixer.md',
'gltf-morph.md', 'morph-targets.md', 'skinning.md', 'physics.md',
'export-glb.md', 'sculpt.md', 'surface.md', 'mesh-query.md', 'primitives.md', 'shrinkwrap.md', 'spume.md',
+ 'vehicle.md',
'camera-path.md', 'lighting.md', 'volumetric.md', 'film-physics.md',
'surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md', 'agent-asset.md', 'agent-render-jobs.md', 'agent-motion.md', 'agent-character-motion.md', 'agent-review.md',
];
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index 53f585d1..c4158d77 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -23,6 +23,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.
- Relative facial or shape deformation uses `src/morph.js` and the checkout's `docs/morph-targets.md`. Check source versus published support first.
- Recorded contacts or articulated physics use optional `src/physics.js` and the checkout's `docs/physics.md`.
- Baked liquid (jets, geysers, torrents, whitewater) uses optional `src/spume.js` and the checkout's `docs/spume.md`. Bake with the Spume solver first; never fake it with displaced primitives.
+- Wheeled vehicles driving a path (wheel spin, steering, body roll and pitch, ground following) use optional `src/vehicle.js` and the checkout's `docs/vehicle.md`.
- A flat scene or axis view uses `src/canvas2d.js`, `src/camera.js` and `src/view2d.js`.
- 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`.
diff --git a/src/vehicle.js b/src/vehicle.js
new file mode 100644
index 00000000..bf05c131
--- /dev/null
+++ b/src/vehicle.js
@@ -0,0 +1,897 @@
+import { mat4, vec3 } from 'gl-matrix';
+
+// Local vehicle frame: x is left, y is up, z is forward, origin on the ground under the wheel centroid.
+const FORWARD_AXES = Object.freeze({
+ '+x': [1, 0, 0],
+ '-x': [-1, 0, 0],
+ '+z': [0, 0, 1],
+ '-z': [0, 0, -1],
+});
+const UP_AXIS = Object.freeze([0, 1, 0]);
+const DEFAULT_MAX_STEER_ANGLE = 35 * Math.PI / 180;
+const MAX_BODY_ANGLE = 0.35;
+const SIMULATION_STEP_SECONDS = 1 / 240;
+const SETTLE_SECONDS = 2;
+const PATH_SPACING_METRES = 0.1;
+const MAX_PATH_SAMPLES = 20000;
+const MINIMUM_SPEED_LIMIT = 0.5;
+
+const WHEEL_WORDS = new Map([
+ ['wheel', 'wheel'], ['wheels', 'wheel'],
+ ['tire', 'tire'], ['tires', 'tire'], ['tyre', 'tire'], ['tyres', 'tire'],
+ ['rim', 'rim'], ['rims', 'rim'], ['hub', 'rim'], ['hubcap', 'rim'], ['hubcaps', 'rim'],
+]);
+const NON_ROLLING_WORDS = new Set([
+ 'steering', 'spare', 'fender', 'fenders', 'mudguard', 'arch', 'arches', 'well', 'wells',
+ 'guard', 'brake', 'brakes', 'caliper', 'rotor', 'disc', 'housing', 'cover', 'shield',
+]);
+const CORNER_WORDS = new Map([
+ ['fl', ['front', 'left']], ['fr', ['front', 'right']], ['rl', ['rear', 'left']], ['rr', ['rear', 'right']],
+ ['bl', ['rear', 'left']], ['br', ['rear', 'right']], ['lf', ['front', 'left']], ['rf', ['front', 'right']],
+ ['lr', ['rear', 'left']], ['lb', ['rear', 'left']], ['rb', ['rear', 'right']],
+]);
+const AXLE_WORDS = new Map([['front', 'front'], ['rear', 'rear'], ['back', 'rear']]);
+const SIDE_WORDS = new Map([['left', 'left'], ['l', 'left'], ['right', 'right'], ['r', 'right']]);
+
+function createMatrix() {
+ return mat4.identity(new Float64Array(16));
+}
+
+function assertFinitePositive(value, message) {
+ if (!Number.isFinite(value) || value <= 0) throw new RangeError(message);
+}
+
+function clamp(value, minimum, maximum) {
+ return Math.min(maximum, Math.max(minimum, value));
+}
+
+function nameTokens(name) {
+ return name
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
+ .toLowerCase()
+ .split(/[^a-z0-9]+/)
+ .filter(Boolean);
+}
+
+function cornerFromTokens(tokens) {
+ let axle = null;
+ let side = null;
+ for (const token of tokens) {
+ const corner = CORNER_WORDS.get(token);
+ if (corner) {
+ axle ??= corner[0];
+ side ??= corner[1];
+ }
+ axle ??= AXLE_WORDS.get(token) ?? null;
+ side ??= SIDE_WORDS.get(token) ?? null;
+ }
+ return { axle, side };
+}
+
+/**
+ * Reports which names look like rolling wheels and which wheel-like names were rejected, so an agent can confirm.
+ * Each match carries `kind` (wheel, tire or rim), `side` and `axle` when the name states them.
+ */
+export function findWheelCandidates(names) {
+ if (!Array.isArray(names) || names.some(name => typeof name !== 'string')) {
+ throw new TypeError('findWheelCandidates needs an array of name strings.');
+ }
+ const wheels = [];
+ const rejected = [];
+ names.forEach((name, index) => {
+ const tokens = nameTokens(name);
+ const wheelToken = tokens.find(token => WHEEL_WORDS.has(token));
+ if (!wheelToken) return;
+ const blocker = tokens.find(token => NON_ROLLING_WORDS.has(token));
+ if (blocker) {
+ rejected.push({ index, name, reason: `contains "${blocker}", which does not roll with the wheel` });
+ return;
+ }
+ const { axle, side } = cornerFromTokens(tokens);
+ const corner = axle && side ? `${axle}-${side}` : null;
+ wheels.push({ index, name, kind: WHEEL_WORDS.get(wheelToken), axle, side, corner });
+ });
+ return { wheels, rejected };
+}
+
+function createPartsSource(parts) {
+ if (!Array.isArray(parts) || parts.length === 0) {
+ throw new TypeError('parts must be a non-empty array of parts with a 16-value matrix.');
+ }
+ const entries = parts.map((part, index) => {
+ if (!part || !part.matrix || part.matrix.length !== 16) {
+ throw new TypeError(`Part ${index} needs a 16-value matrix.`);
+ }
+ const restWorld = Float64Array.from(part.matrix);
+ return {
+ key: part,
+ label: String(part.name ?? `part-${index}`),
+ parentKey: null,
+ restWorld,
+ meshes: part.geometry ? [{ geometry: part.geometry, matrix: restWorld }] : [],
+ };
+ });
+ return finishSource('parts', entries);
+}
+
+function createGraphSource(graph) {
+ if (!graph || !graph.nodes || graph.nodes.length === 0) {
+ throw new TypeError('graph must be a scene graph with nodes.');
+ }
+ const entries = Array.from(graph.nodes, node => {
+ const restWorld = Float64Array.from(node.worldMatrix);
+ return {
+ key: node.name,
+ label: node.name,
+ parentKey: node.parent,
+ restWorld,
+ pivot: node.pivot,
+ meshes: node.geometry ? [{ geometry: node.geometry, matrix: restWorld }] : [],
+ };
+ });
+ return finishSource('graph', entries);
+}
+
+function composeNodeMatrix(metadata) {
+ const matrix = createMatrix();
+ mat4.fromRotationTranslationScale(matrix, metadata.rotation, metadata.translation, metadata.scale);
+ return matrix;
+}
+
+function createAssetSource(asset) {
+ if (!asset || !asset.nodes || !asset.parts || typeof asset.stagePose !== 'function') {
+ throw new TypeError('asset must be a loadGltf result with nodes, parts and stagePose.');
+ }
+ const metadataById = new Map(asset.nodes.map(metadata => [metadata.id, metadata]));
+ const worlds = new Map();
+ function worldOf(id) {
+ if (worlds.has(id)) return worlds.get(id);
+ const metadata = metadataById.get(id);
+ const local = composeNodeMatrix(metadata);
+ const world = metadata.parent === null ? local : mat4.multiply(createMatrix(), worldOf(metadata.parent), local);
+ worlds.set(id, world);
+ return world;
+ }
+ const entries = asset.nodes.map(metadata => ({
+ key: metadata.id,
+ label: metadata.label,
+ parentKey: metadata.parent,
+ restWorld: worldOf(metadata.id),
+ editable: metadata.editable,
+ meshes: (metadata.meshIds ?? []).map(meshId => {
+ const part = asset.parts[Number(meshId.slice(5))];
+ return { geometry: part.geometry, matrix: Float64Array.from(part.matrix) };
+ }),
+ }));
+ return finishSource('asset', entries);
+}
+
+function finishSource(kind, entries) {
+ const byKey = new Map(entries.map(entry => [entry.key, entry]));
+ for (const entry of entries) entry.childKeys = [];
+ for (const entry of entries) {
+ if (entry.parentKey !== null && byKey.has(entry.parentKey)) byKey.get(entry.parentKey).childKeys.push(entry.key);
+ }
+ return { kind, entries, byKey };
+}
+
+function createSource({ parts, graph, asset }) {
+ const supplied = [parts, graph, asset].filter(value => value !== undefined);
+ if (supplied.length !== 1) {
+ throw new TypeError('createVehicleRig needs exactly one of parts, graph or asset.');
+ }
+ if (parts !== undefined) return createPartsSource(parts);
+ if (graph !== undefined) return createGraphSource(graph);
+ return createAssetSource(asset);
+}
+
+function resolveEntry(source, reference) {
+ if (source.byKey.has(reference)) return source.byKey.get(reference);
+ if (Number.isInteger(reference) && source.kind === 'parts' && source.entries[reference]) return source.entries[reference];
+ if (typeof reference === 'string') {
+ const matches = source.entries.filter(entry => entry.label === reference);
+ if (matches.length === 1) return matches[0];
+ if (matches.length > 1) throw new RangeError(`Vehicle ${source.kind} name is ambiguous: ${reference}`);
+ }
+ throw new RangeError(`Vehicle ${source.kind} was not found: ${String(reference?.name ?? reference)}`);
+}
+
+function collectMeshes(source, entry, meshes = []) {
+ meshes.push(...entry.meshes);
+ for (const childKey of entry.childKeys) collectMeshes(source, source.byKey.get(childKey), meshes);
+ return meshes;
+}
+
+function meshBounds(meshes) {
+ const minimum = [Infinity, Infinity, Infinity];
+ const maximum = [-Infinity, -Infinity, -Infinity];
+ const point = vec3.create();
+ for (const { geometry, matrix } of meshes) {
+ const positions = geometry.positions;
+ for (let offset = 0; offset + 2 < positions.length; offset += 3) {
+ vec3.set(point, positions[offset], positions[offset + 1], positions[offset + 2]);
+ vec3.transformMat4(point, point, matrix);
+ for (let axis = 0; axis < 3; axis++) {
+ minimum[axis] = Math.min(minimum[axis], point[axis]);
+ maximum[axis] = Math.max(maximum[axis], point[axis]);
+ }
+ }
+ }
+ return Number.isFinite(minimum[0]) ? { minimum, maximum } : null;
+}
+
+function extentAlong(bounds, axisVector) {
+ let extent = 0;
+ for (let axis = 0; axis < 3; axis++) {
+ extent += Math.abs(axisVector[axis]) * (bounds.maximum[axis] - bounds.minimum[axis]);
+ }
+ return extent;
+}
+
+function measureWheel(bounds, forward) {
+ const center = bounds.minimum.map((value, axis) => (value + bounds.maximum[axis]) / 2);
+ const radius = Math.max(extentAlong(bounds, UP_AXIS), extentAlong(bounds, forward)) / 2;
+ return { center, radius };
+}
+
+function isDescendantOfAny(source, entry, keys) {
+ let parentKey = entry.parentKey;
+ while (parentKey !== null && source.byKey.has(parentKey)) {
+ if (keys.has(parentKey)) return true;
+ parentKey = source.byKey.get(parentKey).parentKey;
+ }
+ return false;
+}
+
+function detectWheelGroups(source, forward) {
+ const labels = source.entries.map(entry => entry.label);
+ const { wheels: candidates, rejected } = findWheelCandidates(labels);
+ const candidateKeys = new Set(candidates.map(candidate => source.entries[candidate.index].key));
+ const independent = candidates.filter(candidate => !isDescendantOfAny(source, source.entries[candidate.index], candidateKeys));
+ const groups = new Map();
+ const loose = [];
+ for (const candidate of independent) {
+ if (candidate.corner) {
+ const group = groups.get(candidate.corner) ?? { id: candidate.corner, axle: candidate.axle, side: candidate.side, entries: [] };
+ group.entries.push(source.entries[candidate.index]);
+ groups.set(candidate.corner, group);
+ } else {
+ loose.push(source.entries[candidate.index]);
+ }
+ }
+ const measured = entry => {
+ const bounds = meshBounds(collectMeshes(source, entry));
+ return bounds ? { entry, ...measureWheel(bounds, forward) } : { entry, center: null, radius: 0 };
+ };
+ const clusters = Array.from(groups.values()).map(group => {
+ const largest = group.entries.map(measured).sort((first, second) => second.radius - first.radius)[0];
+ return { ...group, center: largest.center, radius: largest.radius };
+ });
+ for (const item of loose.map(measured).sort((first, second) => second.radius - first.radius)) {
+ const home = item.center && clusters.find(cluster => cluster.center && vec3.distance(cluster.center, item.center) < cluster.radius * 0.6);
+ if (home) {
+ home.entries.push(item.entry);
+ } else {
+ clusters.push({ id: `wheel-${clusters.length}`, axle: null, side: null, entries: [item.entry], center: item.center, radius: item.radius });
+ }
+ }
+ return { groups: clusters, rejected };
+}
+
+function normalizeWheelSpec(source, spec, index) {
+ const references = spec.targets ?? spec.parts ?? spec.nodes ?? [spec.target ?? spec.part ?? spec.node];
+ if (!Array.isArray(references) || references.length === 0 || references.includes(undefined)) {
+ throw new TypeError(`Wheel ${index} needs a part, node or targets list.`);
+ }
+ const entries = references.map(reference => resolveEntry(source, reference));
+ return { id: spec.id ?? entries[0].label, entries, axle: spec.axle, side: spec.side, spec };
+}
+
+function describeWheels(source, wheelOption, forward) {
+ if (wheelOption === undefined || wheelOption === 'auto') {
+ const { groups, rejected } = detectWheelGroups(source, forward);
+ return { described: groups.map(group => ({ id: group.id, entries: group.entries, axle: group.axle, side: group.side, spec: {} })), rejected };
+ }
+ if (!Array.isArray(wheelOption)) throw new TypeError("wheels must be an array of wheel descriptions or 'auto'.");
+ return { described: wheelOption.map((spec, index) => normalizeWheelSpec(source, spec, index)), rejected: [] };
+}
+
+function measureDescribedWheel(source, described, forward) {
+ const bounds = meshBounds(described.entries.flatMap(entry => collectMeshes(source, entry)));
+ const measured = bounds ? measureWheel(bounds, forward) : null;
+ const center = described.spec.center ?? measured?.center;
+ const radius = described.spec.radius ?? measured?.radius;
+ if (!center || radius === undefined) {
+ throw new RangeError(`Wheel ${described.id} needs a radius and center, or geometry to measure them from.`);
+ }
+ if (center.length !== 3 || !Array.from(center).every(Number.isFinite)) {
+ throw new RangeError(`Wheel ${described.id} center must be three finite numbers.`);
+ }
+ assertFinitePositive(radius, `Wheel ${described.id} radius must be positive and finite.`);
+ return { ...described, center: Array.from(center), radius };
+}
+
+function createRestFrame(left, forward, anchor) {
+ const frame = createMatrix();
+ frame.set([...left, 0, ...UP_AXIS, 0, ...forward, 0, ...anchor, 1]);
+ return frame;
+}
+
+function mean(values) {
+ return values.reduce((total, value) => total + value, 0) / values.length;
+}
+
+function resolveWheelLayout(measuredWheels, forward) {
+ const left = vec3.cross(vec3.create(), UP_AXIS, forward);
+ const centroid = [0, 1, 2].map(axis => mean(measuredWheels.map(wheel => wheel.center[axis])));
+ const anchor = vec3.scaleAndAdd(vec3.create(), centroid, UP_AXIS, -mean(measuredWheels.map(wheel => wheel.radius)));
+ const restFrame = createRestFrame(left, forward, anchor);
+ const inverseRestFrame = mat4.invert(createMatrix(), restFrame);
+ const wheels = measuredWheels.map((wheel, index) => {
+ const centerLocal = vec3.transformMat4(vec3.create(), wheel.center, inverseRestFrame);
+ const side = wheel.side ?? (Math.abs(centerLocal[0]) < 1e-4 ? 'center' : centerLocal[0] > 0 ? 'left' : 'right');
+ const axle = wheel.axle ?? (centerLocal[2] >= 0 ? 'front' : 'rear');
+ if (!['left', 'right', 'center'].includes(side)) throw new RangeError(`Wheel ${wheel.id} side must be left, right or center.`);
+ if (!['front', 'rear'].includes(axle)) throw new RangeError(`Wheel ${wheel.id} axle must be front or rear.`);
+ const spinSign = wheel.spec.spinSign ?? 1;
+ if (spinSign !== 1 && spinSign !== -1) throw new RangeError(`Wheel ${wheel.id} spinSign must be 1 or -1.`);
+ return {
+ id: wheel.id || `wheel-${index}`,
+ entries: wheel.entries,
+ side,
+ axle,
+ radius: wheel.radius,
+ steerable: wheel.spec.steerable ?? axle === 'front',
+ spinSign,
+ centerLocal: Array.from(centerLocal),
+ };
+ });
+ return { wheels, restFrame, inverseRestFrame };
+}
+
+function resolveWheelbase(wheels, wheelbaseOption) {
+ if (wheelbaseOption !== undefined) {
+ assertFinitePositive(wheelbaseOption, 'wheelbase must be positive and finite.');
+ return wheelbaseOption;
+ }
+ const front = wheels.filter(wheel => wheel.axle === 'front');
+ const rear = wheels.filter(wheel => wheel.axle === 'rear');
+ if (front.length && rear.length) {
+ const distance = mean(front.map(wheel => wheel.centerLocal[2])) - mean(rear.map(wheel => wheel.centerLocal[2]));
+ if (distance > 1e-6) return distance;
+ }
+ if (wheels.some(wheel => wheel.steerable)) {
+ throw new RangeError('Cannot measure the wheelbase from the wheels. Pass wheelbase in metres or mark axles front and rear.');
+ }
+ return 0;
+}
+
+function resolveBodyEntries(source, bodyOption, wheels) {
+ if (bodyOption !== undefined) {
+ if (!Array.isArray(bodyOption) || bodyOption.length === 0) throw new TypeError('body must be a non-empty array of parts or nodes.');
+ return bodyOption.map(reference => resolveEntry(source, reference));
+ }
+ const wheelKeys = new Set(wheels.flatMap(wheel => wheel.entries.map(entry => entry.key)));
+ const bodyEntries = source.entries.filter(entry => !wheelKeys.has(entry.key) && !isDescendantOfAny(source, entry, wheelKeys) &&
+ (source.kind === 'parts' || entry.parentKey === null));
+ if (bodyEntries.length === 0) throw new RangeError('No body parts remain after removing the wheels. Pass body explicitly.');
+ return bodyEntries;
+}
+
+function assertNoPivot(entries) {
+ for (const entry of entries) {
+ if (entry.pivot && entry.pivot.some(component => component !== 0)) {
+ throw new RangeError(`Vehicle node ${entry.label} has a nonzero pivot, which vehicle poses do not support.`);
+ }
+ }
+}
+
+/**
+ * Describes a vehicle: a rigid body plus wheels, found in `parts`, a scene `graph` or a loaded glTF `asset`.
+ * `wheels` is an array of `{ id, part|node|targets, side, axle, radius, center, steerable, spinSign }` or 'auto'.
+ */
+export function createVehicleRig({ parts, graph, asset, body, wheels = 'auto', forwardAxis = '+z', wheelbase, maxSteerAngle = DEFAULT_MAX_STEER_ANGLE } = {}) {
+ const forward = FORWARD_AXES[forwardAxis];
+ if (!forward) throw new RangeError('forwardAxis must be one of +x, -x, +z or -z.');
+ assertFinitePositive(maxSteerAngle, 'maxSteerAngle must be positive radians.');
+ const source = createSource({ parts, graph, asset });
+ const { described, rejected } = describeWheels(source, wheels, forward);
+ if (described.length < 2) {
+ throw new RangeError(`A vehicle rig needs at least two wheels, found ${described.length}. Pass wheels explicitly or check findWheelCandidates.`);
+ }
+ const measuredWheels = described.map(item => measureDescribedWheel(source, item, forward));
+ const layout = resolveWheelLayout(measuredWheels, forward);
+ const bodyEntries = resolveBodyEntries(source, body, layout.wheels);
+ assertNoPivot([...bodyEntries, ...layout.wheels.flatMap(wheel => wheel.entries)]);
+ return Object.freeze({
+ kind: source.kind,
+ source,
+ forwardAxis,
+ wheelbase: resolveWheelbase(layout.wheels, wheelbase),
+ maxSteerAngle,
+ restFrame: layout.restFrame,
+ inverseRestFrame: layout.inverseRestFrame,
+ bodyEntries,
+ wheels: Object.freeze(layout.wheels),
+ rejectedNames: rejected,
+ });
+}
+
+function validatePoint(point, index) {
+ if ((!Array.isArray(point) && !ArrayBuffer.isView(point)) || point.length !== 3 || !Array.from(point).every(Number.isFinite)) {
+ throw new TypeError(`Path point ${index} must be three finite numbers.`);
+ }
+}
+
+function pointsFromPath(path, pathSamples) {
+ if (Array.isArray(path)) return path.map(point => Array.from(point));
+ if (path && typeof path.sample === 'function' && Number.isFinite(path.duration) && path.duration > 0) {
+ const points = [];
+ for (let index = 0; index <= pathSamples; index++) {
+ points.push(Array.from(path.sample(path.duration * index / pathSamples).eye));
+ }
+ return points;
+ }
+ throw new TypeError('Path must be an array of [x, y, z] points or a camera path with duration and sample(time).');
+}
+
+function removeRepeatedPoints(points) {
+ return points.filter((point, index) => index === 0 || vec3.distance(point, points[index - 1]) > 1e-6);
+}
+
+function centripetalPoint(points, parameters, time) {
+ const blend = (first, second, firstTime, secondTime) => {
+ const span = secondTime - firstTime;
+ return first.map((value, axis) => (secondTime - time) / span * value + (time - firstTime) / span * second[axis]);
+ };
+ const [point0, point1, point2, point3] = points;
+ const [time0, time1, time2, time3] = parameters;
+ const first = blend(point0, point1, time0, time1);
+ const second = blend(point1, point2, time1, time2);
+ const third = blend(point2, point3, time2, time3);
+ return blend(blend(first, second, time0, time2), blend(second, third, time1, time3), time1, time2);
+}
+
+function splinePolyline(points) {
+ if (points.length === 2) return points;
+ const reflected = (inner, outer) => inner.map((value, axis) => 2 * value - outer[axis]);
+ const padded = [reflected(points[0], points[1]), ...points, reflected(points.at(-1), points.at(-2))];
+ const polyline = [points[0]];
+ for (let segment = 1; segment < padded.length - 2; segment++) {
+ const control = padded.slice(segment - 1, segment + 3);
+ const parameters = [0];
+ for (let index = 1; index < 4; index++) {
+ parameters.push(parameters[index - 1] + Math.sqrt(vec3.distance(control[index - 1], control[index])));
+ }
+ const count = clamp(Math.ceil(vec3.distance(control[1], control[2]) / 0.05), 8, 2000);
+ for (let step = 1; step <= count; step++) {
+ polyline.push(centripetalPoint(control, parameters, parameters[1] + (parameters[2] - parameters[1]) * step / count));
+ }
+ }
+ return polyline;
+}
+
+function resampleUniformly(polyline) {
+ const lengths = [0];
+ for (let index = 1; index < polyline.length; index++) {
+ lengths.push(lengths[index - 1] + vec3.distance(polyline[index - 1], polyline[index]));
+ }
+ const total = lengths.at(-1);
+ if (!(total > 1e-6)) throw new RangeError('Path has zero length.');
+ const intervals = Math.max(2, Math.ceil(total / Math.max(PATH_SPACING_METRES, total / MAX_PATH_SAMPLES)));
+ const spacing = total / intervals;
+ const positions = [];
+ let segment = 0;
+ for (let index = 0; index <= intervals; index++) {
+ const distance = index * spacing;
+ while (segment < polyline.length - 2 && lengths[segment + 1] < distance) segment++;
+ const span = lengths[segment + 1] - lengths[segment];
+ const fraction = span > 0 ? clamp((distance - lengths[segment]) / span, 0, 1) : 0;
+ positions.push(polyline[segment].map((value, axis) => value + (polyline[segment + 1][axis] - value) * fraction));
+ }
+ return { positions, spacing, length: total };
+}
+
+function smoothed(values, radius) {
+ return values.map((_, index) => {
+ const first = Math.max(0, index - radius);
+ const last = Math.min(values.length - 1, index + radius);
+ let total = 0;
+ for (let neighbour = first; neighbour <= last; neighbour++) total += values[neighbour];
+ return total / (last - first + 1);
+ });
+}
+
+function buildPathTable(path, pathSamples) {
+ const points = pointsFromPath(path, pathSamples);
+ points.forEach(validatePoint);
+ const distinct = removeRepeatedPoints(points);
+ if (distinct.length < 2) throw new RangeError('Path needs at least two distinct points.');
+ const { positions, spacing, length } = resampleUniformly(splinePolyline(distinct));
+ const headings = [];
+ const slopes = [];
+ positions.forEach((_, index) => {
+ const before = positions[Math.max(0, index - 1)];
+ const after = positions[Math.min(positions.length - 1, index + 1)];
+ const horizontal = Math.hypot(after[0] - before[0], after[2] - before[2]);
+ let heading = horizontal > 1e-9 ? Math.atan2(after[0] - before[0], after[2] - before[2]) : (headings.at(-1) ?? 0);
+ if (index > 0) heading += Math.round((headings[index - 1] - heading) / (2 * Math.PI)) * 2 * Math.PI;
+ headings.push(heading);
+ slopes.push(horizontal > 1e-9 ? Math.atan2(after[1] - before[1], horizontal) : 0);
+ });
+ const rawCurvature = headings.map((heading, index) => {
+ const before = Math.max(0, index - 1);
+ const after = Math.min(headings.length - 1, index + 1);
+ return (headings[after] - headings[before]) / ((after - before) * spacing);
+ });
+ return { positions, headings, slopes, curvature: smoothed(rawCurvature, 5), spacing, length };
+}
+
+function createSpeedProfile(table, options) {
+ const { cruiseSpeed, acceleration, braking, startSpeed, endSpeed, maxLateralAcceleration } = options;
+ const count = table.positions.length;
+ const limitSquared = table.curvature.map(curvature => {
+ const lateralLimit = maxLateralAcceleration / Math.max(Math.abs(curvature), 1e-9);
+ return Math.min(cruiseSpeed ** 2, Math.max(lateralLimit, MINIMUM_SPEED_LIMIT ** 2));
+ });
+ const speedSquared = Float64Array.from(limitSquared);
+ speedSquared[0] = Math.min(startSpeed ** 2, limitSquared[0]);
+ for (let index = 1; index < count; index++) {
+ speedSquared[index] = Math.min(speedSquared[index], speedSquared[index - 1] + 2 * acceleration * table.spacing);
+ }
+ speedSquared[count - 1] = Math.min(speedSquared[count - 1], endSpeed ** 2);
+ for (let index = count - 2; index >= 0; index--) {
+ speedSquared[index] = Math.min(speedSquared[index], speedSquared[index + 1] + 2 * braking * table.spacing);
+ }
+ const speeds = speedSquared.map(Math.sqrt);
+ const times = new Float64Array(count);
+ for (let index = 1; index < count; index++) {
+ const meanSpeed = (speeds[index - 1] + speeds[index]) / 2;
+ if (meanSpeed < 1e-9) throw new RangeError('The speed profile never leaves rest. Raise acceleration or startSpeed.');
+ times[index] = times[index - 1] + table.spacing / meanSpeed;
+ }
+ return { speeds, times, duration: times[count - 1] };
+}
+
+function findInterval(times, time) {
+ let low = 0;
+ let high = times.length - 1;
+ while (high - low > 1) {
+ const middle = (low + high) >> 1;
+ if (times[middle] <= time) low = middle;
+ else high = middle;
+ }
+ return low;
+}
+
+function createMotion(table, options) {
+ const startTime = options.startTime;
+ if (options.speed !== undefined) {
+ const duration = table.length / options.speed;
+ return {
+ duration: startTime + duration,
+ distanceAt: time => clamp((time - startTime) * options.speed, 0, table.length),
+ speedAt: time => (time > startTime && time < startTime + duration ? options.speed : 0),
+ };
+ }
+ const profile = createSpeedProfile(table, options);
+ const spacing = table.spacing;
+ function intervalAt(time) {
+ const index = findInterval(profile.times, time);
+ const startSpeedSquared = profile.speeds[index] ** 2;
+ const endSpeedSquared = profile.speeds[index + 1] ** 2;
+ return { index, elapsed: time - profile.times[index], acceleration: (endSpeedSquared - startSpeedSquared) / (2 * spacing) };
+ }
+ return {
+ duration: startTime + profile.duration,
+ distanceAt(time) {
+ const local = time - startTime;
+ if (local <= 0) return 0;
+ if (local >= profile.duration) return table.length;
+ const { index, elapsed, acceleration } = intervalAt(local);
+ return index * spacing + profile.speeds[index] * elapsed + 0.5 * acceleration * elapsed ** 2;
+ },
+ speedAt(time) {
+ const local = time - startTime;
+ if (local <= 0 || local >= profile.duration) return 0;
+ const { index, elapsed, acceleration } = intervalAt(local);
+ return Math.max(0, profile.speeds[index] + acceleration * elapsed);
+ },
+ };
+}
+
+function interpolateTable(values, spacing, distance) {
+ const position = clamp(distance / spacing, 0, values.length - 1);
+ const index = Math.min(Math.floor(position), values.length - 2);
+ const fraction = position - index;
+ const first = values[index];
+ const second = values[index + 1];
+ return Array.isArray(first) ? first.map((value, axis) => value + (second[axis] - value) * fraction) : first + (second - first) * fraction;
+}
+
+function integrateBodyMotion(table, motion, options) {
+ const steps = Math.ceil((motion.duration + SETTLE_SECONDS) / SIMULATION_STEP_SECONDS) + 1;
+ const pitches = new Float64Array(steps);
+ const rolls = new Float64Array(steps);
+ const omega = 2 * Math.PI * options.bounceFrequency;
+ const damping = 2 * options.dampingRatio * omega;
+ let pitch = 0;
+ let roll = 0;
+ let pitchRate = 0;
+ let rollRate = 0;
+ for (let step = 0; step < steps; step++) {
+ const time = step * SIMULATION_STEP_SECONDS;
+ const speed = motion.speedAt(time);
+ const longitudinal = (motion.speedAt(time + SIMULATION_STEP_SECONDS) - motion.speedAt(time - SIMULATION_STEP_SECONDS)) / (2 * SIMULATION_STEP_SECONDS);
+ const curvature = interpolateTable(table.curvature, table.spacing, motion.distanceAt(time));
+ const pitchTarget = clamp(options.pitchGain * longitudinal, -MAX_BODY_ANGLE, MAX_BODY_ANGLE);
+ const rollTarget = clamp(options.rollGain * speed * speed * curvature, -MAX_BODY_ANGLE, MAX_BODY_ANGLE);
+ pitchRate += (omega ** 2 * (pitchTarget - pitch) - damping * pitchRate) * SIMULATION_STEP_SECONDS;
+ rollRate += (omega ** 2 * (rollTarget - roll) - damping * rollRate) * SIMULATION_STEP_SECONDS;
+ pitch += pitchRate * SIMULATION_STEP_SECONDS;
+ roll += rollRate * SIMULATION_STEP_SECONDS;
+ pitches[step] = pitch;
+ rolls[step] = roll;
+ }
+ return { pitches, rolls };
+}
+
+function groundPlane(rig, position, heading, groundHeight) {
+ const cosine = Math.cos(heading);
+ const sine = Math.sin(heading);
+ const samples = rig.wheels.map(wheel => {
+ const [left, , forward] = wheel.centerLocal;
+ const x = position[0] + left * cosine + forward * sine;
+ const z = position[2] - left * sine + forward * cosine;
+ return { left, forward, height: readGroundHeight(groundHeight, x, z) };
+ });
+ const meanLeft = mean(samples.map(sample => sample.left));
+ const meanForward = mean(samples.map(sample => sample.forward));
+ const meanHeight = mean(samples.map(sample => sample.height));
+ let leftLeft = 0;
+ let forwardForward = 0;
+ let leftForward = 0;
+ let leftHeight = 0;
+ let forwardHeight = 0;
+ for (const sample of samples) {
+ const left = sample.left - meanLeft;
+ const forward = sample.forward - meanForward;
+ const height = sample.height - meanHeight;
+ leftLeft += left * left;
+ forwardForward += forward * forward;
+ leftForward += left * forward;
+ leftHeight += left * height;
+ forwardHeight += forward * height;
+ }
+ const determinant = leftLeft * forwardForward - leftForward ** 2;
+ const wellPosed = determinant > 1e-9 * Math.max(1, leftLeft * forwardForward);
+ const leftSlope = wellPosed ? (leftHeight * forwardForward - forwardHeight * leftForward) / determinant : 0;
+ const forwardSlope = wellPosed ? (forwardHeight * leftLeft - leftHeight * leftForward) / determinant : 0;
+ return {
+ height: meanHeight - leftSlope * meanLeft - forwardSlope * meanForward,
+ pitch: Math.atan(forwardSlope),
+ roll: Math.atan(leftSlope),
+ };
+}
+
+function readGroundHeight(groundHeight, x, z) {
+ const height = groundHeight(x, z);
+ if (!Number.isFinite(height)) throw new TypeError('groundHeight must return a finite number.');
+ return height;
+}
+
+function bodyWorldMatrix(position, heading, pitch, roll) {
+ const matrix = mat4.fromTranslation(createMatrix(), position);
+ mat4.rotateY(matrix, matrix, heading);
+ mat4.rotateX(matrix, matrix, -pitch);
+ mat4.rotateZ(matrix, matrix, roll);
+ return matrix;
+}
+
+function suspensionOffsets(rig, bodyMatrix, groundHeight, travel) {
+ const point = vec3.create();
+ const uprightness = Math.max(0.5, bodyMatrix[5]);
+ return rig.wheels.map(wheel => {
+ if (!groundHeight) return 0;
+ vec3.transformMat4(point, wheel.centerLocal, bodyMatrix);
+ const wanted = readGroundHeight(groundHeight, point[0], point[2]) + wheel.radius;
+ return clamp((wanted - point[1]) / uprightness, -travel, travel);
+ });
+}
+
+/**
+ * Builds a deterministic drive along a path. `sample(seconds)` returns the same pose for the same time.
+ * Speed is `speed` (constant, m/s) or a profile: `cruiseSpeed`, `acceleration`, `braking`, `startSpeed`, `endSpeed`,
+ * `maxLateralAcceleration`. The vehicle holds the path end once it arrives.
+ */
+export function driveAlongPath(rig, path, options = {}) {
+ if (!rig || !rig.wheels || !rig.restFrame) throw new TypeError('driveAlongPath needs a rig from createVehicleRig.');
+ const settings = resolveDriveOptions(rig, options);
+ const table = buildPathTable(path, settings.pathSamples);
+ const motion = createMotion(table, settings);
+ const dynamics = integrateBodyMotion(table, motion, settings);
+ const maxSteer = settings.maxSteerAngle;
+
+ function sample(seconds) {
+ if (!Number.isFinite(seconds)) throw new RangeError('Sample time must be finite.');
+ const distance = motion.distanceAt(seconds);
+ const heading = interpolateTable(table.headings, table.spacing, distance);
+ const curvature = interpolateTable(table.curvature, table.spacing, distance);
+ const headingChange = heading - table.headings[0];
+ const dynamicIndex = clamp(seconds, 0, (dynamics.pitches.length - 1) * SIMULATION_STEP_SECONDS) / SIMULATION_STEP_SECONDS;
+ const lower = Math.min(Math.floor(dynamicIndex), dynamics.pitches.length - 2);
+ const blend = dynamicIndex - lower;
+ const dynamicPitch = dynamics.pitches[lower] + (dynamics.pitches[lower + 1] - dynamics.pitches[lower]) * blend;
+ const dynamicRoll = dynamics.rolls[lower] + (dynamics.rolls[lower + 1] - dynamics.rolls[lower]) * blend;
+ const position = interpolateTable(table.positions, table.spacing, distance);
+ let slopePitch = interpolateTable(table.slopes, table.spacing, distance);
+ let slopeRoll = 0;
+ if (settings.groundHeight) {
+ const plane = groundPlane(rig, position, heading, settings.groundHeight);
+ position[1] = plane.height;
+ slopePitch = plane.pitch;
+ slopeRoll = plane.roll;
+ }
+ const pitch = slopePitch + dynamicPitch;
+ const roll = slopeRoll + dynamicRoll;
+ const bodyMatrix = bodyWorldMatrix(position, heading, pitch, roll);
+ const offsets = suspensionOffsets(rig, bodyMatrix, settings.groundHeight, settings.suspensionTravel);
+ const steerAngle = clamp(Math.atan(rig.wheelbase * curvature), -maxSteer, maxSteer);
+ return {
+ time: seconds,
+ distance,
+ speed: motion.speedAt(seconds),
+ position,
+ heading,
+ pitch,
+ roll,
+ steerAngle,
+ wheels: rig.wheels.map((wheel, index) => ({
+ id: wheel.id,
+ spinAngle: wheel.spinSign * (distance - wheel.centerLocal[0] * headingChange) / wheel.radius,
+ steerAngle: wheel.steerable ? steerAngle : 0,
+ suspensionOffset: offsets[index],
+ })),
+ };
+ }
+
+ return Object.freeze({ rig, length: table.length, duration: motion.duration, sample });
+}
+
+function resolveDriveOptions(rig, options) {
+ const {
+ speed, cruiseSpeed, acceleration = 3, braking = 4, startSpeed = 0, endSpeed = 0, maxLateralAcceleration = Infinity,
+ startTime = 0, groundHeight, maxSteerAngle = rig.maxSteerAngle, rollGain = 0.012, pitchGain = 0.012,
+ bounceFrequency = 1.6, dampingRatio = 0.45, suspensionTravel = 0.2, pathSamples = 400,
+ } = options;
+ if ((speed === undefined) === (cruiseSpeed === undefined)) {
+ throw new TypeError('Give exactly one of speed (constant) or cruiseSpeed (with acceleration and braking).');
+ }
+ if (speed !== undefined) assertFinitePositive(speed, 'speed must be positive and finite.');
+ if (cruiseSpeed !== undefined) {
+ assertFinitePositive(cruiseSpeed, 'cruiseSpeed must be positive and finite.');
+ assertFinitePositive(acceleration, 'acceleration must be positive and finite.');
+ assertFinitePositive(braking, 'braking must be positive and finite.');
+ }
+ if (!Number.isFinite(startTime) || startTime < 0) throw new RangeError('startTime must be zero or positive.');
+ if (groundHeight !== undefined && typeof groundHeight !== 'function') throw new TypeError('groundHeight must be a function (x, z) => height.');
+ assertFinitePositive(maxSteerAngle, 'maxSteerAngle must be positive radians.');
+ assertFinitePositive(bounceFrequency, 'bounceFrequency must be positive.');
+ assertFinitePositive(dampingRatio, 'dampingRatio must be positive.');
+ if (!Number.isFinite(startSpeed) || startSpeed < 0 || !Number.isFinite(endSpeed) || endSpeed < 0) {
+ throw new RangeError('startSpeed and endSpeed must be zero or positive.');
+ }
+ if (!(maxLateralAcceleration > 0)) throw new RangeError('maxLateralAcceleration must be positive.');
+ if (!Number.isInteger(pathSamples) || pathSamples < 8) throw new RangeError('pathSamples must be an integer of at least 8.');
+ return {
+ speed, cruiseSpeed, acceleration, braking, startSpeed, endSpeed, maxLateralAcceleration, startTime, groundHeight,
+ maxSteerAngle, rollGain, pitchGain, bounceFrequency, dampingRatio, suspensionTravel, pathSamples,
+ };
+}
+
+function wheelMotionMatrix(wheel, wheelPose) {
+ const matrix = mat4.fromTranslation(createMatrix(), [0, wheelPose.suspensionOffset, 0]);
+ mat4.translate(matrix, matrix, wheel.centerLocal);
+ mat4.rotateY(matrix, matrix, wheelPose.steerAngle);
+ mat4.rotateX(matrix, matrix, wheelPose.spinAngle);
+ mat4.translate(matrix, matrix, wheel.centerLocal.map(value => -value));
+ return matrix;
+}
+
+/** World matrices for every moved entry, keyed by the entry key (part object, node name or glTF node id). */
+function computeTargetWorlds(rig, pose) {
+ if (!pose || !Array.isArray(pose.wheels) || pose.wheels.length !== rig.wheels.length) {
+ throw new TypeError('pose must come from drive.sample for this rig.');
+ }
+ const bodyMatrix = bodyWorldMatrix(pose.position, pose.heading, pose.pitch, pose.roll);
+ const bodyFromModel = mat4.multiply(createMatrix(), bodyMatrix, rig.inverseRestFrame);
+ const worlds = new Map();
+ for (const entry of rig.bodyEntries) {
+ worlds.set(entry.key, mat4.multiply(createMatrix(), bodyFromModel, entry.restWorld));
+ }
+ rig.wheels.forEach((wheel, index) => {
+ const wheelFromModel = mat4.multiply(createMatrix(), bodyMatrix, wheelMotionMatrix(wheel, pose.wheels[index]));
+ mat4.multiply(wheelFromModel, wheelFromModel, rig.inverseRestFrame);
+ for (const entry of wheel.entries) {
+ worlds.set(entry.key, mat4.multiply(createMatrix(), wheelFromModel, entry.restWorld));
+ }
+ });
+ return worlds;
+}
+
+function assertKind(rig, kind) {
+ if (rig.kind !== kind) throw new TypeError(`This rig was built from ${rig.kind}, not ${kind}.`);
+}
+
+/** Writes sampled world matrices into the part.matrix of a rig built from `parts`. Returns the moved parts. */
+export function applyVehiclePoseToParts(rig, pose) {
+ assertKind(rig, 'parts');
+ const worlds = computeTargetWorlds(rig, pose);
+ const moved = [];
+ for (const [part, world] of worlds) {
+ part.matrix.set(world);
+ moved.push(part);
+ }
+ return moved;
+}
+
+function createLocalMatrixResolver(rig, worlds) {
+ const { byKey } = rig.source;
+ const memo = new Map();
+ function newWorld(key) {
+ if (worlds.has(key)) return worlds.get(key);
+ if (memo.has(key)) return memo.get(key);
+ const entry = byKey.get(key);
+ let world = entry.restWorld;
+ if (entry.parentKey !== null && byKey.has(entry.parentKey)) {
+ const parentRest = byKey.get(entry.parentKey).restWorld;
+ const restLocal = mat4.multiply(createMatrix(), mat4.invert(createMatrix(), parentRest), entry.restWorld);
+ world = mat4.multiply(createMatrix(), newWorld(entry.parentKey), restLocal);
+ }
+ memo.set(key, world);
+ return world;
+ }
+ return function localMatrix(entry, world) {
+ if (entry.parentKey === null || !byKey.has(entry.parentKey)) return Float64Array.from(world);
+ const inverseParent = mat4.invert(createMatrix(), newWorld(entry.parentKey));
+ return mat4.multiply(createMatrix(), inverseParent, world);
+ };
+}
+
+/** Writes sampled poses into the localMatrix of scene-graph nodes and calls graph.update(). Returns graph.parts. */
+export function applyVehiclePoseToSceneGraph(rig, pose, graph) {
+ assertKind(rig, 'graph');
+ const worlds = computeTargetWorlds(rig, pose);
+ const localMatrix = createLocalMatrixResolver(rig, worlds);
+ for (const [name, world] of worlds) {
+ graph.getNode(name).localMatrix.set(localMatrix(rig.source.byKey.get(name), world));
+ }
+ return graph.update();
+}
+
+/** Node overrides for `asset.stagePose({ nodeOverrides })` on a rig built from a loadGltf asset. */
+export function createVehicleNodeOverrides(rig, pose) {
+ assertKind(rig, 'asset');
+ const worlds = computeTargetWorlds(rig, pose);
+ const localMatrix = createLocalMatrixResolver(rig, worlds);
+ const overrides = [];
+ for (const [id, world] of worlds) {
+ const entry = rig.source.byKey.get(id);
+ if (entry.editable === false) throw new RangeError(`Imported node ${entry.label} has an authored pose that cannot be overridden.`);
+ const local = localMatrix(entry, world);
+ overrides.push({
+ id,
+ translation: Array.from(mat4.getTranslation(vec3.create(), local)),
+ rotation: Array.from(mat4.getRotation(new Float64Array(4), local)),
+ scale: Array.from(mat4.getScaling(vec3.create(), local)),
+ });
+ }
+ return overrides;
+}
+
+/** Stages and commits the sampled pose on a loadGltf asset, then returns what `commit()` returned. */
+export function applyVehiclePoseToAsset(rig, pose, asset) {
+ const staged = asset.stagePose({ nodeOverrides: createVehicleNodeOverrides(rig, pose) });
+ return staged.commit();
+}
diff --git a/tests/vehicle.test.js b/tests/vehicle.test.js
new file mode 100644
index 00000000..0c5c5072
--- /dev/null
+++ b/tests/vehicle.test.js
@@ -0,0 +1,352 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mat4, vec3 } from 'gl-matrix';
+import { createSceneGraph } from '../src/scene-graph.js';
+import {
+ applyVehiclePoseToAsset,
+ applyVehiclePoseToParts,
+ applyVehiclePoseToSceneGraph,
+ createVehicleNodeOverrides,
+ createVehicleRig,
+ driveAlongPath,
+ findWheelCandidates,
+} from '../src/vehicle.js';
+
+const WHEEL_RADIUS = 0.35;
+const WHEEL_CORNERS = [
+ { id: 'FL', x: 0.8, z: 1.2 },
+ { id: 'FR', x: -0.8, z: 1.2 },
+ { id: 'RL', x: 0.8, z: -1.2 },
+ { id: 'RR', x: -0.8, z: -1.2 },
+];
+
+function boxGeometry(center, size) {
+ const positions = [];
+ for (const sx of [-1, 1]) {
+ for (const sy of [-1, 1]) {
+ for (const sz of [-1, 1]) {
+ positions.push(center[0] + sx * size[0] / 2, center[1] + sy * size[1] / 2, center[2] + sz * size[2] / 2);
+ }
+ }
+ }
+ return { positions: new Float32Array(positions) };
+}
+
+function wheelGeometry(center, radius, width) {
+ const positions = [];
+ for (let step = 0; step < 24; step++) {
+ const angle = step / 24 * Math.PI * 2;
+ for (const side of [-1, 1]) {
+ positions.push(center[0] + side * width / 2, center[1] + Math.sin(angle) * radius, center[2] + Math.cos(angle) * radius);
+ }
+ }
+ return { positions: new Float32Array(positions) };
+}
+
+function createTestVehicleParts() {
+ const body = { name: 'Body', geometry: boxGeometry([0, 0.8, 0], [1.6, 0.5, 3.4]), matrix: mat4.create() };
+ const wheels = WHEEL_CORNERS.map(corner => ({
+ name: `Wheel_${corner.id}`,
+ geometry: wheelGeometry([corner.x, WHEEL_RADIUS, corner.z], WHEEL_RADIUS, 0.2),
+ matrix: mat4.create(),
+ }));
+ return { body, wheels, parts: [body, ...wheels] };
+}
+
+function createTestRig(options = {}) {
+ const { body, wheels, parts } = createTestVehicleParts();
+ const rig = createVehicleRig({
+ parts,
+ body: [body],
+ wheels: wheels.map((part, index) => ({ id: WHEEL_CORNERS[index].id, part })),
+ ...options,
+ });
+ return { rig, body, wheels, parts };
+}
+
+const STRAIGHT_PATH = [[0, 0, 0], [0, 0, 10], [0, 0, 20]];
+
+function arcPath(radius, direction) {
+ const points = [];
+ for (let step = 0; step <= 12; step++) {
+ const angle = step / 12 * Math.PI / 2;
+ points.push([direction * radius * (1 - Math.cos(angle)), 0, radius * Math.sin(angle)]);
+ }
+ return points;
+}
+
+function transformPoint(matrix, point) {
+ return Array.from(vec3.transformMat4(vec3.create(), point, matrix));
+}
+
+test('wheel spin equals distance over radius and rolls the top of the tire forward', () => {
+ const { rig, wheels } = createTestRig();
+ const drive = driveAlongPath(rig, STRAIGHT_PATH, { speed: 5 });
+ const pose = drive.sample(2);
+ assert.ok(Math.abs(pose.distance - 10) < 1e-6);
+ for (const wheelPose of pose.wheels) {
+ assert.ok(Math.abs(wheelPose.spinAngle - 10 / WHEEL_RADIUS) < 1e-6);
+ assert.equal(wheelPose.steerAngle, 0);
+ }
+ applyVehiclePoseToParts(rig, pose);
+ const center = [0.8, WHEEL_RADIUS, 1.2];
+ const top = [0.8, 2 * WHEEL_RADIUS, 1.2];
+ const movedCenter = transformPoint(wheels[0].matrix, center);
+ const movedTop = transformPoint(wheels[0].matrix, top);
+ const spin = 10 / WHEEL_RADIUS;
+ assert.ok(Math.abs(movedTop[2] - movedCenter[2] - WHEEL_RADIUS * Math.sin(spin)) < 1e-4);
+ assert.ok(Math.abs(movedCenter[2] - (1.2 + 10)) < 1e-4);
+});
+
+test('spinSign flips a wheel whose model axis is mirrored', () => {
+ const { body, wheels, parts } = createTestVehicleParts();
+ const rig = createVehicleRig({
+ parts,
+ body: [body],
+ wheels: wheels.map((part, index) => ({ id: WHEEL_CORNERS[index].id, part, spinSign: index === 1 ? -1 : 1 })),
+ });
+ const pose = driveAlongPath(rig, STRAIGHT_PATH, { speed: 5 }).sample(1);
+ assert.ok(pose.wheels[0].spinAngle > 0);
+ assert.ok(pose.wheels[1].spinAngle < 0);
+});
+
+test('inner wheels turn slower than outer wheels in a corner', () => {
+ const { rig } = createTestRig();
+ const pose = driveAlongPath(rig, arcPath(10, 1), { speed: 5 }).sample(2);
+ const [frontLeft, frontRight] = pose.wheels;
+ assert.ok(frontLeft.spinAngle < frontRight.spinAngle);
+});
+
+test('steering turns the front wheels toward the turn and leaves the rear straight', () => {
+ const { rig } = createTestRig();
+ const leftPose = driveAlongPath(rig, arcPath(10, 1), { speed: 5 }).sample(1.5);
+ const rightPose = driveAlongPath(rig, arcPath(10, -1), { speed: 5 }).sample(1.5);
+ const expected = Math.atan(rig.wheelbase / 10);
+ assert.ok(Math.abs(rig.wheelbase - 2.4) < 1e-6);
+ assert.ok(Math.abs(leftPose.steerAngle - expected) < 0.02);
+ assert.ok(Math.abs(rightPose.steerAngle + expected) < 0.02);
+ assert.ok(leftPose.heading > 0.1);
+ assert.ok(rightPose.heading < -0.1);
+ assert.equal(leftPose.wheels[2].steerAngle, 0);
+ assert.equal(leftPose.wheels[0].steerAngle, leftPose.steerAngle);
+});
+
+test('front wheel matrices yaw toward the turn relative to the body', () => {
+ const { rig, wheels } = createTestRig();
+ const pose = driveAlongPath(rig, arcPath(10, 1), { speed: 5 }).sample(1.5);
+ applyVehiclePoseToParts(rig, pose);
+ const wheelForward = vec3.transformMat4(vec3.create(), [0, 0, 1], mat4.fromValues(...wheels[0].matrix.slice(0, 12), 0, 0, 0, 1));
+ const wheelYaw = Math.atan2(wheelForward[0], wheelForward[2]);
+ assert.ok(wheelYaw > pose.heading);
+});
+
+test('body leans outward in a turn and stays level on a straight path', () => {
+ const { rig } = createTestRig();
+ const straight = driveAlongPath(rig, STRAIGHT_PATH, { speed: 5 });
+ for (let time = 0; time <= 4; time += 0.25) {
+ assert.ok(Math.abs(straight.sample(time).roll) < 1e-9, `roll at ${time}`);
+ }
+ const leftTurn = driveAlongPath(rig, arcPath(10, 1), { speed: 5 }).sample(2);
+ const rightTurn = driveAlongPath(rig, arcPath(10, -1), { speed: 5 }).sample(2);
+ assert.ok(leftTurn.roll > 0.01);
+ assert.ok(rightTurn.roll < -0.01);
+});
+
+test('braking pitches the nose down and accelerating pitches it up', () => {
+ const { rig } = createTestRig();
+ const drive = driveAlongPath(rig, [[0, 0, 0], [0, 0, 40], [0, 0, 80]], { cruiseSpeed: 12, acceleration: 3, braking: 5 });
+ assert.ok(drive.sample(0.6).pitch > 0.005);
+ assert.ok(drive.sample(drive.duration - 0.6).pitch < -0.005);
+ assert.ok(drive.sample(0).speed === 0);
+ assert.ok(drive.sample(drive.duration + 5).speed === 0);
+ assert.ok(Math.abs(drive.sample(drive.duration + 5).distance - drive.length) < 1e-6);
+});
+
+test('a lateral acceleration limit slows the vehicle in corners', () => {
+ const { rig } = createTestRig();
+ const fast = driveAlongPath(rig, arcPath(10, 1), { cruiseSpeed: 20, acceleration: 8, braking: 8 });
+ const limited = driveAlongPath(rig, arcPath(10, 1), { cruiseSpeed: 20, acceleration: 8, braking: 8, maxLateralAcceleration: 4 });
+ assert.ok(limited.duration > fast.duration);
+ let peak = 0;
+ for (let time = 0; time <= limited.duration; time += 0.05) peak = Math.max(peak, limited.sample(time).speed);
+ assert.ok(peak <= Math.sqrt(4 * 10) + 0.5);
+});
+
+test('sampling is deterministic regardless of order', () => {
+ const { rig, parts } = createTestRig();
+ const ground = (x, z) => 0.05 * Math.sin(x * 0.7) * Math.cos(z * 0.4);
+ const drive = driveAlongPath(rig, arcPath(12, 1), { cruiseSpeed: 8, groundHeight: ground });
+ const first = drive.sample(1.37);
+ drive.sample(0.2);
+ drive.sample(3);
+ const second = drive.sample(1.37);
+ assert.deepEqual(second, first);
+ applyVehiclePoseToParts(rig, first);
+ const matricesFirst = parts.map(part => Array.from(part.matrix));
+ applyVehiclePoseToParts(rig, drive.sample(2.5));
+ applyVehiclePoseToParts(rig, second);
+ assert.deepEqual(parts.map(part => Array.from(part.matrix)), matricesFirst);
+});
+
+test('wheels stay on uneven ground', () => {
+ const { rig, wheels } = createTestRig();
+ const ground = (x, z) => 0.06 * Math.sin(x * 0.8) + 0.05 * Math.cos(z * 0.6);
+ const drive = driveAlongPath(rig, [[0, 0, 0], [3, 0, 8], [-2, 0, 16], [0, 0, 24]], { speed: 4, groundHeight: ground });
+ for (const time of [0.5, 1.5, 3, 4.5]) {
+ applyVehiclePoseToParts(rig, drive.sample(time));
+ WHEEL_CORNERS.forEach((corner, index) => {
+ const center = transformPoint(wheels[index].matrix, [corner.x, WHEEL_RADIUS, corner.z]);
+ const contactHeight = center[1] - WHEEL_RADIUS;
+ assert.ok(Math.abs(contactHeight - ground(center[0], center[2])) < 0.02, `${corner.id} at ${time}`);
+ });
+ }
+});
+
+test('name detection finds wheels, groups corners and rejects look-alikes', () => {
+ const names = ['Body', 'Wheel.001', 'FrontLeftWheel', 'tire_FR', 'RL_tyre', 'rim_rr', 'Steering wheel', 'Spare wheel', 'Wheel arch', 'Primary light', 'wheel_L'];
+ const { wheels, rejected } = findWheelCandidates(names);
+ const byName = new Map(wheels.map(wheel => [wheel.name, wheel]));
+ assert.equal(byName.get('FrontLeftWheel').corner, 'front-left');
+ assert.equal(byName.get('tire_FR').corner, 'front-right');
+ assert.equal(byName.get('RL_tyre').corner, 'rear-left');
+ assert.equal(byName.get('rim_rr').corner, 'rear-right');
+ assert.equal(byName.get('rim_rr').kind, 'rim');
+ assert.equal(byName.get('Wheel.001').corner, null);
+ assert.equal(byName.get('wheel_L').side, 'left');
+ assert.deepEqual(rejected.map(item => item.name).sort(), ['Spare wheel', 'Steering wheel', 'Wheel arch']);
+ assert.ok(!byName.has('Primary light'));
+ assert.ok(!byName.has('Body'));
+});
+
+test('automatic rigs group tire, hub and bolts per corner and ignore the steering wheel', () => {
+ const body = { name: 'Chassis', geometry: boxGeometry([0, 0.8, 0], [1.6, 0.5, 3.4]), matrix: mat4.create() };
+ const steering = { name: 'Steering wheel', geometry: boxGeometry([0.3, 1.3, 0], [0.4, 0.4, 0.05]), matrix: mat4.create() };
+ const parts = [body, steering];
+ for (const corner of WHEEL_CORNERS) {
+ const center = [corner.x, WHEEL_RADIUS, corner.z];
+ parts.push({ name: 'Rubber road tire', geometry: wheelGeometry(center, WHEEL_RADIUS, 0.25), matrix: mat4.create() });
+ parts.push({ name: 'Steel wheel hub', geometry: wheelGeometry(center, 0.2, 0.3), matrix: mat4.create() });
+ parts.push({ name: 'Wheel lug bolt', geometry: boxGeometry([corner.x, WHEEL_RADIUS + 0.1, corner.z], [0.03, 0.03, 0.03]), matrix: mat4.create() });
+ }
+ const rig = createVehicleRig({ parts });
+ assert.equal(rig.wheels.length, 4);
+ assert.ok(rig.wheels.every(wheel => wheel.entries.length === 3));
+ assert.ok(rig.wheels.every(wheel => Math.abs(wheel.radius - WHEEL_RADIUS) < 1e-6));
+ assert.equal(rig.wheels.filter(wheel => wheel.steerable).length, 2);
+ assert.ok(Math.abs(rig.wheelbase - 2.4) < 1e-6);
+ assert.deepEqual(rig.rejectedNames.map(item => item.name), ['Steering wheel']);
+ assert.ok(rig.bodyEntries.some(entry => entry.label === 'Steering wheel'));
+});
+
+test('forwardAxis lets a vehicle modelled along +x drive forward', () => {
+ const body = { name: 'Body', geometry: boxGeometry([0, 0.8, 0], [3.4, 0.5, 1.6]), matrix: mat4.create() };
+ const wheels = WHEEL_CORNERS.map(corner => ({
+ name: `Wheel_${corner.id}`,
+ geometry: boxGeometry([corner.z, WHEEL_RADIUS, -corner.x], [0.7, 0.7, 0.2]),
+ matrix: mat4.create(),
+ }));
+ const rig = createVehicleRig({ parts: [body, ...wheels], body: [body], forwardAxis: '+x', wheels: wheels.map(part => ({ part })) });
+ assert.ok(Math.abs(rig.wheelbase - 2.4) < 1e-6);
+ const pose = driveAlongPath(rig, STRAIGHT_PATH, { speed: 5 }).sample(1);
+ applyVehiclePoseToParts(rig, pose);
+ const movedBody = transformPoint(body.matrix, [1.7, 0.8, 0]);
+ assert.ok(Math.abs(movedBody[2] - (5 + 1.7)) < 1e-4);
+ assert.ok(Math.abs(movedBody[0]) < 1e-4);
+});
+
+test('a camera path object can serve as the drive path', () => {
+ const { rig } = createTestRig();
+ const cameraPathLike = {
+ duration: 10,
+ sample: time => ({ eye: [Math.sin(time * 0.3) * 4, 0, time * 3] }),
+ };
+ const drive = driveAlongPath(rig, cameraPathLike, { speed: 6 });
+ assert.ok(drive.length > 30);
+ assert.ok(drive.sample(1).position[2] > 5);
+});
+
+test('scene-graph nodes receive the same world poses as parts', () => {
+ const { body, wheels, parts } = createTestVehicleParts();
+ const partRig = createVehicleRig({ parts, body: [body], wheels: wheels.map((part, index) => ({ id: WHEEL_CORNERS[index].id, part })) });
+ const definitions = [
+ { name: 'car' },
+ { name: 'shell', parent: 'car', geometry: body.geometry, material: {} },
+ ...wheels.map((part, index) => ({ name: part.name, parent: 'car', geometry: part.geometry, material: {} })),
+ ];
+ const graph = createSceneGraph(definitions);
+ const graphRig = createVehicleRig({ graph, body: ['car'], wheels: wheels.map((part, index) => ({ id: WHEEL_CORNERS[index].id, node: part.name })) });
+ const path = arcPath(12, 1);
+ const pose = driveAlongPath(partRig, path, { speed: 5 }).sample(1.5);
+ applyVehiclePoseToParts(partRig, pose);
+ applyVehiclePoseToSceneGraph(graphRig, pose, graph);
+ wheels.forEach(part => {
+ const expected = Array.from(part.matrix);
+ const actual = Array.from(graph.getNode(part.name).worldMatrix);
+ actual.forEach((value, index) => assert.ok(Math.abs(value - expected[index]) < 1e-4, `${part.name}[${index}]`));
+ });
+ const shellActual = Array.from(graph.getNode('shell').worldMatrix);
+ const shellExpected = Array.from(body.matrix);
+ shellActual.forEach((value, index) => assert.ok(Math.abs(value - shellExpected[index]) < 1e-4, `shell[${index}]`));
+});
+
+test('imported glTF nodes get local overrides that reproduce the world pose', () => {
+ const { body, wheels, parts } = createTestVehicleParts();
+ const partRig = createVehicleRig({ parts, body: [body], wheels: wheels.map((part, index) => ({ id: WHEEL_CORNERS[index].id, part })) });
+ const nodes = [
+ { id: 'node-0', label: 'Car', parent: null, translation: [0, 0, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1], editable: true, meshIds: [] },
+ { id: 'node-1', label: 'Shell', parent: 'node-0', translation: [0, 0, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1], editable: true, meshIds: ['mesh-0'] },
+ ...wheels.map((part, index) => ({
+ id: `node-${index + 2}`, label: part.name, parent: 'node-0', translation: [0, 0, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1],
+ editable: true, meshIds: [`mesh-${index + 1}`],
+ })),
+ ];
+ let stagedInput = null;
+ const asset = {
+ nodes,
+ parts: parts.map(part => ({ geometry: part.geometry, matrix: Float32Array.from(part.matrix) })),
+ stagePose(input) {
+ stagedInput = input;
+ return { commit: () => 'committed' };
+ },
+ };
+ const rig = createVehicleRig({ asset });
+ assert.equal(rig.wheels.length, 4);
+ const pose = driveAlongPath(rig, arcPath(12, 1), { speed: 5 }).sample(1.5);
+ assert.equal(applyVehiclePoseToAsset(rig, pose, asset), 'committed');
+ const overrides = new Map(stagedInput.nodeOverrides.map(override => [override.id, override]));
+ assert.equal(overrides.size, 5);
+ const compose = override => mat4.fromRotationTranslationScale(mat4.create(), override.rotation, override.translation, override.scale);
+ const carWorld = compose(overrides.get('node-0'));
+ applyVehiclePoseToParts(partRig, pose);
+ wheels.forEach((part, index) => {
+ const world = mat4.multiply(mat4.create(), carWorld, compose(overrides.get(`node-${index + 2}`)));
+ world.forEach((value, element) => assert.ok(Math.abs(value - part.matrix[element]) < 1e-4, `${part.name}[${element}]`));
+ });
+ assert.equal(createVehicleNodeOverrides(rig, pose).length, 5);
+});
+
+test('bad input produces specific errors', () => {
+ const { body, wheels, parts } = createTestVehicleParts();
+ const wheelSpecs = wheels.map(part => ({ part }));
+ assert.throws(() => createVehicleRig({}), /exactly one of parts, graph or asset/);
+ assert.throws(() => createVehicleRig({ parts, wheels: [wheelSpecs[0]] }), /at least two wheels/);
+ assert.throws(() => createVehicleRig({ parts, wheels: wheelSpecs, forwardAxis: '+y' }), /forwardAxis/);
+ assert.throws(() => createVehicleRig({ parts, wheels: [{ part: 'Nothing' }, wheelSpecs[0]] }), /was not found: Nothing/);
+ assert.throws(() => createVehicleRig({ parts, wheels: [{ part: wheels[0], radius: -1, center: [0, 0, 0] }, wheelSpecs[1]] }), /radius must be positive/);
+ assert.throws(() => createVehicleRig({ parts: [body, { name: 'W1', matrix: mat4.create() }, { name: 'W2', matrix: mat4.create() }], wheels: [{ part: 'W1' }, { part: 'W2' }] }), /needs a radius and center/);
+ assert.throws(() => createVehicleRig({ parts, wheels: wheelSpecs, body: [] }), /body must be a non-empty array/);
+ const { rig } = createTestRig();
+ assert.throws(() => driveAlongPath({}, STRAIGHT_PATH, { speed: 3 }), /needs a rig/);
+ assert.throws(() => driveAlongPath(rig, [[0, 0, 0]], { speed: 3 }), /at least two distinct points/);
+ assert.throws(() => driveAlongPath(rig, [[0, 0, 0], [0, 0, NaN]], { speed: 3 }), /Path point 1/);
+ assert.throws(() => driveAlongPath(rig, 'road', { speed: 3 }), /Path must be/);
+ assert.throws(() => driveAlongPath(rig, STRAIGHT_PATH, {}), /exactly one of speed/);
+ assert.throws(() => driveAlongPath(rig, STRAIGHT_PATH, { speed: 3, cruiseSpeed: 4 }), /exactly one of speed/);
+ assert.throws(() => driveAlongPath(rig, STRAIGHT_PATH, { speed: -3 }), /speed must be positive/);
+ assert.throws(() => driveAlongPath(rig, STRAIGHT_PATH, { speed: 3, groundHeight: 4 }), /groundHeight must be a function/);
+ const drive = driveAlongPath(rig, STRAIGHT_PATH, { speed: 3, groundHeight: () => NaN });
+ assert.throws(() => drive.sample(1), /groundHeight must return a finite number/);
+ assert.throws(() => driveAlongPath(rig, STRAIGHT_PATH, { speed: 3 }).sample(Infinity), /Sample time must be finite/);
+ assert.throws(() => applyVehiclePoseToSceneGraph(rig, driveAlongPath(rig, STRAIGHT_PATH, { speed: 3 }).sample(0), {}), /built from parts, not graph/);
+ assert.throws(() => findWheelCandidates('wheel'), /array of name strings/);
+});
diff --git a/vite.lib.config.js b/vite.lib.config.js
index b90d09e4..715cbf4c 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -26,6 +26,7 @@ export default defineConfig({
'surface-attachment': 'src/surface-attachment.js',
physics: 'src/physics.js',
spume: 'src/spume.js',
+ vehicle: 'src/vehicle.js',
'agent-scene': 'src/agent-scene.js',
'agent-asset': 'src/agent-asset.js',
},