3D engine that AI agents drive
Float rigid bodies on the ocean with buoyancy (#982)
Nguyen Xuan An983301a6b7c7
diff --git a/changes/982.md b/changes/982.mdnew file mode 100644index 00000000..3232e44d--- /dev/null+++ b/changes/982.md@@ -0,0 +1,2 @@+- Rigid bodies float on the ocean: `physics.ocean` and a body `float` field make crates and hulls bob, roll and settle on the drawn waves (#982)+ media: https://raw.githubusercontent.com/codepawl/67.js/982-buoyancy/docs/buoyancy-still.jpg Crates and a boat riding ocean wavesdiff --git a/docs/mesh.md b/docs/mesh.mdindex 7cb6df80..1125e66c 100644--- a/docs/mesh.md+++ b/docs/mesh.md@@ -255,7 +255,7 @@ Normals stay those of the base mesh. Test: `tests/mesh-shape-keys.test.js`.| `bounding_box` | none | Replaces the mesh with the axis-aligned box around all its vertices: 8 vertices and 6 quads. Tags and attributes are dropped. || `convex_hull` | none | Replaces the mesh with its convex hull, outward triangles on the extreme vertices only, from at most 8192 vertices. A mesh whose vertices lie on one line or in one plane has no hull and is refused. Tags and attributes are dropped. || `build` | `order` (index, random or axis), `seed` (0, random only), `axis` (y, axis only), `frame` (0), `start` (0), `length` (60 frames, above 0), `reverse` (false) | Shows the first faces in that order: none before `start`, all from `start + length`, linear between; `reverse` unbuilds. Unused vertices drop, tags and corner attributes follow their faces, and while no face shows the mesh is one zero-area triangle. Same fields and frame give the same bytes on every seek. Works on imported meshes. |-| `ocean` | `axis` (y, the up axis), `windSpeed` (10 m/s, above 0 to 60), `direction` (0 degrees from +x toward +z), `choppiness` (1, 0 to 4), `size` (100 m, 1 to 10000), `seed` (0), `time` (0 s), `resolution` (8, 1 to 16) | A seeded sea like Blender's Ocean modifier, without the FFT: a sum of travelling waves on a lattice of wave vectors with a Phillips spectrum for the wind, so the surface repeats every `size` metres and the same seed and time give identical vertices. Waves lift the up axis; choppiness pulls vertices toward the crests along the other two. The squeeze of that move is written as the vertex group `foam` (0 flat, 1 folded). Waves cost (2 x resolution + 1)^2 - 1 per vertex, capped at 50 million evaluations. A box base has few vertices across a flat face (bevel 0 has none inside it), so run `subdivide_edges` with `cuts` first, or the waves have nothing to move. For an open sea: delete every face but the top, `subdivide_edges` with 16 cuts, `subdivide` 4 levels (about 74,000 vertices), scale the sheet to hundreds of metres, then `ocean` with a `size` of 50 (smaller than the wind's longest wave, so the sea has short chop), and a `vertex_color` field that mixes deep blue to white by `{ "attr": "group", "name": "foam" }`. A part with the `water` tag needs none of that: its shader reads the `foam` group itself and draws white rough foam on the folded crests, with a fresnel sky reflection, a sun glint and a deeper body colour at grazing angles. The mesh smooths over 180 degrees unless `smoothAngle` is set, so choppiness does not split the normals. |+| `ocean` | `axis` (y, the up axis), `windSpeed` (10 m/s, above 0 to 60), `direction` (0 degrees from +x toward +z), `choppiness` (1, 0 to 4), `size` (100 m, 1 to 10000), `seed` (0), `time` (0 s), `resolution` (8, 1 to 16) | A seeded sea like Blender's Ocean modifier, without the FFT: a sum of travelling waves on a lattice of wave vectors with a Phillips spectrum for the wind, so the surface repeats every `size` metres and the same seed and time give identical vertices. Waves lift the up axis; choppiness pulls vertices toward the crests along the other two. The squeeze of that move is written as the vertex group `foam` (0 flat, 1 folded). Waves cost (2 x resolution + 1)^2 - 1 per vertex, capped at 50 million evaluations. A box base has few vertices across a flat face (bevel 0 has none inside it), so run `subdivide_edges` with `cuts` first, or the waves have nothing to move. For an open sea: delete every face but the top, `subdivide_edges` with 16 cuts, `subdivide` 4 levels (about 74,000 vertices), scale the sheet to hundreds of metres, then `ocean` with a `size` of 50 (smaller than the wind's longest wave, so the sea has short chop), and a `vertex_color` field that mixes deep blue to white by `{ "attr": "group", "name": "foam" }`. A part with the `water` tag needs none of that: its shader reads the `foam` group itself and draws white rough foam on the folded crests, with a fresnel sky reflection, a sun glint and a deeper body colour at grazing angles. The mesh smooths over 180 degrees unless `smoothAngle` is set, so choppiness does not split the normals. Rigid bodies float on this sea: [Floating on the ocean](physics.md#floating-on-the-ocean). |`triangulate` and `edge_split` check their output size before building it, against the same vertex and face limits as the other edits. Each op has cases in `tests/fixtures/blender/cases.json` and matches Blender 5.2 with no listed difference. `screw` and `wireframe` have cases in the same fixtures (the volume of the open screw strips differs by winding, listed in `differences.json`); `wave` matches Blender on two cases; `skin`, `lattice`, `curve` and `hook` are not compared with Blender, because each needs a second object there. The two normal modifiers are tested by their own properties, because the Blender comparison does not measure normals. Not yet: `shrinkwrap` and `scatter_on_surface` as stack nodes (`instances` already scatters), and cast shapes other than the sphere.diff --git a/docs/physics.md b/docs/physics.mdindex e9b25f1e..cc115b94 100644--- a/docs/physics.md+++ b/docs/physics.md@@ -389,6 +389,29 @@ Rapier is loaded on demand, an optional peer dependency. The MCP runtime serves`scene_inspect` returns a `physics` report: per body the `finalPosition`, `finalSpeed` and `restsAtTime` (null while moving), the `contacts` between bodies with `firstTime`, `count` and `touchingAtEnd`, and the sensor `enter` and `leave` events with times.An agent can check that a ball came to rest on a mesh from these numbers, without a picture.+### Floating on the ocean++A crate or a boat can float on the sea that the `ocean` mesh edit draws. Give the section a sea and mark the bodies that float:++```json+"physics": {+ "duration": 8,+ "ocean": { "geometry": "sea", "level": 0, "waterDensity": 1000 },+ "bodies": [+ { "node": "crate", "density": 500, "float": { "drag": 2, "angularDrag": 2 } },+ { "node": "boat", "shape": "convex", "density": 300, "float": { "points": [[-1.5, 0, -0.6], [1.5, 0, -0.6], [-1.5, 0, 0.6], [1.5, 0, 0.6]] } }+ ]+}+```++`ocean.geometry` names a mesh geometry whose stack has an `ocean` node with axis `y`. The body floats on that node's waves (`windSpeed`, `direction`, `choppiness`, `size`, `seed`, `resolution`), read through the same function that moves the drawn vertices, so what the body rides is what the camera sees. The sea clock at physics time 0 is the node's `time`; drive an `oceanTime` track at one second per second to keep the drawn sea in step. `level` is the world height of the calm sea and `waterDensity` is in kg/m3.++Each `float` body carries sample points in body space, 16 at most. Without `points` it gets four, in a 2 x 2 grid across the collider bounds at mid height. Every point owns an equal share of the body's volume as a column as tall as the body. Where the surface stands above the point, the column is submerged by a fraction and the water pushes up at that point with `waterDensity x gravity x volume / points x fraction`. A body lighter than water bobs and rolls; a box of density 500 sinks to half its height. Spread the points over the hull, wide for roll and long for pitch, so the body rights itself when a wave tips it. `drag` and `angularDrag` (1/s, 0 to 100, default 2) damp the linear and angular velocity in proportion to the mean submerged fraction. Only dynamic bodies float, and a float body needs a volume, so trimesh does not work.++The definition form of the same thing is `ocean` on the definition and `float` on a body (`src/physics-buoyancy.js`); the live runtime applies it on every step with the same code, and the bake is identical across runs. The cost is waves x points x frames, capped at 100 million wave evaluations, so a long bake with 16 points and `resolution` 16 is rejected with a message that names the limits. A boat controller and a wake behind a moving hull are not part of this yet ([#982](https://github.com/codepawl/67.js/issues/982)).+++## Fracture and breakable glue`src/fracture.js` splits a closed convex part (a box, cylinder, sphere or any convex mesh of at most 2048 triangles) into Voronoi fragments and describes the glue that holds them together. A concave part is rejected with a message to split it into convex parts first.diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex d0959d40..16117600 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -619,6 +619,7 @@ const physicsBody = z.strictObject({angularVelocity: vector3.optional(),layer: z.number().int().min(0).max(15).optional(),collidesWith: z.array(z.number().int().min(0).max(15)).max(16).optional().describe('Layers hit; both bodies must list each other. Defaults to all.'),+ float: z.record(z.string(), z.unknown()).optional().describe('Floats on physics.ocean (dynamic bodies only): drag 2 and angularDrag 2 (1/s, 0-100) damp the body while it is under water; points is 1-16 [x,y,z] in body space (default a 2 x 2 grid at mid height). Each point pushes up by waterDensity x gravity x (volume / points) x its submerged fraction, so density 500 settles at half depth; spread points over a hull so it rolls upright. Needs a volume: not trimesh.'),});const physicsJoint = z.strictObject({type: z.enum(['spherical', 'revolute', 'prismatic', 'fixed']),@@ -634,6 +635,7 @@ const physics = z.strictObject({gravity: vector3.optional().describe('Defaults to [0, -9.81, 0].'),bodies: z.array(physicsBody).min(1).max(64),joints: z.array(physicsJoint).max(64).optional().describe('Joint bodies are the node IDs of physics bodies.'),+ ocean: z.record(z.string(), z.unknown()).optional().describe('Sea for floating bodies: geometry is a mesh geometry whose stack has an ocean node (axis y) whose waves they ride; level 0 is the world height of the calm sea; waterDensity 1000 kg/m3. The sea clock at physics time 0 is the ocean node time, so drive an oceanTime track at 1 s per s to keep the drawn sea in step.'),}).describe('Rigid bodies recorded offline with Rapier (optional peer) at 60 fps and seeked by motionTime. scene_inspect reports contacts and resting state. A node cannot have a body and a motion translation or rotation track.');const looseRecord = z.record(z.string(), z.unknown()).meta({ id: 'LooseRecord' });const clothSheet = z.strictObject({diff --git a/scripts/render-buoyancy-film.mjs b/scripts/render-buoyancy-film.mjsnew file mode 100644index 00000000..f3d64169--- /dev/null+++ b/scripts/render-buoyancy-film.mjs@@ -0,0 +1,140 @@+// Film of crates and a boat bobbing on ocean waves through the MCP render job, for the buoyancy docs and the pull request.+// Usage: node scripts/render-buoyancy-film.mjs [--backend gpu|cpu] [--width 640] [--height 360] [--duration 4] [--out artifacts/982]+// The boat is the CC0 Kenney Watercraft Kit `boat-fishing-small.glb`; it is downloaded next to the output on first use.+// CHROME_PATH names another Chrome or Chromium executable. --vulkan wraps the Chrome it finds with the flags a Linux GPU box needs.+import { mkdir, writeFile, readFile } from 'node:fs/promises';+import { existsSync, writeFileSync, chmodSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { spawnSync } from 'node:child_process';+import { join, resolve } from 'node:path';+import { setTimeout as delay } from 'node:timers/promises';+import { Client } from '@modelcontextprotocol/client';+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';++const KIT_URL = 'https://raw.githubusercontent.com/leaukojo/carlito/HEAD/kit/raw/watercraft';+const BOAT_FILE = 'boat-fishing-small.glb';+const BOAT_SIZE = { width: 1.78, length: 3.87, hullHeight: 0.7 };++function option(name, fallback) {+ const index = process.argv.indexOf(`--${name}`);+ return index === -1 ? fallback : process.argv[index + 1];+}++const backend = option('backend', 'gpu');+const width = Number(option('width', 640));+const height = Number(option('height', 360));+const duration = Number(option('duration', 4));+const outputFolder = resolve(option('out', 'artifacts/982'));+const assetFolder = join(outputFolder, 'assets');+const jobsFolder = join(outputFolder, 'jobs');++/** A shell wrapper that starts the installed Chrome with Vulkan GPU flags, for the server's --browser option. */+function vulkanChromeWrapper() {+ const names = ['google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser'];+ const found = names.map(name => spawnSync('which', [name], { encoding: 'utf8' }).stdout.trim()).find(Boolean);+ if (!found) throw new Error('No Chrome or Chromium on the PATH; install one or pass CHROME_PATH.');+ const wrapper = join(tmpdir(), 'chrome-vulkan.sh');+ writeFileSync(wrapper, `#!/bin/sh+exec ${found} --use-angle=vulkan --enable-features=Vulkan --ignore-gpu-blocklist --no-sandbox "$@"+`);+ chmodSync(wrapper, 0o755);+ return wrapper;+}++async function fetchKitFile(relativePath) {+ const target = join(assetFolder, relativePath);+ if (existsSync(target)) return;+ const response = await fetch(`${KIT_URL}/${relativePath}`);+ if (!response.ok) throw new Error(`Could not download ${relativePath}: HTTP ${response.status}`);+ await writeFile(target, Buffer.from(await response.arrayBuffer()));+}++function crate(id, translation, density) {+ return { node: { id, geometry: 'crate', material: 'wood', translation, scale: [0.9, 0.9, 0.9] }, body: { node: id, density, float: {} } };+}++function buildRecipe(boatAssetId) {+ const crates = [+ crate('crate-a', [-3.2, 1.6, 2.2], 350), crate('crate-b', [3.4, 1.1, -1.4], 500), crate('crate-c', [-2.6, 2.0, -3.2], 600),+ crate('crate-d', [2.8, 1.4, 3.1], 250), crate('crate-e', [0.4, 1.8, -4.4], 450),+ ];+ const seaEdits = [+ { op: 'delete', select: { not: { normal: [0, 1, 0], maxAngle: 10 } } },+ { op: 'subdivide_edges', edges: { all: true }, cuts: 16 },+ { op: 'subdivide', levels: 2 },+ { op: 'set_position', position: { mul: [{ attr: 'position' }, [40, 1, 40]] } },+ ];+ const boatLift = BOAT_SIZE.hullHeight / 2;+ return {+ format: '67js.scene', schemaVersion: 1,+ geometries: [+ { id: 'crate', type: 'box' },+ { id: 'hull', type: 'box' },+ { id: 'sea', type: 'mesh', base: { type: 'box', bevel: 0 }, edits: seaEdits, stack: [{ op: 'ocean', windSpeed: 6, choppiness: 0.4, size: 30, seed: 5, resolution: 5 }] },+ ],+ materials: [+ { id: 'wood', color: [0.55, 0.34, 0.16], roughness: 0.8 },+ { id: 'water', color: [0.02, 0.12, 0.2], tag: 'water' },+ { id: 'ghost', color: [1, 1, 1], opacity: 0 },+ ],+ nodes: [+ { id: 'sea', geometry: 'sea', material: 'water' },+ ...crates.map(entry => entry.node),+ { id: 'hull', geometry: 'hull', material: 'ghost', castShadow: false, translation: [0, 0.9, 0], scale: [BOAT_SIZE.width, BOAT_SIZE.hullHeight, BOAT_SIZE.length] },+ { id: 'boat', parent: 'hull', asset: { id: boatAssetId }, translation: [0, -boatLift / BOAT_SIZE.hullHeight, 0], scale: [1 / BOAT_SIZE.width, 1 / BOAT_SIZE.hullHeight, 1 / BOAT_SIZE.length] },+ ],+ camera: { eye: [6.5, 2.4, 8], target: [0, 0.4, 0], fov: 42 },+ motion: { duration, tracks: [{ kind: 'geometry', id: 'sea', property: 'oceanTime', interpolation: 'LINEAR', keyframes: [{ time: 0, value: 0 }, { time: duration, value: duration }] }] },+ physics: {+ duration,+ ocean: { geometry: 'sea' },+ bodies: [+ ...crates.map(entry => entry.body),+ { node: 'hull', density: 350, float: { drag: 1.5, angularDrag: 1.5, points: [[-0.6, 0, -1.4], [0.6, 0, -1.4], [-0.6, 0, 1.4], [0.6, 0, 1.4]] } },+ ],+ },+ };+}++await mkdir(join(assetFolder, 'Textures'), { recursive: true });+await mkdir(jobsFolder, { recursive: true });+await fetchKitFile(BOAT_FILE);+await fetchKitFile('Textures/colormap.png');++const serverArguments = [resolve('bin/67js-mcp.mjs'), '--backend', backend, '--memory', '384', '--assets', assetFolder, '--jobs', jobsFolder];+const browserPath = process.argv.includes('--vulkan') ? vulkanChromeWrapper() : process.env.CHROME_PATH;+if (browserPath) serverArguments.push('--browser', browserPath);+const transport = new StdioClientTransport({ command: process.execPath, args: serverArguments, stderr: 'inherit' });+const client = new Client({ name: '67js-buoyancy-film', version: '1' });++async function call(name, argumentsValue = {}, timeout = 120000) {+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout });+ if (result.isError) throw new Error(`${name}: ${result.content?.find(item => item.type === 'text')?.text}`);+ return result;+}++try {+ await client.connect(transport);+ const catalog = (await call('scene_asset_catalog')).structuredContent;+ const boat = catalog.assets.find(asset => JSON.stringify(asset).includes('boat-fishing-small'));+ if (!boat) throw new Error(`The catalog has no boat: ${JSON.stringify(catalog).slice(0, 400)}`);+ const created = (await call('scene_create', { recipe: buildRecipe(boat.assetId) }, 300000)).structuredContent;+ const report = (await call('scene_inspect', { sessionId: created.sessionId })).structuredContent.physics;+ console.log(JSON.stringify(report.bodies.map(body => [body.node, body.finalPosition])));+ const still = (await call('scene_look', { sessionId: created.sessionId, width: 1024, height: 576, motionTime: duration * 0.6 })).content.find(item => item.type === 'image');+ await writeFile(join(outputFolder, 'buoyancy-still.png'), Buffer.from(still.data, 'base64'));+ const job = (await call('scene_render_submit', { sessionId: created.sessionId, expectedRevision: created.revision ?? 0, settings: { kind: 'video', width, height, fps: 24, duration, motion: { start: 0 } } })).structuredContent;+ for (;;) {+ const state = (await call('scene_render_status', { jobId: job.jobId })).structuredContent;+ if (['completed', 'failed', 'cancelled'].includes(state.state)) {+ if (state.state !== 'completed') throw new Error(`Render ${state.state}: ${JSON.stringify(state).slice(0, 400)}`);+ break;+ }+ await delay(500);+ }+ const result = (await call('scene_render_result', { jobId: job.jobId })).structuredContent;+ await writeFile(join(outputFolder, 'buoyancy.mp4'), await readFile(result.artifacts[0].path));+ console.log(`wrote ${join(outputFolder, 'buoyancy.mp4')}`);+} finally {+ await client.close();+}diff --git a/src/agent-physics.js b/src/agent-physics.jsindex 66f1b166..2a31f76f 100644--- a/src/agent-physics.js+++ b/src/agent-physics.js@@ -4,6 +4,7 @@ import { restWorldMatrix, boneTails, boneNodeId } from './rig.js';import { createRagdoll, ragdollPatches, ragdollReport } from './ragdoll.js';import { bakePhysicsScene, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader } from './physics.js';import { normalizeForceFields } from './force-fields.js';+import { normalizeFloat } from './physics-buoyancy.js';import { AGENT_SCENE_CAPABILITIES } from './agent-scene-capabilities.js';export { loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader };@@ -24,12 +25,14 @@ const BODY_TYPES = ['dynamic', 'fixed', 'kinematic'];const SHAPES = ['box', 'ball', 'capsule', 'cylinder', 'cone', 'convex', 'trimesh', 'compound'];const COMPOUND_PART_SHAPES = ['box', 'ball', 'capsule', 'cylinder', 'cone'];const JOINT_TYPES = ['spherical', 'revolute', 'prismatic', 'fixed', 'spring'];-const BODY_FIELDS = ['node', 'type', 'shape', 'shapes', 'mass', 'density', 'friction', 'restitution', 'sensor', 'velocity', 'angularVelocity', 'layer', 'collidesWith'];+const BODY_FIELDS = ['node', 'type', 'shape', 'shapes', 'mass', 'density', 'friction', 'restitution', 'sensor', 'velocity', 'angularVelocity', 'layer', 'collidesWith', 'float'];const COMPOUND_PART_FIELDS = ['shape', 'translation', 'rotation', 'halfExtents', 'radius', 'halfHeight'];const JOINT_FIELDS = ['name', 'type', 'bodyA', 'bodyB', 'anchorA', 'anchorB', 'axis', 'limits', 'motor', 'restLength', 'stiffness', 'damping', 'contactsEnabled', 'breakImpulse'];const MOTOR_FIELDS = ['mode', 'target', 'stiffness', 'damping', 'maxForce'];const EVENT_FIELDS = ['time', 'tick', 'type', 'body', 'joint', 'impulse', 'torqueImpulse', 'point', 'translation', 'rotation', 'motor'];-const PHYSICS_FIELDS = ['duration', 'gravity', 'bodies', 'joints', 'events', 'fields', 'ragdoll'];+const PHYSICS_FIELDS = ['duration', 'gravity', 'bodies', 'joints', 'events', 'fields', 'ragdoll', 'ocean'];+const OCEAN_FIELDS = ['geometry', 'level', 'waterDensity'];+const OCEAN_WAVE_KEYS = ['windSpeed', 'direction', 'choppiness', 'size', 'seed', 'time', 'resolution'];const RAGDOLL_FIELDS = ['armature', 'density', 'friction', 'restitution', 'layer'];function knownKeys(value, fields, path) {@@ -125,6 +128,12 @@ function normalizeBody(input, recipeNodes, motionNodeIds, claimedNodes, path) {if (input.velocity !== undefined) body.velocity = numberList(input.velocity, 3, `${path}.velocity`);if (input.angularVelocity !== undefined) body.angularVelocity = numberList(input.angularVelocity, 3, `${path}.angularVelocity`);if (input.layer !== undefined) body.layer = Math.trunc(finiteNumber(input.layer, `${path}.layer`, 0, MAX_LAYER));+ if (input.float !== undefined) {+ if (type !== 'dynamic') {+ throw invalidField(`${path}.float`, input.float, `no float since the body is ${type}; only dynamic bodies float, such as type "dynamic"`, TypeError);+ }+ body.float = normalizeFloat(input.float, `${path}.float`);+ }if (shape === 'compound') {const parts = boundedArray(input.shapes, MAX_COMPOUND_SHAPES, `${path}.shapes`);if (!parts.length) {@@ -346,9 +355,43 @@ export function normalizeAgentPhysics(input, recipe) {if (input.fields !== undefined) {result.fields = normalizeForceFields(input.fields, 'physics.fields');}+ if (input.ocean !== undefined) {+ result.ocean = normalizeOceanReference(input.ocean, recipe);+ } else if (bodies.some(body => body.float)) {+ throw invalidField('physics.ocean', undefined, 'a sea for floating bodies, such as { "geometry": "sea" } naming a mesh geometry whose stack has an ocean node');+ }return result;}+/** Find the ocean node a physics ocean reads: the first ocean in the stack of the named mesh geometry. */+function oceanNodeOf(geometryId, recipe) {+ const geometry = (recipe.geometries ?? []).find(candidate => candidate.id === geometryId);+ return geometry?.type === 'mesh' ? (geometry.stack ?? []).find(node => node?.op === 'ocean') : undefined;+}++function normalizeOceanReference(input, recipe) {+ knownKeys(input, OCEAN_FIELDS, 'physics.ocean');+ if (!oceanNodeOf(input.geometry, recipe)) {+ const known = (recipe.geometries ?? []).filter(geometry => oceanNodeOf(geometry.id, recipe)).slice(0, 5).map(geometry => geometry.id).join(', ') || 'none yet; add a mesh geometry with stack [{ "op": "ocean" }]';+ throw invalidField('physics.ocean.geometry', input.geometry, `the ID of a mesh geometry whose stack has an ocean node, one of ${known}`);+ }+ if ((oceanNodeOf(input.geometry, recipe).axis ?? 'y') !== 'y') {+ throw invalidField('physics.ocean.geometry', input.geometry, 'a sea that lifts the y axis; set axis "y" on its ocean node');+ }+ const ocean = { geometry: input.geometry };+ if (input.level !== undefined) ocean.level = finiteNumber(input.level, 'physics.ocean.level', -10000, 10000);+ if (input.waterDensity !== undefined) ocean.waterDensity = finiteNumber(input.waterDensity, 'physics.ocean.waterDensity', 1, 20000);+ return ocean;+}++/** The sea of the definition: the wave fields of the referenced ocean node plus the level and water density. */+function oceanDefinition(oceanReference, recipe) {+ const node = oceanNodeOf(oceanReference.geometry, recipe);+ const waves = Object.fromEntries(OCEAN_WAVE_KEYS.filter(key => node[key] !== undefined).map(key => [key, node[key]]));+ const { geometry, ...water } = oceanReference;+ return { ...waves, ...water };+}+function scaledBounds(positions, scale) {const minimum = [Infinity, Infinity, Infinity];const maximum = [-Infinity, -Infinity, -Infinity];@@ -475,6 +518,10 @@ function physicsDefinition(physics, recipe, geometries, ragdoll) {(physics.joints ?? []).forEach((joint, index) => definition.joints.push({ name: joint.name ?? `joint-${index}`, ...joint }));if (physics.events) definition.events = physics.events;if (physics.fields) definition.fields = physics.fields;+ if (physics.ocean) definition.ocean = oceanDefinition(physics.ocean, recipe);+ for (const body of physics.bodies) {+ if (body.float) definition.bodies.find(candidate => candidate.name === body.node).float = body.float;+ }return definition;}@@ -526,7 +573,8 @@ function bodyReport(scene, physics) {export function physicsBakeKey(recipe, geometryRecords) {const bodyNodes = recipe.nodes.filter(node => recipe.physics.bodies.some(body => body.node === node.id));const rig = recipe.physics.ragdoll ? [recipe.nodes, recipe.armatures] : null;- return JSON.stringify([recipe.physics, bodyNodes, bodyNodes.map(node => geometryRecords.get(node.geometry).signature), rig]);+ const sea = recipe.physics.ocean ? oceanNodeOf(recipe.physics.ocean.geometry, recipe) : null;+ return JSON.stringify([recipe.physics, bodyNodes, bodyNodes.map(node => geometryRecords.get(node.geometry).signature), rig, sea]);}/**diff --git a/src/mesh-fields.js b/src/mesh-fields.jsindex b66c672d..92fb16ac 100644--- a/src/mesh-fields.js+++ b/src/mesh-fields.js@@ -1,3 +1,4 @@+import { hashCell, seededRandom } from './seeded-random.js';import { TAG_PREFIX, meshTags, vertexGroupWeights } from './mesh-data.js';import { MAX_FIELD_NODES, MAX_FIELD_DEPTH, MAX_FIELD_ELEMENTS, MAX_FIELD_WORK, FIELD_ATTRIBUTES } from './mesh-operations.js';import { faceCentroids, faceNormals, vertexNormals } from './mesh-normals.js';@@ -5,6 +6,8 @@ import {COMPONENTS, compileNode, createOperators, describeKey, isBoundedNumber, isPlainObject, requireScalar, scalarValue, vectorValue,} from './expression.js';+export { seededRandom };+// Bounded field expressions: the field context of the one expression language in expression.js. It computes one value// per mesh element (a number, or a vector of three numbers) from attributes, noise and math. Agents may be following instructions injected into their input,// so an expression is data and never code: it is read by walking plain objects against a fixed table of operators,@@ -32,13 +35,6 @@ function fieldError(message) {// ---------------------------------------------------------------------------------------------------------------// Hashing and noise. Integer hashing keeps results identical on every platform.-function hashCell(cellX, cellY, cellZ, seed) {- let hash = Math.imul(cellX, 0x27d4eb2d) ^ Math.imul(cellY, 0x165667b1) ^ Math.imul(cellZ, 0x85ebca77) ^ Math.imul(seed, 0x9e3779b1);- hash = Math.imul(hash ^ (hash >>> 15), 0x85ebca6b);- hash = Math.imul(hash ^ (hash >>> 13), 0xc2b2ae35);- return ((hash ^ (hash >>> 16)) >>> 0) / 4294967296;-}-function fade(fraction) {return fraction * fraction * fraction * (fraction * (fraction * 6 - 15) + 10);}@@ -61,11 +57,6 @@ export function valueNoise(x, y, z, seed) {return interpolate(nearY0, nearY1, fractionZ);}-/** Per-element random number in 0 to 1 from a whole-number key and a seed. */-export function seededRandom(key, channel, seed) {- return hashCell(key, channel, 0, seed);-}-function fractalNoise(x, y, z, seed, octaves) {let total = 0;let amplitude = 1;diff --git a/src/mesh-ocean-modifier.js b/src/mesh-ocean-modifier.jsindex 3b0f30f8..a6f95e8f 100644--- a/src/mesh-ocean-modifier.js+++ b/src/mesh-ocean-modifier.js@@ -1,99 +1,14 @@import { GROUP_PREFIX, createMeshData } from './mesh-data.js';-import { seededRandom } from './mesh-fields.js';+import { oceanWaves, oceanSurfaceAt } from './ocean-waves.js';import { registerModifierNormalizer, registerModifierRunner } from './mesh-modifiers.js';-// Ocean modifier: a deterministic spectrum displacement like Blender's Ocean modifier, without the FFT. The sea is a sum of-// travelling waves on a lattice of wave vectors, so the surface repeats exactly every `size` metres. Each wave has an-// amplitude from the Phillips spectrum for the wind (damped for the smallest waves), a seeded random gaussian and a seeded-// phase, and travels at the deep water speed, so the same seed and time give the same vertices on every run.-// The waves lift the up axis; `choppiness` also pulls vertices toward the crests along the horizontal axes. The squeeze of-// the surface (the Jacobian of that horizontal move) becomes the vertex group `foam`: 0 where the surface is not squeezed-// and 1 where it folds over itself.+export { oceanWaves, oceanSurfaceAt };export const MAX_OCEAN_RESOLUTION = 16;export const MAX_OCEAN_WORK = 50_000_000;-const GRAVITY = 9.81;-const SIGNIFICANT_HEIGHT_PER_WIND_SQUARED = 0.21;-const FOAM_START = 0.75;-const FOAM_FULL = 0.25;-const CHANNEL_GAUSSIAN_RADIUS = 40;-const CHANNEL_GAUSSIAN_ANGLE = 41;-const CHANNEL_PHASE = 42;const UP_AXES = Object.freeze({ x: 0, y: 1, z: 2 });const MAX_SEED = 0x7fffffff;-function windSpectrum(waveNumber, alignment, windSpeed) {- const largestWave = windSpeed * windSpeed / GRAVITY;- const smallestWave = largestWave / 1000;- const spectrum = Math.exp(-1 / (waveNumber * largestWave) ** 2) / waveNumber ** 4 * alignment * alignment;- return spectrum * Math.exp(-((waveNumber * smallestWave) ** 2));-}--function gaussian(key, seed) {- const radius = Math.sqrt(-2 * Math.log(Math.max(seededRandom(key, CHANNEL_GAUSSIAN_RADIUS, seed), 1e-12)));- return radius * Math.cos(2 * Math.PI * seededRandom(key, CHANNEL_GAUSSIAN_ANGLE, seed));-}--/**- * The waves of a sea: wave vector (waveX, waveZ along the two horizontal axes), amplitude, phase and angular frequency.- * The amplitudes are scaled so the significant wave height (4 standard deviations of the height) is- * 0.21 * windSpeed^2 / g, the height of a fully developed sea.- */-export function oceanWaves({ windSpeed, direction, size, seed, resolution }) {- const windX = Math.cos(direction * Math.PI / 180);- const windZ = Math.sin(direction * Math.PI / 180);- const waves = [];- let variance = 0;- const step = 2 * Math.PI / size;- for (let row = -resolution; row <= resolution; row++) {- for (let column = -resolution; column <= resolution; column++) {- if (row === 0 && column === 0) continue;- const waveX = column * step;- const waveZ = row * step;- const waveNumber = Math.hypot(waveX, waveZ);- const alignment = (waveX * windX + waveZ * windZ) / waveNumber;- const amplitude = Math.sqrt(windSpectrum(waveNumber, alignment, windSpeed)) * gaussian(waves.length, seed);- variance += amplitude * amplitude / 2;- waves.push({- waveX, waveZ, waveNumber, amplitude,- phase: seededRandom(waves.length, CHANNEL_PHASE, seed) * 2 * Math.PI,- frequency: Math.sqrt(GRAVITY * waveNumber),- });- }- }- const targetHeight = SIGNIFICANT_HEIGHT_PER_WIND_SQUARED * windSpeed * windSpeed / GRAVITY / 4;- const scale = variance > 0 ? targetHeight / Math.sqrt(variance) : 0;- for (const wave of waves) wave.amplitude *= scale;- return waves;-}--/** Height, horizontal move and foam of the sea at one rest point and time. */-export function oceanSurfaceAt(waves, restX, restZ, time, choppiness) {- let height = 0;- let moveX = 0;- let moveZ = 0;- let squeezeXX = 0;- let squeezeZZ = 0;- let squeezeXZ = 0;- for (const wave of waves) {- const angle = wave.waveX * restX + wave.waveZ * restZ - wave.frequency * time + wave.phase;- const sine = Math.sin(angle);- const cosine = Math.cos(angle);- const directionX = wave.waveX / wave.waveNumber;- const directionZ = wave.waveZ / wave.waveNumber;- height += wave.amplitude * cosine;- moveX -= choppiness * directionX * wave.amplitude * sine;- moveZ -= choppiness * directionZ * wave.amplitude * sine;- const slope = choppiness * wave.amplitude * wave.waveNumber * cosine;- squeezeXX -= directionX * directionX * slope;- squeezeZZ -= directionZ * directionZ * slope;- squeezeXZ -= directionX * directionZ * slope;- }- const jacobian = (1 + squeezeXX) * (1 + squeezeZZ) - squeezeXZ * squeezeXZ;- const foam = Math.min(1, Math.max(0, (FOAM_START - jacobian) / (FOAM_START - FOAM_FULL)));- return { height, moveX, moveZ, foam };-}-/** Displace every vertex by the sea and write the vertex group `foam`; `axis` is the up axis of the sea. */export function oceanMesh(mesh, { axis, windSpeed, direction, choppiness, size, seed, time, resolution }) {const waves = oceanWaves({ windSpeed, direction, size, seed, resolution });diff --git a/src/ocean-waves.js b/src/ocean-waves.jsnew file mode 100644index 00000000..75d59702--- /dev/null+++ b/src/ocean-waves.js@@ -0,0 +1,89 @@+import { seededRandom } from './seeded-random.js';++// Ocean modifier: a deterministic spectrum displacement like Blender's Ocean modifier, without the FFT. The sea is a sum of+// travelling waves on a lattice of wave vectors, so the surface repeats exactly every `size` metres. Each wave has an+// amplitude from the Phillips spectrum for the wind (damped for the smallest waves), a seeded random gaussian and a seeded+// phase, and travels at the deep water speed, so the same seed and time give the same vertices on every run.+// The waves lift the up axis; `choppiness` also pulls vertices toward the crests along the horizontal axes. The squeeze of+// the surface (the Jacobian of that horizontal move) becomes the vertex group `foam`: 0 where the surface is not squeezed+// and 1 where it folds over itself.++const SIGNIFICANT_HEIGHT_PER_WIND_SQUARED = 0.21;+const FOAM_START = 0.75;+const FOAM_FULL = 0.25;+const CHANNEL_GAUSSIAN_RADIUS = 40;+const CHANNEL_GAUSSIAN_ANGLE = 41;+const CHANNEL_PHASE = 42;+const GRAVITY = 9.81;++function windSpectrum(waveNumber, alignment, windSpeed) {+ const largestWave = windSpeed * windSpeed / GRAVITY;+ const smallestWave = largestWave / 1000;+ const spectrum = Math.exp(-1 / (waveNumber * largestWave) ** 2) / waveNumber ** 4 * alignment * alignment;+ return spectrum * Math.exp(-((waveNumber * smallestWave) ** 2));+}++function gaussian(key, seed) {+ const radius = Math.sqrt(-2 * Math.log(Math.max(seededRandom(key, CHANNEL_GAUSSIAN_RADIUS, seed), 1e-12)));+ return radius * Math.cos(2 * Math.PI * seededRandom(key, CHANNEL_GAUSSIAN_ANGLE, seed));+}++/**+ * The waves of a sea: wave vector (waveX, waveZ along the two horizontal axes), amplitude, phase and angular frequency.+ * The amplitudes are scaled so the significant wave height (4 standard deviations of the height) is+ * 0.21 * windSpeed^2 / g, the height of a fully developed sea.+ */+export function oceanWaves({ windSpeed, direction, size, seed, resolution }) {+ const windX = Math.cos(direction * Math.PI / 180);+ const windZ = Math.sin(direction * Math.PI / 180);+ const waves = [];+ let variance = 0;+ const step = 2 * Math.PI / size;+ for (let row = -resolution; row <= resolution; row++) {+ for (let column = -resolution; column <= resolution; column++) {+ if (row === 0 && column === 0) continue;+ const waveX = column * step;+ const waveZ = row * step;+ const waveNumber = Math.hypot(waveX, waveZ);+ const alignment = (waveX * windX + waveZ * windZ) / waveNumber;+ const amplitude = Math.sqrt(windSpectrum(waveNumber, alignment, windSpeed)) * gaussian(waves.length, seed);+ variance += amplitude * amplitude / 2;+ waves.push({+ waveX, waveZ, waveNumber, amplitude,+ phase: seededRandom(waves.length, CHANNEL_PHASE, seed) * 2 * Math.PI,+ frequency: Math.sqrt(GRAVITY * waveNumber),+ });+ }+ }+ const targetHeight = SIGNIFICANT_HEIGHT_PER_WIND_SQUARED * windSpeed * windSpeed / GRAVITY / 4;+ const scale = variance > 0 ? targetHeight / Math.sqrt(variance) : 0;+ for (const wave of waves) wave.amplitude *= scale;+ return waves;+}++/** Height, horizontal move and foam of the sea at one rest point and time. */+export function oceanSurfaceAt(waves, restX, restZ, time, choppiness) {+ let height = 0;+ let moveX = 0;+ let moveZ = 0;+ let squeezeXX = 0;+ let squeezeZZ = 0;+ let squeezeXZ = 0;+ for (const wave of waves) {+ const angle = wave.waveX * restX + wave.waveZ * restZ - wave.frequency * time + wave.phase;+ const sine = Math.sin(angle);+ const cosine = Math.cos(angle);+ const directionX = wave.waveX / wave.waveNumber;+ const directionZ = wave.waveZ / wave.waveNumber;+ height += wave.amplitude * cosine;+ moveX -= choppiness * directionX * wave.amplitude * sine;+ moveZ -= choppiness * directionZ * wave.amplitude * sine;+ const slope = choppiness * wave.amplitude * wave.waveNumber * cosine;+ squeezeXX -= directionX * directionX * slope;+ squeezeZZ -= directionZ * directionZ * slope;+ squeezeXZ -= directionX * directionZ * slope;+ }+ const jacobian = (1 + squeezeXX) * (1 + squeezeZZ) - squeezeXZ * squeezeXZ;+ const foam = Math.min(1, Math.max(0, (FOAM_START - jacobian) / (FOAM_START - FOAM_FULL)));+ return { height, moveX, moveZ, foam };+}diff --git a/src/physics-buoyancy.js b/src/physics-buoyancy.jsnew file mode 100644index 00000000..0d0bf56c--- /dev/null+++ b/src/physics-buoyancy.js@@ -0,0 +1,214 @@+import { oceanSurfaceAt, oceanWaves } from './ocean-waves.js';++// Buoyancy for rigid bodies on the ocean. A floating body carries up to 16 sample points. Each point owns an equal share of+// the body's volume as a vertical column the height of the body. Where the sea surface (the same function the ocean+// modifier draws) stands above the point, the column is submerged by a fraction and the water pushes up with+// waterDensity * gravity * (volume / points) * fraction, applied at the point. That lifts, tips and rolls the body. Drag then+// damps the body's linear and angular velocity in proportion to how much of it is under water. Nothing is random, so the same+// seed and definition give the same frames.++export const BUOYANCY_LIMITS = Object.freeze({ maxPointsPerBody: 16, maxWaveEvaluations: 100_000_000 });++const OCEAN_KEYS = ['level', 'waterDensity', 'windSpeed', 'direction', 'choppiness', 'size', 'seed', 'time', 'resolution'];+const FLOAT_KEYS = ['drag', 'angularDrag', 'points'];+const MAX_SEED = 0x7fffffff;+const DEFAULT_DRAG = 2;+const CHOPPY_REST_PASSES = 2;++function rejectUnknownKeys(value, allowed, label) {+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {+ throw new TypeError(`${label} must be an object like { ${allowed[0]}: 1 }`);+ }+ for (const key of Object.keys(value)) {+ if (!allowed.includes(key)) throw new TypeError(`${label}.${key} is unsupported; use one of ${allowed.join(', ')}`);+ }+}++function boundedNumber(value, label, minimum, maximum, example, exclusiveMinimum = false) {+ const belowMinimum = exclusiveMinimum ? value <= minimum : value < minimum;+ if (typeof value !== 'number' || !Number.isFinite(value) || belowMinimum || value > maximum) {+ throw new RangeError(`${label} must be a number ${exclusiveMinimum ? 'above' : 'from'} ${minimum} to ${maximum}, such as ${example}`);+ }+ return value;+}++function boundedInteger(value, label, minimum, maximum, example) {+ if (!Number.isInteger(value) || value < minimum || value > maximum) {+ throw new RangeError(`${label} must be an integer from ${minimum} to ${maximum}, such as ${example}`);+ }+ return value;+}++/**+ * Validate the sea bodies float on. The wave fields are those of the ocean mesh edit (same defaults), so a body floats on the+ * surface that edit draws. `level` is the world height of the calm sea, `waterDensity` is in kg/m3, `time` is the sea clock at+ * physics time 0 in seconds.+ */+export function normalizeOcean(input, label = 'ocean') {+ rejectUnknownKeys(input, OCEAN_KEYS, label);+ const ocean = {+ level: boundedNumber(input.level ?? 0, `${label}.level`, -10000, 10000, 0),+ waterDensity: boundedNumber(input.waterDensity ?? 1000, `${label}.waterDensity`, 1, 20000, 1000),+ windSpeed: boundedNumber(input.windSpeed ?? 10, `${label}.windSpeed`, 0, 60, 10, true),+ direction: boundedNumber(input.direction ?? 0, `${label}.direction`, -3600, 3600, 0),+ choppiness: boundedNumber(input.choppiness ?? 1, `${label}.choppiness`, 0, 4, 1),+ size: boundedNumber(input.size ?? 100, `${label}.size`, 1, 10000, 100),+ seed: boundedInteger(input.seed ?? 0, `${label}.seed`, 0, MAX_SEED, 0),+ time: boundedNumber(input.time ?? 0, `${label}.time`, -1e6, 1e6, 0),+ resolution: boundedInteger(input.resolution ?? 8, `${label}.resolution`, 1, 16, 8),+ };+ ocean.waves = oceanWaves(ocean);+ return ocean;+}++/** Validate the `float` field of a body: drag and angularDrag in 1/s (2 each) and up to 16 sample points [x, y, z] in body space. */+export function normalizeFloat(input, label) {+ rejectUnknownKeys(input, FLOAT_KEYS, label);+ const result = {+ drag: boundedNumber(input.drag ?? DEFAULT_DRAG, `${label}.drag`, 0, 100, DEFAULT_DRAG),+ angularDrag: boundedNumber(input.angularDrag ?? DEFAULT_DRAG, `${label}.angularDrag`, 0, 100, DEFAULT_DRAG),+ };+ if (input.points !== undefined) {+ const points = input.points;+ if (!Array.isArray(points) || points.length < 1 || points.length > BUOYANCY_LIMITS.maxPointsPerBody) {+ throw new RangeError(`${label}.points must be 1 to ${BUOYANCY_LIMITS.maxPointsPerBody} points in body space, such as [[-1, 0, -1], [1, 0, 1]]`);+ }+ result.points = points.map((point, index) => {+ if (!Array.isArray(point) || point.length !== 3) {+ throw new TypeError(`${label}.points[${index}] must be [x, y, z] in body space, such as [0, 0, 0]`);+ }+ return point.map((component, axis) => boundedNumber(component, `${label}.points[${index}][${axis}]`, -1e6, 1e6, 0));+ });+ }+ return result;+}++function colliderBounds(collider) {+ const [offsetX, offsetY, offsetZ] = collider.translation;+ let half;+ let center = [offsetX, offsetY, offsetZ];+ if (collider.points) {+ const low = [Infinity, Infinity, Infinity];+ const high = [-Infinity, -Infinity, -Infinity];+ for (let index = 0; index < collider.points.length; index += 3) {+ for (let axis = 0; axis < 3; axis++) {+ low[axis] = Math.min(low[axis], collider.points[index + axis]);+ high[axis] = Math.max(high[axis], collider.points[index + axis]);+ }+ }+ half = low.map((value, axis) => (high[axis] - value) / 2);+ center = center.map((value, axis) => value + (low[axis] + high[axis]) / 2);+ } else if (collider.halfExtents) {+ half = collider.halfExtents;+ } else if (collider.shape === 'ball') {+ half = [collider.radius, collider.radius, collider.radius];+ } else if (collider.shape === 'capsule') {+ half = [collider.radius, collider.halfHeight + collider.radius, collider.radius];+ } else {+ half = [collider.radius, collider.halfHeight, collider.radius];+ }+ return { low: center.map((value, axis) => value - half[axis]), high: center.map((value, axis) => value + half[axis]) };+}++/**+ * The buoyancy data of one floating body: displaced volume, the height of each column and the sample points. Without+ * `points` four sit in a 2 x 2 grid across the collider bounds at mid height. Collider rotations are ignored for the bounds.+ */+export function floatingBody(floatSpec, bodyColliders, label) {+ const solid = bodyColliders.filter(collider => collider.volume !== undefined);+ if (!solid.length) throw new TypeError(`${label} needs a ball, box, capsule, cylinder, cone or convex collider to float; trimesh has no volume`);+ const low = [Infinity, Infinity, Infinity];+ const high = [-Infinity, -Infinity, -Infinity];+ for (const collider of solid) {+ const bounds = colliderBounds(collider);+ for (let axis = 0; axis < 3; axis++) {+ low[axis] = Math.min(low[axis], bounds.low[axis]);+ high[axis] = Math.max(high[axis], bounds.high[axis]);+ }+ }+ const middle = low.map((value, axis) => (value + high[axis]) / 2);+ const quarter = [(high[0] - low[0]) / 4, 0, (high[2] - low[2]) / 4];+ const points = floatSpec.points ?? [[-1, -1], [1, -1], [-1, 1], [1, 1]].map(([sideX, sideZ]) => [middle[0] + sideX * quarter[0], middle[1], middle[2] + sideZ * quarter[2]]);+ return {+ drag: floatSpec.drag,+ angularDrag: floatSpec.angularDrag,+ points,+ volume: solid.reduce((total, collider) => total + collider.volume, 0),+ columnHeight: Math.max(high[1] - low[1], 1e-6),+ };+}++/** The reason a scene's float work is too large, or null: wave evaluations over all points and frames. */+export function checkBuoyancyWork(ocean, floatingBodies, frameCount) {+ const pointCount = floatingBodies.reduce((total, body) => total + body.points.length, 0);+ const passes = ocean.choppiness > 0 ? CHOPPY_REST_PASSES + 1 : 1;+ const evaluations = ocean.waves.length * pointCount * frameCount * passes;+ if (evaluations > BUOYANCY_LIMITS.maxWaveEvaluations) {+ throw new RangeError(`buoyancy would make ${evaluations} wave evaluations, over the limit of ${BUOYANCY_LIMITS.maxWaveEvaluations}. Lower ocean.resolution, the float points or the duration.`);+ }+}++/** Height of the sea surface above the calm level at a world position and physics time, following the horizontal pull of choppy waves. */+export function seaHeightAt(ocean, worldX, worldZ, time) {+ const seaTime = ocean.time + time;+ let restX = worldX;+ let restZ = worldZ;+ if (ocean.choppiness > 0) {+ for (let pass = 0; pass < CHOPPY_REST_PASSES; pass++) {+ const surface = oceanSurfaceAt(ocean.waves, restX, restZ, seaTime, ocean.choppiness);+ restX = worldX - surface.moveX;+ restZ = worldZ - surface.moveZ;+ }+ }+ return oceanSurfaceAt(ocean.waves, restX, restZ, seaTime, ocean.choppiness).height;+}++function rotateByQuaternion(point, rotation) {+ const [pointX, pointY, pointZ] = point;+ const { x, y, z, w } = rotation;+ const crossX = 2 * (y * pointZ - z * pointY);+ const crossY = 2 * (z * pointX - x * pointZ);+ const crossZ = 2 * (x * pointY - y * pointX);+ return [+ pointX + w * crossX + (y * crossZ - z * crossY),+ pointY + w * crossY + (z * crossX - x * crossZ),+ pointZ + w * crossZ + (x * crossY - y * crossX),+ ];+}++/**+ * Push every floating body for one step of `preparedScene.timestep` seconds at physics `time`: an upward impulse at each+ * sample point by its submerged fraction, then drag on both velocities by the body's mean submerged fraction.+ */+export function applyBuoyancy(preparedScene, bodies, time) {+ const { ocean, floating } = preparedScene.buoyancy;+ const step = preparedScene.timestep;+ const gravity = Math.hypot(...preparedScene.gravity);+ for (const floater of floating) {+ const body = bodies[floater.bodyIndex];+ const translation = body.translation();+ const rotation = body.rotation();+ const pointVolume = floater.volume / floater.points.length;+ let submergedTotal = 0;+ for (const localPoint of floater.points) {+ const offset = rotateByQuaternion(localPoint, rotation);+ const pointX = translation.x + offset[0];+ const pointY = translation.y + offset[1];+ const pointZ = translation.z + offset[2];+ const surfaceHeight = ocean.level + seaHeightAt(ocean, pointX, pointZ, time);+ const submerged = Math.min(1, Math.max(0, (surfaceHeight - pointY) / floater.columnHeight + 0.5));+ if (submerged === 0) continue;+ submergedTotal += submerged;+ const lift = ocean.waterDensity * gravity * pointVolume * submerged * step;+ body.applyImpulseAtPoint({ x: 0, y: lift, z: 0 }, { x: pointX, y: pointY, z: pointZ }, true);+ }+ if (submergedTotal === 0) continue;+ const meanSubmerged = submergedTotal / floater.points.length;+ const linearKeep = Math.exp(-floater.drag * meanSubmerged * step);+ const angularKeep = Math.exp(-floater.angularDrag * meanSubmerged * step);+ const linear = body.linvel();+ const angular = body.angvel();+ body.setLinvel({ x: linear.x * linearKeep, y: linear.y * linearKeep, z: linear.z * linearKeep }, true);+ body.setAngvel({ x: angular.x * angularKeep, y: angular.y * angularKeep, z: angular.z * angularKeep }, true);+ }+}diff --git a/src/physics-runtime.js b/src/physics-runtime.jsindex 052c9d38..209fab1f 100644--- a/src/physics-runtime.js+++ b/src/physics-runtime.js@@ -4,6 +4,7 @@// so the bake path and the live path share one adapter. Another engine plugs in as an object with the same shape as// `rapierAdapter`; see docs/physics-runtime.md. Nothing here touches the film path.import { mat4, quat } from 'gl-matrix';+import { applyBuoyancy } from './physics-buoyancy.js';import { applyForceFieldImpulses, createRapierWorld, loadPhysicsEngine, prepareLivePhysics, requireRapier } from './physics.js';export const PHYSICS_RUNTIME_LIMITS = Object.freeze({@@ -101,6 +102,7 @@ export const rapierAdapter = Object.freeze({step(stepSeconds, elapsedSeconds) {world.timestep = stepSeconds;if (prepared.fields.length) applyForceFieldImpulses({ ...prepared, timestep: stepSeconds }, bodies, elapsedSeconds);+ if (prepared.buoyancy) applyBuoyancy({ ...prepared, timestep: stepSeconds }, bodies, elapsedSeconds);world.step(eventQueue);},readPose(bodyIndex, output) {diff --git a/src/physics.js b/src/physics.jsindex 057552a1..9f765ac7 100644--- a/src/physics.js+++ b/src/physics.js@@ -1,5 +1,6 @@import { mat4, quat, vec3 } from 'gl-matrix';import { evaluateForceFields, normalizeForceFields } from './force-fields.js';+import { applyBuoyancy, checkBuoyancyWork, floatingBody, normalizeFloat, normalizeOcean } from './physics-buoyancy.js';let rapierPromise;let rapierEngine;@@ -258,7 +259,7 @@ function meshCollider(collider, body, limits, budget) {}function prepare(definition, options) {- fields(definition, ['bodies', 'colliders', 'joints', 'events', 'fields', 'gravity'], 'definition');+ fields(definition, ['bodies', 'colliders', 'joints', 'events', 'fields', 'gravity', 'ocean'], 'definition');fields(options, ['frameCount', 'timestep', 'solverIterations', 'maxMemoryBytes', ...Object.keys(LIMITS)], 'options');const limits = {};for (const [key, [fallback, cap]] of Object.entries(LIMITS)) {@@ -290,7 +291,7 @@ function prepare(definition, options) {throw new RangeError(`physics memory plan ${estimatedPeakBytes} exceeds maxMemoryBytes ${maxMemoryBytes}`);}const bodies = rawBodies.map(body => {- fields(body, ['name', 'type', 'translation', 'rotation', 'linearVelocity', 'angularVelocity', 'linearDamping', 'angularDamping', 'ccd'], `body ${body.name}`);+ fields(body, ['name', 'type', 'translation', 'rotation', 'linearVelocity', 'angularVelocity', 'linearDamping', 'angularDamping', 'ccd', 'float'], `body ${body.name}`);const type = body.type ?? 'dynamic';if (!['dynamic', 'fixed', 'kinematic'].includes(type)) {throw new TypeError(`body ${body.name} has unsupported type`);@@ -301,9 +302,16 @@ function prepare(definition, options) {if (body.ccd !== undefined && typeof body.ccd !== 'boolean') {throw new TypeError('ccd must be boolean');}+ if (body.float !== undefined && type !== 'dynamic') {+ throw new TypeError(`body ${body.name} only floats when dynamic; set type "dynamic" or drop float`);+ }+ if (body.float !== undefined && definition.ocean === undefined) {+ throw new TypeError(`body ${body.name} floats but the definition has no ocean; add ocean, such as { windSpeed: 5 }`);+ }return {name: body.name,type,+ float: body.float === undefined ? undefined : normalizeFloat(body.float, `body ${body.name}.float`),translation: vector(body.translation, 3, 'translation', ZERO),rotation: rotation(body.rotation, 'rotation'),linearVelocity: vector(body.linearVelocity, 3, 'linearVelocity', ZERO),@@ -402,6 +410,7 @@ function prepare(definition, options) {return {...common,shape: collider.shape,+ volume,radius,halfHeight,halfExtents,@@ -550,6 +559,7 @@ function prepare(definition, options) {const forceFields = normalizeForceFields(definition.fields ?? [], 'fields');const gravity = vector(definition.gravity, 3, 'gravity', [0, -9.81, 0]);validateMotionBounds(bodies, events, gravity, forceFields, timestep, frameCount, massTotals, minimumInertiaTotals, maximumColliderOffsets, joints, inertiaTotals);+ const buoyancy = buoyancyPlan(definition.ocean, bodies, colliders, frameCount);const memoryPlan = Object.freeze({timelineBytes,solverReserveBytes,@@ -568,6 +578,7 @@ function prepare(definition, options) {events,fields: forceFields,gravity,+ buoyancy,frameCount,timestep,solverIterations,@@ -576,6 +587,20 @@ function prepare(definition, options) {};}+/** The sea and the floating bodies of a definition, or null when no body has a float field. */+function buoyancyPlan(oceanInput, bodies, colliders, frameCount) {+ const floating = [];+ bodies.forEach((body, bodyIndex) => {+ if (body.float === undefined) return;+ const bodyColliders = colliders.filter(collider => collider.body === bodyIndex);+ floating.push({ bodyIndex, ...floatingBody(body.float, bodyColliders, `body ${body.name}`) });+ });+ const ocean = oceanInput === undefined ? null : normalizeOcean(oceanInput);+ if (!floating.length) return null;+ checkBuoyancyWork(ocean, floating, frameCount);+ return { ocean, floating };+}+function validateMotorBounds(bodies, joints, events, timestep, duration, massTotals, minimumInertiaTotals, maximumInertiaTotals, maximumColliderOffsets, linearSpeedBounds, angularSpeedBounds) {const components = bodies.map((_, index) => index);function component(index) {@@ -922,6 +947,7 @@ function bakePrepared(preparedScene) {}}if (preparedScene.fields.length) applyForceFieldImpulses(preparedScene, bodies, (frame - 1) * preparedScene.timestep);+ if (preparedScene.buoyancy) applyBuoyancy(preparedScene, bodies, (frame - 1) * preparedScene.timestep);world.step(eventQueue);eventQueue.drainCollisionEvents((firstHandle, secondHandle, started) => {if (contactEvents.length >= preparedScene.maxContactEvents) {diff --git a/src/seeded-random.js b/src/seeded-random.jsnew file mode 100644index 00000000..be920746--- /dev/null+++ b/src/seeded-random.js@@ -0,0 +1,13 @@+// Integer hashing keeps seeded results identical on every platform.++export function hashCell(cellX, cellY, cellZ, seed) {+ let hash = Math.imul(cellX, 0x27d4eb2d) ^ Math.imul(cellY, 0x165667b1) ^ Math.imul(cellZ, 0x85ebca77) ^ Math.imul(seed, 0x9e3779b1);+ hash = Math.imul(hash ^ (hash >>> 15), 0x85ebca6b);+ hash = Math.imul(hash ^ (hash >>> 13), 0xc2b2ae35);+ return ((hash ^ (hash >>> 16)) >>> 0) / 4294967296;+}++/** Per-element random number in 0 to 1 from a whole-number key and a seed. */+export function seededRandom(key, channel, seed) {+ return hashCell(key, channel, 0, seed);+}diff --git a/tests/physics-buoyancy-recipe.test.js b/tests/physics-buoyancy-recipe.test.jsnew file mode 100644index 00000000..d396fa14--- /dev/null+++ b/tests/physics-buoyancy-recipe.test.js@@ -0,0 +1,42 @@+import './support/load-agent-scene-modules.mjs';+import test from 'node:test';+import assert from 'node:assert/strict';+import { createAgentScene, loadPhysicsEngine } from '../src/agent-scene.js';++await loadPhysicsEngine();++function seaRecipe(physics, oceanNode = { op: 'ocean', windSpeed: 0.5, size: 50, seed: 4 }) {+ return {+ format: '67js.scene', schemaVersion: 1,+ geometries: [+ { id: 'cube', type: 'box' },+ { id: 'sea', type: 'mesh', base: { type: 'grid', segments: 8 }, stack: [oceanNode] },+ ],+ materials: [{ id: 'paint', color: [0.6, 0.5, 0.4] }],+ nodes: [{ id: 'crate', geometry: 'cube', material: 'paint', translation: [0, 0.4, 0] }],+ physics,+ };+}++test('a recipe floats a crate on the sea of a mesh geometry and settles at half depth', () => {+ const scene = createAgentScene(seaRecipe({ duration: 10, ocean: { geometry: 'sea' }, bodies: [{ node: 'crate', density: 500, float: {} }] }));+ scene.sampleMotion(10);+ const settledHeight = scene.parts[0].matrix[13];+ assert.ok(Math.abs(settledHeight) < 0.03, `box centre ${settledHeight} sits at the waterline`);+});++test('the sea level and water density of the recipe move the waterline', () => {+ const physics = { duration: 10, ocean: { geometry: 'sea', level: 2 }, bodies: [{ node: 'crate', density: 500, float: {} }] };+ const scene = createAgentScene(seaRecipe(physics));+ scene.sampleMotion(10);+ assert.ok(Math.abs(scene.parts[0].matrix[13] - 2) < 0.03);+});++test('recipe physics rejects float without an ocean and an ocean without waves', () => {+ const body = { node: 'crate', float: {} };+ assert.throws(() => createAgentScene(seaRecipe({ duration: 2, bodies: [body] })), /physics\.ocean/);+ assert.throws(() => createAgentScene(seaRecipe({ duration: 2, ocean: { geometry: 'cube' }, bodies: [body] })), /physics\.ocean\.geometry.*ocean node/);+ assert.throws(() => createAgentScene(seaRecipe({ duration: 2, ocean: { geometry: 'sea', level: 'high' }, bodies: [body] })), /physics\.ocean\.level/);+ assert.throws(() => createAgentScene(seaRecipe({ duration: 2, ocean: { geometry: 'sea' }, bodies: [{ node: 'crate', type: 'fixed', float: {} }] })), /physics\.bodies\[0\]\.float/);+ assert.throws(() => createAgentScene(seaRecipe({ duration: 2, ocean: { geometry: 'sea' }, bodies: [{ node: 'crate', float: { drag: 'a lot' } }] })), /physics\.bodies\[0\]\.float\.drag must be a number/);+});diff --git a/tests/physics-buoyancy.test.js b/tests/physics-buoyancy.test.jsnew file mode 100644index 00000000..16c205bc--- /dev/null+++ b/tests/physics-buoyancy.test.js@@ -0,0 +1,126 @@+import { createHash } from 'node:crypto';+import test from 'node:test';+import assert from 'node:assert/strict';+import { bakePhysicsScene, loadPhysicsEngine, planPhysicsScene } from '../src/physics.js';+import { seaHeightAt, normalizeOcean } from '../src/physics-buoyancy.js';++const CALM_SEA = { windSpeed: 0.5, size: 50, seed: 4 };+const FRAMES_PER_SECOND = 60;++function crateDefinition({ density = 500, ocean = CALM_SEA, float = {}, translation = [0, 0.4, 0], halfExtents = [0.5, 0.5, 0.5] } = {}) {+ return {+ ocean,+ bodies: [{ name: 'crate', translation, float }],+ colliders: [{ name: 'crate', body: 'crate', shape: 'cuboid', halfExtents, density }],+ };+}++function bake(definition, seconds) {+ return bakePhysicsScene(definition, { frameCount: Math.round(seconds * FRAMES_PER_SECOND) + 1 });+}++function bodyHeight(scene, time) {+ return scene.sample(time)[1];+}++function digest(scene, seconds) {+ const hash = createHash('sha256');+ for (let frame = 0; frame <= seconds * FRAMES_PER_SECOND; frame++) {+ hash.update(Buffer.from(scene.sample(frame / FRAMES_PER_SECOND).buffer.slice(0)));+ }+ return hash.digest('hex');+}++test.before(() => loadPhysicsEngine());++test('a box of density 500 on a calm sea settles at half its height under water', () => {+ const scene = bake(crateDefinition(), 20);+ const settledHeight = bodyHeight(scene, 20);+ const surface = seaHeightAt(normalizeOcean(CALM_SEA), 0, 0, 20);+ const submergedDepth = surface - (settledHeight - 0.5);+ assert.ok(Math.abs(submergedDepth - 0.5) <= 0.5 * 0.05, `submerged ${submergedDepth} m of a 1 m box`);+});++test('the submerged depth follows the density: 250 sinks a quarter, 750 sinks three quarters', () => {+ for (const [density, expected] of [[250, 0.25], [750, 0.75]]) {+ const scene = bake(crateDefinition({ density }), 20);+ const surface = seaHeightAt(normalizeOcean(CALM_SEA), 0, 0, 20);+ const submergedDepth = surface - (bodyHeight(scene, 20) - 0.5);+ assert.ok(Math.abs(submergedDepth - expected) <= expected * 0.05, `density ${density} sank ${submergedDepth}`);+ }+});++test('a body on a rough sea follows the wave height over time', () => {+ const rough = { windSpeed: 9, size: 60, seed: 2, choppiness: 0 };+ const scene = bake(crateDefinition({ ocean: rough, density: 400, translation: [0, 0, 0], halfExtents: [0.6, 0.6, 0.6] }), 12);+ const sea = normalizeOcean(rough);+ const heights = [];+ const waves = [];+ for (let time = 4; time <= 12; time += 0.25) {+ heights.push(bodyHeight(scene, time));+ waves.push(seaHeightAt(sea, scene.sample(time)[0], scene.sample(time)[2], time));+ }+ const meanHeight = heights.reduce((total, value) => total + value, 0) / heights.length;+ const meanWave = waves.reduce((total, value) => total + value, 0) / waves.length;+ let covariance = 0;+ let heightVariance = 0;+ let waveVariance = 0;+ heights.forEach((height, index) => {+ covariance += (height - meanHeight) * (waves[index] - meanWave);+ heightVariance += (height - meanHeight) ** 2;+ waveVariance += (waves[index] - meanWave) ** 2;+ });+ assert.ok(waveVariance > 0.01, 'the sea moves');+ assert.ok(covariance / Math.sqrt(heightVariance * waveVariance) > 0.8, 'the body rises and falls with the surface');+});++test('a tilted hull rolls back upright with points spread across it', () => {+ const definition = crateDefinition({+ float: { points: [[-1, 0, -0.5], [1, 0, -0.5], [-1, 0, 0.5], [1, 0, 0.5]] },+ halfExtents: [1, 0.25, 0.5], density: 400, translation: [0, 0, 0],+ });+ definition.bodies[0].rotation = [Math.sin(0.25), 0, 0, Math.cos(0.25)];+ const scene = bake(definition, 15);+ const rotation = scene.sample(15).slice(3, 7);+ assert.ok(Math.abs(rotation[0]) < 0.03, `roll ${rotation[0]} settled`);+});++test('the bake is identical across runs and changes with the sea seed', () => {+ const rough = { windSpeed: 8, size: 60, seed: 7 };+ const first = digest(bake(crateDefinition({ ocean: rough }), 4), 4);+ const second = digest(bake(crateDefinition({ ocean: rough }), 4), 4);+ const otherSeed = digest(bake(crateDefinition({ ocean: { ...rough, seed: 8 } }), 4), 4);+ assert.equal(first, second);+ assert.notEqual(first, otherSeed);+});++test('a body without float ignores the sea', () => {+ const definition = crateDefinition();+ delete definition.bodies[0].float;+ const scene = bake(definition, 1);+ assert.ok(bodyHeight(scene, 1) < 0.4, 'it falls');+});++test('float and ocean fields name the field and what to pass', () => {+ const plan = definition => () => planPhysicsScene(definition, { frameCount: 2 });+ assert.throws(plan(crateDefinition({ float: { drag: -1 } })), /body crate\.float\.drag must be a number from 0 to 100/);+ assert.throws(plan(crateDefinition({ float: { bogus: 1 } })), /float\.bogus is unsupported; use one of drag, angularDrag, points/);+ assert.throws(plan(crateDefinition({ float: { points: [] } })), /float\.points must be 1 to 16 points/);+ assert.throws(plan(crateDefinition({ float: { points: Array(17).fill([0, 0, 0]) } })), /1 to 16 points/);+ assert.throws(plan(crateDefinition({ float: { points: [[0, 0]] } })), /float\.points\[0\] must be \[x, y, z\]/);+ assert.throws(plan(crateDefinition({ ocean: { windSpeed: 0 } })), /ocean\.windSpeed must be a number above 0 to 60/);+ assert.throws(plan(crateDefinition({ ocean: { waterDensity: 0 } })), /ocean\.waterDensity must be a number from 1 to 20000/);+ assert.throws(plan(crateDefinition({ ocean: { resolution: 17 } })), /ocean\.resolution must be an integer from 1 to 16/);+ assert.throws(plan(crateDefinition({ ocean: { windy: 1 } })), /ocean\.windy is unsupported/);+ const noOcean = crateDefinition();+ delete noOcean.ocean;+ assert.throws(plan(noOcean), /floats but the definition has no ocean/);+ const fixedFloater = crateDefinition();+ fixedFloater.bodies[0].type = 'fixed';+ assert.throws(plan(fixedFloater), /only floats when dynamic/);+});++test('the wave work of a long bake with many points is bounded', () => {+ const definition = crateDefinition({ ocean: { resolution: 16 }, float: { points: Array(16).fill([0, 0, 0]) } });+ assert.throws(() => planPhysicsScene(definition, { frameCount: 3601 }), /wave evaluations, over the limit/);+});