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): a model is the steps that build it, baked to the mesh a scene draws, so one number changes the whole shape
yhhee2a747287eb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 36d172e3a..608c450ba 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,8 @@ 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.+- **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.### Fixeddiff --git a/desktop b/desktopindex 37893949f..9cb5663cd 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 37893949f3700b5810b310035d27677130f79cd3+Subproject commit 9cb5663cd1b28e2947f93aec390a1edc9904b14ddiff --git a/pipeline/src/modeling/index.ts b/pipeline/src/modeling/index.tsnew file mode 100644index 000000000..728b71962--- /dev/null+++ b/pipeline/src/modeling/index.ts@@ -0,0 +1,12 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Modeling: `.esmodel` sources, the steps they run, and the `.esmesh` they bake to.+ * Pure: no filesystem and no engine instance, so the editor and a test run the same code.+ */+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 { bakeModel, type BakedModel, type ModelReport } from './modelBake';+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.tsnew file mode 100644index 000000000..04cb4bfb5--- /dev/null+++ b/pipeline/src/modeling/modelBake.ts@@ -0,0 +1,272 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file modelBake.ts — from polygons to the `.esmesh` a scene draws, and the report+ * that says what came out.+ *+ * The report exists because the caller often cannot look: a model that says+ * "2 open edges" or "this shell is inside out" gets fixed on the next call,+ * where the same fault in a lit picture reads as a slightly odd shadow.+ */+import { MeshChannel, MeshChannelType, packChannels, unwrapLightmapUV, type MeshData } from 'esengine';+import { buildPolyMesh, validateModelSource, type ModelSource, type StepReport } from './modelSource';+import {+ boundsOf, collectEdges, cross, dot, faceArea, faceNormal, length, normalize, sub,+ type Face, type PolyMesh, type Vec3,+} from './polyMesh';++const DEFAULT_SMOOTH_ANGLE = 30;++export interface ModelReport {+ vertices: number;+ triangles: number;+ faces: number;+ /** Separate connected pieces. A building of a body and a roof that never share a vertex is two, and that is fine. */+ shells: number;+ bounds: { min: Vec3; max: Vec3; size: Vec3; center: Vec3 };+ /** How many faces carry each tag. */+ tags: Record<string, number>;+ /** Edges with one face: a hole you can see into. */+ openEdges: number;+ /** Edges with three or more faces: something a later bevel will refuse. */+ nonManifoldEdges: number;+ /** Faces with no area, which draw nothing and shade badly beside them. */+ degenerateFaces: number;+ /** Closed shells whose faces point inward, which render as their own inside. */+ insideOutShells: number;+ steps: StepReport[];+ /** The findings above that are worth stopping for, as sentences. */+ warnings: string[];+}++export interface BakedModel {+ poly: PolyMesh;+ data: MeshData;+ report: ModelReport;+ /** One triangle per entry: its three positions' indices, and the face it came from. */+ triangles: { v: [number, number, number]; face: number }[];+}++// ---- Triangulation ---------------------------------------------------------------++/** Ear clipping in the face's own plane: n-gons here can be concave (a prism's floor plan). */+function triangulateFace(mesh: PolyMesh, face: Face): [number, number, number][] {+ const count = face.v.length;+ if (count < 3) return [];+ if (count === 3) return [[face.v[0]!, face.v[1]!, face.v[2]!]];+ const n = faceNormal(mesh, face);+ const ref = Math.abs(n[0]) < 0.9 ? [1, 0, 0] as Vec3 : [0, 1, 0] as Vec3;+ const u = normalize(cross(ref, n));+ const w = cross(n, u);+ const flat = face.v.map((i) => {+ const p = mesh.positions[i]!;+ return [dot(p, u), dot(p, w)] as const;+ });+ const area2 = (a: number, b: number, c: number): number => {+ const [ax, ay] = flat[a]!, [bx, by] = flat[b]!, [cx, cy] = flat[c]!;+ return (bx - ax) * (cy - ay) - (cx - ax) * (by - ay);+ };+ const span = Math.max(...flat.map((q) => Math.hypot(q[0] - flat[0]![0], q[1] - flat[0]![1])), 1e-9);+ const tiny = span * span * 1e-10;+ const out: [number, number, number][] = [];+ const loop = flat.map((_, i) => i);+ let guard = count * count + 8;+ while (loop.length > 3 && guard-- > 0) {+ let clipped = false;+ for (let i = 0; i < loop.length; i++) {+ const a = loop[(i + loop.length - 1) % loop.length]!, b = loop[i]!, c = loop[(i + 1) % loop.length]!;+ if (area2(a, b, c) <= tiny) continue; // reflex, or a vertex lying on a straight run (kept: a neighbour may rely on it)+ let blocked = false;+ for (const q of loop) {+ if (q === a || q === b || q === c) continue;+ if (area2(a, b, q) >= -tiny && area2(b, c, q) >= -tiny && area2(c, a, q) >= -tiny) { blocked = true; break; }+ }+ if (blocked) continue;+ out.push([face.v[a]!, face.v[b]!, face.v[c]!]);+ loop.splice(i, 1);+ clipped = true;+ break;+ }+ if (!clipped) break;+ }+ // What is left is a triangle, or a loop no ear could be cut from: a self-crossing face. Fanned, it still draws something to look at.+ for (let i = 1; i + 1 < loop.length; i++) {+ if (Math.abs(area2(loop[0]!, loop[i]!, loop[i + 1]!)) > tiny) {+ out.push([face.v[loop[0]!]!, face.v[loop[i]!]!, face.v[loop[i + 1]!]!]);+ }+ }+ return out;+}++// ---- Report -----------------------------------------------------------------------++/** Shells as lists of faces: faces sharing a vertex are one. */+function findShells(mesh: PolyMesh): number[][] {+ const parent = mesh.positions.map((_, 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 face of mesh.faces) for (let i = 1; i < face.v.length; i++) parent[find(face.v[i]!)] = find(face.v[0]!);+ const shells = new Map<number, number[]>();+ mesh.faces.forEach((face, f) => {+ if (face.v.length === 0) return;+ const root = find(face.v[0]!);+ const at = shells.get(root);+ if (at) at.push(f); else shells.set(root, [f]);+ });+ return [...shells.values()];+}++function signedVolume(mesh: PolyMesh, faces: readonly number[], tris: readonly [number, number, number][][]): number {+ let v = 0;+ for (const f of faces) {+ for (const [a, b, c] of tris[f]!) v += dot(mesh.positions[a]!, cross(mesh.positions[b]!, mesh.positions[c]!));+ }+ return v / 6;+}++// ---- Bake -------------------------------------------------------------------------++/** Per-corner normals: each face's, averaged with those of the faces round that vertex within @p smoothAngle. */+function cornerNormals(mesh: PolyMesh, smoothAngle: number): Vec3[][] {+ const normals = mesh.faces.map((f) => faceNormal(mesh, f));+ const cosine = Math.cos((smoothAngle * Math.PI) / 180);+ const around = new Map<number, number[]>();+ mesh.faces.forEach((face, f) => {+ for (const v of face.v) {+ const at = around.get(v);+ if (at) at.push(f); else around.set(v, [f]);+ }+ });+ 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]!;+ let sum: Vec3 = [0, 0, 0];+ for (const g of around.get(v)!) {+ if (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];+ }+ return length(sum) > 0 ? normalize(sum) : normals[f]!;+ }));+}++/** A box projection, face by face: the same scale everywhere, so a tiling texture does not stretch. */+function projectUv(p: Vec3, n: Vec3, uvScale: number): [number, number] {+ const [ax, ay, az] = [Math.abs(n[0]), Math.abs(n[1]), Math.abs(n[2])];+ if (ay >= ax && ay >= az) return [p[0] / uvScale, (n[1] > 0 ? -p[2] : p[2]) / uvScale];+ if (ax >= az) return [(n[0] > 0 ? -p[2] : p[2]) / uvScale, p[1] / uvScale];+ return [(n[2] > 0 ? p[0] : -p[0]) / uvScale, p[1] / uvScale];+}++function toMeshData(mesh: PolyMesh, triangles: readonly [number, number, number][][], source: ModelSource): MeshData {+ const { channels, vertexStride } = packChannels([+ { semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32 },+ { semantic: MeshChannel.TexCoord0, components: 2, type: MeshChannelType.Float32 },+ { semantic: MeshChannel.Color, components: 4, type: MeshChannelType.UNorm8 },+ { semantic: MeshChannel.Normal, components: 3, type: MeshChannelType.Float32 },+ ]);+ const normals = cornerNormals(mesh, source.smoothAngle ?? DEFAULT_SMOOTH_ANGLE);+ const uvScale = source.uvScale ?? 1;+ const seen = new Map<string, number>();+ const pos: number[] = [], nrm: number[] = [], uv: number[] = [], col: number[] = [];+ const indices: number[] = [];+ const vertexOf = (f: number, v: number): number => {+ const face = mesh.faces[f]!;+ const n = normals[f]![face.v.indexOf(v)]!;+ const flat = faceNormal(mesh, face);+ const p = mesh.positions[v]!;+ const [tu, tv] = projectUv(p, flat, uvScale);+ const color = (face.color ?? [1, 1, 1, 1]).map((c) => Math.round(c * 255));+ const key = `${v}|${n.map((x) => x.toFixed(4))}|${tu.toFixed(5)},${tv.toFixed(5)}|${color}`;+ let at = seen.get(key);+ if (at === undefined) {+ at = pos.length / 3;+ seen.set(key, at);+ pos.push(p[0], p[1], p[2]);+ nrm.push(n[0], n[1], n[2]);+ uv.push(tu, tv);+ col.push(...color);+ }+ return at;+ };+ triangles.forEach((tris, f) => {+ for (const [a, b, c] of tris) indices.push(vertexOf(f, a), vertexOf(f, b), vertexOf(f, c));+ });+ const vertexCount = pos.length / 3;+ const vertices = new Uint8Array(vertexCount * vertexStride);+ const view = new DataView(vertices.buffer);+ const offset = (semantic: number): number => channels.find((c) => c.semantic === semantic)!.offset;+ const [posAt, uvAt, colorAt, normalAt] = [+ offset(MeshChannel.Position), offset(MeshChannel.TexCoord0), offset(MeshChannel.Color), offset(MeshChannel.Normal),+ ];+ for (let i = 0; i < vertexCount; i++) {+ const at = i * vertexStride;+ for (let k = 0; k < 3; k++) {+ view.setFloat32(at + posAt + k * 4, pos[i * 3 + k]!, true);+ view.setFloat32(at + normalAt + k * 4, nrm[i * 3 + k]!, true);+ }+ view.setFloat32(at + uvAt, uv[i * 2]!, true);+ view.setFloat32(at + uvAt + 4, uv[i * 2 + 1]!, true);+ for (let k = 0; k < 4; k++) view.setUint8(at + colorAt + k, col[i * 4 + k]!);+ }+ const { min, max } = boundsOf(mesh);+ return {+ channels, vertexStride, vertexCount, vertices,+ indices: new Uint32Array(indices),+ aabbMin: [...min] as [number, number, number],+ aabbMax: [...max] as [number, number, number],+ };+}++/** Validates, builds and bakes @p raw. Throws a ModelBuildError naming the step that failed; writes nothing, so a failure leaves nothing half made. */+export function bakeModel(raw: unknown): BakedModel {+ const source = validateModelSource(raw);+ const { mesh, steps } = buildPolyMesh(source);+ if (mesh.faces.length === 0) throw new Error('the steps leave no faces; a model starts with a box, cylinder, cone, sphere, plane or prism');++ const triangles = mesh.faces.map((f) => triangulateFace(mesh, f));+ const unwrapped = unwrapLightmapUV(toMeshData(mesh, triangles, source)).mesh;++ const edges = [...collectEdges(mesh).values()];+ const openEdges = edges.filter((e) => e.faces.length === 1).length;+ const nonManifoldEdges = edges.filter((e) => e.faces.length > 2).length;+ const degenerateFaces = mesh.faces.filter((f) => faceArea(mesh, f) < 1e-10).length;+ const shells = findShells(mesh);+ const edgeFaces = new Map<number, boolean>();+ for (const e of edges) for (const f of e.faces) if (e.faces.length !== 2) edgeFaces.set(f, true);+ const insideOutShells = shells.filter((faces) =>+ faces.every((f) => !edgeFaces.has(f)) && signedVolume(mesh, faces, triangles) < 0).length;++ const { min, max } = boundsOf(mesh);+ const tags: Record<string, number> = {};+ for (const f of mesh.faces) if (f.tag) tags[f.tag] = (tags[f.tag] ?? 0) + 1;+ const triangleCount = triangles.reduce((n, t) => n + t.length, 0);++ 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 (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`);++ const roundVec = (v: readonly number[]): Vec3 => v.map((x) => Math.round(x * 1e5) / 1e5) as unknown as Vec3;+ return {+ poly: mesh,+ data: unwrapped,+ triangles: triangles.flatMap((tris, face) => tris.map((v) => ({ v, face }))),+ report: {+ vertices: unwrapped.vertexCount,+ triangles: triangleCount,+ faces: mesh.faces.length,+ shells: shells.length,+ bounds: {+ min: roundVec(min), max: roundVec(max),+ size: roundVec(sub(max, min)),+ center: roundVec([(min[0] + max[0]) / 2, (min[1] + max[1]) / 2, (min[2] + max[2]) / 2]),+ },+ tags, openEdges, nonManifoldEdges, degenerateFaces, insideOutShells, steps, warnings,+ },+ };+}diff --git a/pipeline/src/modeling/modelOps.ts b/pipeline/src/modeling/modelOps.tsnew file mode 100644index 000000000..04b85aa68--- /dev/null+++ b/pipeline/src/modeling/modelOps.ts@@ -0,0 +1,723 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file modelOps.ts — what a model's steps do to its mesh.+ *+ * Each operation takes the mesh and answers a new one, and throws a sentence+ * when it cannot: the caller is usually a model reading the reply, so "width+ * 0.6 overruns an edge 1 long" gets the next attempt right where a clamped+ * shape would have passed silently and looked wrong.+ */+import {+ add, boundsOf, collectEdges, compact, cross, dot, edgeKey, faceCenter, faceNormal, length, normalize, scale,+ selectEdges, selectFaces, sub,+ type EdgeSelector, type Face, type FaceSelector, type PolyMesh, type Vec3,+} from './polyMesh';++const EPS = 1e-6;+const DEG = Math.PI / 180;+/** The most faces one model may hold: past this an `array` typo is a hang, not a model. */+export const MAX_FACES = 200000;++function guardSize(faces: number): void {+ if (faces > MAX_FACES) throw new Error(`this would make ${faces} faces; a model holds at most ${MAX_FACES}`);+}++/** Selection that found nothing is a mistake worth stopping for: every step below it would be working on the wrong thing. */+function requireFaces(mesh: PolyMesh, selector: FaceSelector, name = 'faces'): number[] {+ const hit = selectFaces(mesh, selector);+ if (hit.length === 0) {+ const tags = [...new Set(mesh.faces.map((f) => f.tag))].filter(Boolean);+ throw new Error(`\`${name}\` ${JSON.stringify(selector)} matched no face. Tags here: ${tags.length ? tags.join(', ') : '(none)'}; ${mesh.faces.length} faces in all`);+ }+ return hit;+}++const usedVertices = (mesh: PolyMesh, faces: readonly number[]): Set<number> => {+ const used = new Set<number>();+ for (const f of faces) for (const v of mesh.faces[f]!.v) used.add(v);+ return used;+};++// ---- Primitives: each appends a shell, leaving what is there alone ------------++interface Placed { at?: Vec3; tag?: string; color?: readonly number[] }++/** A colour as a face holds it. Refused rather than clamped: past 1 is a sum gone wrong. */+function toColor(c: readonly number[]): NonNullable<Face['color']> {+ 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 append(mesh: PolyMesh, positions: readonly Vec3[], loops: readonly number[][], placed: Placed): PolyMesh {+ guardSize(mesh.faces.length + loops.length);+ const base = mesh.positions.length;+ const at = placed.at ?? [0, 0, 0];+ const color = placed.color ? toColor(placed.color) : null;+ return {+ positions: [...mesh.positions, ...positions.map((p) => add(p, at))],+ faces: [...mesh.faces, ...loops.map((loop) => ({+ v: loop.map((i) => i + base), tag: placed.tag ?? '', ...(color ? { color } : {}),+ }))],+ };+}++export function box(mesh: PolyMesh, p: Placed & { size: number | Vec3 }): PolyMesh {+ const s: Vec3 = typeof p.size === 'number' ? [p.size, p.size, p.size] : p.size;+ if (s.some((v) => v <= 0)) throw new Error(`size ${JSON.stringify(p.size)} must be positive on every axis`);+ const [x, y, z] = [s[0] / 2, s[1] / 2, s[2] / 2];+ const positions: Vec3[] = [+ [-x, -y, z], [x, -y, z], [x, y, z], [-x, y, z],+ [-x, -y, -z], [x, -y, -z], [x, y, -z], [-x, y, -z],+ ];+ return append(mesh, positions, [+ [0, 1, 2, 3], [5, 4, 7, 6], [1, 5, 6, 2], [4, 0, 3, 7], [3, 2, 6, 7], [4, 5, 1, 0],+ ], p);+}++export function plane(mesh: PolyMesh, p: Placed & { size: number | readonly [number, number] }): PolyMesh {+ const s: readonly [number, number] = typeof p.size === 'number' ? [p.size, p.size] : p.size;+ if (s.some((v) => v <= 0)) throw new Error(`size ${JSON.stringify(p.size)} must be positive`);+ const [x, z] = [s[0] / 2, s[1] / 2];+ return append(mesh, [[-x, 0, z], [x, 0, z], [x, 0, -z], [-x, 0, -z]], [[0, 1, 2, 3]], p);+}++/** A cylinder, or with `radiusTop` a tapered one. */+export function cylinder(mesh: PolyMesh, p: Placed & { radius: number; height: number; radiusTop?: number; sides?: number }): PolyMesh {+ const sides = p.sides ?? 24;+ const top = p.radiusTop ?? p.radius;+ if (sides < 3 || !Number.isInteger(sides)) throw new Error(`sides ${sides} must be a whole number of at least 3`);+ if (p.radius <= 0 || p.height <= 0 || top < 0) throw new Error('radius and height must be positive, radiusTop at least 0');+ if (top === 0) return cone(mesh, { ...p, sides });+ const h = p.height / 2;+ const positions: Vec3[] = [];+ for (let i = 0; i < sides; i++) {+ const t = (i / sides) * Math.PI * 2;+ const s = Math.sin(t), c = Math.cos(t);+ positions.push([s * p.radius, -h, c * p.radius], [s * top, h, c * top]);+ }+ const loops: number[][] = [];+ for (let i = 0; i < sides; i++) {+ const j = (i + 1) % sides;+ loops.push([i * 2, j * 2, j * 2 + 1, i * 2 + 1]);+ }+ loops.push(Array.from({ length: sides }, (_, i) => i * 2 + 1));+ loops.push(Array.from({ length: sides }, (_, i) => (sides - 1 - i) * 2));+ return append(mesh, positions, loops, p);+}++export function cone(mesh: PolyMesh, p: Placed & { radius: number; height: number; sides?: number }): PolyMesh {+ const sides = p.sides ?? 24;+ if (sides < 3 || !Number.isInteger(sides)) throw new Error(`sides ${sides} must be a whole number of at least 3`);+ if (p.radius <= 0 || p.height <= 0) throw new Error('radius and height must be positive');+ const h = p.height / 2;+ const positions: Vec3[] = [[0, h, 0]];+ for (let i = 0; i < sides; i++) {+ const t = (i / sides) * Math.PI * 2;+ positions.push([Math.sin(t) * p.radius, -h, Math.cos(t) * p.radius]);+ }+ const loops: number[][] = [];+ for (let i = 0; i < sides; i++) loops.push([1 + i, 1 + (i + 1) % sides, 0]);+ loops.push(Array.from({ length: sides }, (_, i) => 1 + (sides - 1 - i)));+ return append(mesh, positions, loops, p);+}++export function sphere(mesh: PolyMesh, p: Placed & { radius: number; rings?: number; sides?: number }): PolyMesh {+ const rings = p.rings ?? 12, sides = p.sides ?? 24;+ if (rings < 2 || sides < 3 || !Number.isInteger(rings) || !Number.isInteger(sides)) {+ throw new Error(`rings ${rings} must be at least 2 and sides ${sides} at least 3, both whole`);+ }+ if (p.radius <= 0) throw new Error('radius must be positive');+ const positions: Vec3[] = [[0, p.radius, 0], [0, -p.radius, 0]];+ for (let r = 1; r < rings; r++) {+ const phi = (r / rings) * Math.PI;+ for (let i = 0; i < sides; i++) {+ const t = (i / sides) * Math.PI * 2;+ positions.push([Math.sin(phi) * Math.sin(t) * p.radius, Math.cos(phi) * p.radius, Math.sin(phi) * Math.cos(t) * p.radius]);+ }+ }+ const at = (r: number, i: number): number => 2 + (r - 1) * sides + (i % sides);+ const loops: number[][] = [];+ for (let i = 0; i < sides; i++) {+ loops.push([0, at(1, i), at(1, i + 1)]);+ loops.push([1, at(rings - 1, i + 1), at(rings - 1, i)]);+ for (let r = 1; r < rings - 1; r++) loops.push([at(r, i), at(r + 1, i), at(r + 1, i + 1), at(r, i + 1)]);+ }+ return append(mesh, positions, loops, p);+}++/** A floor plan `points` ([x, z], either winding) stood up `height`: an L-shaped room, a gable end laid flat, a star. */+export function prism(mesh: PolyMesh, p: Placed & { points: readonly (readonly [number, number])[]; height: number }): PolyMesh {+ if (p.points.length < 3) throw new Error(`a prism needs at least 3 points, not ${p.points.length}`);+ if (p.height <= 0) throw new Error('height must be positive');+ // Counter-clockwise seen from above, whichever way the caller walked it; in XZ, that is a negative shoelace.+ let area = 0;+ p.points.forEach((a, i) => {+ const b = p.points[(i + 1) % p.points.length]!;+ area += a[0] * b[1] - b[0] * a[1];+ });+ if (Math.abs(area) < EPS) throw new Error('the points enclose no area');+ const pts = area > 0 ? [...p.points].reverse() : p.points;+ const n = pts.length, h = p.height / 2;+ const positions: Vec3[] = [];+ for (const q of pts) positions.push([q[0], -h, q[1]], [q[0], h, q[1]]);+ const loops: number[][] = [];+ for (let i = 0; i < n; i++) {+ const j = (i + 1) % n;+ loops.push([i * 2, j * 2, j * 2 + 1, i * 2 + 1]);+ }+ loops.push(Array.from({ length: n }, (_, i) => i * 2 + 1));+ loops.push(Array.from({ length: n }, (_, i) => (n - 1 - i) * 2));+ return append(mesh, positions, loops, p);+}++// ---- Moving and copying --------------------------------------------------------++function rotateVector(v: Vec3, degrees: Vec3): Vec3 {+ 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)];+ // X, then Y, then Z.+ const a: Vec3 = [v[0], cx * v[1] - sx * v[2], sx * v[1] + cx * v[2]];+ const b: Vec3 = [cy * a[0] + sy * a[2], a[1], -sy * a[0] + cy * a[2]];+ return [cz * b[0] - sz * b[1], sz * b[0] + cz * b[1], b[2]];+}++function pivotOf(mesh: PolyMesh, vertices: Iterable<number>, pivot: 'center' | 'base' | Vec3 | undefined): Vec3 {+ if (Array.isArray(pivot)) return pivot as Vec3;+ const { min, max } = boundsOf(mesh, vertices);+ const center: Vec3 = [(min[0] + max[0]) / 2, (min[1] + max[1]) / 2, (min[2] + max[2]) / 2];+ return pivot === 'base' ? [center[0], min[1], center[2]] : center;+}++/** Moves the vertices of the chosen faces: a whole shell moves, a top face scaled in makes a roof of the box under it. */+export function transform(mesh: PolyMesh, p: {+ faces?: FaceSelector; translate?: Vec3; rotate?: Vec3; scale?: number | Vec3; pivot?: 'center' | 'base' | Vec3;+}): PolyMesh {+ if (!p.translate && !p.rotate && p.scale === undefined) throw new Error('give at least one of translate, rotate, scale');+ const s: Vec3 = typeof p.scale === 'number' ? [p.scale, p.scale, p.scale] : p.scale ?? [1, 1, 1];+ if (s.some((v) => v <= 0)) throw new Error(`scale ${JSON.stringify(p.scale)} must be positive; a negative one turns faces inside out, which is what \`mirror\` is for`);+ const vertices = usedVertices(mesh, requireFaces(mesh, p.faces ?? 'all'));+ const pivot = pivotOf(mesh, vertices, p.pivot);+ const positions = mesh.positions.slice();+ for (const i of vertices) {+ let q = sub(positions[i]!, pivot);+ q = [q[0] * s[0], q[1] * s[1], q[2] * s[2]];+ if (p.rotate) q = rotateVector(q, p.rotate);+ positions[i] = add(add(q, pivot), p.translate ?? [0, 0, 0]);+ }+ return { ...mesh, positions };+}++/** A copy of the chosen faces with vertices of their own, each position put through @p move. */+function cloneFaces(mesh: PolyMesh, faces: readonly number[], move: (p: Vec3) => Vec3, flip = false): { positions: Vec3[]; faces: Face[] } {+ const remap = new Map<number, number>();+ const positions: Vec3[] = [];+ const base = mesh.positions.length;+ const out = faces.map((f) => {+ const face = mesh.faces[f]!;+ const v = face.v.map((i) => {+ let to = remap.get(i);+ if (to === undefined) {+ to = base + positions.length;+ remap.set(i, to);+ positions.push(move(mesh.positions[i]!));+ }+ return to;+ });+ return { ...face, v: flip ? v.reverse() : v };+ });+ return { positions, faces: out };+}++/** `count` copies in all, the original included: a row of windows, or with `rotate` a ring of columns. */+export function array(mesh: PolyMesh, p: {+ faces?: FaceSelector; count: number; offset?: Vec3; rotate?: Vec3; pivot?: 'center' | 'base' | Vec3; tag?: string;+}): PolyMesh {+ if (!Number.isInteger(p.count) || p.count < 2) throw new Error(`count ${p.count} must be a whole number of at least 2 (it includes the original)`);+ if (!p.offset && !p.rotate) throw new Error('give offset, rotate, or both');+ const hit = requireFaces(mesh, p.faces ?? 'all');+ guardSize(mesh.faces.length + hit.length * (p.count - 1));+ const vertices = usedVertices(mesh, hit);+ const pivot = p.rotate ? pivotOf(mesh, vertices, p.pivot) : [0, 0, 0] as Vec3;+ let out = mesh;+ for (let n = 1; n < p.count; n++) {+ const step = scale(p.offset ?? [0, 0, 0], n);+ const angle: Vec3 | null = p.rotate ? [p.rotate[0] * n, p.rotate[1] * n, p.rotate[2] * n] : null;+ const copy = cloneFaces({ ...mesh, positions: out.positions }, hit, (q) => {+ const turned = angle ? add(rotateVector(sub(q, pivot), angle), pivot) : q;+ return add(turned, step);+ });+ out = {+ positions: [...out.positions, ...copy.positions],+ faces: [...out.faces, ...copy.faces.map((f) => (p.tag ? { ...f, tag: p.tag } : f))],+ };+ }+ return out;+}++/** Mirror across the plane `axis = at`, adding the reflection (or with `keep: false`, replacing the original with it). */+export function mirror(mesh: PolyMesh, p: { faces?: FaceSelector; axis: 'x' | 'y' | 'z'; at?: number; keep?: boolean; tag?: string }): PolyMesh {+ const k = { x: 0, y: 1, z: 2 }[p.axis];+ const at = p.at ?? 0;+ const hit = requireFaces(mesh, p.faces ?? 'all');+ guardSize(mesh.faces.length + hit.length);+ const copy = cloneFaces(mesh, hit, (q) => {+ const r = [q[0], q[1], q[2]] as [number, number, number];+ r[k] = 2 * at - r[k];+ return r;+ }, true);+ const gone = p.keep === false ? new Set(hit) : null;+ return compact({+ positions: [...mesh.positions, ...copy.positions],+ faces: [...mesh.faces.filter((_, i) => !gone?.has(i)), ...copy.faces.map((f) => (p.tag ? { ...f, tag: p.tag } : f))],+ });+}++// ---- Changing the surface -------------------------------------------------------++/** Each chosen face (`individual`), or each connected run of them, pushed out with walls joining it to where it was. A negative distance recesses. */+export function extrude(mesh: PolyMesh, p: {+ faces: FaceSelector; distance: number; direction?: Vec3; individual?: boolean; tag?: string; sideTag?: string;+}): PolyMesh {+ if (p.distance === 0) throw new Error('distance must not be 0');+ const hit = requireFaces(mesh, p.faces);+ const groups = p.individual ? hit.map((f) => [f]) : [hit];+ const positions = mesh.positions.slice();+ const faces = mesh.faces.slice();+ const direction = p.direction ? normalize(p.direction) : null;+ if (p.direction && length(direction!) === 0) throw new Error('direction must not be zero');++ for (const group of groups) {+ const selected = new Set(group);+ const normals = new Map<number, Vec3[]>();+ for (const f of group) {+ const n = faceNormal(mesh, mesh.faces[f]!);+ for (const v of mesh.faces[f]!.v) {+ const at = normals.get(v) ?? [];+ if (!at.some((m) => dot(m, n) > 1 - 1e-9)) at.push(n);+ normals.set(v, at);+ }+ }+ const moved = new Map<number, number>();+ for (const [v, ns] of normals) {+ let offset: Vec3;+ if (direction) offset = scale(direction, p.distance);+ else {+ const mean = normalize(ns.reduce<Vec3>((a, b) => add(a, b), [0, 0, 0]));+ // Mitred: the shifted faces stay `distance` from where they were at a corner too.+ const lean = Math.max(dot(mean, ns[0]!), 0.25);+ offset = scale(mean, p.distance / lean);+ }+ moved.set(v, positions.length);+ positions.push(add(mesh.positions[v]!, offset));+ }+ const used = new Set<string>();+ for (const f of selected) {+ for (let i = 0; i < mesh.faces[f]!.v.length; i++) {+ used.add(`${mesh.faces[f]!.v[i]}>${mesh.faces[f]!.v[(i + 1) % mesh.faces[f]!.v.length]}`);+ }+ }+ for (const f of selected) {+ const face = mesh.faces[f]!;+ for (let i = 0; i < face.v.length; i++) {+ const a = face.v[i]!, b = face.v[(i + 1) % face.v.length]!;+ if (used.has(`${b}>${a}`)) continue; // its other side moved with it: no wall here+ faces.push({ ...face, v: [a, b, moved.get(b)!, moved.get(a)!], tag: p.sideTag ?? face.tag });+ }+ faces[f] = { ...face, v: face.v.map((v) => moved.get(v)!), tag: p.tag ?? face.tag };+ }+ }+ guardSize(faces.length);+ return compact({ positions, faces });+}++/** The point in the face's plane `amountNext` inside the edge leaving along @p toNext and `amountPrev` inside the one along @p toPrev. */+function offsetCorner(corner: Vec3, normal: Vec3, toNext: Vec3, toPrev: Vec3, amountNext: number, amountPrev: number): Vec3 {+ // Inward in the plane, for a counter-clockwise loop.+ const inNext = normalize(cross(normal, toNext));+ const inPrev = normalize(cross(toPrev, normal));+ const denom = 1 - dot(inNext, inPrev) ** 2;+ if (denom < 1e-9) return add(corner, scale(inNext, amountNext));+ const d = dot(inNext, inPrev);+ const a = (amountNext - amountPrev * d) / denom;+ const b = (amountPrev - amountNext * d) / denom;+ return add(add(corner, scale(inNext, a)), scale(inPrev, b));+}++/** A smaller copy of each chosen face inside it, tagged `tag`, joined to the old outline by quads tagged as the face was. */+export function inset(mesh: PolyMesh, p: { faces: FaceSelector; amount: number; tag?: string }): PolyMesh {+ if (p.amount <= 0) throw new Error(`amount ${p.amount} must be positive`);+ const hit = requireFaces(mesh, p.faces);+ const positions = mesh.positions.slice();+ const faces = mesh.faces.slice();+ for (const f of hit) {+ const face = mesh.faces[f]!;+ const n = faceNormal(mesh, face);+ const count = face.v.length;+ const ring = face.v.map((v, i) => {+ const at = mesh.positions[v]!;+ const next = mesh.positions[face.v[(i + 1) % count]!]!;+ const prev = mesh.positions[face.v[(i + count - 1) % count]!]!;+ return offsetCorner(at, n, normalize(sub(next, at)), normalize(sub(prev, at)), p.amount, p.amount);+ });+ // Each edge of the new outline must still run the way the old one did; past the face's own width it runs backwards.+ for (let i = 0; i < count; i++) {+ const was = sub(mesh.positions[face.v[(i + 1) % count]!]!, mesh.positions[face.v[i]!]!);+ const now = sub(ring[(i + 1) % count]!, ring[i]!);+ if (dot(was, now) <= 0) {+ throw new Error(`amount ${p.amount} is more than the face at ${JSON.stringify(roundVec(faceCenter(mesh, face)))} can hold (its edge ${roundNum(length(was))} long collapses)`);+ }+ }+ const base = positions.length;+ positions.push(...ring);+ for (let i = 0; i < count; i++) {+ const j = (i + 1) % count;+ faces.push({ ...face, v: [face.v[i]!, face.v[j]!, base + j, base + i] });+ }+ faces[f] = { ...face, v: ring.map((_, i) => base + i), tag: p.tag ?? face.tag };+ }+ guardSize(faces.length);+ return { positions, faces };+}++const roundNum = (v: number): number => Math.round(v * 1000) / 1000;+const roundVec = (v: Vec3): number[] => v.map(roundNum);++/**+ * Cuts faces across planes `axis = at`, so a wall gains the seams a window is placed+ * between. Faces outside `faces` are not cut, but take the new vertex on an edge they+ * share with one that was, so no crack opens along it.+ */+export function slice(mesh: PolyMesh, p: { faces?: FaceSelector; axis: 'x' | 'y' | 'z'; at: number | readonly number[] }): PolyMesh {+ const k = { x: 0, y: 1, z: 2 }[p.axis];+ const planes = typeof p.at === 'number' ? [p.at] : p.at;+ if (planes.length === 0) throw new Error('`at` names no plane');+ let out = mesh;+ for (const at of planes) {+ let cut = false;+ const targets = new Set(requireFaces(out, p.faces ?? 'all'));+ const positions = out.positions.slice();+ const crossing = new Map<string, number>();+ const side = (v: number): number => {+ const d = positions[v]![k]! - at;+ return Math.abs(d) < EPS ? 0 : d;+ };+ for (const f of targets) {+ const face = out.faces[f]!;+ for (let i = 0; i < face.v.length; i++) {+ const a = face.v[i]!, b = face.v[(i + 1) % face.v.length]!;+ const da = side(a), db = side(b);+ if (da * db >= 0) continue;+ const key = edgeKey(a, b);+ if (crossing.has(key)) continue;+ const t = da / (da - db);+ crossing.set(key, positions.length);+ positions.push(add(positions[a]!, scale(sub(positions[b]!, positions[a]!), t)));+ }+ }+ const faces: Face[] = [];+ out.faces.forEach((face, f) => {+ const loop: number[] = [];+ for (let i = 0; i < face.v.length; i++) {+ const a = face.v[i]!, b = face.v[(i + 1) % face.v.length]!;+ loop.push(a);+ const mid = crossing.get(edgeKey(a, b));+ if (mid !== undefined) loop.push(mid);+ }+ if (!targets.has(f)) { faces.push({ ...face, v: loop }); return; }+ const on: number[] = [];+ loop.forEach((v, i) => { if (Math.abs(positions[v]![k]! - at) < EPS) on.push(i); });+ const hasBothSides = loop.some((v) => positions[v]![k]! - at > EPS) && loop.some((v) => positions[v]![k]! - at < -EPS);+ if (!hasBothSides || on.length < 2) { faces.push({ ...face, v: loop }); return; }+ if (on.length !== 2) {+ throw new Error(`plane ${p.axis} = ${at} crosses the concave face at ${JSON.stringify(roundVec(faceCenter(out, face)))} more than once; slice it somewhere it crosses once, or build it from convex parts`);+ }+ const [i, j] = on as [number, number];+ faces.push({ ...face, v: loop.slice(i, j + 1) });+ faces.push({ ...face, v: [...loop.slice(j), ...loop.slice(0, i + 1)] });+ cut = true;+ });+ if (!cut) throw new Error(`no chosen face crosses ${p.axis} = ${at}; the mesh spans ${JSON.stringify(rangeOn(out, k))} on that axis`);+ guardSize(faces.length);+ out = { positions, faces };+ }+ return out;+}++const rangeOn = (mesh: PolyMesh, k: number): number[] => {+ const { min, max } = boundsOf(mesh);+ return [roundNum(min[k]!), roundNum(max[k]!)];+};++export function deleteFaces(mesh: PolyMesh, p: { faces: FaceSelector }): PolyMesh {+ const gone = new Set(requireFaces(mesh, p.faces));+ return compact({ positions: mesh.positions, faces: mesh.faces.filter((_, i) => !gone.has(i)) });+}++/** Recolours faces: linear RGB or RGBA in 0..1, multiplied into whatever material draws the mesh. */+export function paint(mesh: PolyMesh, p: { faces: FaceSelector; color: readonly number[] }): PolyMesh {+ const color = toColor(p.color);+ const hit = new Set(requireFaces(mesh, p.faces));+ return { ...mesh, faces: mesh.faces.map((f, i) => (hit.has(i) ? { ...f, color } : f)) };+}++/** Names faces, so later steps can ask for them by what they are. */+export function tagFaces(mesh: PolyMesh, p: { faces: FaceSelector; tag: string }): PolyMesh {+ const hit = new Set(requireFaces(mesh, p.faces));+ return { ...mesh, faces: mesh.faces.map((f, i) => (hit.has(i) ? { ...f, tag: p.tag } : f)) };+}++/**+ * Merges vertices closer than `distance`, then removes what that leaves meaningless:+ * edges of no length, faces of under three corners, and pairs of faces lying back to+ * back on each other, which is the wall a mirrored half leaves down its middle.+ */+export function weld(mesh: PolyMesh, p: { distance?: number }): PolyMesh {+ const distance = p.distance ?? 1e-4;+ if (distance <= 0) throw new Error(`distance ${distance} must be positive`);+ const cell = new Map<string, number[]>();+ const parent = mesh.positions.map((_, i) => i);+ const keyOf = (q: Vec3): number[] => q.map((v) => Math.floor(v / distance));+ mesh.positions.forEach((q, i) => {+ const [x, y, z] = keyOf(q) as [number, number, number];+ for (let dx = -1; dx <= 1 && parent[i] === i; dx++) {+ for (let dy = -1; dy <= 1 && parent[i] === i; dy++) {+ for (let dz = -1; dz <= 1 && parent[i] === i; dz++) {+ for (const j of cell.get(`${x + dx},${y + dy},${z + dz}`) ?? []) {+ if (length(sub(q, mesh.positions[j]!)) <= distance) { parent[i] = j; break; }+ }+ }+ }+ }+ if (parent[i] === i) {+ const key = `${x},${y},${z}`;+ const at = cell.get(key);+ if (at) at.push(i); else cell.set(key, [i]);+ }+ });+ const faces: Face[] = [];+ for (const face of mesh.faces) {+ const v: number[] = [];+ for (const i of face.v) {+ const to = parent[i]!;+ if (v[v.length - 1] !== to) v.push(to);+ }+ while (v.length > 1 && v[0] === v[v.length - 1]) v.pop();+ if (v.length >= 3 && new Set(v).size === v.length) faces.push({ ...face, v });+ }+ // Same corners, opposite way round: neither side can ever be seen.+ const signature = (v: readonly number[]): string => [...v].sort((a, b) => a - b).join(',');+ const bySet = new Map<string, number[]>();+ faces.forEach((f, i) => {+ const key = signature(f.v);+ const at = bySet.get(key);+ if (at) at.push(i); else bySet.set(key, [i]);+ });+ const hidden = new Set<number>();+ for (const group of bySet.values()) {+ if (group.length < 2) continue;+ for (let a = 0; a < group.length; a++) {+ for (let b = a + 1; b < group.length; b++) {+ if (hidden.has(group[a]!) || hidden.has(group[b]!)) continue;+ if (dot(faceNormal(mesh, faces[group[a]!]!), faceNormal(mesh, faces[group[b]!]!)) < -0.99) {+ hidden.add(group[a]!);+ hidden.add(group[b]!);+ }+ }+ }+ }+ return compact({ positions: mesh.positions, faces: faces.filter((_, i) => !hidden.has(i)) });+}++// ---- Bevel ----------------------------------------------------------------------++/**+ * Chamfers the chosen edges flat, `width` back on each side, mitring where they meet.+ * A corner between two chosen edges moves inside its face; one beside a single chosen+ * edge slides along the other. Three or more new vertices round a vertex close with a+ * cap; two are the edge the strips share, which is the mitre.+ */+export function bevel(mesh: PolyMesh, p: { edges: EdgeSelector | 'all'; width: number; tag?: string }): PolyMesh {+ if (p.width <= 0) throw new Error(`width ${p.width} must be positive`);+ const chosen = selectEdges(mesh, p.edges === 'all' ? {} : p.edges);+ if (chosen.length === 0) throw new Error(`\`edges\` ${JSON.stringify(p.edges)} matched no edge between two faces. Open rims cannot be bevelled, and edges closer to flat than \`sharp\` (default 10 degrees) are left out`);+ const edges = collectEdges(mesh);+ for (const edge of edges.values()) {+ if (edge.faces.length > 2) throw new Error(`an edge at ${JSON.stringify(roundVec(mesh.positions[edge.a]!))} is shared by ${edge.faces.length} faces; weld or separate them first`);+ }+ const isChosen = new Set(chosen.map((e) => edgeKey(e.a, e.b)));+ const positions = mesh.positions.slice();+ const width = p.width;++ // How far each end of an edge is eaten, to refuse a bevel wider than the edge. The most any face at that end asks: two faces share it.+ const eaten = new Map<string, number>();+ const eat = (v: number, far: number, t: number): void => {+ const key = `${v}>${far}`;+ eaten.set(key, Math.max(eaten.get(key) ?? 0, t));+ };++ // A corner is (face, position in loop). What it becomes is a run of new vertices.+ const corners = new Map<string, number[]>();+ const cornerKey = (f: number, i: number): string => `${f}/${i}`;+ /** Slid vertices, by (vertex, far end of the edge slid along): both faces beside that edge land on one. */+ const slides = new Map<string, number>();++ const touched = new Set<number>();+ for (const e of chosen) { touched.add(e.a); touched.add(e.b); }++ const slideOn = (v: number, far: number, along: Vec3, across: Vec3): number => {+ const key = `${v}>${far}`;+ const known = slides.get(key);+ if (known !== undefined) return known;+ const lean = dot(along, across);+ // An edge running away from the chamfer, or nearly along it, has no distance that is `width` across: fall back on `width`.+ const t = lean > 0.05 ? width / lean : width;+ eat(v, far, t);+ const at = positions.length;+ positions.push(add(mesh.positions[v]!, scale(along, t)));+ slides.set(key, at);+ return at;+ };++ mesh.faces.forEach((face, f) => {+ const n = faceNormal(mesh, face);+ const count = face.v.length;+ face.v.forEach((v, i) => {+ if (!touched.has(v)) return;+ const next = face.v[(i + 1) % count]!, prev = face.v[(i + count - 1) % count]!;+ const nextChosen = isChosen.has(edgeKey(v, next)), prevChosen = isChosen.has(edgeKey(v, prev));+ const at = mesh.positions[v]!;+ const toNext = normalize(sub(mesh.positions[next]!, at)), toPrev = normalize(sub(mesh.positions[prev]!, at));+ const inNext = normalize(cross(n, toNext)), inPrev = normalize(cross(toPrev, n));+ let run: number[];+ if (nextChosen && prevChosen) {+ const q = offsetCorner(at, n, toNext, toPrev, width, width);+ eat(v, next, dot(sub(q, at), toNext));+ eat(v, prev, dot(sub(q, at), toPrev));+ run = [positions.length];+ positions.push(q);+ } else if (nextChosen) {+ run = [slideOn(v, prev, toPrev, inNext)];+ } else if (prevChosen) {+ run = [slideOn(v, next, toNext, inPrev)];+ } else {+ run = []; // filled in below, once every chosen-side slide along its edges exists+ }+ corners.set(cornerKey(f, i), run);+ });+ });++ // Refused before any face is built: an overrun edge is a bow-tie, and it would look like a rendering bug.+ for (const [key, t] of eaten) {+ const [a, b] = key.split('>').map(Number) as [number, number];+ const needs = t + (eaten.get(`${b}>${a}`) ?? 0);+ const long = length(sub(mesh.positions[a]!, mesh.positions[b]!));+ if (needs >= long - 1e-9) {+ throw new Error(`width ${width} overruns the edge ${roundNum(long)} long at ${JSON.stringify(roundVec(mesh.positions[a]!))}; it would need ${roundNum(needs)}`);+ }+ }++ // A corner with no chosen edge beside it, at a vertex that has one elsewhere: take the slides its two edges got, or stay put on an edge that got none.+ const stay = new Map<number, number>();+ const stayAt = (v: number): number => {+ let at = stay.get(v);+ if (at === undefined) {+ at = positions.length;+ positions.push(mesh.positions[v]!);+ stay.set(v, at);+ }+ return at;+ };+ mesh.faces.forEach((face, f) => {+ const count = face.v.length;+ face.v.forEach((v, i) => {+ if (!touched.has(v)) return;+ const key = cornerKey(f, i);+ if (corners.get(key)!.length > 0) return;+ const next = face.v[(i + 1) % count]!, prev = face.v[(i + count - 1) % count]!;+ const a = slides.get(`${v}>${prev}`) ?? stayAt(v);+ const b = slides.get(`${v}>${next}`) ?? stayAt(v);+ corners.set(key, a === b ? [a] : [a, b]);+ });+ });++ const faces: Face[] = mesh.faces.map((face, f) => ({+ ...face,+ v: face.v.flatMap((v, i) => corners.get(cornerKey(f, i)) ?? [v]),+ }));++ const tagFor = (face: Face): Pick<Face, 'tag' | 'color'> => ({+ tag: p.tag ?? face.tag, ...(face.color ? { color: face.color } : {}),+ });++ // The strip along each chosen edge, joining what the two faces now leave open beside it. A face runs+ // last(corner) -> first(next corner) where the edge was; the strip runs that the other way, so all of it agrees on outside.+ const openSide = (face: number, from: number, to: number): { a: number; b: number } | null => {+ const v = mesh.faces[face]!.v;+ for (let i = 0; i < v.length; i++) {+ const j = (i + 1) % v.length;+ if (v[i] !== from || v[j] !== to) continue;+ const runA = corners.get(cornerKey(face, i))!, runB = corners.get(cornerKey(face, j))!;+ return { a: runA[runA.length - 1]!, b: runB[0]! };+ }+ return null;+ };+ for (const edge of chosen) {+ const [f, g] = edge.faces as [number, number];+ const forward = openSide(f, edge.a, edge.b);+ const first = forward ?? openSide(f, edge.b, edge.a)!;+ const second = forward ? openSide(g, edge.b, edge.a) : openSide(g, edge.a, edge.b);+ if (!second) {+ throw new Error(`the faces either side of the edge at ${JSON.stringify(roundVec(mesh.positions[edge.a]!))} are wound opposite ways, so one is inside out`);+ }+ const loop = [first.b, first.a, second.b, second.a].filter((q, i, all) => q !== all[(i + 1) % all.length]);+ if (loop.length >= 3) faces.push({ v: loop, ...tagFor(mesh.faces[f]!) });+ }++ // Round each vertex the strips leave a hole, which three or more new vertices make a face of. The walk+ // goes clockwise seen from outside, and a run is in its face's order, which is the same way: the cap is that loop reversed.+ for (const v of touched) {+ const around = faceFan(mesh, v);+ if (!around) continue; // on an open rim there is no hole to close+ const loop: number[] = [];+ for (const { face, index } of around) {+ for (const q of corners.get(cornerKey(face, index))!) {+ if (loop[loop.length - 1] !== q) loop.push(q);+ }+ }+ while (loop.length > 1 && loop[0] === loop[loop.length - 1]) loop.pop();+ if (loop.length >= 3) faces.push({ v: loop.reverse(), ...tagFor(mesh.faces[around[0]!.face]!) });+ }++ guardSize(faces.length);+ return compact({ positions, faces });+}++/** The faces round a vertex in order, or null when they do not close round it. */+function faceFan(mesh: PolyMesh, v: number): { face: number; index: number }[] | null {+ const byIncoming = new Map<number, { face: number; index: number }>();+ let total = 0;+ mesh.faces.forEach((face, f) => {+ const i = face.v.indexOf(v);+ if (i < 0) return;+ // A corner's face arrives along prev -> v, and leaves along v -> next. The face round the corner uses next -> v.+ byIncoming.set(face.v[(i + face.v.length - 1) % face.v.length]!, { face: f, index: i });+ total++;+ });+ if (total === 0) return null;+ const out: { face: number; index: number }[] = [];+ let at = byIncoming.values().next().value!;+ for (let n = 0; n < total; n++) {+ out.push(at);+ const face = mesh.faces[at.face]!;+ const next = face.v[(at.index + 1) % face.v.length]!;+ const round = byIncoming.get(next);+ if (!round) return null;+ at = round;+ }+ return at === out[0] ? out : null;+}+diff --git a/pipeline/src/modeling/modelSource.ts b/pipeline/src/modeling/modelSource.tsnew file mode 100644index 000000000..e2132f700--- /dev/null+++ b/pipeline/src/modeling/modelSource.ts@@ -0,0 +1,278 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file modelSource.ts — `.esmodel`: a model as the steps that build it.+ *+ * The file a person or an agent edits. The `.esmesh` beside it is what a scene+ * draws, and it can always be made again from this. Steps rather than vertices+ * because that is what can be changed afterwards: making a door wider is one+ * number here, and everything built on top of the door follows it.+ *+ * Every step is checked against the table below before anything runs. An+ * unknown field is an error, not a thing ignored: a misspelt `widht` that+ * builds without complaint is a shape quietly using the default.+ */+import * as ops from './modelOps';+import { compact, type Face, type FaceSelector, type PolyMesh, type Vec3 } from './polyMesh';++export const MODEL_SOURCE_VERSION = 1;+export const MODEL_SOURCE_EXT = '.esmodel';++export interface ModelStep {+ /** What later edits call this step. Optional, and unique when given. */+ id?: string;+ op: string;+ [param: string]: unknown;+}++export interface ModelSource {+ version: number;+ /** Faces meeting flatter than this (degrees) share a smooth normal; 0 draws every face flat. Default 30. */+ smoothAngle?: number;+ /** World units one texture repeat covers. Default 1. */+ uvScale?: number;+ steps: ModelStep[];+}++type Kind = 'number' | 'integer' | 'boolean' | 'string' | 'vec3' | 'number|vec3' | 'number|vec2' | 'number|numbers'+ | 'color' | 'points' | 'faces' | 'edges' | 'axis' | 'pivot';++interface OpSpec {+ params: Record<string, Kind>;+ required: readonly string[];+ run: (mesh: PolyMesh, params: never) => PolyMesh;+ /** One line on what it does, for the catalog a tool description quotes. */+ says: string;+}++const PLACED = { at: 'vec3', tag: 'string', color: 'color' } as const;++/** Every op a step may name. Add one here and validation, the docs line and the build all know it. */+export const MODEL_OPS: Record<string, OpSpec> = {+ box: { params: { size: 'number|vec3', ...PLACED }, required: ['size'], run: ops.box as OpSpec['run'], says: 'adds a box centred on `at`' },+ plane: { params: { size: 'number|vec2', ...PLACED }, required: ['size'], run: ops.plane as OpSpec['run'], says: 'adds a flat XZ rectangle facing up' },+ cylinder: { params: { radius: 'number', height: 'number', radiusTop: 'number', sides: 'integer', ...PLACED }, required: ['radius', 'height'], run: ops.cylinder as OpSpec['run'], says: 'adds an upright cylinder; `radiusTop` tapers it' },+ 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`' },+ 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`' },+ extrude: { params: { faces: 'faces', distance: 'number', direction: 'vec3', individual: 'boolean', tag: 'string', sideTag: 'string' }, required: ['faces', 'distance'], run: ops.extrude as OpSpec['run'], says: 'pushes faces out along their normals, walls joining them to where they were; negative recesses' },+ inset: { params: { faces: 'faces', amount: 'number', tag: 'string' }, required: ['faces', 'amount'], run: ops.inset as OpSpec['run'], says: 'adds a smaller copy inside each face; `tag` names that copy' },+ bevel: { params: { edges: 'edges', width: 'number', tag: 'string' }, required: ['edges', 'width'], run: ops.bevel as OpSpec['run'], says: 'chamfers edges flat, mitring where they meet' },+ slice: { params: { faces: 'faces', axis: 'axis', at: 'number|numbers' }, required: ['axis', 'at'], run: ops.slice as OpSpec['run'], says: 'cuts faces across planes, making the seams a window sits between' },+ delete: { params: { faces: 'faces' }, required: ['faces'], run: ops.deleteFaces as OpSpec['run'], says: 'removes faces, leaving a hole' },+ paint: { params: { faces: 'faces', color: 'color' }, required: ['faces', 'color'], run: ops.paint as OpSpec['run'], says: 'sets vertex colour: linear [r, g, b] in 0..1, multiplied into the material' },+ tag: { params: { faces: 'faces', tag: 'string' }, required: ['faces', 'tag'], run: ops.tagFaces as OpSpec['run'], says: 'names faces for later steps' },+ weld: { params: { distance: 'number' }, required: [], run: ops.weld as OpSpec['run'], says: 'merges coincident vertices and removes the back-to-back faces that leaves' },+};++const isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);+const isNums = (v: unknown, n?: number): boolean => Array.isArray(v) && (n === undefined || v.length === n) && v.every(isNum);++const FACE_KEYS = new Set(['tag', 'facing', 'tolerance', 'within', 'extreme', 'any', 'not']);+const EDGE_KEYS = new Set(['of', 'between', 'along', 'within', 'sharp']);+const AXIS_NAMES = new Set(['+x', '-x', '+y', '-y', '+z', '-z']);++function checkBox(box: unknown): string | null {+ if (typeof box !== 'object' || box === null) return 'must be { min?, max? }';+ for (const [key, value] of Object.entries(box)) {+ if (key !== 'min' && key !== 'max') return `has an unknown key "${key}"; it takes min and max`;+ if (!Array.isArray(value) || value.length !== 3 || !value.every((v) => v === null || isNum(v))) return `${key} must be [x, y, z], null for an open axis`;+ }+ return null;+}++/** What is wrong with a face selector, or null. */+function checkFaces(sel: unknown): string | null {+ if (typeof sel === 'string') return null;+ if (typeof sel !== 'object' || sel === null || Array.isArray(sel)) return 'must be "all", an axis like "+y", a tag, or an object';+ const s = sel as Record<string, unknown>;+ for (const key of Object.keys(s)) if (!FACE_KEYS.has(key)) return `has an unknown key "${key}"; it takes ${[...FACE_KEYS].join(', ')}`;+ if (s.facing !== undefined && !(typeof s.facing === 'string' && AXIS_NAMES.has(s.facing)) && !isNums(s.facing, 3)) return 'facing must be an axis like "+y" or a direction [x, y, z]';+ if (s.extreme !== undefined && !(typeof s.extreme === 'string' && AXIS_NAMES.has(s.extreme))) return 'extreme must be an axis like "+y"';+ if (s.tolerance !== undefined && !isNum(s.tolerance)) return 'tolerance must be degrees';+ if (s.tag !== undefined && typeof s.tag !== 'string' && !(Array.isArray(s.tag) && s.tag.every((t) => typeof t === 'string'))) return 'tag must be a string or strings';+ if (s.within !== undefined) { const bad = checkBox(s.within); if (bad) return `within ${bad}`; }+ if (s.any !== undefined) {+ if (!Array.isArray(s.any)) return 'any must be an array of selectors';+ for (const part of s.any) { const bad = checkFaces(part); if (bad) return `any: ${bad}`; }+ }+ if (s.not !== undefined) { const bad = checkFaces(s.not); if (bad) return `not: ${bad}`; }+ return null;+}++function checkEdges(sel: unknown): string | null {+ if (sel === 'all') return null;+ if (typeof sel !== 'object' || sel === null || Array.isArray(sel)) return 'must be "all" or an object';+ const s = sel as Record<string, unknown>;+ for (const key of Object.keys(s)) if (!EDGE_KEYS.has(key)) return `has an unknown key "${key}"; it takes ${[...EDGE_KEYS].join(', ')}`;+ if (s.of !== undefined) { const bad = checkFaces(s.of); if (bad) return `of: ${bad}`; }+ if (s.between !== undefined) {+ if (!Array.isArray(s.between) || s.between.length !== 2) return 'between must be two face selectors';+ for (const part of s.between) { const bad = checkFaces(part); if (bad) return `between: ${bad}`; }+ }+ if (s.along !== undefined && !['x', 'y', 'z'].includes(s.along as string)) return 'along must be x, y or z';+ if (s.sharp !== undefined && !isNum(s.sharp)) return 'sharp must be degrees';+ if (s.within !== undefined) { const bad = checkBox(s.within); if (bad) return `within ${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'),+ boolean: (v) => (typeof v === 'boolean' ? null : 'must be true or false'),+ string: (v) => (typeof v === 'string' ? null : 'must be a string'),+ vec3: (v) => (isNums(v, 3) ? null : 'must be [x, y, z]'),+ 'number|vec3': (v) => (isNum(v) || isNums(v, 3) ? null : 'must be a number or [x, y, z]'),+ 'number|vec2': (v) => (isNum(v) || isNums(v, 2) ? null : 'must be a number or [x, z]'),+ 'number|numbers': (v) => (isNum(v) || isNums(v) ? null : 'must be a number or an array of them'),+ color: (v) => (isNums(v) ? null : 'must be [r, g, b] or [r, g, b, a]'),+ points: (v) => (Array.isArray(v) && v.every((q) => isNums(q, 2)) ? null : 'must be an array of [x, z]'),+ faces: checkFaces,+ edges: checkEdges,+ axis: (v) => (v === 'x' || v === 'y' || v === 'z' ? null : 'must be x, y or z'),+ pivot: (v) => (v === 'center' || v === 'base' || isNums(v, 3) ? null : 'must be "center", "base" or [x, y, z]'),+};++export class ModelBuildError extends Error {+ constructor(message: string, readonly stepIndex: number | null, readonly stepId: string | null, readonly op: string | null) {+ super(message);+ this.name = 'ModelBuildError';+ }+}++const stepLabel = (step: Partial<ModelStep> | null, index: number): string =>+ `step ${index}${step?.id ? ` "${step.id}"` : ''}${step?.op ? ` (${step.op})` : ''}`;++/** The source if it is well formed; otherwise throws, naming the step and the field. */+export function validateModelSource(raw: unknown): ModelSource {+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) throw new ModelBuildError('a model source must be an object with `steps`', null, null, null);+ const source = raw as Record<string, unknown>;+ for (const key of Object.keys(source)) {+ if (!['version', 'smoothAngle', 'uvScale', 'steps'].includes(key)) {+ throw new ModelBuildError(`unknown field "${key}"; a model source has version, smoothAngle, uvScale, steps`, null, null, null);+ }+ }+ if (source.version !== undefined && source.version !== MODEL_SOURCE_VERSION) {+ throw new ModelBuildError(`version ${String(source.version)} is not one this editor reads (${MODEL_SOURCE_VERSION})`, null, null, null);+ }+ if (source.smoothAngle !== undefined && !(isNum(source.smoothAngle) && source.smoothAngle >= 0 && source.smoothAngle <= 180)) {+ throw new ModelBuildError('smoothAngle must be degrees, 0..180', null, null, null);+ }+ if (source.uvScale !== undefined && !(isNum(source.uvScale) && source.uvScale > 0)) {+ throw new ModelBuildError('uvScale must be a positive number', null, null, null);+ }+ if (!Array.isArray(source.steps)) throw new ModelBuildError('`steps` must be an array', null, null, null);+ const ids = new Set<string>();+ source.steps.forEach((step: Partial<ModelStep> | null, index: number) => {+ const refuse = (what: string): never => {+ throw new ModelBuildError(`${stepLabel(step, index)}: ${what}`, index, step?.id ?? null, step?.op ?? null);+ };+ if (typeof step !== 'object' || step === null) return refuse('must be an object');+ if (typeof step.id === 'string') {+ if (ids.has(step.id)) refuse(`the id "${step.id}" is already used by an earlier step`);+ ids.add(step.id);+ } else if (step.id !== undefined) refuse('id must be a string');+ const spec = typeof step.op === 'string' ? MODEL_OPS[step.op] : undefined;+ if (!spec) return refuse(`unknown op ${JSON.stringify(step.op)}; there are ${Object.keys(MODEL_OPS).join(', ')}`);+ for (const [key, value] of Object.entries(step)) {+ if (key === 'id' || key === 'op') continue;+ const kind = spec.params[key];+ if (!kind) refuse(`unknown field "${key}"; ${step.op} takes ${Object.keys(spec.params).join(', ')}`);+ const bad = KIND_CHECK[kind!](value);+ if (bad) refuse(`${key} ${bad}`);+ }+ for (const need of spec.required) if (step[need] === undefined) refuse(`${need} is required`);+ return undefined;+ });+ return { version: MODEL_SOURCE_VERSION, ...(source as unknown as Omit<ModelSource, 'version'>) };+}++export interface StepReport {+ index: number;+ id?: string;+ op: string;+ /** Faces in the mesh after it ran. */+ faces: number;+}++export interface ModelBuild {+ mesh: PolyMesh;+ steps: StepReport[];+}++/** Runs the steps in order. A step that cannot run throws a {@link ModelBuildError} naming it. */+export function buildPolyMesh(source: ModelSource): ModelBuild {+ let mesh: PolyMesh = { positions: [], faces: [] };+ const steps: StepReport[] = [];+ source.steps.forEach((step, index) => {+ const { id, op, ...params } = step;+ try {+ mesh = MODEL_OPS[op]!.run(mesh, params as never);+ } catch (e) {+ throw new ModelBuildError(`${stepLabel(step, index)}: ${e instanceof Error ? e.message : String(e)}`, index, id ?? null, op);+ }+ steps.push({ index, ...(id ? { id } : {}), op, faces: mesh.faces.length });+ });+ return { mesh: compact(mesh), steps };+}++// ---- Edits: changing a source without restating it ------------------------------++export type ModelEdit =+ | { op: 'set'; step: string | number; fields: Record<string, unknown> }+ | { op: 'insert'; step: ModelStep; before?: string | number; after?: string | number }+ | { op: 'remove'; step: string | number }+ | { op: 'settings'; fields: Pick<ModelSource, 'smoothAngle' | 'uvScale'> };++function indexOfStep(source: ModelSource, ref: string | number): number {+ const i = typeof ref === 'number' ? ref : source.steps.findIndex((s) => s.id === ref);+ if (i < 0 || i >= source.steps.length || !Number.isInteger(i)) {+ const ids = source.steps.map((s) => s.id).filter(Boolean);+ throw new ModelBuildError(`no step ${JSON.stringify(ref)}; ${source.steps.length} steps, ids: ${ids.join(', ') || '(none)'}`, null, null, null);+ }+ return i;+}++/** The source with @p edits applied, in order. A `null` field in `set` removes it. Refuses without changing anything. */+export function applyModelEdits(source: ModelSource, edits: readonly ModelEdit[]): ModelSource {+ const next: ModelSource = { ...source, steps: source.steps.map((s) => ({ ...s })) };+ for (const edit of edits) {+ switch (edit?.op) {+ case 'set': {+ const i = indexOfStep(next, edit.step);+ const step = { ...next.steps[i]! } as Record<string, unknown>;+ for (const [key, value] of Object.entries(edit.fields ?? {})) {+ if (value === null) delete step[key];+ else step[key] = value;+ }+ next.steps[i] = step as ModelStep;+ break;+ }+ case 'insert': {+ const at = edit.before !== undefined ? indexOfStep(next, edit.before)+ : edit.after !== undefined ? indexOfStep(next, edit.after) + 1 : next.steps.length;+ next.steps.splice(at, 0, edit.step);+ break;+ }+ case 'remove':+ next.steps.splice(indexOfStep(next, edit.step), 1);+ break;+ case 'settings':+ Object.assign(next, edit.fields);+ break;+ default:+ throw new ModelBuildError(`unknown edit ${JSON.stringify((edit as { op?: unknown })?.op)}; there are set, insert, remove, settings`, null, null, null);+ }+ }+ return validateModelSource(next);+}++/** The op vocabulary as text, for what a tool tells its caller. */+export const describeModelOps = (): string => Object.entries(MODEL_OPS)+ .map(([name, spec]) => `${name}(${Object.keys(spec.params).map((p) => (spec.required.includes(p) ? p : `${p}?`)).join(', ')}): ${spec.says}`)+ .join('; ');++export type { Face, FaceSelector, PolyMesh, Vec3 };diff --git a/pipeline/src/modeling/modelViews.ts b/pipeline/src/modeling/modelViews.tsnew file mode 100644index 000000000..60c6a331b--- /dev/null+++ b/pipeline/src/modeling/modelViews.ts@@ -0,0 +1,142 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file modelViews.ts — a contact sheet of a model, drawn on the CPU.+ *+ * Each view is drawn twice: shaded with its polygon edges, and as a bare+ * silhouette under it. The silhouette is not decoration. Faults in a blockout+ * (a limb too thin, a gap, a wrong proportion) have survived every lit view+ * and shown at once in outline, because shading gives the eye something else+ * to read.+ *+ * Orthographic and at one scale across all panels, so sizes compare between+ * them. On the CPU rather than through the engine so what it shows depends on+ * the mesh alone: no scene, camera, lights or GPU, and a test can read it.+ * 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';++export const MODEL_VIEWS = {+ front: { right: [1, 0, 0], up: [0, 1, 0], toward: [0, 0, 1] },+ back: { right: [-1, 0, 0], up: [0, 1, 0], toward: [0, 0, -1] },+ right: { right: [0, 0, -1], up: [0, 1, 0], toward: [1, 0, 0] },+ 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(),+} 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]);+ const right = normalize(cross([0, 1, 0], toward));+ return { right, up: cross(toward, right), toward };+}++export interface ModelSheet {+ width: number;+ height: number;+ /** RGBA, row by row from the top. */+ rgba: Uint8Array;+ /** Which view each column is, left to right; the top row is shaded, the bottom row is silhouette. */+ views: readonly ModelViewName[];+ /** World units per pixel, the same in every panel. */+ unitsPerPixel: number;+}++const PAPER = [236, 236, 236] as const;+const SILHOUETTE = [20, 20, 20] as const;+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 {+ 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);+ 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;+ const unitsPerPixel = diameter / (panel * 0.92);++ const width = views.length * panel + (views.length - 1);+ const height = panel * 2 + 1;+ const rgba = new Uint8Array(width * height * 4);+ for (let i = 0; i < width * height; i++) {+ rgba[i * 4] = GUTTER[0]; rgba[i * 4 + 1] = GUTTER[1]; rgba[i * 4 + 2] = GUTTER[2]; rgba[i * 4 + 3] = 255;+ }+ const put = (x: number, y: number, c: readonly number[]): void => {+ const at = (y * width + x) * 4;+ rgba[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));+ const depth = new Float32Array(panel * panel);++ views.forEach((name, column) => {+ const basis = MODEL_VIEWS[name];+ const ox = column * (panel + 1);+ const toScreen = (p: Vec3): [number, number, number] => {+ const q = sub(p, center);+ return [panel / 2 + dot(q, basis.right) / unitsPerPixel, panel / 2 - dot(q, basis.up) / unitsPerPixel, dot(q, basis.toward)];+ };+ const screen = poly.positions.map(toScreen);+ depth.fill(-Infinity);+ for (let y = 0; y < panel; y++) {+ for (let x = 0; x < panel; x++) { put(ox + x, y, PAPER); put(ox + x, panel + 1 + y, PAPER); }+ }+ for (const { v, face } of triangles) {+ const [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);+ // 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 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])));+ const y1 = Math.min(panel - 1, Math.ceil(Math.max(a[1], b[1], c[1])));+ for (let y = y0; y <= y1; y++) {+ for (let x = x0; x <= x1; x++) {+ const px = x + 0.5, py = y + 0.5;+ const w0 = ((b[0] - px) * (c[1] - py) - (c[0] - px) * (b[1] - py)) / area;+ const w1 = ((c[0] - px) * (a[1] - py) - (a[0] - px) * (c[1] - py)) / area;+ const w2 = 1 - w0 - w1;+ if (w0 < 0 || w1 < 0 || w2 < 0) continue;+ put(ox + x, panel + 1 + y, SILHOUETTE);+ const 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);+ }+ }+ }+ // 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) {+ 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]))));+ for (let s = 0; s <= steps; s++) {+ const t = s / steps;+ const x = Math.floor(a[0] + (b[0] - a[0]) * t), y = Math.floor(a[1] + (b[1] - a[1]) * t);+ if (x < 0 || y < 0 || x >= panel || y >= panel) continue;+ if (a[2] + (b[2] - a[2]) * t + bias < depth[y * panel + x]!) continue;+ put(ox + x, y, WIRE);+ }+ }+ }+ });+ return { width, height, rgba, views, unitsPerPixel };+}diff --git a/pipeline/src/modeling/polyMesh.ts b/pipeline/src/modeling/polyMesh.tsnew file mode 100644index 000000000..985cb930e--- /dev/null+++ b/pipeline/src/modeling/polyMesh.ts@@ -0,0 +1,238 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file polyMesh.ts — the polygon mesh a model's steps work on, and the vector+ * arithmetic and selection they share.+ *+ * Faces stay n-gons until the bake: an extrude's walls and a sliced wall are+ * one polygon each, so a selector asks about the faces a person would name.+ * Vertices are shared between faces, which is what makes an edge something+ * two faces agree on (a bevel needs that; a triangle soup cannot say it).+ */++export type Vec3 = readonly [number, number, number];++export interface Face {+ /** Vertex indices, counter-clockwise seen from outside. */+ v: number[];+ tag: string;+ /** Linear RGBA, as MeshRenderer.color is; absent draws white. */+ color?: readonly [number, number, number, number];+}++export interface PolyMesh {+ positions: Vec3[];+ faces: Face[];+}++export const add = (a: Vec3, b: Vec3): Vec3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];+export const sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];+export const scale = (a: Vec3, s: number): Vec3 => [a[0] * s, a[1] * s, a[2] * s];+export const dot = (a: Vec3, b: Vec3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];+export const cross = (a: Vec3, b: Vec3): Vec3 => [+ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0],+];+export const length = (a: Vec3): number => Math.hypot(a[0], a[1], a[2]);+export const normalize = (a: Vec3): Vec3 => {+ const l = length(a);+ return l > 0 ? [a[0] / l, a[1] / l, a[2] / l] : [0, 0, 0];+};++/** Newell's normal, length twice the polygon's area: holds for a concave or slightly non-planar loop. */+function areaVector(mesh: PolyMesh, face: Face): Vec3 {+ let x = 0, y = 0, z = 0;+ for (let i = 0; i < face.v.length; i++) {+ const a = mesh.positions[face.v[i]!]!;+ const b = mesh.positions[face.v[(i + 1) % face.v.length]!]!;+ x += (a[1] - b[1]) * (a[2] + b[2]);+ y += (a[2] - b[2]) * (a[0] + b[0]);+ z += (a[0] - b[0]) * (a[1] + b[1]);+ }+ return [x, y, z];+}++export const faceNormal = (mesh: PolyMesh, face: Face): Vec3 => normalize(areaVector(mesh, face));+export const faceArea = (mesh: PolyMesh, face: Face): number => length(areaVector(mesh, face)) / 2;++export function faceCenter(mesh: PolyMesh, face: Face): Vec3 {+ let c: Vec3 = [0, 0, 0];+ for (const i of face.v) c = add(c, mesh.positions[i]!);+ return scale(c, 1 / face.v.length);+}++export const edgeKey = (a: number, b: number): string => (a < b ? `${a}:${b}` : `${b}:${a}`);++export interface Edge {+ a: number;+ b: number;+ /** Faces using it. Two on a closed surface, one on an open rim. */+ faces: number[];+}++export function collectEdges(mesh: PolyMesh): Map<string, Edge> {+ const edges = new Map<string, Edge>();+ mesh.faces.forEach((face, fi) => {+ for (let i = 0; i < face.v.length; i++) {+ const a = face.v[i]!, b = face.v[(i + 1) % face.v.length]!;+ const key = edgeKey(a, b);+ const edge = edges.get(key);+ if (edge) edge.faces.push(fi);+ else edges.set(key, { a, b, faces: [fi] });+ }+ });+ return edges;+}++/** Drops vertices no face uses, keeping every face's indices right. */+export function compact(mesh: PolyMesh): PolyMesh {+ const remap = new Map<number, number>();+ const positions: Vec3[] = [];+ const faces = mesh.faces.map((face) => ({+ ...face,+ v: face.v.map((i) => {+ let to = remap.get(i);+ if (to === undefined) {+ to = positions.length;+ remap.set(i, to);+ positions.push(mesh.positions[i]!);+ }+ return to;+ }),+ }));+ return { positions, faces };+}++/** The bounds of @p indices, or of every vertex. */+export function boundsOf(mesh: PolyMesh, indices?: Iterable<number>): { min: Vec3; max: Vec3 } {+ const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];+ const visit = (p: Vec3): void => {+ for (let k = 0; k < 3; k++) {+ if (p[k]! < min[k]!) min[k] = p[k]!;+ if (p[k]! > max[k]!) max[k] = p[k]!;+ }+ };+ if (indices) for (const i of indices) visit(mesh.positions[i]!);+ else mesh.positions.forEach(visit);+ return { min: min as unknown as Vec3, max: max as unknown as Vec3 };+}++// ---- Selection ----------------------------------------------------------------++/** A box any axis of which may be left open with null. */+export interface SelectBox {+ min?: readonly (number | null)[];+ max?: readonly (number | null)[];+}++export type AxisName = '+x' | '-x' | '+y' | '-y' | '+z' | '-z';++/**+ * Which faces a step acts on. Faces are asked for by what they ARE, never by index:+ * an index is the one thing a parameter edit further up changes under the steps below it.+ *+ * A string is `"all"`, an axis (`"+y"`: facing up) or a tag. In an object every key+ * present must hold.+ */+export type FaceSelector = string | {+ tag?: string | string[];+ /** Facing this axis or direction, within `tolerance` degrees (default 5). */+ facing?: AxisName | readonly [number, number, number];+ tolerance?: number;+ /** Centre inside this box. */+ within?: SelectBox;+ /** Of the faces the other keys let through, those furthest along this axis. */+ extreme?: AxisName;+ any?: FaceSelector[];+ not?: FaceSelector;+};++const AXES: Record<AxisName, Vec3> = {+ '+x': [1, 0, 0], '-x': [-1, 0, 0], '+y': [0, 1, 0], '-y': [0, -1, 0], '+z': [0, 0, 1], '-z': [0, 0, -1],+};++export const isAxisName = (s: string): s is AxisName => s in AXES;+export const axisVector = (a: AxisName): Vec3 => AXES[a];++const inBox = (p: Vec3, box: SelectBox): boolean => {+ for (let k = 0; k < 3; k++) {+ const lo = box.min?.[k], hi = box.max?.[k];+ // A hair of slack: a face exactly on the box's wall is inside it, whatever the arithmetic that put it there.+ if (lo !== null && lo !== undefined && p[k]! < lo - 1e-6) return false;+ if (hi !== null && hi !== undefined && p[k]! > hi + 1e-6) return false;+ }+ return true;+};++/** Indices of the faces @p selector names. */+export function selectFaces(mesh: PolyMesh, selector: FaceSelector): number[] {+ if (typeof selector === 'string') {+ if (selector === 'all') return mesh.faces.map((_, i) => i);+ if (isAxisName(selector)) return selectFaces(mesh, { facing: selector });+ return selectFaces(mesh, { tag: selector });+ }+ const tags = selector.tag === undefined ? null : new Set([selector.tag].flat());+ const facing = selector.facing === undefined ? null+ : typeof selector.facing === 'string' ? AXES[selector.facing] : normalize(selector.facing);+ const cosine = Math.cos(((selector.tolerance ?? 5) * Math.PI) / 180);+ const any = selector.any?.map((s) => new Set(selectFaces(mesh, s)));+ const not = selector.not === undefined ? null : new Set(selectFaces(mesh, selector.not));++ let out: number[] = [];+ mesh.faces.forEach((face, i) => {+ if (tags && !tags.has(face.tag)) return;+ if (facing && dot(faceNormal(mesh, face), facing) < cosine) return;+ if (selector.within && !inBox(faceCenter(mesh, face), selector.within)) return;+ if (any && !any.some((set) => set.has(i))) return;+ if (not?.has(i)) return;+ out.push(i);+ });+ if (selector.extreme) {+ const axis = AXES[selector.extreme];+ const along = out.map((i) => dot(faceCenter(mesh, mesh.faces[i]!), axis));+ const top = Math.max(...along);+ out = out.filter((_, n) => along[n]! >= top - 1e-6);+ }+ return out;+}++/**+ * Which edges a bevel rounds off. Every key present must hold, and an edge between+ * two faces closer to flat than `sharp` degrees (default 10) is never one: it is the+ * seam a slice left across a wall, and nobody asking for "the top's edges" meant it.+ */+export interface EdgeSelector {+ /** Edges of these faces. */+ of?: FaceSelector;+ /** Edges with one of the first faces on one side and one of the second on the other. */+ between?: [FaceSelector, FaceSelector];+ /** Running along this axis. */+ along?: 'x' | 'y' | 'z';+ /** Both ends inside this box. */+ within?: SelectBox;+ sharp?: number;+}++const ALONG: Record<'x' | 'y' | 'z', Vec3> = { x: [1, 0, 0], y: [0, 1, 0], z: [0, 0, 1] };++/** The closed edges @p selector names, as their keys. */+export function selectEdges(mesh: PolyMesh, selector: EdgeSelector): Edge[] {+ const edges = collectEdges(mesh);+ const of = selector.of === undefined ? null : new Set(selectFaces(mesh, selector.of));+ const a = selector.between ? new Set(selectFaces(mesh, selector.between[0])) : null;+ const b = selector.between ? new Set(selectFaces(mesh, selector.between[1])) : null;+ const sharp = Math.cos(((selector.sharp ?? 10) * Math.PI) / 180);++ const out: Edge[] = [];+ for (const edge of edges.values()) {+ if (edge.faces.length !== 2) continue;+ const [f, g] = edge.faces as [number, number];+ if (dot(faceNormal(mesh, mesh.faces[f]!), faceNormal(mesh, mesh.faces[g]!)) > sharp) continue;+ if (of && !of.has(f) && !of.has(g)) continue;+ if (a && b && !((a.has(f) && b.has(g)) || (a.has(g) && b.has(f)))) continue;+ const pa = mesh.positions[edge.a]!, pb = mesh.positions[edge.b]!;+ if (selector.along && Math.abs(dot(normalize(sub(pb, pa)), ALONG[selector.along])) < 0.999) continue;+ if (selector.within && !(inBox(pa, selector.within) && inBox(pb, selector.within))) continue;+ out.push(edge);+ }+ return out;+}diff --git a/pipeline/tests/modeling.test.ts b/pipeline/tests/modeling.test.tsnew file mode 100644index 000000000..2ca4a3c20--- /dev/null+++ b/pipeline/tests/modeling.test.ts@@ -0,0 +1,503 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * The modeling kernel, held to what geometry can prove: a surface that closes, faces+ * that point out, and volumes that match the sums. A count of faces passes a bevel+ * that is inside out, so the counts here are never the only thing asked.+ */+import { describe, expect, it } from 'vitest';+import { decodeMesh, encodeMesh, MeshChannel } from 'esengine';+import {+ applyModelEdits, bakeModel, describeModelOps, MODEL_OPS, ModelBuildError, renderModelSheet, validateModelSource,+ type BakedModel, type ModelStep,+} from '../src/modeling';++const model = (...steps: ModelStep[]): BakedModel => bakeModel({ version: 1, steps });++/** Divergence theorem over the triangles: the volume enclosed, positive when the faces point out. */+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 expectSound(m: BakedModel): void {+ expect(m.report.openEdges).toBe(0);+ expect(m.report.nonManifoldEdges).toBe(0);+ expect(m.report.insideOutShells).toBe(0);+ expect(m.report.degenerateFaces).toBe(0);+ expect(m.report.warnings).toEqual([]);+}++const cube: ModelStep = { op: 'box', size: 1, tag: 'body' };++describe('primitives', () => {+ it.each<[string, ModelStep, number, number]>([+ ['box', { op: 'box', size: [1, 2, 3] }, 6, 0.0001],+ ['cylinder', { op: 'cylinder', radius: 1, height: 2, sides: 64 }, 2 * Math.PI, 0.02],+ ['tapered', { op: 'cylinder', radius: 1, radiusTop: 0.5, height: 3, sides: 64 }, (Math.PI * 3 * (1 + 0.5 + 0.25)) / 3, 0.02],+ ['cone', { op: 'cone', radius: 1, height: 3, sides: 64 }, Math.PI, 0.02],+ ['sphere', { op: 'sphere', radius: 1, rings: 32, sides: 64 }, (4 / 3) * Math.PI, 0.03],+ ['prism', { op: 'prism', points: [[0, 0], [2, 0], [2, 1], [1, 1], [1, 2], [0, 2]], height: 1 }, 3, 0.0001],+ ])('%s closes, faces out and holds the right volume', (_, step, expected, tolerance) => {+ const m = model(step);+ expectSound(m);+ expect(Math.abs(volume(m) - expected)).toBeLessThan(tolerance);+ });++ it('a prism walked the other way round is the same solid', () => {+ const m = model({ op: 'prism', points: [[0, 2], [1, 2], [1, 1], [2, 1], [2, 0], [0, 0]], height: 1 });+ expectSound(m);+ expect(volume(m)).toBeCloseTo(3, 5);+ });++ it('`at` moves the shell and a second primitive adds one', () => {+ const m = model({ op: 'box', size: 2, at: [0, 1, 0] }, { op: 'box', size: 1, at: [5, 0, 0] });+ expect(m.report.shells).toBe(2);+ expect(m.report.bounds.max).toEqual([5.5, 2, 1]);+ expect(m.report.bounds.min).toEqual([-1, -0.5, -1]);+ expect(volume(m)).toBeCloseTo(9, 5);+ });+});++describe('selection', () => {+ it('finds faces by axis, tag, box and extreme, and ANDs the keys', () => {+ const painted = (faces: unknown): number => {+ const m = model(cube, { op: 'box', size: 1, at: [3, 0, 0], tag: 'other' }, { op: 'paint', faces, color: [1, 0, 0] } as ModelStep);+ return m.poly.faces.filter((f) => f.color).length;+ };+ expect(painted('+y')).toBe(2);+ expect(painted('other')).toBe(6);+ expect(painted({ tag: 'other', facing: '+y' })).toBe(1);+ expect(painted({ facing: '+y', within: { max: [1, null, null] } })).toBe(1);+ expect(painted({ extreme: '+x' })).toBe(1);+ expect(painted({ any: ['+y', '-y'] })).toBe(4);+ expect(painted({ tag: 'body', not: '+y' })).toBe(5);+ });++ it('a selector matching nothing stops the build and lists the tags there are', () => {+ expect(() => model(cube, { op: 'extrude', faces: 'roof', distance: 1 })).toThrow(/step 1 \(extrude\).*matched no face.*body/);+ });+});++describe('extrude and inset', () => {+ it('pushing the top up grows the box by exactly the prism it adds', () => {+ const m = model(cube, { op: 'extrude', faces: '+y', distance: 2 });+ expectSound(m);+ expect(volume(m)).toBeCloseTo(3, 6);+ expect(m.report.bounds.max[1]).toBeCloseTo(2.5, 6);+ });++ it('a negative distance recesses, and still closes', () => {+ const m = model(cube, { op: 'extrude', faces: '+y', distance: -0.25 });+ expectSound(m);+ expect(volume(m)).toBeCloseTo(0.75, 6);+ });++ it('an inset then recess cuts a window-shaped pocket out of a wall', () => {+ const m = model(cube, { op: 'inset', faces: '+z', amount: 0.25, tag: 'window' }, { op: 'extrude', faces: 'window', distance: -0.1 });+ expectSound(m);+ expect(volume(m)).toBeCloseTo(1 - 0.5 * 0.5 * 0.1, 6);+ });++ it('walls take the tag of the face they came from, unless sideTag names them apart', () => {+ const same = model(cube, { op: 'inset', faces: '+z', amount: 0.25, tag: 'window' }, { op: 'extrude', faces: 'window', distance: -0.1 });+ expect(same.report.tags.window).toBe(5);+ const apart = model(cube, { op: 'inset', faces: '+z', amount: 0.25, tag: 'window' }, { op: 'extrude', faces: 'window', distance: -0.1, sideTag: 'reveal' });+ expect(apart.report.tags).toMatchObject({ window: 1, reveal: 4 });+ });++ it('two adjacent faces extrude as a run with no wall between, individually with their own', () => {+ const run = model(cube, { op: 'slice', axis: 'x', at: 0 }, { op: 'extrude', faces: '+y', distance: 1 });+ expectSound(run);+ expect(volume(run)).toBeCloseTo(2, 6);+ const apart = model(cube, { op: 'slice', axis: 'x', at: 0 }, { op: 'extrude', faces: '+y', distance: 1, individual: true });+ expect(volume(apart)).toBeCloseTo(2, 6);+ expect(apart.report.faces).toBe(run.report.faces + 2);+ });++ it('refuses an inset wider than the face rather than turning it inside out', () => {+ expect(() => model(cube, { op: 'inset', faces: '+z', amount: 0.6 })).toThrow(/amount 0\.6 .*collapses/);+ });+});++describe('slice', () => {+ it('cuts a face into two without changing the solid, and neighbours take the new vertices', () => {+ const m = model(cube, { op: 'slice', faces: '+z', axis: 'x', at: [-0.2, 0.2] });+ expectSound(m);+ expect(volume(m)).toBeCloseTo(1, 6);+ expect(m.report.faces).toBe(8);+ });++ it('lets a window be placed off-centre: seams, then recess the piece between them', () => {+ const m = model(+ { op: 'box', size: [4, 3, 1], at: [0, 1.5, 0], tag: 'wall' },+ { op: 'slice', faces: '+z', axis: 'x', at: [0.5, 1.5] },+ { op: 'slice', faces: '+z', axis: 'y', at: [1, 2] },+ { op: 'tag', faces: { facing: '+z', within: { min: [0.5, 1, null], max: [1.5, 2, null] } }, tag: 'window' },+ { op: 'extrude', faces: 'window', distance: -0.2, sideTag: 'reveal' },+ );+ expectSound(m);+ expect(m.report.tags).toMatchObject({ window: 1, reveal: 4 });+ expect(volume(m)).toBeCloseTo(12 - 0.2, 6);+ });++ it('says so when a plane misses, with the range the mesh does span', () => {+ expect(() => model(cube, { op: 'slice', axis: 'x', at: 9 })).toThrow(/no chosen face crosses x = 9.*-0\.5,0\.5/);+ });+});++describe('array, mirror, weld', () => {+ it('array counts the original and copies its tags', () => {+ const m = model({ op: 'box', size: 1, tag: 'col' }, { op: 'array', faces: 'col', count: 4, offset: [2, 0, 0] });+ expectSound(m);+ expect(m.report.shells).toBe(4);+ expect(volume(m)).toBeCloseTo(4, 6);+ expect(m.report.bounds.max[0]).toBeCloseTo(6.5, 6);+ });++ it('a rotated array makes a ring around its pivot', () => {+ const m = model({ op: 'box', size: 1, at: [5, 0, 0] }, { op: 'array', count: 4, rotate: [0, 90, 0], pivot: [0, 0, 0] });+ expectSound(m);+ expect(m.report.bounds.max[2]).toBeCloseTo(5.5, 5);+ expect(m.report.bounds.min[0]).toBeCloseTo(-5.5, 5);+ });++ it('a mirrored copy points outward, not inward', () => {+ const m = model({ op: 'box', size: 1, at: [2, 0, 0] }, { op: 'mirror', axis: 'x' });+ expectSound(m);+ expect(volume(m)).toBeCloseTo(2, 6);+ expect(m.report.bounds.min[0]).toBeCloseTo(-2.5, 6);+ });++ it('welding a half to its mirror leaves one closed solid with no wall inside', () => {+ const m = model({ op: 'box', size: [1, 1, 1], at: [0.5, 0, 0] }, { op: 'mirror', axis: 'x' }, { op: 'weld' });+ expectSound(m);+ expect(m.report.shells).toBe(1);+ expect(m.report.faces).toBe(10);+ expect(volume(m)).toBeCloseTo(2, 6);+ });++ it('delete leaves a hole the report names', () => {+ const m = model(cube, { op: 'delete', faces: '+y' });+ expect(m.report.openEdges).toBe(4);+ expect(m.report.warnings.join()).toMatch(/4 open edges/);+ });+});++describe('transform', () => {+ it('scaling the top in makes a frustum of the box under it', () => {+ const m = model(cube, { op: 'transform', faces: '+y', scale: [0.5, 1, 0.5] });+ expectSound(m);+ expect(volume(m)).toBeCloseTo((1 + 0.25 + 0.5) / 3, 6);+ });++ it('rotates about the selection centre by default', () => {+ const m = model({ op: 'box', size: [2, 1, 1], at: [5, 0, 0] }, { op: 'transform', rotate: [0, 90, 0] });+ expect(m.report.bounds.size[0]).toBeCloseTo(1, 5);+ expect(m.report.bounds.center[0]).toBeCloseTo(5, 5);+ });++ it('refuses a negative scale: that is what mirror is for', () => {+ expect(() => model(cube, { op: 'transform', scale: [-1, 1, 1] })).toThrow(/mirror/);+ });+});++describe('bevel', () => {+ it('one edge of a cube: cuts off exactly the triangular prism under it', () => {+ const w = 0.2;+ const m = model(cube, { op: 'bevel', edges: { between: ['+y', '+z'] }, width: w });+ expectSound(m);+ expect(m.report.faces).toBe(7);+ expect(volume(m)).toBeCloseTo(1 - (w * w) / 2, 6);+ });++ it('a rim: the four top edges mitre at the corners and close', () => {+ const w = 0.1;+ const m = model(cube, { op: 'bevel', edges: { of: '+y' }, width: w });+ expectSound(m);+ expect(m.report.faces).toBe(10);+ // The solid is the cube under the plane through each chamfer; integrate the height over the top.+ const n = 400;+ let sum = 0;+ for (let i = 0; i < n; i++) {+ for (let j = 0; j < n; j++) {+ const dx = 0.5 - Math.abs((i + 0.5) / n - 0.5);+ const dz = 0.5 - Math.abs((j + 0.5) / n - 0.5);+ sum += 1 - Math.max(0, w - Math.min(dx, dz));+ }+ }+ expect(Math.abs(volume(m) - sum / (n * n))).toBeLessThan(1e-3);+ });++ it('every edge of a cube: three meet at each corner and a small triangle closes it', () => {+ const w = 0.1;+ const m = model(cube, { op: 'bevel', edges: 'all', width: w });+ expectSound(m);+ expect(m.report.faces).toBe(6 + 12 + 8);+ // Against the planes that define that shape, integrated on a grid.+ const n = 96;+ let inside = 0;+ for (let i = 0; i < n; i++) {+ for (let j = 0; j < n; j++) {+ for (let k = 0; k < n; k++) {+ const x = Math.abs((i + 0.5) / n - 0.5), y = Math.abs((j + 0.5) / n - 0.5), z = Math.abs((k + 0.5) / n - 0.5);+ if (x + y <= 1 - w && y + z <= 1 - w && x + z <= 1 - w && x + y + z <= 1.5 - 2 * w) inside++;+ }+ }+ }+ expect(Math.abs(volume(m) - inside / n ** 3)).toBeLessThan(0.003);+ });++ it('two edges meeting at a corner mitre with no cap, and remove what the two chamfers remove', () => {+ const w = 0.2;+ const m = model(cube, { op: 'bevel', edges: { between: ['+y', { any: ['+z', '+x'] }] }, width: w });+ expectSound(m);+ expect(m.report.faces).toBe(8);+ const n = 400;+ let sum = 0;+ for (let i = 0; i < n; i++) {+ for (let j = 0; j < n; j++) {+ sum += 1 - Math.max(0, w - Math.min(1 - (i + 0.5) / n, 1 - (j + 0.5) / n));+ }+ }+ expect(Math.abs(volume(m) - sum / (n * n))).toBeLessThan(1e-3);+ });++ it('a seam across a flat face is not an edge to bevel', () => {+ const m = model(cube, { op: 'slice', axis: 'x', at: 0 }, { op: 'bevel', edges: { of: '+y' }, width: 0.1 });+ expectSound(m);+ // Ten faces once sliced, and a strip along each of the rim's six runs: none along the seam.+ expect(m.report.faces).toBe(10 + 6);+ });++ it('holds on a concave corner', () => {+ const m = model(+ { op: 'prism', points: [[0, 0], [2, 0], [2, 1], [1, 1], [1, 2], [0, 2]], height: 1 },+ { op: 'bevel', edges: { of: '+y' }, width: 0.1 },+ );+ expectSound(m);+ expect(volume(m)).toBeLessThan(3);+ expect(volume(m)).toBeGreaterThan(2.9);+ });++ it('refuses a width the edge cannot hold', () => {+ expect(() => model(cube, { op: 'bevel', edges: 'all', width: 0.6 })).toThrow(/overruns the edge 1 long/);+ });++ it('names an edge choice that found nothing', () => {+ expect(() => model(cube, { op: 'slice', axis: 'x', at: 0 }, { op: 'bevel', edges: { of: '+y', along: 'y' }, width: 0.1 })).toThrow(/matched no edge/);+ });+});++describe('the source format', () => {+ it('refuses a misspelt field, listing the ones the op takes', () => {+ expect(() => validateModelSource({ version: 1, steps: [{ op: 'box', size: 1, widht: 2 }] })).toThrow(/step 0 \(box\): unknown field "widht"; box takes size, at, tag, color/);+ });++ it('refuses an unknown op, listing them', () => {+ expect(() => validateModelSource({ steps: [{ op: 'boolean' }] })).toThrow(/unknown op "boolean"; there are box/);+ });++ it('refuses a missing required field and a wrong type', () => {+ expect(() => validateModelSource({ steps: [{ op: 'box' }] })).toThrow(/size is required/);+ expect(() => validateModelSource({ steps: [{ op: 'box', size: 'big' }] })).toThrow(/size must be a number or \[x, y, z\]/);+ expect(() => validateModelSource({ steps: [{ op: 'extrude', faces: { facng: '+y' }, distance: 1 }] })).toThrow(/unknown key "facng"/);+ });++ it('refuses a duplicate id', () => {+ expect(() => validateModelSource({ steps: [{ id: 'a', op: 'box', size: 1 }, { id: 'a', op: 'box', size: 1 }] })).toThrow(/already used/);+ });++ it('a failure names the step it happened in', () => {+ try {+ model({ id: 'body', op: 'box', size: 1 }, { id: 'lip', op: 'bevel', edges: 'all', width: 9 });+ expect.unreachable();+ } catch (e) {+ expect(e).toBeInstanceOf(ModelBuildError);+ expect(e).toMatchObject({ stepIndex: 1, stepId: 'lip', op: 'bevel' });+ }+ });++ it('a model with no faces is refused, not baked to nothing', () => {+ expect(() => model()).toThrow(/no faces/);+ });++ it('every op is described, so the tool cannot offer one it does not explain', () => {+ const text = describeModelOps();+ for (const name of Object.keys(MODEL_OPS)) expect(text).toContain(`${name}(`);+ });+});++describe('edits', () => {+ const source = { version: 1, steps: [{ id: 'body', op: 'box', size: 1 }, { id: 'up', op: 'extrude', faces: '+y', distance: 1 }] };++ it('changes one number and everything below follows', () => {+ const next = applyModelEdits(validateModelSource(source), [{ op: 'set', step: 'up', fields: { distance: 3 } }]);+ expect(volume(bakeModel(next))).toBeCloseTo(4, 6);+ });++ it('inserts, removes, and clears a field with null', () => {+ const next = applyModelEdits(validateModelSource(source), [+ { op: 'insert', after: 'body', step: { id: 'b', op: 'bevel', edges: { of: '-y' }, width: 0.1 } },+ { op: 'set', step: 'b', fields: { tag: 'lip' } },+ { op: 'set', step: 'b', fields: { tag: null } },+ { op: 'remove', step: 'up' },+ ]);+ expect(next.steps.map((s) => s.id)).toEqual(['body', 'b']);+ expect(next.steps[1]).not.toHaveProperty('tag');+ });++ it('refuses an edit that breaks the source, and leaves the original alone', () => {+ const parsed = validateModelSource(source);+ expect(() => applyModelEdits(parsed, [{ op: 'set', step: 'up', fields: { distnce: 3 } }])).toThrow(/unknown field "distnce"/);+ expect(() => applyModelEdits(parsed, [{ op: 'remove', step: 'nope' }])).toThrow(/no step "nope".*body, up/);+ expect(parsed.steps[1]!.distance).toBe(1);+ });+});++describe('the bake', () => {+ const channel = (m: BakedModel, semantic: number) => m.data.channels.find((c) => c.semantic === semantic);++ it('survives the file format with the channels the renderer and a bake read', () => {+ const m = model(cube);+ const back = decodeMesh(encodeMesh(m.data));+ expect(back.vertexCount).toBe(m.data.vertexCount);+ expect([...back.indices]).toEqual([...m.data.indices]);+ expect(back.aabbMin).toEqual([-0.5, -0.5, -0.5]);+ for (const s of [MeshChannel.Position, MeshChannel.Normal, MeshChannel.TexCoord0, MeshChannel.Color, MeshChannel.TexCoord1]) {+ expect(channel(m, s), `channel ${s}`).toBeDefined();+ }+ });++ const normalsOf = (m: BakedModel): number[][] => {+ const at = channel(m, MeshChannel.Normal)!.offset;+ const view = new DataView(m.data.vertices.buffer);+ return Array.from({ length: m.data.vertexCount }, (_, i) =>+ [0, 1, 2].map((k) => view.getFloat32(i * m.data.vertexStride + at + k * 4, true)));+ };++ it('keeps a box hard-edged: three normals at each corner', () => {+ const unique = new Set(normalsOf(model(cube)).map((n) => n.map((x) => x.toFixed(3)).join()));+ expect(unique.size).toBe(6);+ });++ it('smooths a cylinder round its side but keeps the rim hard', () => {+ const normals = normalsOf(model({ op: 'cylinder', radius: 1, height: 1, sides: 24 }));+ // Side normals are level; they would lean if the caps were averaged in.+ const leaning = normals.filter((n) => Math.abs(n[1]!) > 0.01 && Math.abs(n[1]!) < 0.99);+ expect(leaning).toEqual([]);+ expect(new Set(normals.map((n) => n.map((x) => x.toFixed(3)).join())).size).toBeGreaterThan(24);+ });++ it('smoothAngle 0 draws every face flat', () => {+ const flat = bakeModel({ version: 1, smoothAngle: 0, steps: [{ op: 'sphere', radius: 1, rings: 6, sides: 8 }] });+ const smooth = bakeModel({ version: 1, smoothAngle: 89, steps: [{ op: 'sphere', radius: 1, rings: 6, sides: 8 }] });+ expect(flat.data.vertexCount).toBeGreaterThan(smooth.data.vertexCount);+ });++ it('paints into the colour channel', () => {+ const m = model(cube, { op: 'paint', faces: '+y', color: [1, 0, 0] });+ const at = channel(m, MeshChannel.Color)!.offset;+ const colours = new Set(Array.from({ length: m.data.vertexCount }, (_, i) =>+ [...m.data.vertices.subarray(i * m.data.vertexStride + at, i * m.data.vertexStride + at + 4)].join()));+ expect(colours).toEqual(new Set(['255,0,0,255', '255,255,255,255']));+ });++ it('a colour on a primitive reaches the channel whole, with its alpha filled in', () => {+ const m = model({ op: 'box', size: 1, color: [0, 1, 0] });+ const at = channel(m, MeshChannel.Color)!.offset;+ expect([...m.data.vertices.subarray(at, at + 4)]).toEqual([0, 255, 0, 255]);+ expect(() => model({ op: 'box', size: 1, color: [2, 0, 0] })).toThrow(/each 0\.\.1/);+ });++ it('triangulates a concave face without spilling outside it: the area is the plan', () => {+ const m = model({ op: 'prism', points: [[0, 0], [2, 0], [2, 1], [1, 1], [1, 2], [0, 2]], height: 1 });+ const top = m.triangles.filter((t) => m.poly.faces[t.face]!.v.length === 6);+ const area = (t: { v: readonly number[] }): number => {+ const [p, q, r] = [m.poly.positions[t.v[0]!]!, m.poly.positions[t.v[1]!]!, m.poly.positions[t.v[2]!]!];+ return Math.abs((q[0] - p[0]) * (r[2] - p[2]) - (r[0] - p[0]) * (q[2] - p[2])) / 2;+ };+ expect(top.reduce((n, t) => n + area(t), 0)).toBeCloseTo(6, 5); // two caps of 3+ });++ it('reports an inside-out shell: a whole cube pushed in past its own middle', () => {+ const m = model(cube, { op: 'extrude', faces: 'all', distance: -2 });+ expect(volume(m)).toBeLessThan(0);+ expect(m.report.insideOutShells).toBe(1);+ expect(m.report.warnings.join()).toMatch(/inside out/);+ });+});++describe('the contact sheet', () => {+ const pixel = (s: ReturnType<typeof renderModelSheet>, x: number, y: number): number[] =>+ [...s.rgba.subarray((y * s.width + x) * 4, (y * s.width + x) * 4 + 3)];+ /** Pixels of the bottom-row silhouette of one column, by row. */+ function silhouetteRows(s: ReturnType<typeof renderModelSheet>, column: number, panel: number): number[] {+ const rows: number[] = [];+ for (let y = 0; y < panel; y++) {+ let n = 0;+ for (let x = 0; x < panel; x++) {+ if (pixel(s, column * (panel + 1) + x, panel + 1 + y)[0]! < 60) n++;+ }+ rows.push(n);+ }+ return rows;+ }++ it('is one column per view over two rows', () => {+ const s = renderModelSheet(model(cube), ['front', 'iso'], 64);+ expect(s.width).toBe(64 * 2 + 1);+ expect(s.height).toBe(64 * 2 + 1);+ expect(s.rgba.length).toBe(s.width * s.height * 4);+ });++ it('draws a silhouette of the size the mesh is, at one scale in every panel', () => {+ const panel = 200;+ const s = renderModelSheet(model({ op: 'box', size: [4, 2, 1] }), ['front', 'right', 'top'], panel);+ const areaOf = (c: number): number => silhouetteRows(s, c, panel).reduce((a, b) => a + b, 0) * s.unitsPerPixel ** 2;+ expect(areaOf(0)).toBeCloseTo(8, 0); // 4 x 2+ expect(areaOf(1)).toBeCloseTo(2, 0); // 1 x 2+ expect(areaOf(2)).toBeCloseTo(4, 0); // 4 x 1+ });++ it('has up the right way: a cone is narrow at the top of the picture', () => {+ const panel = 128;+ const s = renderModelSheet(model({ op: 'cone', radius: 1, height: 3 }), ['front'], panel);+ const rows = silhouetteRows(s, 0, panel).filter((n) => n > 0);+ expect(rows[0]!).toBeLessThan(rows[rows.length - 1]! / 4);+ });++ it('has right the right way: a block on +x is on the right from the front and the left from behind', () => {+ const panel = 128;+ const m = model({ op: 'box', size: 1, at: [3, 0, 0] }, { op: 'box', size: 0.2 });+ const s = renderModelSheet(m, ['front', 'back'], panel);+ const inHalf = (column: number, right: boolean): number => {+ let n = 0;+ for (let y = 0; y < panel; y++) {+ for (let x = 0; x < panel; x++) {+ if ((x >= panel / 2) === right && pixel(s, column * (panel + 1) + x, panel + 1 + y)[0]! < 60) n++;+ }+ }+ return n;+ };+ expect(inHalf(0, true)).toBeGreaterThan(inHalf(0, false));+ expect(inHalf(1, false)).toBeGreaterThan(inHalf(1, true));+ });++ it('shows paint, and a nearer face hides a further one', () => {+ const panel = 64;+ const m = model(cube, { op: 'paint', faces: '+z', color: [1, 0, 0] }, { op: 'paint', faces: '-z', color: [0, 1, 0] });+ const s = renderModelSheet(m, ['front'], panel);+ const [r, g, b] = pixel(s, Math.floor(panel / 2) + 3, Math.floor(panel / 2) + 3) as [number, number, number];+ expect(r).toBeGreaterThan(g + 50);+ expect(g).toBe(b);+ });++ it('refuses a view it does not have', () => {+ expect(() => renderModelSheet(model(cube), ['side' as never])).toThrow(/unknown view "side"/);+ });+});diff --git a/tools/assetMetaTable.js b/tools/assetMetaTable.jsindex 75db8f129..a6e614d66 100644--- a/tools/assetMetaTable.js+++ b/tools/assetMetaTable.js@@ -87,6 +87,10 @@ export const EXT_TO_TYPE = Object.freeze({'.esenv': 'environment','.esprobes': 'probeVolume','.esmesh': 'mesh',+ // A model as the steps that build it. Never shipped: saving one bakes the sibling+ // `.esmesh`, and that is what a scene references. Typed for the same reason+ // `.esmatgraph` is, and apart from `model` because nothing imports it.+ '.esmodel': 'modeling','.esanim': 'animclip','.esanimclip': 'animclip','.estimeline': 'animation',diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 5b24c40b8..53c9f2e0b 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -3864,4 +3864,8 @@ export const NOTED = {{"note":"A sea seen from above is no longer scored with straight lines."},"fix(examples): Terrain & Water's detail map has waves in every direction, where one wave laid fine diagonal lines across its whole sea":{"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): 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."},};