A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(modeling): an organic step makes one skin over parts that melt into each other, so an agent can build creatures, plants and rocks
yhhb75d099e4c04
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 608c450ba..c458597aa 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,7 +19,7 @@ published separately; it ships inside the editor.- **Glyphs can be put on the atlas before they are shown.** The first page of a novel is hundreds of new characters, all landing in one frame. `preloadGlyphs(app, label, text, { budgetMs })` makes them ahead of time, a slice a frame, drawn as that `Text` will draw them, and returns `progress`, `done` and `release()`. On a Snapdragon 8 Elite a book's 2992 characters at 28 px took 145 ms over 25 frames with the worst frame at 9.5 ms, after which the first page's frame went from 49 to 11 ms and no page made a new glyph. Preloaded glyphs hold their atlas pages (4 MB each, a few hundred characters at that size) until `release()`.- **Voxel GI lights what the camera does not see, and bounces light more than once.** The cache now reads the sun's shadow map back into the world, so a surface the sun lights behind or beside the camera still sends light into the view. Each surface also gives off again the bounce light it received, so a corner or a floor in shade gets light that took two or more bounces to reach it. A ray now brings what it meets at full strength however far it went (it used to fade with distance, 40% at 4 m with 12 cm voxels). Each voxel is weighed by how much of it a surface covers, so a bright patch no longer lights like the whole voxel around it. Together these keep the result close to a path tracer's whatever the voxel size. In a sunlit test room the whole frame carries 0.95 of Cycles' light at the default size and 0.74 at 12 cm voxels; before, it was 0.54 at the default and darker the finer the grid. With the lit patch behind the camera, the walls went from no bounce light to 25–57%. A closed room the sun only lights from outside stays dark. Two inspector controls tune it: **Off-screen Sun Albedo** (the colour the shadow map cannot give, assumed) and **Multi-bounce**. A fine grid no longer drops every voxel: a count truncated by the cache's ageing had kept them below the two samples a ray asks for. The WebGL2 fallback does the same in its own passes: each voxel asks the sun's map whether a sunlit surface stands in it, and traces two rays through last frame's grid for the light it is given. In the test room it carries 1.00 of Cycles' light at the default size (it was 0.56) and 0.80 at 12 cm; with the lit patch behind the camera 0.20 (it was 0). Its voxel pass costs about 1.3 ms more at 720p on a desktop.-**AI agents can build 3D models in the editor from steps.** The `modeling` tool group writes a `.esmodel`, the steps that build a model (boxes, cylinders and floor plans, then extrude, inset, bevel, slice, array, mirror, paint), and bakes the `.esmesh` a scene draws beside it. Changing one number rebuilds it and whatever draws it follows, Undo takes both files back, and `model_views` shows every side with its silhouette, so an agent can check a shape without a scene. Blockouts, buildings and hard-surface props.+**AI agents can build 3D models in the editor from steps.** The `modeling` tool group writes a `.esmodel`, the steps that build a model (boxes, cylinders and floor plans, then extrude, inset, bevel, slice, array, mirror, paint), and bakes the `.esmesh` a scene draws beside it. Changing one number rebuilds it and whatever draws it follows, Undo takes both files back, and `model_views` shows every side with its silhouette, so an agent can check a shape without a scene. Blockouts, buildings and hard-surface props; and with the `organic` step, creatures, plants and rocks, as one skin over parts that melt into each other, carve, mirror and roughen.- **A model of many parts that moves: `CompositeBatch`.** Put it on the root of a ship, a vehicle or a moving platform assembled from many meshes, and while the game runs its parts are drawn in a few draws parented to the root: a mesh repeated four times or more (a deck plank, a rail post) as one instanced set that copies no vertices, every other part merged by draw state into chunks of the root's own space. Moving, turning or scaling the root moves the whole model and merges nothing again. Adding, removing, re-meshing or re-placing a part re-merges only its chunk within half a second (`CompositeBatchingRes.refresh(root)` looks at once), and a part that keeps moving inside the model is let go to draw itself. The root reports what it drew, and so does `get_stats`. On a model of 2,004 parts, the meshes handed to the renderer went from 2,003 to 5 and the CPU frame from 3.3 ms to 1.2–1.4 ms; a model of about a hundred parts costs the same either way. A part under a composite is never also statically batched.diff --git a/desktop b/desktopindex 9cb5663cd..804dd12a6 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 9cb5663cd1b28e2947f93aec390a1edc9904b14d+Subproject commit 804dd12a6c3cbf594c9127c56f4cb7ad73d07326diff --git a/pipeline/src/modeling/index.ts b/pipeline/src/modeling/index.tsindex 728b71962..e130ebdcd 100644--- a/pipeline/src/modeling/index.ts+++ b/pipeline/src/modeling/index.ts@@ -8,5 +8,7 @@ export {MODEL_OPS, MODEL_SOURCE_EXT, MODEL_SOURCE_VERSION, ModelBuildError, applyModelEdits, buildPolyMesh, describeModelOps, validateModelSource,type ModelEdit, type ModelSource, type ModelStep, type StepReport,} from './modelSource';+export { organic, ORGANIC_DEFAULT_RESOLUTION, ORGANIC_MAX_RESOLUTION, type OrganicParams, type OrganicPart } from './organic';export { bakeModel, type BakedModel, type ModelReport } from './modelBake';+export type { FaceSelector } from './polyMesh';export { DEFAULT_MODEL_VIEWS, MODEL_VIEWS, renderModelSheet, type ModelSheet, type ModelViewName } from './modelViews';diff --git a/pipeline/src/modeling/modelBake.ts b/pipeline/src/modeling/modelBake.tsindex 04cb4bfb5..119219498 100644--- a/pipeline/src/modeling/modelBake.ts+++ b/pipeline/src/modeling/modelBake.ts@@ -142,10 +142,11 @@ function cornerNormals(mesh: PolyMesh, smoothAngle: number): Vec3[][] {});const areas = mesh.faces.map((f) => faceArea(mesh, f));return mesh.faces.map((face, f) => face.v.map((v) => {- if (smoothAngle <= 0) return normals[f]!;+ if (smoothAngle <= 0 && !face.smooth) return normals[f]!;let sum: Vec3 = [0, 0, 0];for (const g of around.get(v)!) {- if (dot(normals[f]!, normals[g]!) < cosine) continue;+ const skin = face.smooth && mesh.faces[g]!.smooth;+ if (!skin && dot(normals[f]!, normals[g]!) < cosine) continue;const w = areas[g]!;sum = [sum[0] + normals[g]![0] * w, sum[1] + normals[g]![1] * w, sum[2] + normals[g]![2] * w];}@@ -247,7 +248,7 @@ export function bakeModel(raw: unknown): BakedModel {const warnings: string[] = [];if (openEdges) warnings.push(`${openEdges} open edge${openEdges > 1 ? 's' : ''}: the surface has holes you can see into`);- if (nonManifoldEdges) warnings.push(`${nonManifoldEdges} edge${nonManifoldEdges > 1 ? 's' : ''} shared by more than two faces; \`weld\` may have joined things that should stay apart`);+ if (nonManifoldEdges) warnings.push(`${nonManifoldEdges} edge${nonManifoldEdges > 1 ? 's' : ''} shared by more than two faces, which a later bevel refuses: \`weld\` may have joined things that should stay apart, or on an organic skin two parts just touch, so overlap them or raise blend`);if (degenerateFaces) warnings.push(`${degenerateFaces} face${degenerateFaces > 1 ? 's' : ''} with no area; \`weld\` removes them`);if (insideOutShells) warnings.push(`${insideOutShells} closed shell${insideOutShells > 1 ? 's are' : ' is'} inside out`);diff --git a/pipeline/src/modeling/modelSource.ts b/pipeline/src/modeling/modelSource.tsindex e2132f700..44a66a043 100644--- a/pipeline/src/modeling/modelSource.ts+++ b/pipeline/src/modeling/modelSource.ts@@ -13,6 +13,7 @@* builds without complaint is a shape quietly using the default.*/import * as ops from './modelOps';+import { organic } from './organic';import { compact, type Face, type FaceSelector, type PolyMesh, type Vec3 } from './polyMesh';export const MODEL_SOURCE_VERSION = 1;@@ -35,7 +36,7 @@ export interface ModelSource {}type Kind = 'number' | 'integer' | 'boolean' | 'string' | 'vec3' | 'number|vec3' | 'number|vec2' | 'number|numbers'- | 'color' | 'points' | 'faces' | 'edges' | 'axis' | 'pivot';+ | 'color' | 'points' | 'faces' | 'edges' | 'axis' | 'pivot' | 'parts' | 'noise';interface OpSpec {params: Record<string, Kind>;@@ -55,6 +56,7 @@ export const MODEL_OPS: Record<string, OpSpec> = {cone: { params: { radius: 'number', height: 'number', sides: 'integer', ...PLACED }, required: ['radius', 'height'], run: ops.cone as OpSpec['run'], says: 'adds an upright cone' },sphere: { params: { radius: 'number', rings: 'integer', sides: 'integer', ...PLACED }, required: ['radius'], run: ops.sphere as OpSpec['run'], says: 'adds a sphere' },prism: { params: { points: 'points', height: 'number', ...PLACED }, required: ['points', 'height'], run: ops.prism as OpSpec['run'], says: 'stands a floor plan of [x, z] points up to `height`' },+ organic: { params: { parts: 'parts', resolution: 'integer', blend: 'number', noise: 'noise', at: 'vec3', tag: 'string', color: 'color' }, required: ['parts'], run: organic as unknown as OpSpec['run'], says: 'adds one continuous skin over a body of parts that melt into each other' },transform: { params: { faces: 'faces', translate: 'vec3', rotate: 'vec3', scale: 'number|vec3', pivot: 'pivot' }, required: [], run: ops.transform as OpSpec['run'], says: 'moves the vertices of the faces (default all): scaling a top face in makes a roof' },array: { params: { faces: 'faces', count: 'integer', offset: 'vec3', rotate: 'vec3', pivot: 'pivot', tag: 'string' }, required: ['count'], run: ops.array as OpSpec['run'], says: 'repeats the faces, `count` including the original' },mirror: { params: { faces: 'faces', axis: 'axis', at: 'number', keep: 'boolean', tag: 'string' }, required: ['axis'], run: ops.mirror as OpSpec['run'], says: 'adds a reflection across `axis` = `at`' },@@ -119,6 +121,51 @@ function checkEdges(sel: unknown): string | null {return null;}+const NOISE_KEYS = new Set(['amplitude', 'scale', 'octaves', 'seed']);+function checkNoise(v: unknown): string | null {+ if (typeof v !== 'object' || v === null || Array.isArray(v)) return 'must be { amplitude, scale, octaves?, seed? }';+ const n = v as Record<string, unknown>;+ for (const key of Object.keys(n)) if (!NOISE_KEYS.has(key)) return `has an unknown key "${key}"; it takes ${[...NOISE_KEYS].join(', ')}`;+ if (!isNum(n.amplitude) || !isNum(n.scale) || n.scale <= 0) return 'needs a number amplitude and a positive scale';+ if (n.octaves !== undefined && !(Number.isInteger(n.octaves) && (n.octaves as number) >= 1 && (n.octaves as number) <= 6)) return 'octaves must be 1..6';+ if (n.seed !== undefined && !Number.isInteger(n.seed)) return 'seed must be a whole number';+ return null;+}++const PART_FIELDS: Record<string, (v: unknown) => string | null> = {+ shape: (v) => (['sphere', 'ellipsoid', 'box', 'torus', 'chain'].includes(v as string) ? null : 'must be sphere, ellipsoid, box, torus or chain'),+ tag: (v) => (typeof v === 'string' ? null : 'must be a string'),+ at: (v) => (isNums(v, 3) ? null : 'must be [x, y, z]'),+ rotate: (v) => (isNums(v, 3) ? null : 'must be [x, y, z] degrees'),+ radius: (v) => (isNum(v) ? null : 'must be a number'),+ radii: (v) => (isNums(v, 3) ? null : 'must be [x, y, z]'),+ size: (v) => (isNums(v, 3) ? null : 'must be [x, y, z]'),+ rounding: (v) => (isNum(v) ? null : 'must be a number'),+ tube: (v) => (isNum(v) ? null : 'must be a number'),+ points: (v) => (Array.isArray(v) && v.every((q) => isNums(q, 4)) ? null : 'must be an array of [x, y, z, radius]'),+ blend: (v) => (isNum(v) ? null : 'must be a number'),+ subtract: (v) => (typeof v === 'boolean' ? null : 'must be true or false'),+ mirror: (v) => (v === 'x' || v === 'y' || v === 'z' ? null : 'must be x, y or z'),+ color: (v) => (isNums(v) ? null : 'must be [r, g, b] or [r, g, b, a]'),+ noise: checkNoise,+};++function checkParts(v: unknown): string | null {+ if (!Array.isArray(v) || v.length === 0) return 'must be a non-empty array of parts';+ for (let i = 0; i < v.length; i++) {+ const part = v[i] as Record<string, unknown> | null;+ if (typeof part !== 'object' || part === null) return `[${i}] must be an object`;+ if (part.shape === undefined) return `[${i}] needs a shape`;+ for (const [key, value] of Object.entries(part)) {+ const check = PART_FIELDS[key];+ if (!check) return `[${i}] has an unknown field "${key}"; a part takes ${Object.keys(PART_FIELDS).join(', ')}`;+ const bad = check(value);+ if (bad) return `[${i}].${key} ${bad}`;+ }+ }+ return null;+}+const KIND_CHECK: Record<Kind, (v: unknown) => string | null> = {number: (v) => (isNum(v) ? null : 'must be a number'),integer: (v) => (Number.isInteger(v) ? null : 'must be a whole number'),@@ -133,6 +180,8 @@ const KIND_CHECK: Record<Kind, (v: unknown) => string | null> = {faces: checkFaces,edges: checkEdges,axis: (v) => (v === 'x' || v === 'y' || v === 'z' ? null : 'must be x, y or z'),+ parts: checkParts,+ noise: checkNoise,pivot: (v) => (v === 'center' || v === 'base' || isNums(v, 3) ? null : 'must be "center", "base" or [x, y, z]'),};diff --git a/pipeline/src/modeling/modelViews.ts b/pipeline/src/modeling/modelViews.tsindex 60c6a331b..66fedc0c3 100644--- a/pipeline/src/modeling/modelViews.ts+++ b/pipeline/src/modeling/modelViews.ts@@ -15,7 +15,7 @@* What the model looks like in the game is what `screenshot` is for.*/import type { BakedModel } from './modelBake';-import { boundsOf, cross, dot, faceNormal, normalize, sub, type Vec3 } from './polyMesh';+import { add, boundsOf, cross, dot, faceNormal, normalize, selectFaces, sub, type FaceSelector, type Vec3 } from './polyMesh';export const MODEL_VIEWS = {front: { right: [1, 0, 0], up: [0, 1, 0], toward: [0, 0, 1] },@@ -24,14 +24,17 @@ export const MODEL_VIEWS = {left: { right: [0, 0, 1], up: [0, 1, 0], toward: [-1, 0, 0] },top: { right: [1, 0, 0], up: [0, 0, -1], toward: [0, 1, 0] },bottom: { right: [1, 0, 0], up: [0, 0, 1], toward: [0, -1, 0] },- iso: isoBasis(),+ iso: isoBasis([1, 0.8, 1]),+ 'iso-left': isoBasis([-1, 0.8, 1]),+ 'iso-back': isoBasis([1, 0.8, -1]),+ 'iso-low': isoBasis([1, -0.5, 1]),} as const satisfies Record<string, { right: Vec3; up: Vec3; toward: Vec3 }>;export type ModelViewName = keyof typeof MODEL_VIEWS;export const DEFAULT_MODEL_VIEWS: readonly ModelViewName[] = ['front', 'right', 'top', 'iso'];-function isoBasis(): { right: Vec3; up: Vec3; toward: Vec3 } {- const toward = normalize([1, 0.8, 1]);+function isoBasis(from: Vec3): { right: Vec3; up: Vec3; toward: Vec3 } {+ const toward = normalize(from);const right = normalize(cross([0, 1, 0], toward));return { right, up: cross(toward, right), toward };}@@ -53,13 +56,19 @@ const WIRE = [30, 30, 30] as const;const GUTTER = [120, 120, 120] as const;/** Lays the views out as columns over two rows, each panel `panel` pixels square. */-export function renderModelSheet(model: BakedModel, views: readonly ModelViewName[] = DEFAULT_MODEL_VIEWS, panel = 384): ModelSheet {+export function renderModelSheet(model: BakedModel, views: readonly ModelViewName[] = DEFAULT_MODEL_VIEWS, panel = 384, focus?: FaceSelector): ModelSheet {if (views.length === 0) throw new Error('name at least one view');for (const v of views) {if (!(v in MODEL_VIEWS)) throw new Error(`unknown view "${v}"; there are ${Object.keys(MODEL_VIEWS).join(', ')}`);}const { poly, triangles } = model;- const { min, max } = boundsOf(poly);+ let framed: Iterable<number> | undefined;+ if (focus !== undefined) {+ const hit = selectFaces(poly, focus);+ if (hit.length === 0) throw new Error(`focus ${JSON.stringify(focus)} matched no face`);+ framed = new Set(hit.flatMap((f) => poly.faces[f]!.v));+ }+ const { min, max } = boundsOf(poly, framed);const center: Vec3 = [(min[0] + max[0]) / 2, (min[1] + max[1]) / 2, (min[2] + max[2]) / 2];// The bounding sphere's diameter fits every view, the iso one included.const diameter = Math.hypot(max[0] - min[0], max[1] - min[1], max[2] - min[2]) || 1;@@ -76,6 +85,13 @@ export function renderModelSheet(model: BakedModel, views: readonly ModelViewNamrgba[at] = c[0]!; rgba[at + 1] = c[1]!; rgba[at + 2] = c[2]!; rgba[at + 3] = 255;};const normals = poly.faces.map((f) => faceNormal(poly, f));+ // A skin is shaded by its vertices, or a fine grid reads as gravel and hides the form being judged.+ const vertexNormals: (Vec3 | undefined)[] = [];+ poly.faces.forEach((f, i) => {+ if (!f.smooth) return;+ for (const v of f.v) vertexNormals[v] = add(vertexNormals[v] ?? [0, 0, 0], normals[i]!);+ });+ for (let i = 0; i < vertexNormals.length; i++) if (vertexNormals[i]) vertexNormals[i] = normalize(vertexNormals[i]!);const depth = new Float32Array(panel * panel);views.forEach((name, column) => {@@ -94,15 +110,15 @@ export function renderModelSheet(model: BakedModel, views: readonly ModelViewNamconst [a, b, c] = [screen[v[0]]!, screen[v[1]]!, screen[v[2]]!];const area = (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1]);if (Math.abs(area) < 1e-9) continue;- const n = normals[face]!;- const facing = dot(n, basis.toward);+ const flat = normals[face]!;+ const skin = poly.faces[face]!.smooth;+ const [na, nb, nc] = skin ? [vertexNormals[v[0]]!, vertexNormals[v[1]]!, vertexNormals[v[2]]!] : [flat, flat, flat];+ const facing = dot(flat, basis.toward);// A key from over the viewer's shoulder, so that facing faces still differ.- const key = dot(n, normalize([basis.toward[0] + basis.up[0] * 0.5 + basis.right[0] * 0.4,- basis.toward[1] + basis.up[1] * 0.5 + basis.right[1] * 0.4,- basis.toward[2] + basis.up[2] * 0.5 + basis.right[2] * 0.4]));- const light = facing > 0 ? 0.3 + 0.7 * Math.max(0, key) : 0.12; // a face seen from behind reads dark+ const keyDir = normalize([basis.toward[0] + basis.up[0] * 0.5 + basis.right[0] * 0.4,+ basis.toward[1] + basis.up[1] * 0.5 + basis.right[1] * 0.4,+ basis.toward[2] + basis.up[2] * 0.5 + basis.right[2] * 0.4]);const tint = poly.faces[face]!.color ?? [0.82, 0.82, 0.82, 1];- const rgb = [tint[0]! * light * 255, tint[1]! * light * 255, tint[2]! * light * 255];const x0 = Math.max(0, Math.floor(Math.min(a[0], b[0], c[0])));const x1 = Math.min(panel - 1, Math.ceil(Math.max(a[0], b[0], c[0])));const y0 = Math.max(0, Math.floor(Math.min(a[1], b[1], c[1])));@@ -118,13 +134,18 @@ export function renderModelSheet(model: BakedModel, views: readonly ModelViewNamconst z = w0 * a[2] + w1 * b[2] + w2 * c[2];if (z <= depth[y * panel + x]!) continue;depth[y * panel + x] = z;- put(ox + x, y, rgb);+ const nx = w0 * na[0] + w1 * nb[0] + w2 * nc[0], ny = w0 * na[1] + w1 * nb[1] + w2 * nc[1], nz = w0 * na[2] + w1 * nb[2] + w2 * nc[2];+ const len = Math.hypot(nx, ny, nz) || 1;+ const key = (nx * keyDir[0] + ny * keyDir[1] + nz * keyDir[2]) / len;+ const light = facing > 0 ? 0.3 + 0.7 * Math.max(0, key) : 0.12; // a face seen from behind reads dark+ put(ox + x, y, [tint[0]! * light * 255, tint[1]! * light * 255, tint[2]! * light * 255]);}}}// Polygon edges, on top of whatever they are not behind: what tells a person how the surface is built.const bias = unitsPerPixel * 2;for (const face of poly.faces) {+ if (face.smooth) continue;for (let i = 0; i < face.v.length; i++) {const a = screen[face.v[i]!]!, b = screen[face.v[(i + 1) % face.v.length]!]!;const steps = Math.max(1, Math.ceil(Math.max(Math.abs(b[0] - a[0]), Math.abs(b[1] - a[1]))));diff --git a/pipeline/src/modeling/organic.ts b/pipeline/src/modeling/organic.tsnew file mode 100644index 000000000..bc84e036e--- /dev/null+++ b/pipeline/src/modeling/organic.ts@@ -0,0 +1,511 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file organic.ts — a body from its parts: the `organic` step.+ *+ * Living shapes are what steps on polygons cannot say: a shoulder has no edges+ * to select. So this describes volumes instead, the way a person sketching a+ * creature does, as a torso, limbs running from a joint to a joint, a skull. Each+ * part melts into those before it by `blend`, or carves into them, and the skin+ * is found afterwards. Nothing needs its topology thought about, and moving a+ * shoulder is one number, which is what makes this something an agent can steer.+ *+ * The volume is a signed distance field; the skin is Naive Surface Nets over a+ * grid of it, with each vertex then settled onto the true surface. The result+ * is one more shell of quads, so every later step can act on it. Its faces are+ * marked smooth, and each carries the tag and colour of the part nearest it.+ */+import { add, type Face, type PolyMesh, type Vec3 } from './polyMesh';++export type OrganicShape = 'sphere' | 'ellipsoid' | 'box' | 'torus' | 'chain';++export interface OrganicNoise {+ /** How far the surface moves, in and out. */+ amplitude: number;+ /** Size of the bumps, in world units. */+ scale: number;+ octaves?: number;+ seed?: number;+}++export interface OrganicPart {+ shape: OrganicShape;+ tag?: string;+ at?: Vec3;+ /** Degrees, X then Y then Z: for ellipsoid, box and torus. */+ rotate?: Vec3;+ /** sphere; torus's ring. */+ radius?: number;+ /** ellipsoid's three half-axes. */+ radii?: Vec3;+ /** box's whole size. */+ size?: Vec3;+ /** box's corners. */+ rounding?: number;+ /** torus's thickness. */+ tube?: number;+ /** chain: a limb, a tail, a branch, as [x, y, z, radius] along its length. */+ points?: readonly (readonly [number, number, number, number])[];+ /** How far this melts into what is before it; 0 is a hard crease. Defaults to the step's. */+ blend?: number;+ /** Carves this volume out of what is before it: an eye socket, a mouth. */+ subtract?: boolean;+ /** Also exists reflected across this axis's zero plane: the other arm. */+ mirror?: 'x' | 'y' | 'z';+ color?: readonly number[];+ noise?: OrganicNoise;+}++export interface OrganicParams {+ parts: readonly OrganicPart[];+ /** Grid cells along the longest side. More resolves more detail, at the cost of triangles. */+ resolution?: number;+ blend?: number;+ noise?: OrganicNoise;+ at?: Vec3;+ tag?: string;+ color?: readonly number[];+}++export const ORGANIC_DEFAULT_RESOLUTION = 64;+export const ORGANIC_MAX_RESOLUTION = 160;+const DEG = Math.PI / 180;++type Color = readonly [number, number, number, number];+type Eval = (x: number, y: number, z: number) => number;++// ---- Noise: value noise, seeded and platform-independent, so a bake is the same everywhere ----++function hash3(x: number, y: number, z: number, seed: number): number {+ let h = Math.imul(x, 374761393) + Math.imul(y, 668265263) + Math.imul(z, 2147483647 - 1274126177) + Math.imul(seed, 1442695041);+ h = Math.imul(h ^ (h >>> 13), 1274126177);+ h ^= h >>> 16;+ return ((h >>> 0) / 4294967295) * 2 - 1;+}++const fade = (t: number): number => t * t * t * (t * (t * 6 - 15) + 10);+const mix = (a: number, b: number, t: number): number => a + (b - a) * t;++function valueNoise(x: number, y: number, z: number, seed: number): number {+ const [ix, iy, iz] = [Math.floor(x), Math.floor(y), Math.floor(z)];+ const [u, v, w] = [fade(x - ix), fade(y - iy), fade(z - iz)];+ const at = (dx: number, dy: number, dz: number): number => hash3(ix + dx, iy + dy, iz + dz, seed);+ return mix(+ mix(mix(at(0, 0, 0), at(1, 0, 0), u), mix(at(0, 1, 0), at(1, 1, 0), u), v),+ mix(mix(at(0, 0, 1), at(1, 0, 1), u), mix(at(0, 1, 1), at(1, 1, 1), u), v),+ w,+ );+}++function noiseField(n: OrganicNoise): Eval {+ const octaves = n.octaves ?? 3;+ const seed = n.seed ?? 1;+ return (x, y, z) => {+ let sum = 0, amp = 1, total = 0, f = 1 / n.scale;+ for (let o = 0; o < octaves; o++) {+ sum += amp * valueNoise(x * f, y * f, z * f, seed + o);+ total += amp;+ amp *= 0.5;+ f *= 2;+ }+ return (sum / total) * n.amplitude;+ };+}++// ---- Shapes ---------------------------------------------------------------------++/** World to part space: the inverse of rotating X, then Y, then Z. */+function inverseRotation(degrees: Vec3): (x: number, y: number, z: number, out: number[]) => void {+ const [cx, sx] = [Math.cos(degrees[0] * DEG), Math.sin(degrees[0] * DEG)];+ const [cy, sy] = [Math.cos(degrees[1] * DEG), Math.sin(degrees[1] * DEG)];+ const [cz, sz] = [Math.cos(degrees[2] * DEG), Math.sin(degrees[2] * DEG)];+ return (x, y, z, out) => {+ const ax = cz * x + sz * y, ay = -sz * x + cz * y;+ const bx = cy * ax - sy * z, bz = sy * ax + cy * z;+ out[0] = bx;+ out[1] = cx * ay + sx * bz;+ out[2] = -sx * ay + cx * bz;+ };+}++/** The part's distance function in its own frame, and how far from `at` it can reach. */+function shapeField(part: OrganicPart): { field: Eval; reach: number; thinnest: number } {+ const need = (name: keyof OrganicPart): void => {+ if (part[name] === undefined) throw new Error(`a ${part.shape} part needs \`${name}\``);+ };+ switch (part.shape) {+ case 'sphere': {+ need('radius');+ const r = part.radius!;+ if (r <= 0) throw new Error('radius must be positive');+ return { field: (x, y, z) => Math.sqrt(x * x + y * y + z * z) - r, reach: r, thinnest: r };+ }+ case 'ellipsoid': {+ need('radii');+ const [a, b, c] = part.radii!;+ if (a <= 0 || b <= 0 || c <= 0) throw new Error('radii must be positive');+ return {+ field: (x, y, z) => {+ const k0 = Math.sqrt((x * x) / (a * a) + (y * y) / (b * b) + (z * z) / (c * c));+ const k1 = Math.sqrt((x * x) / a ** 4 + (y * y) / b ** 4 + (z * z) / c ** 4);+ return k1 > 1e-12 ? (k0 * (k0 - 1)) / k1 : -Math.min(a, b, c);+ },+ reach: Math.max(a, b, c),+ thinnest: Math.min(a, b, c),+ };+ }+ case 'box': {+ need('size');+ const [hx, hy, hz] = [part.size![0] / 2, part.size![1] / 2, part.size![2] / 2];+ if (hx <= 0 || hy <= 0 || hz <= 0) throw new Error('size must be positive');+ const r = Math.min(part.rounding ?? 0, hx, hy, hz);+ return {+ field: (x, y, z) => {+ const qx = Math.abs(x) - hx + r, qy = Math.abs(y) - hy + r, qz = Math.abs(z) - hz + r;+ const ox = Math.max(qx, 0), oy = Math.max(qy, 0), oz = Math.max(qz, 0);+ return Math.sqrt(ox * ox + oy * oy + oz * oz) + Math.min(Math.max(qx, qy, qz), 0) - r;+ },+ reach: Math.hypot(hx, hy, hz),+ thinnest: Math.min(hx, hy, hz),+ };+ }+ case 'torus': {+ need('radius');+ need('tube');+ const [ring, tube] = [part.radius!, part.tube!];+ if (ring <= 0 || tube <= 0) throw new Error('radius and tube must be positive');+ return {+ field: (x, y, z) => {+ const q = Math.sqrt(x * x + z * z) - ring;+ return Math.sqrt(q * q + y * y) - tube;+ },+ reach: ring + tube,+ thinnest: tube,+ };+ }+ case 'chain': {+ need('points');+ const pts = part.points!;+ if (pts.length < 2) throw new Error(`a chain needs at least 2 points, not ${pts.length}`);+ if (pts.some((p) => p[3] <= 0)) throw new Error('every chain point needs a positive radius, its fourth number');+ return {+ field: (x, y, z) => {+ let best = Infinity;+ for (let i = 0; i + 1 < pts.length; i++) {+ const a = pts[i]!, b = pts[i + 1]!;+ const [bx, by, bz] = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];+ const [px, py, pz] = [x - a[0], y - a[1], z - a[2]];+ const len2 = bx * bx + by * by + bz * bz;+ const t = len2 > 0 ? Math.min(1, Math.max(0, (px * bx + py * by + pz * bz) / len2)) : 0;+ const [dx, dy, dz] = [px - bx * t, py - by * t, pz - bz * t];+ const d = Math.sqrt(dx * dx + dy * dy + dz * dz) - (a[3] + (b[3] - a[3]) * t);+ if (d < best) best = d;+ }+ return best;+ },+ reach: Math.max(...pts.map((p) => Math.hypot(p[0], p[1], p[2]) + p[3])),+ // Its widest: a limb tapering to a point past the grid is a limb, and only one wholly under it goes missing.+ thinnest: Math.max(...pts.map((p) => p[3])),+ };+ }+ default:+ throw new Error(`unknown shape ${JSON.stringify(part.shape)}; there are sphere, ellipsoid, box, torus, chain`);+ }+}++interface CompiledPart {+ distance: Eval;+ blend: number;+ subtract: boolean;+ tag: string;+ color: Color | null;+ min: Vec3;+ max: Vec3;+ thinnest: number;+ label: string;+}++const toColor = (c: readonly number[] | undefined): Color | null => {+ if (!c) return null;+ if ((c.length !== 3 && c.length !== 4) || c.some((v) => v < 0 || v > 1)) {+ throw new Error(`color ${JSON.stringify(c)} must be [r, g, b] or [r, g, b, a], each 0..1 (linear)`);+ }+ return [c[0]!, c[1]!, c[2]!, c[3] ?? 1];+};++function compilePart(part: OrganicPart, index: number, params: OrganicParams): CompiledPart {+ const { field, reach, thinnest } = shapeField(part);+ const at = part.at ?? [0, 0, 0];+ const noise = part.noise ? noiseField(part.noise) : null;+ const rotate = part.rotate && part.shape !== 'sphere' && part.shape !== 'chain' ? inverseRotation(part.rotate) : null;+ const local = [0, 0, 0];+ const axis = part.mirror === undefined ? -1 : { x: 0, y: 1, z: 2 }[part.mirror];+ const label = part.tag ? `"${part.tag}"` : `${index}`;+ if (part.rotate && !rotate) throw new Error(`part ${label}: rotate means nothing on a ${part.shape}`);++ const distance: Eval = (wx, wy, wz) => {+ let x = wx, y = wy, z = wz;+ // Folded across the plane: both halves of a symmetric pair are one evaluation, and meet without a seam of their own.+ if (axis === 0) x = Math.abs(x);+ else if (axis === 1) y = Math.abs(y);+ else if (axis === 2) z = Math.abs(z);+ x -= at[0]; y -= at[1]; z -= at[2];+ if (rotate) { rotate(x, y, z, local); x = local[0]!; y = local[1]!; z = local[2]!; }+ const d = field(x, y, z);+ return noise ? d + noise(wx, wy, wz) : d;+ };++ const margin = part.noise?.amplitude ?? 0;+ const extent = reach + margin;+ let min: Vec3, max: Vec3;+ if (part.shape === 'chain') {+ // A chain's points are already placed by `at`'s offset.+ const pts = part.points!;+ min = [0, 1, 2].map((k) => Math.min(...pts.map((p) => p[k]! - p[3])) + at[k]! - margin) as unknown as Vec3;+ max = [0, 1, 2].map((k) => Math.max(...pts.map((p) => p[k]! + p[3])) + at[k]! + margin) as unknown as Vec3;+ } else {+ min = [at[0] - extent, at[1] - extent, at[2] - extent];+ max = [at[0] + extent, at[1] + extent, at[2] + extent];+ }+ if (axis >= 0) {+ // The reflection is in the bounds too.+ const lo = [...min], hi = [...max];+ lo[axis] = Math.min(min[axis]!, -max[axis]!);+ hi[axis] = Math.max(max[axis]!, -min[axis]!);+ min = lo as unknown as Vec3;+ max = hi as unknown as Vec3;+ }+ const blend = part.blend ?? params.blend ?? 0;+ if (blend < 0) throw new Error(`part ${label}: blend ${blend} must not be negative`);+ return {+ distance, blend, subtract: part.subtract === true, tag: part.tag ?? params.tag ?? '',+ color: toColor(part.color), min, max, thinnest, label,+ };+}++// ---- The whole body ------------------------------------------------------------++/** Folds the parts in order. `h` is how much of the running result survives the part, 0..1: smooth min's own weight. */+function bodyField(parts: readonly CompiledPart[], noise: Eval | null): Eval {+ return (x, y, z) => {+ let d = Infinity;+ for (const part of parts) {+ const p = part.distance(x, y, z);+ if (part.subtract) {+ const k = part.blend;+ if (k <= 0) { d = Math.max(d, -p); continue; }+ const h = Math.min(1, Math.max(0, 0.5 - (0.5 * (d + p)) / k));+ d = mix(d, -p, h) + k * h * (1 - h);+ } else {+ const k = part.blend;+ if (k <= 0 || d === Infinity) { d = Math.min(d, p); continue; }+ const h = Math.min(1, Math.max(0, 0.5 + (0.5 * (p - d)) / k));+ d = mix(p, d, h) - k * h * (1 - h);+ }+ }+ return noise ? d + noise(x, y, z) : d;+ };+}++/** Which part owns a point on the skin, and the colour there: the same fold, tracking what each step's weight kept. */+function paintAt(parts: readonly CompiledPart[], base: Color | null, x: number, y: number, z: number): { tag: string; color: Color | null } {+ let d = Infinity;+ let tag = '';+ let color: Color | null = base;+ const take = (part: CompiledPart, weight: number): void => {+ // `weight` is how much the part shows here.+ if (weight > 0.5) tag = part.tag;+ const c = part.color ?? base;+ if (c && color && c !== color) color = [0, 1, 2, 3].map((i) => mix(color![i]!, c[i]!, weight)) as unknown as Color;+ else if (c && !color && weight > 0.5) color = c;+ };+ for (const part of parts) {+ const p = part.distance(x, y, z);+ const k = Math.max(part.blend, 1e-5);+ if (part.subtract) {+ const h = Math.min(1, Math.max(0, 0.5 - (0.5 * (d + p)) / k));+ d = mix(d, -p, h) + k * h * (1 - h);+ if (part.color) take(part, h);+ } else if (d === Infinity) {+ d = p;+ tag = part.tag;+ color = part.color ?? base;+ } else {+ const h = Math.min(1, Math.max(0, 0.5 + (0.5 * (p - d)) / k));+ d = mix(p, d, h) - k * h * (1 - h);+ take(part, 1 - h);+ }+ }+ return { tag, color };+}++/** Under this many quads, a separate piece of skin is the grid losing a thin tip, never a part: a part is refused long before it is this small. */+const SPECK_QUADS = 24;++/** The quads without the specks a taper past the grid's resolution leaves floating off its end. */+function keepLargeIslands(quads: readonly number[][], vertices: number): number[][] {+ const parent = Array.from({ length: vertices }, (_, i) => i);+ const find = (i: number): number => {+ let at = i;+ while (parent[at] !== at) { parent[at] = parent[parent[at]!]!; at = parent[at]!; }+ return at;+ };+ for (const q of quads) for (let i = 1; i < 4; i++) parent[find(q[i]!)] = find(q[0]!);+ const size = new Map<number, number>();+ for (const q of quads) size.set(find(q[0]!), (size.get(find(q[0]!)) ?? 0) + 1);+ return quads.filter((q) => size.get(find(q[0]!))! >= SPECK_QUADS);+}++/** One more shell: the skin of @p params' parts, in the steps' usual outward winding. */+export function organic(mesh: PolyMesh, params: OrganicParams): PolyMesh {+ if (!params.parts?.length) throw new Error('`parts` names nothing to build');+ const resolution = params.resolution ?? ORGANIC_DEFAULT_RESOLUTION;+ if (!Number.isInteger(resolution) || resolution < 8 || resolution > ORGANIC_MAX_RESOLUTION) {+ throw new Error(`resolution ${resolution} must be a whole number, 8..${ORGANIC_MAX_RESOLUTION}`);+ }+ const parts = params.parts.map((p, i) => {+ try {+ return compilePart(p, i, params);+ } catch (e) {+ throw new Error(`part ${p.tag ? `"${p.tag}"` : i}: ${(e as Error).message}`);+ }+ });+ if (parts[0]!.subtract) throw new Error('the first part cannot subtract: there is nothing yet to carve');+ const adding = parts.filter((p) => !p.subtract);++ const noise = params.noise ? noiseField(params.noise) : null;+ const field = bodyField(parts, noise);+ const margin = (params.noise?.amplitude ?? 0) + Math.max(...adding.map((p) => p.blend));+ const min = [0, 1, 2].map((k) => Math.min(...adding.map((p) => p.min[k]!)) - margin);+ const max = [0, 1, 2].map((k) => Math.max(...adding.map((p) => p.max[k]!)) + margin);+ const longest = Math.max(max[0]! - min[0]!, max[1]! - min[1]!, max[2]! - min[2]!);+ const cell = longest / resolution;++ // A part the grid cannot see simply is not in the result, and it reads as a model that ignored the request.+ for (const part of parts) {+ if (part.thinnest * 2 < cell * 1.5) {+ const needed = Math.ceil((longest * 1.5) / (part.thinnest * 2));+ throw new Error(`part ${part.label} is ${(part.thinnest * 2).toFixed(4)} across, too thin for the grid's cell of ${cell.toFixed(4)}, so it would vanish; `+ + (needed <= ORGANIC_MAX_RESOLUTION+ ? `make it thicker or raise resolution to at least ${needed}`+ : `make it at least ${((longest / ORGANIC_MAX_RESOLUTION) * 1.5).toFixed(4)} across, or build this body smaller and separate from its small details`));+ }+ }++ const pad = 2;+ const [nx, ny, nz] = [0, 1, 2].map((k) => Math.ceil((max[k]! - min[k]!) / cell) + pad * 2 + 1) as [number, number, number];+ const ox = min[0]! - pad * cell, oy = min[1]! - pad * cell, oz = min[2]! - pad * cell;+ const values = new Float32Array(nx * ny * nz);+ const idx = (i: number, j: number, k: number): number => i + nx * (j + ny * k);+ // Most of the grid is nowhere near the skin and only its sign is ever read. A block whose centre is clearly further+ // from the surface than the block is wide takes that one value. Doubled, as an ellipsoid's distance is an estimate.+ const BLOCK = 4;+ const clear = Math.sqrt(3) * BLOCK * cell;+ for (let bk = 0; bk < nz; bk += BLOCK) {+ for (let bj = 0; bj < ny; bj += BLOCK) {+ for (let bi = 0; bi < nx; bi += BLOCK) {+ const centre = field(ox + (bi + BLOCK / 2) * cell, oy + (bj + BLOCK / 2) * cell, oz + (bk + BLOCK / 2) * cell);+ const far = Math.abs(centre) > clear;+ for (let k = bk; k < Math.min(nz, bk + BLOCK); k++) {+ for (let j = bj; j < Math.min(ny, bj + BLOCK); j++) {+ for (let i = bi; i < Math.min(nx, bi + BLOCK); i++) {+ values[idx(i, j, k)] = far ? centre : field(ox + i * cell, oy + j * cell, oz + k * cell);+ }+ }+ }+ }+ }+ }++ // Surface Nets: one vertex per cell the surface passes through, at the mean of where it crosses that cell's edges.+ const CORNERS = [[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0], [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1]] as const;+ const EDGES = [[0, 1], [2, 3], [4, 5], [6, 7], [0, 2], [1, 3], [4, 6], [5, 7], [0, 4], [1, 5], [2, 6], [3, 7]] as const;+ const cellVertex = new Int32Array(nx * ny * nz).fill(-1);+ const positions: Vec3[] = [];+ const corner = new Float32Array(8);+ for (let k = 0; k < nz - 1; k++) {+ for (let j = 0; j < ny - 1; j++) {+ for (let i = 0; i < nx - 1; i++) {+ let inside = 0;+ for (let c = 0; c < 8; c++) {+ const v = values[idx(i + CORNERS[c]![0], j + CORNERS[c]![1], k + CORNERS[c]![2])]!;+ corner[c] = v;+ if (v < 0) inside++;+ }+ if (inside === 0 || inside === 8) continue;+ let sx = 0, sy = 0, sz = 0, count = 0;+ for (const [a, b] of EDGES) {+ const va = corner[a]!, vb = corner[b]!;+ if ((va < 0) === (vb < 0)) continue;+ const t = va / (va - vb);+ const A = CORNERS[a]!, B = CORNERS[b]!;+ sx += A[0] + (B[0] - A[0]) * t;+ sy += A[1] + (B[1] - A[1]) * t;+ sz += A[2] + (B[2] - A[2]) * t;+ count++;+ }+ cellVertex[idx(i, j, k)] = positions.length;+ positions.push([ox + (i + sx / count) * cell, oy + (j + sy / count) * cell, oz + (k + sz / count) * cell]);+ }+ }+ }+ if (positions.length === 0) throw new Error('these parts leave no surface: everything was carved away');++ // Settled onto the true surface: the mean of the crossings is only near it, and that is what makes a grid show through as terracing.+ const e = cell * 0.25;+ for (let n = 0; n < positions.length; n++) {+ let [x, y, z] = positions[n]!;+ for (let step = 0; step < 2; step++) {+ const d = field(x, y, z);+ const gx = field(x + e, y, z) - field(x - e, y, z);+ const gy = field(x, y + e, z) - field(x, y - e, z);+ const gz = field(x, y, z + e) - field(x, y, z - e);+ const g2 = (gx * gx + gy * gy + gz * gz) / (4 * e * e);+ if (g2 < 1e-8) break;+ // Bounded, so a crease's bad gradient cannot throw a vertex across the cell.+ const s = Math.max(-cell * 0.5, Math.min(cell * 0.5, d / Math.sqrt(g2)));+ const n2 = Math.sqrt(g2) * 2 * e;+ x -= (s * gx) / n2; y -= (s * gy) / n2; z -= (s * gz) / n2;+ }+ positions[n] = [x, y, z];+ }++ // A quad across every grid edge the surface crosses, wound by which end is inside.+ const quads: number[][] = [];+ const quad = (a: number, b: number, c: number, d: number, flip: boolean): void => {+ if (a < 0 || b < 0 || c < 0 || d < 0) return;+ quads.push(flip ? [d, c, b, a] : [a, b, c, d]);+ };+ for (let k = 1; k < nz - 1; k++) {+ for (let j = 1; j < ny - 1; j++) {+ for (let i = 1; i < nx - 1; i++) {+ const here = values[idx(i, j, k)]! < 0;+ if (here !== (values[idx(i + 1, j, k)]! < 0)) {+ quad(cellVertex[idx(i, j - 1, k - 1)]!, cellVertex[idx(i, j, k - 1)]!, cellVertex[idx(i, j, k)]!, cellVertex[idx(i, j - 1, k)]!, !here);+ }+ if (here !== (values[idx(i, j + 1, k)]! < 0)) {+ quad(cellVertex[idx(i - 1, j, k - 1)]!, cellVertex[idx(i - 1, j, k)]!, cellVertex[idx(i, j, k)]!, cellVertex[idx(i, j, k - 1)]!, !here);+ }+ if (here !== (values[idx(i, j, k + 1)]! < 0)) {+ quad(cellVertex[idx(i - 1, j - 1, k)]!, cellVertex[idx(i, j - 1, k)]!, cellVertex[idx(i, j, k)]!, cellVertex[idx(i - 1, j, k)]!, !here);+ }+ }+ }+ }++ const base = toColor(params.color);+ const at = params.at ?? [0, 0, 0];+ const start = mesh.positions.length;+ const faces: Face[] = keepLargeIslands(quads, positions.length).map((loop) => {+ let cx = 0, cy = 0, cz = 0;+ for (const v of loop) {+ cx += positions[v]![0]; cy += positions[v]![1]; cz += positions[v]![2];+ }+ const { tag, color } = paintAt(parts, base, cx / 4, cy / 4, cz / 4);+ return { v: loop.map((v) => v + start), tag: tag || params.tag || '', smooth: true, ...(color ? { color } : {}) };+ });+ return {+ positions: [...mesh.positions, ...positions.map((p) => add(p, at))],+ faces: [...mesh.faces, ...faces],+ };+}diff --git a/pipeline/src/modeling/polyMesh.ts b/pipeline/src/modeling/polyMesh.tsindex 985cb930e..9d1561317 100644--- a/pipeline/src/modeling/polyMesh.ts+++ b/pipeline/src/modeling/polyMesh.ts@@ -18,6 +18,8 @@ export interface Face {tag: string;/** Linear RGBA, as MeshRenderer.color is; absent draws white. */color?: readonly [number, number, number, number];+ /** Part of a continuous skin: shaded smooth with its neighbours whatever the angle, and its edges are not features. */+ smooth?: boolean;}export interface PolyMesh {diff --git a/pipeline/tests/modeling-organic.test.ts b/pipeline/tests/modeling-organic.test.tsnew file mode 100644index 000000000..9761c52aa--- /dev/null+++ b/pipeline/tests/modeling-organic.test.ts@@ -0,0 +1,234 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * The organic step, held to its sums: a skin that closes and points out, the volume+ * a shape must enclose, and refusals that say what to change.+ */+import { describe, expect, it } from 'vitest';+import { MeshChannel } from 'esengine';+import { bakeModel, renderModelSheet, validateModelSource, type BakedModel, type OrganicPart } from '../src/modeling';++const body = (parts: OrganicPart[], extra: Record<string, unknown> = {}): BakedModel =>+ bakeModel({ version: 1, steps: [{ op: 'organic', resolution: 48, parts, ...extra }] });++function volume(m: BakedModel): number {+ let v = 0;+ for (const { v: [a, b, c] } of m.triangles) {+ const [p, q, r] = [m.poly.positions[a]!, m.poly.positions[b]!, m.poly.positions[c]!];+ v += p[0] * (q[1] * r[2] - q[2] * r[1]) + p[1] * (q[2] * r[0] - q[0] * r[2]) + p[2] * (q[0] * r[1] - q[1] * r[0]);+ }+ return v / 6;+}++function expectClosed(m: BakedModel): void {+ expect(m.report.openEdges).toBe(0);+ expect(m.report.insideOutShells).toBe(0);+ expect(m.report.shells).toBe(1);+}++const sphereVolume = (r: number): number => (4 / 3) * Math.PI * r ** 3;++describe('shapes', () => {+ it.each<[string, OrganicPart, number]>([+ ['sphere', { shape: 'sphere', radius: 1 }, sphereVolume(1)],+ ['ellipsoid', { shape: 'ellipsoid', radii: [1, 0.5, 0.75] }, (4 / 3) * Math.PI * 1 * 0.5 * 0.75],+ ['box', { shape: 'box', size: [2, 1, 1] }, 2],+ ['torus', { shape: 'torus', radius: 1, tube: 0.3 }, 2 * Math.PI ** 2 * 1 * 0.3 ** 2],+ // A capsule: the cylinder and the two ends of a uniform chain.+ ['chain', { shape: 'chain', points: [[0, 0, 0, 0.5], [0, 2, 0, 0.5]] }, Math.PI * 0.25 * 2 + sphereVolume(0.5)],+ ])('%s closes, points out and holds the right volume', (_, part, expected) => {+ const m = body([part], { resolution: 64 });+ expectClosed(m);+ expect(Math.abs(volume(m) - expected) / expected).toBeLessThan(0.02);+ });++ it('rotates a part about its own centre', () => {+ const m = body([{ shape: 'box', size: [2, 0.5, 0.5], at: [3, 0, 0], rotate: [0, 0, 90] }]);+ expect(m.report.bounds.size[1]).toBeGreaterThan(1.9);+ expect(m.report.bounds.size[0]).toBeLessThan(0.6);+ expect(m.report.bounds.center[0]).toBeCloseTo(3, 1);+ });++ it('a rotation on a shape that has none to give is a mistake', () => {+ expect(() => body([{ shape: 'sphere', radius: 1, rotate: [0, 45, 0] }])).toThrow(/rotate means nothing on a sphere/);+ });+});++describe('how parts combine', () => {+ const a: OrganicPart = { shape: 'sphere', radius: 1, at: [-0.8, 0, 0] };+ const b: OrganicPart = { shape: 'sphere', radius: 1, at: [0.8, 0, 0] };++ it('blend fills the join: more volume than the hard union, and still one piece', () => {+ const hard = volume(body([a, b], { resolution: 64 }));+ const soft = volume(body([a, { ...b, blend: 0.6 }], { resolution: 64 }));+ expect(soft).toBeGreaterThan(hard * 1.02);+ expect(hard).toBeLessThan(2 * sphereVolume(1));+ });++ it('two parts apart stay two shells', () => {+ const m = body([{ ...a, at: [-3, 0, 0] }, { ...b, at: [3, 0, 0] }]);+ expect(m.report.shells).toBe(2);+ });++ it('subtract carves, and a colour on it paints the cut', () => {+ const whole = body([{ shape: 'sphere', radius: 1 }], { resolution: 64 });+ const carved = body([+ { shape: 'sphere', radius: 1, color: [1, 1, 1] },+ { shape: 'sphere', radius: 0.5, at: [0, 0, 1], subtract: true, color: [1, 0, 0], tag: 'mouth' },+ ], { resolution: 64 });+ expectClosed(carved);+ expect(volume(carved)).toBeLessThan(volume(whole) * 0.97);+ expect(carved.report.tags.mouth).toBeGreaterThan(0);+ const red = carved.poly.faces.filter((f) => f.tag === 'mouth');+ expect(red.every((f) => f.color![1]! < 0.5)).toBe(true);+ });++ it('a first part cannot subtract: there is nothing to carve', () => {+ expect(() => body([{ shape: 'sphere', radius: 1, subtract: true }])).toThrow(/first part cannot subtract/);+ });++ it('carving everything away is said, not baked to nothing', () => {+ expect(() => body([{ shape: 'sphere', radius: 1 }, { shape: 'sphere', radius: 3, subtract: true }])).toThrow(/carved away/);+ });++ it('mirror makes the other side, exactly', () => {+ const m = body([+ { shape: 'sphere', radius: 1 },+ { shape: 'chain', mirror: 'x', points: [[0.8, 0, 0, 0.3], [2, 0, 0, 0.2]], tag: 'arm' },+ ], { blend: 0.1 });+ expectClosed(m);+ expect(m.report.bounds.min[0]).toBeCloseTo(-m.report.bounds.max[0], 1);+ expect(m.report.bounds.max[0]).toBeGreaterThan(2.1);+ });+});++describe('what the skin carries', () => {+ const creature = body([+ { shape: 'sphere', radius: 1, tag: 'torso', color: [0, 1, 0] },+ { shape: 'sphere', radius: 0.5, at: [0, 1.3, 0], tag: 'head', color: [1, 0, 0], blend: 0.05 },+ ], { blend: 0.2 });++ it('each face takes the tag and colour of the part nearest it', () => {+ expect(creature.report.tags.torso).toBeGreaterThan(creature.report.tags.head!);+ const faces = creature.poly.faces;+ const top = faces.filter((f) => f.tag === 'head');+ expect(top.every((f) => f.color![0]! > f.color![1]!)).toBe(true);+ });++ it('a later step can act on a part by its tag', () => {+ const m = bakeModel({ version: 1, steps: [+ { op: 'organic', resolution: 32, parts: [{ shape: 'sphere', radius: 1, tag: 'a' }, { shape: 'sphere', radius: 1, at: [5, 0, 0], tag: 'b' }] },+ { op: 'paint', faces: 'b', color: [0, 0, 1] },+ ] });+ expect(m.poly.faces.filter((f) => f.color).every((f) => f.tag === 'b')).toBe(true);+ });++ it('is shaded smooth: a normal per vertex position, whatever the source angle', () => {+ const at = creature.data.channels.find((c) => c.semantic === MeshChannel.Normal)!.offset;+ const posAt = creature.data.channels.find((c) => c.semantic === MeshChannel.Position)!.offset;+ const view = new DataView(creature.data.vertices.buffer);+ const seen = new Map<string, Set<string>>();+ for (let i = 0; i < creature.data.vertexCount; i++) {+ const base = i * creature.data.vertexStride;+ const p = [0, 1, 2].map((k) => view.getFloat32(base + posAt + k * 4, true).toFixed(4)).join();+ const n = [0, 1, 2].map((k) => view.getFloat32(base + at + k * 4, true).toFixed(2)).join();+ const set = seen.get(p) ?? new Set();+ set.add(n);+ seen.set(p, set);+ }+ expect(Math.max(...[...seen.values()].map((s) => s.size))).toBeLessThanOrEqual(2); // rounding only+ });++ it('survives in a source alongside polygon steps and hard shells', () => {+ const m = bakeModel({ version: 1, steps: [+ { op: 'box', size: 1, at: [5, 0, 0], tag: 'crate' },+ { op: 'organic', resolution: 32, parts: [{ shape: 'sphere', radius: 1 }] },+ ] });+ expect(m.report.shells).toBe(2);+ expect(m.poly.faces.filter((f) => f.smooth).length).toBeGreaterThan(100);+ expect(m.poly.faces.filter((f) => !f.smooth).length).toBe(6);+ });+});++describe('noise', () => {+ const rock = (seed: number): BakedModel => body([{ shape: 'sphere', radius: 1 }], { noise: { amplitude: 0.1, scale: 0.4, seed } });++ it('roughens the surface, the same way every time, and differently per seed', () => {+ const r = (m: BakedModel): number[] => m.poly.positions.map((p) => Math.hypot(p[0], p[1], p[2]));+ const radii = r(rock(1));+ expect(Math.max(...radii) - Math.min(...radii)).toBeGreaterThan(0.05);+ expect(rock(1).poly.positions).toEqual(rock(1).poly.positions);+ expect(rock(2).poly.positions).not.toEqual(rock(1).poly.positions);+ });++ it('on one part leaves the others smooth', () => {+ const m = body([+ { shape: 'sphere', radius: 1, tag: 'smooth' },+ { shape: 'sphere', radius: 1, at: [3, 0, 0], tag: 'rough', noise: { amplitude: 0.1, scale: 0.3 } },+ ]);+ const radii = m.poly.faces.filter((f) => f.tag === 'smooth').flatMap((f) => f.v).map((i) => Math.hypot(...m.poly.positions[i]!));+ expect(Math.max(...radii) - Math.min(...radii)).toBeLessThan(0.01);+ });+});++describe('refusals name what to change', () => {+ it('a part the grid cannot see', () => {+ expect(() => body([{ shape: 'sphere', radius: 1 }, { shape: 'sphere', radius: 0.01, at: [1, 0, 0], tag: 'wart' }])).toThrow(/part "wart" .*too thin.*raise resolution to at least \d+/);+ });++ it('past the most resolution there is', () => {+ expect(() => body([{ shape: 'sphere', radius: 10 }, { shape: 'sphere', radius: 0.01, tag: 'wart' }])).toThrow(/part "wart" .*make it at least/);+ });++ it('a tapering limb is judged by its widest, not its tip', () => {+ expect(() => body([{ shape: 'chain', points: [[0, 0, 0, 0.5], [0, 3, 0, 0.001]] }])).not.toThrow();+ });++ it('the tip of a taper past the grid leaves no floating specks', () => {+ const m = body([{ shape: 'chain', points: [[0, 0, 0, 0.4], [0, 3, 0, 0.05], [0, 5, 0, 0.002]] }], {+ noise: { amplitude: 0.03, scale: 0.1, seed: 4 }, resolution: 40,+ });+ expect(m.report.shells).toBe(1);+ });++ it('a misspelt field in a part, listing the ones it takes', () => {+ expect(() => validateModelSource({ steps: [{ op: 'organic', parts: [{ shape: 'sphere', radious: 1 }] }] })).toThrow(/\[0\] has an unknown field "radious"; a part takes shape/);+ });++ it('a shape without what it needs, and a shape there is not', () => {+ expect(() => body([{ shape: 'ellipsoid' }])).toThrow(/part 0: a ellipsoid part needs `radii`/);+ expect(() => validateModelSource({ steps: [{ op: 'organic', parts: [{ shape: 'blob' }] }] })).toThrow(/shape must be sphere/);+ });++ it('a resolution out of range', () => {+ expect(() => body([{ shape: 'sphere', radius: 1 }], { resolution: 500 })).toThrow(/resolution 500 must be/);+ });+});++describe('looking at one', () => {+ const m = body([+ { shape: 'sphere', radius: 1, tag: 'body' },+ { shape: 'sphere', radius: 0.15, at: [0, 1.05, 0], tag: 'knob', blend: 0.02 },+ ], { resolution: 64 });++ it('focus fills the panel with that part, by the selector steps use', () => {+ const whole = renderModelSheet(m, ['front'], 128);+ const close = renderModelSheet(m, ['front'], 128, 'knob');+ expect(close.unitsPerPixel).toBeLessThan(whole.unitsPerPixel / 3);+ });++ it('refuses a focus that names nothing', () => {+ expect(() => renderModelSheet(m, ['front'], 64, 'nope')).toThrow(/focus "nope" matched no face/);+ });++ it('draws no wire over a skin: the form is what is being judged', () => {+ const s = renderModelSheet(m, ['front'], 128);+ let dark = 0;+ for (let y = 0; y < 128; y++) {+ for (let x = 0; x < 128; x++) {+ if (s.rgba[(y * s.width + x) * 4]! < 45) dark++;+ }+ }+ expect(dark).toBe(0);+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 53c9f2e0b..ee844120b 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -3866,6 +3866,10 @@ export const NOTED = {{"note":"A sea seen from above is no longer scored with straight lines."},"feat(mcp): an agent builds a 3D model in the editor from steps, changes it by one number, and sees every side of it":{"note":"AI agents can build 3D models in the editor from steps."},+ "feat(modeling): an organic step makes one skin over parts that melt into each other, so an agent can build creatures, plants and rocks":+ {"note":"AI agents can build 3D models in the editor from steps."},+ "feat(mcp): model_views looks at one part up close and from more sides, and model_write explains how to build a body":+ {"note":"AI agents can build 3D models in the editor from steps."},"feat(modeling): a model is the steps that build it, baked to the mesh a scene draws, so one number changes the whole shape":{"note":"AI agents can build 3D models in the editor from steps."},};