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 whole person from a few numbers, clothes from the body's own surface, and a pose by where a hand should be
yhh195f1ed9eaaf
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex df3a92d16..7595a45c7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,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.+- **An AI can build a person, and not a picture of one.** The `humanoid` step makes a whole body from a few numbers, with fingers, a face and ears, seen right from every side, and `rig: { humanoid: true }` gives it bones that fit. `garment` makes clothes from the body's own surface: loose or tight, a bell sleeve that hangs, a clean hem, a thickness; what a body wears now takes its weights from the skin under it, so an arm stays in its sleeve. `pose` holds a body in a pose by angles, or with `reach` by where a hand should be. `organic` gains `limb`, cross-sections along a path, and `fine`, regions split finer on one skin. `displace` gains `folds`, running the way cloth hangs. `scene_views` no longer takes on a shot's lens blur and grade.+- **An AI can read shapes and colours off a picture as numbers.** `reference_trace` grows a part of a reference from places inside it and answers its outline as points, ready for an `outline`, or its strongest edges as lines, ready for a `sculpt` press. `reference_probe` answers the colour at the same places in the reference and the game. `reference_compare` with `overlay: "parts"` draws only the outline of the entities named on the reference. Each shows what it found on the picture, and judges nothing.- **An AI can take a frame apart to see why it looks wrong.** `reference_compare` draws a `region` close through the camera, from the same place and at full size, where it used to cut one out of a smaller picture and hide what a surface was doing. `camera_layers` shows one frame as the shape under a plain light, the shape under the scene's lights, the paint, the triangles and the scene before its effects. `light_sheet` shows it with each light alone. Each puts everything back.diff --git a/desktop b/desktopindex acc2c856b..2f5cfb2f9 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit acc2c856baf0ae660a98bcdbc5647e5f74cb038c+Subproject commit 2f5cfb2f9c866b4c59b9f7c151ab8acdd6f89fa2diff --git a/pipeline/src/modeling/displace.ts b/pipeline/src/modeling/displace.tsindex ec13ca9bc..558e2a071 100644--- a/pipeline/src/modeling/displace.ts+++ b/pipeline/src/modeling/displace.ts@@ -13,7 +13,7 @@ import { boundsOf, compact, dot, faceArea, faceNormal, normalize, selectFaces, timport { hash3 } from './organic';import { triangulateFace } from './triangulate';-export const DISPLACE_PATTERNS = ['bumps', 'wrinkles', 'cracks', 'scales', 'pores', 'ribs', 'weave', 'scratches', 'pleats'] as const;+export const DISPLACE_PATTERNS = ['bumps', 'wrinkles', 'cracks', 'scales', 'pores', 'ribs', 'weave', 'scratches', 'pleats', 'folds'] as const;export type DisplacePattern = typeof DISPLACE_PATTERNS[number];export interface DisplaceParams {@@ -30,6 +30,10 @@ export interface DisplaceParams {seed?: number;/** Multiplies `scale` along each axis: [4, 1, 1] draws a pattern out along x, as wrinkles across a forehead. */stretch?: Vec3;+ /** folds: which way they run, the way cloth hangs or pulls. Default straight down. */+ along?: Vec3;+ /** folds: how much longer than wide. Default 4. */+ long?: number;/** Bends the pattern's lines, as a share of `scale`, so they stop looking drawn with a ruler. Default 0. */warp?: number;/** How wide a line or dot is, as a share of a feature: cracks, pores, scratches. */@@ -188,6 +192,18 @@ function patternAt(p: DisplaceParams, x: number, y: number, z: number, n: Vec3):}case 'scratches':return scratches(x, y, z, seed, p.width ?? 0.12, n);+ case 'folds': {+ // Soft ridges and hollows, the sharper edge on the valley's: |noise| is a crease where it crosses zero, and cloth has more swell than crease.+ let sum = 0, amp = 1, total = 0, f = 1;+ for (let o = 0; o < octaves; o++) {+ const g = gradientNoise(x * f, y * f, z * f, seed + o);+ sum += amp * (Math.sqrt(Math.abs(g) * 1.6 + 0.02) - 0.55);+ total += amp;+ amp *= 0.45;+ f *= 2;+ }+ return Math.max(-1, Math.min(1, (sum / total) * 2.2));+ }case 'pleats':// A sawtooth softened at its peak: a pressed fold is sharp on one side, where a wave is even on both.return Math.pow(((Math.atan2(x, z) / (2 * Math.PI) + 1) * (p.count ?? 24)) % 1, 1.5) * 2 - 1;@@ -207,6 +223,7 @@ export function finestShare(p: DisplaceParams): number {case 'weave': return 1 / 6;case 'scratches': return (p.width ?? 0.12) / 2;case 'pleats': return 1 / 8;+ case 'folds': return 1 / (5 * layers);}}@@ -341,8 +358,15 @@ export function patternField(p: DisplaceParams): (x: number, y: number, z: numbeconst [sx, sy, sz] = [p.scale * stretch[0], p.scale * stretch[1], p.scale * stretch[2]];const seed = p.seed ?? 1;const warp = p.warp ?? 0;+ // Folds run along their own axis: the point is turned so that axis is y, and y counts for less.+ const along = p.pattern === 'folds' ? normalize(p.along ?? [0, -1, 0]) : null;+ const long = p.long ?? 4;+ const across1: Vec3 | null = along ? normalize(Math.abs(along[1]) < 0.9 ? [along[2], 0, -along[0]] : [1, 0, 0]) : null;+ const across2: Vec3 | null = along && across1 ? [along[1] * across1[2] - along[2] * across1[1], along[2] * across1[0] - along[0] * across1[2], along[0] * across1[1] - along[1] * across1[0]] : null;return (px, py, pz, n) => {- let [x, y, z] = [px / sx, py / sy, pz / sz];+ let [x, y, z] = along && across1 && across2+ ? [dot([px, py, pz], across1) / sx, dot([px, py, pz], along) / (sy * long), dot([px, py, pz], across2) / sz]+ : [px / sx, py / sy, pz / sz];if (warp > 0) {const [wx, wy, wz] = [gradientNoise(x * 0.7 + 3.1, y * 0.7, z * 0.7, seed + 40),@@ -372,6 +396,7 @@ export function displace(mesh: PolyMesh, p: DisplaceParams, budget = MAX_DISPLACif (hit.length === 0) throw new Error(`no surface of \`faces\` within ${p.near.radius} of ${JSON.stringify(p.near.at)}`);}+ if (p.long !== undefined && !(p.long > 0)) throw new Error(`long ${p.long} must be positive`);const smallest = Math.min(...(p.stretch ?? [1, 1, 1])) * p.scale;const longest = p.detail ?? smallest * finestShare(p);const { mesh: fine, short } = refine(mesh, new Set(hit), longest, budget);diff --git a/pipeline/src/modeling/garment.ts b/pipeline/src/modeling/garment.tsnew file mode 100644index 000000000..bbb4ef1c5--- /dev/null+++ b/pipeline/src/modeling/garment.ts@@ -0,0 +1,207 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file garment.ts — the `garment` step: clothes that come off the body they are for.+ *+ * A shirt drawn by itself has nothing in its sleeve, and nothing to follow when the arm moves. So this takes a piece of the+ * surface already there, relaxes it as cloth lies over what is under it, stands it off by how loose it is, and cuts and hems it.+ * It fits from every side because the body does, and bones found for it are the ones the body has.+ */+import { compact, faceNormal, faceArea, normalize, selectFaces, type Face, type FaceSelector, type PolyMesh, type Vec3 } from './polyMesh';++export interface GarmentLoose {+ /** A line along the body, say from a shoulder to a wrist. */+ from: Vec3;+ to: Vec3;+ /** How much further out, evenly spaced along it: a bell sleeve grows toward its cuff. */+ ease?: readonly number[];+ /** How far it hangs below that, evenly spaced along it, the underside the most: a bell sleeve falling. */+ hang?: readonly number[];+ /** Also its reflection across this axis. */+ mirror?: 'x';+}++export interface GarmentCut {+ /** A point on the plane where the cloth stops. */+ at: Vec3;+ /** Toward the side that is kept. */+ keep: Vec3;+ mirror?: 'x';+}++export interface GarmentParams {+ /** The surface it is made from. */+ faces: FaceSelector;+ /** How far it stands off the body. Default 0.006. */+ ease?: number;+ /** Passes of relaxing first, so it spans a hollow instead of following into it: 0 for a stocking, 30 for a shirt. Default 12. */+ relax?: number;+ loose?: readonly GarmentLoose[];+ cut?: readonly GarmentCut[];+ /** The cloth's thickness: a hem shows it. Default 0.002. */+ thickness?: number;+ /** Takes away the body under it, so it cannot show through when it bends. Default false. */+ hide?: boolean;+ color?: readonly number[];+ tag?: string;+}++const mirrored = (v: Vec3): Vec3 => [-v[0], v[1], v[2]];+/** How far in from a hem the inside of the cloth goes on. */+const INSIDE_RINGS = 8;++export function garment(mesh: PolyMesh, p: GarmentParams): PolyMesh {+ const ease = p.ease ?? 0.006;+ const relax = p.relax ?? 12;+ const thickness = p.thickness ?? 0.002;+ if (!(thickness > 0)) throw new Error(`thickness ${thickness} must be positive`);+ if (!(relax >= 0)) throw new Error(`relax ${relax} must not be negative`);+ if (p.color && p.color.length < 3) throw new Error('color must be [r, g, b]');+ const hit = selectFaces(mesh, p.faces);+ if (hit.length === 0) throw new Error(`\`faces\` ${JSON.stringify(p.faces)} matched no face`);+ const tag = p.tag ?? 'garment';++ // Its own copy of the surface.+ const local = new Map<number, number>();+ const positions: Vec3[] = [];+ const loops: number[][] = hit.map((f) => mesh.faces[f]!.v.map((v) => {+ let at = local.get(v);+ if (at === undefined) { at = positions.length; local.set(v, at); positions.push(mesh.positions[v]!); }+ return at;+ }));+ const links: Set<number>[] = positions.map(() => new Set());+ const edgeUses = new Map<number, number>();+ const edgeKey = (a: number, b: number): number => (a < b ? a * 67108864 + b : b * 67108864 + a);+ for (const loop of loops) {+ loop.forEach((a, i) => {+ const b = loop[(i + 1) % loop.length]!;+ links[a]!.add(b); links[b]!.add(a);+ edgeUses.set(edgeKey(a, b), (edgeUses.get(edgeKey(a, b)) ?? 0) + 1);+ });+ }+ // Relaxed: each point toward the mean of its neighbours, and the piece's open edge left where it is, or it would draw in from there.+ const onEdge = new Uint8Array(positions.length);+ for (const loop of loops) loop.forEach((a, i) => { const b = loop[(i + 1) % loop.length]!; if (edgeUses.get(edgeKey(a, b)) === 1) { onEdge[a] = 1; onEdge[b] = 1; } });+ let current = positions;+ for (let pass = 0; pass < relax; pass++) {+ const next = current.map((q, v): Vec3 => {+ if (onEdge[v] || links[v]!.size === 0) return q;+ let [x, y, z] = [0, 0, 0];+ for (const n of links[v]!) { x += current[n]![0]; y += current[n]![1]; z += current[n]![2]; }+ const c = links[v]!.size;+ return [q[0] + (x / c - q[0]) * 0.6, q[1] + (y / c - q[1]) * 0.6, q[2] + (z / c - q[2]) * 0.6];+ });+ current = next;+ }+ // Standing off, along the way the relaxed surface faces.+ const shell: PolyMesh = { positions: current, faces: loops.map((v) => ({ v, tag: '' })) };+ const normals = current.map((): [number, number, number] => [0, 0, 0]);+ for (const face of shell.faces) {+ const n = faceNormal(shell, face);+ const area = faceArea(shell, face);+ for (const v of face.v) { normals[v]![0] += n[0] * area; normals[v]![1] += n[1] * area; normals[v]![2] += n[2] * area; }+ }+ const faces = normals.map((n) => normalize(n));+ const looses = (p.loose ?? []).flatMap((l) => (l.mirror ? [l, { ...l, from: mirrored(l.from), to: mirrored(l.to) }] : [l]));+ const sampled = (values: readonly number[] | undefined, t: number): number => {+ if (!values?.length) return 0;+ if (values.length === 1) return values[0]!;+ const at = Math.max(0, Math.min(1, t)) * (values.length - 1);+ const i = Math.min(values.length - 2, Math.floor(at));+ const s = at - i;+ return values[i]! + (values[i + 1]! - values[i]!) * s * s * (3 - 2 * s) ** 1;+ };+ let placed: Vec3[] = current.map((q, v) => {+ const n = faces[v]!;+ let out: Vec3 = [q[0] + n[0] * ease, q[1] + n[1] * ease, q[2] + n[2] * ease];+ for (const l of looses) {+ const axis: Vec3 = [l.to[0] - l.from[0], l.to[1] - l.from[1], l.to[2] - l.from[2]];+ const len2 = axis[0] ** 2 + axis[1] ** 2 + axis[2] ** 2;+ if (len2 === 0) continue;+ const t = ((q[0] - l.from[0]) * axis[0] + (q[1] - l.from[1]) * axis[1] + (q[2] - l.from[2]) * axis[2]) / len2;+ // Only what lies along it and near it: a sleeve's line says nothing of the far side of a chest.+ const near: Vec3 = [l.from[0] + axis[0] * t, l.from[1] + axis[1] * t, l.from[2] + axis[2] * t];+ const away = Math.hypot(q[0] - near[0], q[1] - near[1], q[2] - near[2]);+ if (t < -0.1 || t > 1.1 || away > Math.sqrt(len2) * 0.8) continue;+ const grow = sampled(l.ease, t);+ const way = normalize([q[0] - near[0], q[1] - near[1], q[2] - near[2]]);+ out = [out[0] + way[0] * grow, out[1] + way[1] * grow, out[2] + way[2] * grow];+ const hang = sampled(l.hang, t);+ if (hang !== 0) {+ // All of it falls, the underside a little more: cloth hangs from what it rests on.+ const under = Math.max(0, -way[1]);+ out = [out[0], out[1] - hang * (0.4 + 0.6 * under), out[2]];+ }+ }+ return out;+ });++ // Cut: faces wholly past a plane go, and a point left past it is brought back onto it, so the hem is a clean line and not the grid.+ let kept = loops;+ const cuts = (p.cut ?? []).flatMap((c) => (c.mirror ? [c, { at: mirrored(c.at), keep: mirrored(c.keep) }] : [c]));+ for (const c of cuts) {+ const keep = normalize(c.keep);+ const side = (v: number): number => (placed[v]![0] - c.at[0]) * keep[0] + (placed[v]![1] - c.at[1]) * keep[1] + (placed[v]![2] - c.at[2]) * keep[2];+ kept = kept.filter((loop) => loop.some((v) => side(v) > 0));+ const onward = new Set(kept.flat());+ placed = placed.map((q, v) => {+ if (!onward.has(v)) return q;+ const d = side(v);+ return d < 0 ? [q[0] - keep[0] * d, q[1] - keep[1] * d, q[2] - keep[2] * d] : q;+ });+ }+ if (kept.length === 0) throw new Error('`cut` leaves nothing of it');++ // Thickness: the same again inside, turned over, and a band round each open edge joining the two.+ const start = mesh.positions.length;+ const inner = placed.map((q, v): Vec3 => {+ const n = faces[v]!;+ return [q[0] - n[0] * thickness, q[1] - n[1] * thickness, q[2] - n[2] * thickness];+ });+ const color = p.color ? [p.color[0]!, p.color[1]!, p.color[2]!, p.color[3] ?? 1] as const : undefined;+ const face = (v: readonly number[], faceTag = tag): Face => ({ v: [...v], tag: faceTag, smooth: true, ...(color ? { color } : {}) });+ // Its own tag, so a step that pushes the cloth out by its pattern does not push this through it from behind.+ const inside = `${tag}Inside`;+ const count = placed.length;+ const made: Face[] = [];+ const uses = new Map<number, number>();+ for (const loop of kept) loop.forEach((a, i) => { const b = loop[(i + 1) % loop.length]!; uses.set(edgeKey(a, b), (uses.get(edgeKey(a, b)) ?? 0) + 1); });+ // The inside is only seen a little way in from a hem, and the rest of it would be half the model's triangles spent on nothing.+ const nearHem = new Uint8Array(count);+ for (const loop of kept) loop.forEach((a, i) => { const b = loop[(i + 1) % loop.length]!; if (uses.get(edgeKey(a, b)) === 1) { nearHem[a] = 1; nearHem[b] = 1; } });+ for (let ring = 0; ring < INSIDE_RINGS; ring++) {+ const more: number[] = [];+ nearHem.forEach((on, v) => { if (on) for (const n of links[v]!) more.push(n); });+ for (const v of more) nearHem[v] = 1;+ }+ for (const loop of kept) {+ made.push(face(loop.map((v) => v + start)));+ if (loop.some((v) => nearHem[v])) made.push(face([...loop].reverse().map((v) => v + start + count), inside));+ loop.forEach((a, i) => {+ const b = loop[(i + 1) % loop.length]!;+ if (uses.get(edgeKey(a, b)) === 1) made.push(face([a + start + count, b + start + count, b + start, a + start], inside));+ });+ }+ // What it covers can go, but not right up to the hem, or a gap shows when it moves.+ const hidden = new Set<number>();+ if (p.hide) {+ const covered = new Set(kept.flat());+ const reverse = new Map<number, number>();+ local.forEach((to, from) => reverse.set(from, to));+ const edge = new Uint8Array(count);+ for (const loop of kept) loop.forEach((a, i) => { const b = loop[(i + 1) % loop.length]!; if (uses.get(edgeKey(a, b)) === 1) { edge[a] = 1; edge[b] = 1; } });+ for (let grow = 0; grow < 4; grow++) {+ const more: number[] = [];+ edge.forEach((on, v) => { if (on) for (const n of links[v]!) more.push(n); });+ for (const v of more) edge[v] = 1;+ }+ for (const f of hit) {+ const all = mesh.faces[f]!.v.every((v) => { const to = reverse.get(v); return to !== undefined && covered.has(to) && !edge[to]; });+ if (all) hidden.add(f);+ }+ }+ return compact({+ positions: [...mesh.positions, ...placed, ...inner],+ faces: [...mesh.faces.filter((_, f) => !hidden.has(f)), ...made],+ });+}diff --git a/pipeline/src/modeling/humanoid.ts b/pipeline/src/modeling/humanoid.tsnew file mode 100644index 000000000..11993d35b--- /dev/null+++ b/pipeline/src/modeling/humanoid.ts@@ -0,0 +1,320 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file humanoid.ts — the `humanoid` step: a whole person, standing, seen from every side.+ *+ * A person made of a few numbers: proportions are measured off a table of a body's cross-sections, so+ * moving a shoulder is one number, and the skeleton comes from the same table and so fits. It stands in an A-pose+ * with the arms clear of the waist, facing +z, feet on y = 0: a shape to wear clothes and be posed by bones, and+ * never one to be drawn in a pose.+ */+import { organic, type OrganicPart } from './organic';+import type { PolyMesh, Vec3 } from './polyMesh';+import type { RigJointSource } from './rig';++export interface HumanoidBuild {+ /** From the floor to the crown. Default 1.6. */+ height?: number;+ /** Size of the head against the body. Default 1; above it younger or more stylised. */+ head?: number;+ /** Width of each, against the table. Default 1. */+ shoulders?: number;+ chest?: number;+ waist?: number;+ hips?: number;+ /** Thickness of the arms and legs. Default 1. */+ limbs?: number;+}++export interface HumanoidParams extends HumanoidBuild {+ /** Grid cells along the height of the body. Default 240; the face and hands get finer faces anyway. */+ resolution?: number;+ /** `closed` lids the eyes with skin. Default open, with an eyeball of its own colour. */+ eyes?: 'open' | 'closed';+ /** Linear colours. */+ skin?: readonly number[];+ sclera?: readonly number[];+ iris?: readonly number[];+ lips?: readonly number[];+ tag?: string;+}++interface Section { y: number; across: number; front: number; back: number; z: number; x?: number }++/** The table is for a body 1.6 tall. */+const TABLE_HEIGHT = 1.6;++const TORSO: readonly Section[] = [+ { y: 1.345, across: 0.05, front: 0.05, back: 0.055, z: -0.018 },+ { y: 1.315, across: 0.082, front: 0.058, back: 0.066, z: -0.022 },+ { y: 1.285, across: 0.145, front: 0.068, back: 0.074, z: -0.022 },+ { y: 1.25, across: 0.158, front: 0.08, back: 0.08, z: -0.018 },+ { y: 1.2, across: 0.142, front: 0.094, back: 0.082, z: -0.012 },+ { y: 1.145, across: 0.125, front: 0.098, back: 0.076, z: -0.006 },+ { y: 1.09, across: 0.108, front: 0.08, back: 0.068, z: -0.004 },+ { y: 1.03, across: 0.096, front: 0.066, back: 0.056, z: -0.002 },+ { y: 0.975, across: 0.104, front: 0.068, back: 0.058, z: 0 },+ { y: 0.915, across: 0.122, front: 0.074, back: 0.076, z: -0.004 },+ { y: 0.85, across: 0.14, front: 0.076, back: 0.088, z: -0.006 },+ { y: 0.79, across: 0.132, front: 0.07, back: 0.08, z: -0.004 },+ { y: 0.745, across: 0.08, front: 0.06, back: 0.06, z: -0.004 },+];++const ARM_DROP = (62 * Math.PI) / 180;++export interface HumanoidFrame {+ k: number;+ shoulder: Vec3; elbow: Vec3; wrist: Vec3; knuckle: Vec3;+ hip: Vec3; knee: Vec3; ankle: Vec3; ball: Vec3; toe: Vec3;+ pelvis: Vec3; waist: Vec3; chest: Vec3; neck: Vec3; head: Vec3; crown: Vec3;+ /** Along the arm, from the shoulder out and down. */+ along: Vec3;+ fingers: readonly { name: string; base: Vec3; length: number; radius: number }[];+ thumb: { base: Vec3; mid: Vec3; tip: Vec3 };+}++/** Where everything is, in the table's own proportions times its height. Also what a skeleton is laid on. */+export function humanoidFrame(b: HumanoidBuild = {}): HumanoidFrame {+ const k = (b.height ?? TABLE_HEIGHT) / TABLE_HEIGHT;+ const s = (x: number, y: number, z: number): Vec3 => [x * k, y * k, z * k];+ const along: Vec3 = [Math.sin(ARM_DROP), -Math.cos(ARM_DROP), 0];+ const shoulderX = 0.158 * (b.shoulders ?? 1);+ const at = (d: number): Vec3 => s(shoulderX + along[0] * d, 1.268 + along[1] * d, -0.018);+ const palmAt = 0.27 + 0.235 + 0.09;+ const fingers = [+ { name: 'index', z: 0.027, length: 0.078, radius: 0.0085 },+ { name: 'middle', z: 0.009, length: 0.086, radius: 0.0088 },+ { name: 'ring', z: -0.009, length: 0.08, radius: 0.0082 },+ { name: 'little', z: -0.026, length: 0.062, radius: 0.0072 },+ ].map((f) => {+ const base = at(palmAt);+ return { name: f.name, base: [base[0], base[1], base[2] + f.z * k] as Vec3, length: f.length * k, radius: f.radius * k };+ });+ const wrist = at(0.27 + 0.235);+ const thumbBase: Vec3 = [wrist[0] + along[0] * 0.022 * k, wrist[1] + along[1] * 0.022 * k - 0.004 * k, wrist[2] + 0.028 * k];+ const thumbMid: Vec3 = [thumbBase[0] + along[0] * 0.038 * k, thumbBase[1] + along[1] * 0.038 * k - 0.006 * k, thumbBase[2] + 0.024 * k];+ const thumbTip: Vec3 = [thumbMid[0] + along[0] * 0.036 * k, thumbMid[1] + along[1] * 0.036 * k - 0.006 * k, thumbMid[2] + 0.01 * k];+ return {+ k, along,+ shoulder: at(0), elbow: at(0.27), wrist, knuckle: at(palmAt),+ hip: s(0.08, 0.81, -0.004), knee: s(0.068, 0.445, 0.006), ankle: s(0.067, 0.078, -0.016), ball: s(0.072, 0.022, 0.09), toe: s(0.072, 0.018, 0.165),+ pelvis: s(0, 0.86, -0.004), waist: s(0, 1.0, 0), chest: s(0, 1.16, -0.008), neck: s(0, 1.32, -0.022), head: s(0, 1.405, -0.01), crown: s(0, TABLE_HEIGHT, -0.012),+ fingers, thumb: { base: thumbBase, mid: thumbMid, tip: thumbTip },+ };+}++/** The bones of a humanoid of this build, named as a clip names them. `.L` is her left, on +x. */+export function humanoidJoints(b: HumanoidBuild = {}): RigJointSource[] {+ const f = humanoidFrame(b);+ const mid = (a: Vec3, c: Vec3, t: number): Vec3 => [a[0] + (c[0] - a[0]) * t, a[1] + (c[1] - a[1]) * t, a[2] + (c[2] - a[2]) * t];+ const clavicle: Vec3 = [0.03 * f.k, 1.29 * f.k, -0.008 * f.k];+ const joints: RigJointSource[] = [+ { name: 'hips', at: f.pelvis },+ { name: 'spine', at: f.waist, parent: 'hips' },+ { name: 'chest', at: f.chest, parent: 'spine' },+ { name: 'neck', at: f.neck, parent: 'chest' },+ { name: 'head', at: f.head, parent: 'neck' },+ { name: 'crown', at: f.crown, parent: 'head' },+ { name: 'clavicle', at: clavicle, parent: 'chest', mirror: 'x' },+ { name: 'upperArm', at: f.shoulder, parent: 'clavicle', mirror: 'x' },+ { name: 'forearm', at: f.elbow, parent: 'upperArm', mirror: 'x' },+ { name: 'hand', at: f.wrist, parent: 'forearm', mirror: 'x' },+ { name: 'thumb1', at: f.thumb.base, parent: 'hand', mirror: 'x' },+ { name: 'thumb2', at: f.thumb.mid, parent: 'thumb1', mirror: 'x' },+ { name: 'thumb3', at: f.thumb.tip, parent: 'thumb2', mirror: 'x' },+ { name: 'thigh', at: f.hip, parent: 'hips', mirror: 'x' },+ { name: 'shin', at: f.knee, parent: 'thigh', mirror: 'x' },+ { name: 'foot', at: f.ankle, parent: 'shin', mirror: 'x' },+ { name: 'toes', at: f.ball, parent: 'foot', mirror: 'x' },+ { name: 'toeTip', at: f.toe, parent: 'toes', mirror: 'x' },+ ];+ for (const finger of f.fingers) {+ let parent = 'hand';+ for (let i = 0; i < 4; i++) {+ const name = `${finger.name}${i + 1}`;+ const t = [0, 0.45, 0.75, 1][i]!;+ joints.push({ name, at: mid(finger.base, [finger.base[0] + f.along[0] * finger.length, finger.base[1] + f.along[1] * finger.length, finger.base[2]], t), parent, mirror: 'x' });+ parent = name;+ }+ }+ return joints;+}++/** The tags a humanoid's own skin carries: what it wears is everything else. */+export const HUMANOID_TAGS: readonly string[] = ['torso', 'arm', 'hand', 'leg', 'foot', 'neck', 'face', 'scalp', 'ear', 'lips', 'lid', 'eye', 'iris'];++const SKIN = [0.72, 0.5, 0.42] as const;+const SCLERA = [0.82, 0.82, 0.82] as const;+const IRIS = [0.1, 0.16, 0.26] as const;+const LIPS = [0.56, 0.22, 0.22] as const;++/** The parts of a body. The head is built on its own table and moved into place, so a larger head stays a head. */+export function humanoidParts(p: HumanoidParams = {}): OrganicPart[] {+ const f = humanoidFrame(p);+ const k = f.k;+ const limbs = p.limbs ?? 1;+ const sx = (x: number, y: number, z: number): [number, number, number] => [x * k, y * k, z * k];+ /** A torso section's width by which band it is in. */+ const widen = (s: Section): number => {+ if (s.y > 1.22) return p.shoulders ?? 1;+ if (s.y > 1.11) return p.chest ?? 1;+ if (s.y > 0.95) return p.waist ?? 1;+ return p.hips ?? 1;+ };+ const parts: OrganicPart[] = [];+ parts.push({+ shape: 'limb', tag: 'torso', blend: 0.012 * k, curve: 5, power: 2.35, side: [1, 0, 0],+ sections: TORSO.map((s) => ({ at: sx(0, s.y, s.z), across: s.across * k * widen(s), front: s.front * k, back: s.back * k })),+ });+ // Breasts are the chest wall swelling: a separate ball reads as a ball glued on, at any depth.+ parts.push({ shape: 'ellipsoid', tag: 'torso', radii: [0.058 * k * (p.chest ?? 1), 0.054 * k, 0.05 * k], at: sx(0.058, 1.15, 0.056), rotate: [14, 0, 0], mirror: 'x', blend: 0.045 * k });+ // The shoulder blades and the collar bones, faintly; the buttocks, as a body has them.+ parts.push({ shape: 'ellipsoid', tag: 'torso', radii: [0.068 * k, 0.07 * k, 0.058 * k], at: sx(0.062 * (p.hips ?? 1), 0.815, -0.05), mirror: 'x', blend: 0.05 * k });+ parts.push({ shape: 'chain', tag: 'torso', points: [[0.018 * k, 1.292 * k, 0.038 * k, 0.0085 * k], [0.13 * k, 1.292 * k, 0.012 * k, 0.012 * k]], mirror: 'x', blend: 0.024 * k });++ // Arms: out and down from the shoulder, each limb narrower one way than the other.+ const a = f.along;+ const onArm = (d: number): [number, number, number] => [f.shoulder[0] + a[0] * d * k, f.shoulder[1] + a[1] * d * k, f.shoulder[2]];+ const armPart = (d: number, r: number, deep = r): { at: Vec3; across: number; front: number; back: number } => ({ at: onArm(d), across: r * k * limbs, front: deep * k * limbs, back: deep * k * limbs });+ parts.push({+ shape: 'limb', tag: 'arm', mirror: 'x', blend: 0.016 * k, curve: 5, side: [0, 0, 1],+ sections: [armPart(-0.012, 0.044), armPart(0.03, 0.052, 0.05), armPart(0.1, 0.044, 0.044), armPart(0.2, 0.037, 0.038), armPart(0.262, 0.032, 0.031), armPart(0.31, 0.035, 0.034), armPart(0.4, 0.029, 0.026), armPart(0.5, 0.024, 0.018)],+ });+ // A hand: a palm wider than it is thick, and the fingers springing from its end.+ parts.push({+ shape: 'limb', tag: 'hand', mirror: 'x', blend: 0.006 * k, curve: 4, side: [0, 0, 1],+ sections: [armPart(0.5, 0.022, 0.015), armPart(0.53, 0.036, 0.016), armPart(0.57, 0.041, 0.0145), armPart(0.598, 0.04, 0.0115)],+ });+ for (const finger of f.fingers) {+ const end = (t: number): [number, number, number, number] => [+ finger.base[0] - a[0] * 0.008 * k + a[0] * finger.length * t, finger.base[1] - a[1] * 0.008 * k + a[1] * finger.length * t - 0.004 * k * t * t, finger.base[2],+ finger.radius * (1 - 0.25 * t),+ ];+ parts.push({ shape: 'chain', tag: 'hand', mirror: 'x', blend: 0.0025 * k, points: [end(0), end(0.5), end(1)] });+ }+ parts.push({ shape: 'chain', tag: 'hand', mirror: 'x', blend: 0.008 * k, points: [[...f.thumb.base, 0.0125 * k], [...f.thumb.mid, 0.0095 * k], [...f.thumb.tip, 0.0075 * k]] });++ // Legs.+ const leg = (y: number, x: number, z: number, across: number, front: number, back: number): { at: Vec3; across: number; front: number; back: number } => ({ at: sx(x, y, z), across: across * k * limbs, front: front * k * limbs, back: back * k * limbs });+ parts.push({+ shape: 'limb', tag: 'leg', mirror: 'x', blend: 0.022 * k, curve: 5, side: [1, 0, 0], power: 2.15,+ sections: [leg(0.84, 0.08, -0.004, 0.06, 0.07, 0.076), leg(0.745, 0.08, 0, 0.07, 0.072, 0.074), leg(0.62, 0.075, 0.004, 0.058, 0.062, 0.058), leg(0.5, 0.07, 0.006, 0.046, 0.05, 0.048), leg(0.445, 0.068, 0.008, 0.042, 0.046, 0.042), leg(0.39, 0.067, 0.0, 0.04, 0.038, 0.045), leg(0.31, 0.066, -0.012, 0.042, 0.033, 0.052), leg(0.2, 0.066, -0.016, 0.03, 0.026, 0.034), leg(0.1, 0.067, -0.016, 0.022, 0.022, 0.025), leg(0.07, 0.067, -0.018, 0.022, 0.024, 0.026)],+ });+ // A foot: heel behind the ankle, the arch high, the ball broad, the toes tapering. Its depth is up and down: `side` is across it.+ parts.push({+ shape: 'limb', tag: 'foot', mirror: 'x', blend: 0.012 * k, curve: 5, side: [1, 0, 0],+ sections: [+ { at: sx(0.067, 0.036, -0.058), across: 0.022 * k, front: 0.028 * k, back: 0.028 * k },+ { at: sx(0.067, 0.044, -0.03), across: 0.027 * k, front: 0.036 * k, back: 0.036 * k },+ { at: sx(0.069, 0.042, 0.03), across: 0.032 * k, front: 0.03 * k, back: 0.03 * k },+ { at: sx(0.072, 0.024, 0.095), across: 0.04 * k, front: 0.016 * k, back: 0.016 * k },+ { at: sx(0.073, 0.016, 0.15), across: 0.036 * k, front: 0.012 * k, back: 0.012 * k },+ { at: sx(0.073, 0.012, 0.178), across: 0.026 * k, front: 0.0095 * k, back: 0.0095 * k },+ ],+ });++ parts.push(...headParts(p));+ return parts;+}++/** The head, about the point between the ears at the height of the eyes, facing +z. */+function headParts(p: HumanoidParams): OrganicPart[] {+ const f = humanoidFrame(p);+ const k = f.k;+ const size = (p.head ?? 1) * k;+ // Heads are 0.238 tall in the table: crown at 1.6, chin at 1.362.+ const origin: Vec3 = [0, (1.6 - 0.112 * (p.head ?? 1)) * k, -0.012 * k];+ const pt = (x: number, y: number, z: number): [number, number, number] => [origin[0] + x * size, origin[1] + y * size, origin[2] + z * size];+ const skin = p.skin ?? SKIN;+ const parts: OrganicPart[] = [];+ // The neck runs from under the skull to the collar, leaning forward as it rises.+ parts.push({+ shape: 'limb', tag: 'neck', blend: 0.02 * k, curve: 4, side: [1, 0, 0],+ sections: [+ { at: [0, 1.33 * k, -0.024 * k], across: 0.047 * k, front: 0.042 * k, back: 0.048 * k },+ { at: [0, 1.385 * k, -0.018 * k], across: 0.037 * k, front: 0.037 * k, back: 0.04 * k },+ { at: pt(0, -0.045, -0.018), across: 0.04 * size, front: 0.038 * size, back: 0.042 * size },+ ],+ });+ parts.push({ shape: 'ellipsoid', tag: 'scalp', radii: [0.077 * size, 0.088 * size, 0.096 * size], at: pt(0, 0.038, -0.018), blend: 0.02 * size });+ // The face, from the brow to the chin: a mask of sections narrowing to the jaw, deeper in front than a skull.+ parts.push({+ shape: 'limb', tag: 'face', blend: 0.016 * size, curve: 6, side: [1, 0, 0], power: 2.25,+ sections: [+ { at: pt(0, 0.05, -0.002), across: 0.072 * size, front: 0.082 * size, back: 0.06 * size },+ { at: pt(0, 0.012, 0), across: 0.071 * size, front: 0.084 * size, back: 0.06 * size },+ { at: pt(0, -0.028, 0.002), across: 0.065 * size, front: 0.08 * size, back: 0.056 * size },+ { at: pt(0, -0.062, 0.006), across: 0.05 * size, front: 0.073 * size, back: 0.044 * size },+ { at: pt(0, -0.088, 0.012), across: 0.032 * size, front: 0.063 * size, back: 0.028 * size },+ { at: pt(0, -0.106, 0.022), across: 0.016 * size, front: 0.047 * size, back: 0.012 * size },+ ],+ });+ // The planes that make it a face: brow, cheek, chin.+ parts.push({ shape: 'chain', tag: 'face', points: [[...pt(0.008, 0.024, 0.07), 0.0075 * size], [...pt(0.03, 0.027, 0.066), 0.0075 * size], [...pt(0.054, 0.018, 0.044), 0.006 * size]], mirror: 'x', blend: 0.02 * size });+ parts.push({ shape: 'ellipsoid', tag: 'face', radii: [0.021 * size, 0.017 * size, 0.018 * size], at: pt(0.036, -0.026, 0.056), mirror: 'x', blend: 0.016 * size });+ parts.push({ shape: 'ellipsoid', tag: 'face', radii: [0.014 * size, 0.011 * size, 0.012 * size], at: pt(0, -0.097, 0.062), blend: 0.012 * size });+ // The eye sockets go in, and what fills them comes after.+ parts.push({ shape: 'ellipsoid', tag: 'face', subtract: true, radii: [0.0205 * size, 0.0118 * size, 0.013 * size], at: pt(0.031, 0.002, 0.079), mirror: 'x', blend: 0.013 * size });+ // A nose: a bridge coming out of the brow, a tip, and two wings.+ parts.push({+ shape: 'limb', tag: 'face', blend: 0.012 * size, curve: 5, side: [1, 0, 0],+ sections: [+ { at: pt(0, 0.006, 0.066), across: 0.0055 * size, front: 0.0055 * size, back: 0.0055 * size },+ { at: pt(0, -0.016, 0.078), across: 0.0056 * size, front: 0.0062 * size, back: 0.006 * size },+ { at: pt(0, -0.035, 0.086), across: 0.0068 * size, front: 0.0072 * size, back: 0.0065 * size },+ { at: pt(0, -0.04, 0.0855), across: 0.0052 * size, front: 0.0052 * size, back: 0.005 * size },+ ],+ });+ parts.push({ shape: 'ellipsoid', tag: 'face', radii: [0.0052 * size, 0.0045 * size, 0.0055 * size], at: pt(0.0098, -0.0395, 0.0775), mirror: 'x', blend: 0.007 * size });+ // Lips, and the line between them.+ parts.push({ shape: 'ellipsoid', tag: 'lips', color: p.lips ?? LIPS, radii: [0.0135 * size, 0.0036 * size, 0.0065 * size], at: pt(0, -0.0635, 0.0775), blend: 0.005 * size });+ parts.push({ shape: 'ellipsoid', tag: 'lips', color: p.lips ?? LIPS, radii: [0.011 * size, 0.0046 * size, 0.0065 * size], at: pt(0, -0.0718, 0.0755), blend: 0.005 * size });+ parts.push({ shape: 'ellipsoid', tag: 'lips', subtract: true, radii: [0.0135 * size, 0.0009 * size, 0.006 * size], at: pt(0, -0.0675, 0.0822), blend: 0.002 * size });+ // Ears: a flat drawing standing off the side of the skull.+ parts.push({+ shape: 'outline', tag: 'ear', mirror: 'x', depth: 0.005 * size, round: 0.004 * size, curve: 3, blend: 0.004 * size, rotate: [0, -80, 0], at: pt(0.076, -0.002, -0.022),+ points: [[-0.012 * size, 0.022 * size], [0.002 * size, 0.031 * size], [0.015 * size, 0.022 * size], [0.015 * size, 0.002 * size], [0.006 * size, -0.018 * size], [-0.002 * size, -0.026 * size], [-0.007 * size, -0.014 * size], [-0.011 * size, 0.004 * size]],+ });+ parts.push({ shape: 'ellipsoid', tag: 'ear', subtract: true, mirror: 'x', radii: [0.003 * size, 0.012 * size, 0.008 * size], at: pt(0.08, 0.002, -0.02), blend: 0.003 * size });+ if (p.eyes === 'closed') {+ parts.push({ shape: 'ellipsoid', tag: 'lid', radii: [0.0202 * size, 0.0115 * size, 0.0142 * size], at: pt(0.031, 0.002, 0.0615), mirror: 'x', blend: 0.005 * size });+ } else {+ parts.push({ shape: 'sphere', tag: 'eye', radius: 0.0152 * size, at: pt(0.031, 0.002, 0.0585), mirror: 'x', blend: 0, color: p.sclera ?? SCLERA });+ parts.push({ shape: 'ellipsoid', tag: 'iris', radii: [0.0068 * size, 0.0075 * size, 0.0026 * size], at: pt(0.031, 0.002, 0.0722), mirror: 'x', blend: 0, color: p.iris ?? IRIS });+ // Lids over the ball, an upper heavier than the lower, leaving it open between them.+ parts.push({ shape: 'ellipsoid', tag: 'lid', radii: [0.0198 * size, 0.0062 * size, 0.0132 * size], at: pt(0.031, 0.0125, 0.0635), rotate: [-12, 0, 0], mirror: 'x', blend: 0.005 * size, color: skin });+ parts.push({ shape: 'ellipsoid', tag: 'lid', radii: [0.0185 * size, 0.0038 * size, 0.0125 * size], at: pt(0.031, -0.0092, 0.0625), rotate: [12, 0, 0], mirror: 'x', blend: 0.005 * size, color: skin });+ }+ return parts;+}++/** The finest faces go where there is the most to see: on the face, and on the hands. */+export function humanoidFineRegions(p: HumanoidParams = {}): { at: Vec3; radius: number; longest: number; mirror?: 'x' }[] {+ const f = humanoidFrame(p);+ const size = (p.head ?? 1) * f.k;+ const head: Vec3 = [0, (1.6 - 0.112 * (p.head ?? 1) - 0.03 * (p.head ?? 1)) * f.k, 0.012 * f.k];+ const hand: Vec3 = [(f.wrist[0] + f.knuckle[0]) / 2 + f.along[0] * 0.05 * f.k, (f.wrist[1] + f.knuckle[1]) / 2 + f.along[1] * 0.05 * f.k, f.wrist[2]];+ return [+ { at: head, radius: 0.135 * size, longest: 0.0034 * size },+ { at: hand, radius: 0.17 * f.k, longest: 0.0042 * f.k, mirror: 'x' },+ ];+}++const MAX_HUMANOID_RESOLUTION = 400;++export function humanoid(mesh: PolyMesh, p: HumanoidParams): PolyMesh {+ const resolution = p.resolution ?? 240;+ if (!Number.isInteger(resolution) || resolution < 120 || resolution > MAX_HUMANOID_RESOLUTION) throw new Error(`resolution ${resolution} must be a whole number, 120..${MAX_HUMANOID_RESOLUTION}`);+ for (const key of ['height', 'head', 'shoulders', 'chest', 'waist', 'hips', 'limbs'] as const) {+ if (p[key] !== undefined && !(p[key]! > 0)) throw new Error(`${key} ${p[key]} must be positive`);+ }+ if (p.eyes !== undefined && p.eyes !== 'open' && p.eyes !== 'closed') throw new Error(`eyes ${JSON.stringify(p.eyes)} must be open or closed`);+ return organic(mesh, {+ parts: humanoidParts(p),+ resolution,+ maxResolution: MAX_HUMANOID_RESOLUTION,+ color: p.skin ?? SKIN,+ ...(p.tag ? { tag: p.tag } : {}),+ fine: humanoidFineRegions(p),+ });+}diff --git a/pipeline/src/modeling/modelBake.ts b/pipeline/src/modeling/modelBake.tsindex 83f1e3199..baa4b7fa1 100644--- a/pipeline/src/modeling/modelBake.ts+++ b/pipeline/src/modeling/modelBake.ts@@ -13,7 +13,7 @@ import { generateTangents } from '../assets/meshTangents';import { hairMaps, hairRig, hasCards, type HairMaps } from './hair';import { triangulateFace } from './triangulate';import { faceUvs } from './modelUv';-import { adjustWeights, bindMatrices, computeWeights, drapeRig, resolveJoints, shapeDeltas, type ControllerIk, type RigGoal, type RigJoint, type RigSpring, type SkinWeights } from './rig';+import { adjustWeights, bindMatrices, computeWeights, computeWornWeights, drapeRig, resolveJoints, shapeDeltas, type ControllerIk, type RigGoal, type RigJoint, type RigSpring, type SkinWeights } from './rig';import type { NormalBakeReport } from './normalBake';import { buildPolyMesh, validateModelSource, type ModelSource, type StepReport } from './modelSource';import {@@ -338,7 +338,7 @@ export function bakeModel(raw: unknown): BakedModel {let rig: BakedModel['rig'];if (source.rig) {const joints = resolveJoints(source.rig);- const found = adjustWeights(mesh, joints, computeWeights(mesh, joints), source.rig.adjust ?? []);+ const found = adjustWeights(mesh, joints, source.rig.worn ? computeWornWeights(mesh, joints, new Set(source.rig.worn)) : computeWeights(mesh, joints), source.rig.adjust ?? []);const draped = source.rig.drape ? drapeRig(mesh, joints, found, source.rig.drape) : null;rig = { joints: draped?.joints ?? joints, skin: draped?.skin ?? found, ik: source.controller?.ik ?? [], goals: source.rig.goals ?? [], ...(draped ? { springs: draped.springs } : {}) };}diff --git a/pipeline/src/modeling/modelSource.ts b/pipeline/src/modeling/modelSource.tsindex db79c6c59..be037fa8b 100644--- a/pipeline/src/modeling/modelSource.ts+++ b/pipeline/src/modeling/modelSource.ts@@ -22,6 +22,9 @@ import { decimate, triangleCount } from './decimate';import { displace, DISPLACE_PATTERNS } from './displace';import { stain } from './stain';import { sculpt } from './sculpt';+import { garment } from './garment';+import { poseStep } from './pose';+import { HUMANOID_TAGS, humanoid, humanoidJoints, type HumanoidBuild } from './humanoid';import { VIEW_NAMES } from './surfaceLine';import { cardsOnly, hair, hasCards, type HairSway } from './hair';import { scatter } from './scatter';@@ -112,7 +115,7 @@ export interface NormalBakeSource {}type Kind = 'number' | 'integer' | 'boolean' | 'string' | 'vec3' | 'number|vec3' | 'number|vec2' | 'number|numbers'- | 'color' | 'points' | 'faces' | 'edges' | 'axis' | 'pivot' | 'parts' | 'noise' | 'sections' | 'section' | 'vec3s' | 'numbers' | 'operation' | 'uvmode' | 'number|vec2only' | 'vec2' | 'pattern' | 'near' | 'where' | 'guides' | 'line' | 'view' | 'strokes';+ | 'color' | 'points' | 'faces' | 'edges' | 'axis' | 'pivot' | 'parts' | 'noise' | 'sections' | 'section' | 'vec3s' | 'numbers' | 'operation' | 'uvmode' | 'number|vec2only' | 'vec2' | 'pattern' | 'near' | 'where' | 'guides' | 'line' | 'view' | 'strokes' | 'loose' | 'cuts' | 'build' | 'angles' | 'reaches';interface OpSpec {params: Record<string, Kind>;@@ -135,6 +138,9 @@ export const MODEL_OPS: Record<string, OpSpec> = {lathe: { params: { profile: 'points', sides: 'integer', arc: 'number', closed: 'boolean', curve: 'integer', axis: 'axis', ...PLACED }, required: ['profile'], run: lathe as unknown as OpSpec['run'], says: 'turns a half-outline of [distance from axis, height] round an axis: a vase, a glass, a column' },loft: { params: { sections: 'sections', path: 'vec3s', section: 'section', scales: 'numbers', sides: 'integer', closed: 'boolean', curve: 'integer', ...PLACED }, required: [], run: loft as unknown as OpSpec['run'], says: 'joins cross-sections along a path: a pipe, a handle, a bottle, a hull' },organic: { params: { parts: 'parts', resolution: 'integer', blend: 'number', noise: 'noise', at: 'vec3', tag: 'string', color: 'color' }, required: ['parts'], run: organic as unknown as OpSpec['run'], says: 'adds one continuous skin over a body of parts that melt into each other' },+ humanoid: { params: { height: 'number', head: 'number', shoulders: 'number', chest: 'number', waist: 'number', hips: 'number', limbs: 'number', resolution: 'integer', eyes: 'string', skin: 'color', sclera: 'color', iris: 'color', lips: 'color', tag: 'string' }, required: [], run: humanoid as unknown as OpSpec['run'], says: 'adds a whole person standing in an A-pose, facing +z with feet on y 0, whole from every side, with fingers, a face and ears; `rig: { humanoid: {...} }` gives bones that fit the same build' },+ garment: { params: { faces: 'faces', ease: 'number', relax: 'number', loose: 'loose', cut: 'cuts', thickness: 'number', hide: 'boolean', color: 'color', tag: 'string' }, required: ['faces'], run: garment as unknown as OpSpec['run'], says: 'makes clothes from a piece of the surface already there: relaxed, stood off by `ease`, `loose` for a bell sleeve, `cut` for a hem, with a thickness; they fit from every side and move with the same bones' },+ pose: { params: { humanoid: 'build', rotate: 'angles', move: 'angles', reach: 'reaches', rigid: 'string' }, required: ['humanoid'], run: poseStep as unknown as OpSpec['run'], says: 'holds what is there in a pose, by a humanoid\'s bones: for a still, as a character in a game takes hers from a clip' },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`' },@@ -144,7 +150,7 @@ export const MODEL_OPS: Record<string, OpSpec> = {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' },boolean: { params: { operation: 'operation', with: 'faces', from: 'faces', keep: 'boolean', tag: 'string', color: 'color' }, required: ['operation', 'with'], run: booleanOp as unknown as OpSpec['run'], says: 'cuts or joins closed solids: subtract `with` from `from` makes a real hole' },subdivide: { params: { faces: 'faces', levels: 'integer', crease: 'number' }, required: [], run: subdivide as unknown as OpSpec['run'], says: 'rounds whole shells into smooth surfaces, keeping edges sharper than `crease` degrees' },- displace: { params: { faces: 'faces', near: 'near', pattern: 'pattern', amplitude: 'number', scale: 'number', octaves: 'integer', seed: 'integer', stretch: 'vec3', warp: 'number', width: 'number', count: 'integer', axis: 'axis', mirror: 'axis', detail: 'number' }, required: ['pattern', 'amplitude', 'scale'], run: ((mesh: PolyMesh, params: never) => displace(mesh, params)) as OpSpec['run'], says: 'pushes fine detail out of the surface along its normal, splitting faces as far as the pattern needs: bumps, wrinkles, cracks, scales, pores, ribs, weave, scratches or pleats' },+ displace: { params: { faces: 'faces', near: 'near', pattern: 'pattern', amplitude: 'number', scale: 'number', octaves: 'integer', seed: 'integer', stretch: 'vec3', warp: 'number', width: 'number', count: 'integer', axis: 'axis', mirror: 'axis', detail: 'number', along: 'vec3', long: 'number' }, required: ['pattern', 'amplitude', 'scale'], run: ((mesh: PolyMesh, params: never) => displace(mesh, params)) as OpSpec['run'], says: 'pushes fine detail out of the surface along its normal, splitting faces as far as the pattern needs: bumps, wrinkles, cracks, scales, pores, ribs, weave, scratches, pleats or folds' },hair: { params: { faces: 'faces', count: 'integer', length: 'number', guides: 'guides', gather: 'number', width: 'number', segments: 'integer', droop: 'number', comb: 'vec3', spread: 'number', uneven: 'number', wave: 'number', taper: 'number', seed: 'integer', color: 'color', tipColor: 'color', tag: 'string' }, required: ['faces'], run: hair as unknown as OpSpec['run'], says: 'grows cards of hair from these faces, falling around what is there, or along `guides` for a ponytail or a fringe; run it again for another layer, and only the cards are kept' },scatter: { params: { source: 'faces', count: 'integer', faces: 'faces', path: 'vec3s', within: 'vec3s', scale: 'number|numbers', taper: 'number', spin: 'number', tilt: 'number', colors: 'vec3s', keep: 'boolean', seed: 'integer', tag: 'string' }, required: ['source', 'count'], run: scatter as unknown as OpSpec['run'], says: 'puts copies of the `source` faces across `faces`, along a `path` or through a box `within`, each sized, turned and coloured at random: feathers, rivets, the lights of a far city' },stain: { params: { faces: 'faces', near: 'near', line: 'line', hard: 'boolean', color: 'color', roughness: 'number', metallic: 'number', alpha: 'number', amount: 'number', pattern: 'pattern', scale: 'number', octaves: 'integer', seed: 'integer', stretch: 'vec3', warp: 'number', width: 'number', axis: 'axis', mirror: 'axis', threshold: 'number', softness: 'number', where: 'where', reach: 'number', facing: 'vec3', detail: 'number' }, required: [], run: ((mesh: PolyMesh, params: never) => stain(mesh, params)) as OpSpec['run'], says: 'lays colour, `roughness`, `metallic` or `alpha` over the surface by a pattern, by shape (`where`: cavity for dirt in what is sunken, edges for wear on what stands out), by which way it faces, around a spot, or along a `line`: pupils, eyelids, seams, moss, grime' },@@ -220,7 +226,10 @@ function checkNoise(v: unknown): string | null {}const PART_FIELDS: Record<string, (v: unknown) => string | null> = {- shape: (v) => (['sphere', 'ellipsoid', 'box', 'torus', 'chain', 'outline'].includes(v as string) ? null : 'must be sphere, ellipsoid, box, torus, chain or outline'),+ shape: (v) => (['sphere', 'ellipsoid', 'box', 'torus', 'chain', 'outline', 'limb'].includes(v as string) ? null : 'must be sphere, ellipsoid, box, torus, chain, outline or limb'),+ sections: (v) => (Array.isArray(v) && v.every((q) => typeof q === 'object' && q !== null && isNums((q as Record<string, unknown>).at, 3) && isNum((q as Record<string, unknown>).across) && isNum((q as Record<string, unknown>).front)) ? null : 'must be an array of { at: [x, y, z], across, front, back? }'),+ side: (v) => (isNums(v, 3) ? null : 'must be [x, y, z]'),+ power: (v) => (isNum(v) ? null : 'must be a number'),tag: (v) => (typeof v === 'string' ? null : 'must be a string'),at: (v) => (isNums(v, 3) ? null : 'must be [x, y, z]'),rotate: (v) => (isNums(v, 3) ? null : 'must be [x, y, z] degrees'),@@ -317,6 +326,11 @@ const KIND_CHECK: Record<Kind, (v: unknown) => string | null> = {const size = line?.from !== undefined ? 2 : 3;return typeof n === 'object' && n !== null && Array.isArray(n.points) && n.points.length >= 2 && n.points.every((q) => isNums(q, size)) && isNum(n.width) && Object.keys(n).every((k) => k === 'points' || k === 'width' || k === 'from' || k === 'curve') ? null : (size === 2 ? 'must be { points: [[a, b], ...], width, from }, the points in the two axes of the view' : 'must be { points: [[x, y, z], ...], width }');},+ loose: (v) => (Array.isArray(v) && v.every((q) => typeof q === 'object' && q !== null && isNums((q as Record<string, unknown>).from, 3) && isNums((q as Record<string, unknown>).to, 3)) ? null : 'must be an array of { from, to, ease?: [..], hang?: [..], mirror? }'),+ cuts: (v) => (Array.isArray(v) && v.every((q) => typeof q === 'object' && q !== null && isNums((q as Record<string, unknown>).at, 3) && isNums((q as Record<string, unknown>).keep, 3)) ? null : 'must be an array of { at: [x, y, z], keep: [x, y, z], mirror? }'),+ reaches: (v) => (typeof v === 'object' && v !== null && !Array.isArray(v) && Object.values(v).every((q) => typeof q === 'object' && q !== null && isNums((q as Record<string, unknown>).at, 3)) ? null : 'must be { jointName: { at: [x, y, z], pole? } }'),+ build: (v) => (v === true || (typeof v === 'object' && v !== null && !Array.isArray(v)) ? null : 'must be true or the build the humanoid step was given'),+ angles: (v) => (typeof v === 'object' && v !== null && !Array.isArray(v) && Object.values(v).every((q) => isNums(q, 3)) ? null : 'must be { jointName: [x, y, z] }'),view: (v) => (VIEW_NAMES.includes(v as string) ? null : `must be one of ${VIEW_NAMES.join(', ')}`),strokes: (v) => (Array.isArray(v) && v.length > 0 && v.every((s) => typeof s === 'object' && s !== null) ? null : 'must be a non-empty array of strokes, each { brush, ... }'),guides: (v) => (Array.isArray(v) && v.every((line) => Array.isArray(line) && line.length >= 2 && line.every((q) => isNums(q, 3))) ? null : 'must be an array of lines, each two or more [x, y, z]'),@@ -389,6 +403,14 @@ export function validateModelSource(raw: unknown): ModelSource {if (source.uvAtlas !== undefined && typeof source.uvAtlas !== 'boolean') {throw new ModelBuildError('uvAtlas must be true or false', null, null, null);}+ // A humanoid's bones, from the build they fit, before anything looks at the joints.+ const rigged = source.rig as { humanoid?: HumanoidBuild | true; joints?: unknown[] } | undefined;+ if (rigged && typeof rigged === 'object' && rigged.humanoid !== undefined) {+ const build = rigged.humanoid === true ? {} : rigged.humanoid;+ if (typeof build !== 'object' || build === null) throw new ModelBuildError('rig.humanoid must be true or the build the humanoid step was given', null, null, null);+ const { humanoid: _given, ...rest } = rigged;+ source.rig = { ...rest, joints: [...humanoidJoints(build), ...(rigged.joints ?? [])], worn: HUMANOID_TAGS };+ }if (source.rig !== undefined) {const bad = checkRig(source.rig);if (bad) throw new ModelBuildError(bad, null, null, null);diff --git a/pipeline/src/modeling/organic.ts b/pipeline/src/modeling/organic.tsindex cd3d6eb70..9a8c64b2f 100644--- a/pipeline/src/modeling/organic.ts+++ b/pipeline/src/modeling/organic.ts@@ -15,10 +15,21 @@* is one more shell of quads, so every later step can act on it. Its faces are* marked smooth, and each carries the tag and colour of the part nearest it.*/+import { refine } from './displace';import { add, type Face, type PolyMesh, type Vec3 } from './polyMesh';import { curveThrough } from './surfaces';-export type OrganicShape = 'sphere' | 'ellipsoid' | 'box' | 'torus' | 'chain' | 'outline';+export type OrganicShape = 'sphere' | 'ellipsoid' | 'box' | 'torus' | 'chain' | 'outline' | 'limb';++/** One cross-section of a limb: an oval standing square to the line it is on. */+export interface LimbSection {+ at: Vec3;+ /** Half its width, along `side`. */+ across: number;+ /** Half its depth, the way it faces; `back` differs where a body does, a calf or a chest. */+ front: number;+ back?: number;+}export interface OrganicNoise {/** How far the surface moves, in and out. */@@ -51,8 +62,14 @@ export interface OrganicPart {depth?: number;/** outline: how far in from its edge it takes to come up to `depth`. Default the whole way to its middle, a dome with no flat on it; small, a slab with soft edges. */round?: number;- /** outline: this many segments between points, passing through each. A point given twice keeps a corner there. */+ /** outline and limb: this many segments between points, passing through each. A point given twice keeps a corner there. */curve?: number;+ /** limb: its cross-sections, in order along it. */+ sections?: readonly LimbSection[];+ /** limb: the direction that is across it, kept square to the line. Default +x. */+ side?: Vec3;+ /** limb: 2 is an oval; higher squares it, as a chest is squarer than a wrist. Default 2. */+ power?: number;/** How far this melts into what is before it; 0 is a hard crease. Defaults to the step's. */blend?: number;/** Carves this volume out of what is before it: an eye socket, a mouth. */@@ -67,6 +84,10 @@ export interface OrganicParams {parts: readonly OrganicPart[];/** Grid cells along the longest side. More resolves more detail, at the cost of triangles. */resolution?: number;+ /** What `resolution` may go to, where a caller knows the cost: a whole body. */+ maxResolution?: number;+ /** Around these places the skin is split finer and settled back on the true surface: a face, a hand. No seam, as it stays one skin. */+ fine?: readonly { at: Vec3; radius: number; longest: number; mirror?: 'x' }[];blend?: number;noise?: OrganicNoise;at?: Vec3;@@ -146,7 +167,7 @@ function rotateForward(degrees: Vec3, p: Vec3): Vec3 {}/** The part's distance function in its own frame, and how far from `at` it can reach. */-function shapeField(part: OrganicPart): { field: Eval; reach: number; thinnest: number } {+export function shapeField(part: OrganicPart): { field: (x: number, y: number, z: number) => number; reach: number; thinnest: number } {const need = (name: keyof OrganicPart): void => {if (part[name] === undefined) throw new Error(`a ${part.shape} part needs \`${name}\``);};@@ -309,8 +330,76 @@ function shapeField(part: OrganicPart): { field: Eval; reach: number; thinnest:thinnest: depth,};}+ case 'limb': {+ need('sections');+ const sections = part.sections!;+ if (sections.length < 2) throw new Error(`a limb needs at least 2 sections, not ${sections.length}`);+ if (sections.some((s) => !(s.across > 0) || !(s.front > 0) || (s.back !== undefined && !(s.back > 0)))) throw new Error('every limb section needs a positive across and front');+ const power = part.power ?? 2;+ if (!(power >= 1)) throw new Error(`power ${power} must be 1 or more`);+ const rows = curveThrough(sections.map((s) => [s.at[0], s.at[1], s.at[2], s.across, s.front, s.back ?? s.front]), part.curve ?? 1, false);+ const count = rows.length;+ const side = part.side ?? [1, 0, 0];+ // A frame per segment: along it, across as near `side` as being square to it allows, and which way it faces.+ const frames = rows.slice(0, -1).map((row, i) => {+ const next = rows[i + 1]!;+ const [ex, ey, ez] = [next[0]! - row[0]!, next[1]! - row[1]!, next[2]! - row[2]!];+ const len = Math.hypot(ex, ey, ez) || 1;+ const t = [ex / len, ey / len, ez / len];+ const dotted = side[0] * t[0]! + side[1] * t[1]! + side[2] * t[2]!;+ const u = [side[0] - t[0]! * dotted, side[1] - t[1]! * dotted, side[2] - t[2]! * dotted];+ const ul = Math.hypot(u[0]!, u[1]!, u[2]!) || 1;+ u[0]! /= ul; u[1]! /= ul; u[2]! /= ul;+ // Its front: across crossed with the way along, flipped to a limb running up +y having +z in front, and so on down a limb.+ const v = [u[1]! * t[2]! - u[2]! * t[1]!, u[2]! * t[0]! - u[0]! * t[2]!, u[0]! * t[1]! - u[1]! * t[0]!];+ const toFront = v[2]! !== 0 ? Math.sign(v[2]!) : Math.sign(v[1]!) || 1;+ return { t, u, v: [v[0]! * toFront, v[1]! * toFront, v[2]! * toFront], len };+ });+ const widest = Math.max(...sections.map((s) => Math.max(s.across, s.front, s.back ?? s.front)));+ const thinnest = Math.max(...sections.map((s) => Math.min(s.across, s.front, s.back ?? s.front)));+ return {+ field: (x, y, z) => {+ const at = (i: number, raw: number): number => {+ const [a, fr] = [rows[i]!, frames[i]!];+ const s = Math.max(0, Math.min(1, raw));+ // Everything along it runs through a quadratic spline over the rows. Straight between them, the slope would jump at each one.+ const [c0, c1, c2, t] = s < 0.5 ? [rows[Math.max(0, i - 1)]!, a, rows[i + 1]!, s + 0.5] : [a, rows[i + 1]!, rows[Math.min(count - 1, i + 2)]!, s - 0.5];+ const [w0, w1, w2] = [0.5 * (1 - t) * (1 - t), 0.5 + t * (1 - t), 0.5 * t * t];+ const along = (k: number): number => c0[k]! * w0 + c1[k]! * w1 + c2[k]! * w2;+ const [qx, qy, qz] = [x - along(0), y - along(1), z - along(2)];+ const u = qx * fr.u[0]! + qy * fr.u[1]! + qz * fr.u[2]!;+ const v = qx * fr.v[0]! + qy * fr.v[1]! + qz * fr.v[2]!;+ const w = qx * fr.t[0]! + qy * fr.t[1]! + qz * fr.t[2]!;+ const across = along(3);+ // From back to front across the middle, gradually: where the two simply met there would be a seam down each side of a body.+ const [front, back] = [along(4), along(5)];+ const lean = Math.max(0, Math.min(1, v / (across * 1.2) + 0.5));+ const deep = back + (front - back) * lean * lean * (3 - 2 * lean);+ const inPlane = power === 2 ? Math.hypot(u / across, v / deep) : (Math.abs(u / across) ** power + Math.abs(v / deep) ** power) ** (1 / power);+ // Past an end it rounds off, by the smaller of its two radii.+ const radial = Math.min(across, deep);+ const k = Math.abs(w) < 1e-12 ? inPlane : Math.hypot(inPlane, w / radial);+ return (k - 1) * radial;+ };+ // Only the section square to the point: a neighbour's rounded end would stand proud of a narrower place, and the surface would be a row of scallops.+ let best = Infinity;+ const raws = new Float64Array(count - 1);+ for (let i = 0; i < count - 1; i++) {+ const [a, fr] = [rows[i]!, frames[i]!];+ const raw = ((x - a[0]!) * fr.t[0]! + (y - a[1]!) * fr.t[1]! + (z - a[2]!) * fr.t[2]!) / fr.len;+ raws[i] = raw;+ if ((raw >= 0 || i === 0) && (raw <= 1 || i === count - 2)) best = Math.min(best, at(i, raw));+ }+ // Outside a bend, square to nothing: the joint it is nearest.+ if (best === Infinity) for (let i = 0; i < count - 1; i++) best = Math.min(best, at(i, raws[i]!));+ return best;+ },+ reach: widest,+ thinnest,+ };+ }default:- throw new Error(`unknown shape ${JSON.stringify(part.shape)}; there are sphere, ellipsoid, box, torus, chain, outline`);+ throw new Error(`unknown shape ${JSON.stringify(part.shape)}; there are sphere, ellipsoid, box, torus, chain, outline, limb`);}}@@ -324,6 +413,8 @@ interface CompiledPart {max: Vec3;thinnest: number;label: string;+ /** Worth asking its box first. */+ costly: boolean;}const toColor = (c: readonly number[] | undefined): Color | null => {@@ -338,7 +429,7 @@ function compilePart(part: OrganicPart, index: number, params: OrganicParams): Cconst { field, reach, thinnest } = shapeField(part);const at = part.at ?? [0, 0, 0];const noise = part.noise ? noiseField(part.noise) : null;- const rotate = part.rotate && part.shape !== 'sphere' && part.shape !== 'chain' ? inverseRotation(part.rotate) : null;+ const rotate = part.rotate && part.shape !== 'sphere' && part.shape !== 'chain' && part.shape !== 'limb' ? inverseRotation(part.rotate) : null;const local = [0, 0, 0];const axis = part.mirror === undefined ? -1 : { x: 0, y: 1, z: 2 }[part.mirror];const label = part.tag ? `"${part.tag}"` : `${index}`;@@ -364,6 +455,12 @@ function compilePart(part: OrganicPart, index: number, params: OrganicParams): Cconst pts = part.points!;min = [0, 1, 2].map((k) => Math.min(...pts.map((p) => p[k]! - p[3]!)) + at[k]! - margin) as unknown as Vec3;max = [0, 1, 2].map((k) => Math.max(...pts.map((p) => p[k]! + p[3]!)) + at[k]! + margin) as unknown as Vec3;+ } else if (part.shape === 'limb') {+ // A curve can bow past its sections, a little.+ const sections = part.sections!;+ const radius = (s: LimbSection): number => Math.max(s.across, s.front, s.back ?? s.front) * 1.2;+ min = [0, 1, 2].map((k) => Math.min(...sections.map((s) => s.at[k as 0] - radius(s))) + at[k]! - margin) as unknown as Vec3;+ max = [0, 1, 2].map((k) => Math.max(...sections.map((s) => s.at[k as 0] + radius(s))) + at[k]! + margin) as unknown as Vec3;} else if (part.shape === 'outline') {// Round what is drawn and not round `at`: a drawing is traced where it lies, far from the origin, and a ball about the origin would spend the grid on nothing.const pts = part.points!;@@ -391,7 +488,7 @@ function compilePart(part: OrganicPart, index: number, params: OrganicParams): Cif (blend < 0) throw new Error(`part ${label}: blend ${blend} must not be negative`);return {distance, blend, subtract: part.subtract === true, tag: part.tag ?? params.tag ?? '',- color: toColor(part.color), min, max, thinnest, label,+ color: toColor(part.color), min, max, thinnest, label, costly: part.shape === 'limb' || part.shape === 'outline',};}@@ -402,6 +499,11 @@ function bodyField(parts: readonly CompiledPart[], noise: Eval | null): Eval {return (x, y, z) => {let d = Infinity;for (const part of parts) {+ // The dear shapes first ask their box: far enough off to change nothing, and a body has hundreds of grid points for every one near a finger.+ if (part.costly && d !== Infinity) {+ const gap = Math.hypot(Math.max(part.min[0] - x, 0, x - part.max[0]), Math.max(part.min[1] - y, 0, y - part.max[1]), Math.max(part.min[2] - z, 0, z - part.max[2]));+ if (part.subtract ? gap + d > part.blend : gap - d > part.blend) continue;+ }const p = part.distance(x, y, z);if (part.subtract) {const k = part.blend;@@ -468,12 +570,31 @@ function keepLargeIslands(quads: readonly number[][], vertices: number): number[return quads.filter((q) => size.get(find(q[0]!))! >= SPECK_QUADS);}+const FINE_BUDGET = 1_200_000;++/** A point moved onto the surface along the field's slope. */+function settleOnto(field: Eval, q: Vec3, size: number): Vec3 {+ let [x, y, z] = q;+ const e = size * 0.25;+ for (let step = 0; step < 3; step++) {+ const d = field(x, y, z);+ const [gx, gy, gz] = [field(x + e, y, z) - field(x - e, y, z), field(x, y + e, z) - field(x, y - e, z), field(x, y, z + e) - field(x, y, z - e)];+ const length = Math.hypot(gx, gy, gz);+ if (length < 1e-9) break;+ const slope = length / (2 * e);+ const s = Math.max(-size * 2, Math.min(size * 2, d / slope));+ x -= (s * gx) / length; y -= (s * gy) / length; z -= (s * gz) / length;+ }+ return [x, y, z];+}+/** One more shell: the skin of @p params' parts, in the steps' usual outward winding. */export function organic(mesh: PolyMesh, params: OrganicParams): PolyMesh {if (!params.parts?.length) throw new Error('`parts` names nothing to build');const resolution = params.resolution ?? ORGANIC_DEFAULT_RESOLUTION;- if (!Number.isInteger(resolution) || resolution < 8 || resolution > ORGANIC_MAX_RESOLUTION) {- throw new Error(`resolution ${resolution} must be a whole number, 8..${ORGANIC_MAX_RESOLUTION}`);+ const most = params.maxResolution ?? ORGANIC_MAX_RESOLUTION;+ if (!Number.isInteger(resolution) || resolution < 8 || resolution > most) {+ throw new Error(`resolution ${resolution} must be a whole number, 8..${most}`);}const parts = params.parts.map((p, i) => {try {@@ -494,8 +615,14 @@ export function organic(mesh: PolyMesh, params: OrganicParams): PolyMesh {const cell = longest / resolution;// A part the grid cannot see simply is not in the result, and it reads as a model that ignored the request.+ // Inside a region to be split finer, the fine faces are what find it.+ const inFine = (part: CompiledPart): boolean => (params.fine ?? []).some((region) => Math.hypot(+ Math.max(part.min[0] - region.at[0], 0, region.at[0] - part.max[0]),+ Math.max(part.min[1] - region.at[1], 0, region.at[1] - part.max[1]),+ Math.max(part.min[2] - region.at[2], 0, region.at[2] - part.max[2]),+ ) < region.radius);for (const part of parts) {- if (part.thinnest * 2 < cell * 1.5) {+ if (part.thinnest * 2 < cell * 1.5 && !inFine(part)) {const needed = Math.ceil((longest * 1.5) / (part.thinnest * 2));throw new Error(`part ${part.label} is ${(part.thinnest * 2).toFixed(4)} across, too thin for the grid's cell of ${cell.toFixed(4)}, so it would vanish; `+ (needed <= ORGANIC_MAX_RESOLUTION@@ -608,16 +735,36 @@ export function organic(mesh: PolyMesh, params: OrganicParams): PolyMesh {const base = toColor(params.color);const at = params.at ?? [0, 0, 0];const start = mesh.positions.length;- const faces: Face[] = keepLargeIslands(quads, positions.length).map((loop) => {+ const painted = (loop: readonly number[], where: readonly Vec3[]): Face => {let cx = 0, cy = 0, cz = 0;for (const v of loop) {- cx += positions[v]![0]; cy += positions[v]![1]; cz += positions[v]![2];+ cx += where[v]![0]; cy += where[v]![1]; cz += where[v]![2];}- const { tag, color } = paintAt(parts, base, cx / 4, cy / 4, cz / 4);- return { v: loop.map((v) => v + start), tag: tag || params.tag || '', smooth: true, ...(color ? { color } : {}) };- });+ const { tag, color } = paintAt(parts, base, cx / loop.length, cy / loop.length, cz / loop.length);+ return { v: [...loop], tag: tag || params.tag || '', smooth: true, ...(color ? { color } : {}) };+ };+ let skin: PolyMesh = { positions, faces: keepLargeIslands(quads, positions.length).map((loop) => painted(loop, positions)) };+ for (const region of params.fine ?? []) {+ const places: Vec3[] = region.mirror ? [region.at, [-region.at[0], region.at[1], region.at[2]]] : [region.at];+ for (const place of places) {+ const chosen = new Set<number>();+ skin.faces.forEach((face, f) => {+ const p = skin.positions[face.v[0]!]!;+ if (Math.hypot(p[0] - place[0], p[1] - place[1], p[2] - place[2]) < region.radius) chosen.add(f);+ });+ if (chosen.size === 0) continue;+ const before = skin.positions.length;+ const outside = skin.faces.length - chosen.size;+ const { mesh: fine } = refine(skin, chosen, region.longest, FINE_BUDGET);+ if (fine === skin) continue;+ const settled = fine.positions.map((q, n) => (n < before ? q : settleOnto(field, q, region.longest)));+ // Painted again where it was split: a lip's edge is finer than the grid that found it.+ const faces = fine.faces.map((face, n) => (n < outside ? face : painted(face.v, settled)));+ skin = { positions: settled, faces };+ }+ }return {- positions: [...mesh.positions, ...positions.map((p) => add(p, at))],- faces: [...mesh.faces, ...faces],+ positions: [...mesh.positions, ...skin.positions.map((p) => add(p, at))],+ faces: [...mesh.faces, ...skin.faces.map((face) => ({ ...face, v: face.v.map((v) => v + start) }))],};}diff --git a/pipeline/src/modeling/pose.ts b/pipeline/src/modeling/pose.tsnew file mode 100644index 000000000..b16de1b2c--- /dev/null+++ b/pipeline/src/modeling/pose.ts@@ -0,0 +1,64 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file pose.ts — the `pose` step: a body held in a pose, for a picture or a prop that never moves.+ *+ * A character in a game keeps her bones and takes her pose from a clip. This is the same clip's first moment+ * pressed into the surface, by the same weights, so a still and a game agree and a pose is an edit to some angles+ * rather than to a drawing.+ */+import { HUMANOID_TAGS, humanoidJoints, type HumanoidBuild } from './humanoid';+import { compact, type PolyMesh } from './polyMesh';+import { computeWornWeights, posedPositions, resolveJoints, type AnimationTrack, type RigJoint, type SkinWeights } from './rig';++export interface PoseParams {+ /** The bones of a humanoid of this build; true for the default one. */+ humanoid: HumanoidBuild | true;+ /** joint name to [x, y, z] degrees from its rest, X then Y then Z. */+ rotate?: Readonly<Record<string, readonly number[]>>;+ /** joint name to [x, y, z] from where it rests: `hips` lowers a sitting body. */+ move?: Readonly<Record<string, readonly number[]>>;+ /** joint name to where it must be, in the model's own space: a hand on a bow, a foot on the ground. The two bones above it turn to put it there; `pole` is the way the middle one bends. */+ reach?: Readonly<Record<string, { at: readonly number[]; pole?: readonly number[] }>>;+ /** The whole mesh rides on this one joint, whole: hair cards, which have no skin between them for weights to spread over. */+ rigid?: string;+}++export function poseStep(mesh: PolyMesh, p: PoseParams): PolyMesh {+ if (p.humanoid === undefined) throw new Error('`humanoid` says whose bones: true, or the build it was given');+ const joints: RigJoint[] = resolveJoints({ joints: humanoidJoints(p.humanoid === true ? {} : p.humanoid) });+ const names = new Set(joints.map((j) => j.name));+ const known = (name: string): void => {+ if (!names.has(name)) throw new Error(`no joint "${name}"; there are ${[...names].join(', ')}`);+ };+ const tracks = new Map<string, { rotate?: number[][]; move?: number[][]; reach?: number[][]; pole?: readonly number[] }>();+ for (const [name, r] of Object.entries(p.rotate ?? {})) {+ known(name);+ if (r.length !== 3) throw new Error(`rotate of "${name}" must be [x, y, z] degrees`);+ tracks.set(name, { rotate: [[0, r[0]!, r[1]!, r[2]!]] });+ }+ for (const [name, m] of Object.entries(p.move ?? {})) {+ known(name);+ if (m.length !== 3) throw new Error(`move of "${name}" must be [x, y, z]`);+ tracks.set(name, { ...tracks.get(name), move: [[0, m[0]!, m[1]!, m[2]!]] });+ }+ for (const [name, r] of Object.entries(p.reach ?? {})) {+ known(name);+ if (r.at?.length !== 3) throw new Error(`reach of "${name}" needs at: [x, y, z]`);+ tracks.set(name, { ...tracks.get(name), reach: [[0, r.at[0]!, r.at[1]!, r.at[2]!]], ...(r.pole ? { pole: r.pole } : {}) });+ }+ const animation = { name: 'pose', duration: 1, loop: false, tracks: [...tracks].map(([joint, t]) => ({ joint, ...t })) as AnimationTrack[] };+ if (mesh.positions.length === 0) throw new Error('there is nothing yet to pose');+ let skin: SkinWeights;+ if (p.rigid !== undefined) {+ known(p.rigid);+ const j = joints.findIndex((q) => q.name === p.rigid);+ const count = mesh.positions.length;+ const jointsOut = new Uint16Array(count * 4), weights = new Float32Array(count * 4);+ for (let v = 0; v < count; v++) { jointsOut[v * 4] = j; weights[v * 4] = 1; }+ skin = { joints: jointsOut, weights, dominant: [] };+ } else {+ skin = computeWornWeights(mesh, joints, new Set(HUMANOID_TAGS));+ }+ return compact({ positions: posedPositions(mesh, joints, skin, animation, 0), faces: mesh.faces });+}diff --git a/pipeline/src/modeling/rig.ts b/pipeline/src/modeling/rig.tsindex bfb51c7f9..e7544fe74 100644--- a/pipeline/src/modeling/rig.ts+++ b/pipeline/src/modeling/rig.ts@@ -47,6 +47,8 @@ export interface RigSource {/** Shapes on joints that swinging parts stay out of. */colliders?: RigCollider[];joints: readonly RigJointSource[];+ /** Pieces with these tags are the body, and the rest take their weights from it. Set by `humanoid`. */+ worn?: readonly string[];adjust?: readonly WeightAdjust[];goals?: readonly RigGoal[];}@@ -203,6 +205,71 @@ const pointToBones = (p: Vec3, from: Vec3, ends: readonly Vec3[]): number => {return d;};+/**+ * What a body wears moves as the body under it does: each vertex of another piece takes the weights of the nearest vertex of a piece with one of @p bodyTags.+ * Found for itself, a sleeve bends where its own surface says and the arm where its own does, and the arm comes through.+ */+export function computeWornWeights(mesh: PolyMesh, joints: readonly RigJoint[], bodyTags: ReadonlySet<string>): SkinWeights {+ const isBody = new Uint8Array(mesh.positions.length);+ for (const face of mesh.faces) if (bodyTags.has(face.tag)) for (const v of face.v) isBody[v] = 1;+ // Whole pieces: an eye is body, and so is a stretch of skin with a tag that was not asked for, if it is joined on.+ const parent = Array.from({ length: mesh.positions.length }, (_, 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 (const v of face.v) parent[find(v)] = find(face.v[0]!);+ const bodyRoots = new Set<number>();+ isBody.forEach((on, v) => { if (on) bodyRoots.add(find(v)); });+ if (bodyRoots.size === 0) return computeWeights(mesh, joints);+ const keep = mesh.faces.filter((face) => bodyRoots.has(find(face.v[0]!)));+ const index = new Map<number, number>();+ const positions: Vec3[] = [];+ const faces = keep.map((face) => ({ ...face, v: face.v.map((v) => {+ let at = index.get(v);+ if (at === undefined) { at = positions.length; index.set(v, at); positions.push(mesh.positions[v]!); }+ return at;+ }) }));+ const found = computeWeights({ positions, faces }, joints);+ const count = mesh.positions.length;+ const outJoints = new Uint16Array(count * 4), outWeights = new Float32Array(count * 4);+ // Nearest by a grid of cells, widening until something is there.+ const { min, max } = boundsOf({ positions, faces });+ const cell = Math.max(length(sub(max, min)) / 64, 1e-6);+ const cellKey = (x: number, y: number, z: number): number => (x + 512) * 1048576 + (y + 512) * 1024 + (z + 512);+ const grid = new Map<number, number[]>();+ positions.forEach((p, v) => {+ const key = cellKey(Math.floor(p[0] / cell), Math.floor(p[1] / cell), Math.floor(p[2] / cell));+ const list = grid.get(key);+ if (list) list.push(v); else grid.set(key, [v]);+ });+ const nearest = (p: Vec3): number => {+ const [cx, cy, cz] = [Math.floor(p[0] / cell), Math.floor(p[1] / cell), Math.floor(p[2] / cell)];+ let best = -1, bestD = Infinity;+ for (let r = 0; r < 64; r++) {+ for (let dx = -r; dx <= r; dx++) {+ for (let dy = -r; dy <= r; dy++) {+ for (let dz = -r; dz <= r; dz++) {+ if (Math.max(Math.abs(dx), Math.abs(dy), Math.abs(dz)) !== r) continue;+ for (const v of grid.get(cellKey(cx + dx, cy + dy, cz + dz)) ?? []) {+ const d = length(sub(positions[v]!, p));+ if (d < bestD) { bestD = d; best = v; }+ }+ }+ }+ }+ // Anything in a further shell of cells is at least this far.+ if (best >= 0 && bestD <= r * cell) break;+ }+ return best;+ };+ for (let v = 0; v < count; v++) {+ const from = index.get(v) ?? nearest(mesh.positions[v]!);+ for (let k = 0; k < 4; k++) {+ outJoints[v * 4 + k] = found.joints[from * 4 + k]!;+ outWeights[v * 4 + k] = found.weights[from * 4 + k]!;+ }+ }+ return { joints: outJoints, weights: outWeights, dominant: found.dominant };+}+export function computeWeights(mesh: PolyMesh, joints: readonly RigJoint[]): SkinWeights {const count = mesh.positions.length;const neighbours: number[][] = Array.from({ length: count }, () => []);@@ -597,7 +664,7 @@ const vec3 = (v: unknown): boolean => Array.isArray(v) && v.length === 3 && v.evexport function checkRig(raw: unknown): string | null {const r = raw as { joints?: unknown };if (typeof raw !== 'object' || raw === null || !Array.isArray(r.joints)) return 'rig must be { joints: [{ name, at, parent?, mirror? }] }';- for (const key of Object.keys(raw)) if (!['joints', 'adjust', 'goals', 'drape', 'colliders'].includes(key)) return `rig has an unknown field "${key}"; it takes joints, adjust, goals`;+ for (const key of Object.keys(raw)) if (!['joints', 'adjust', 'goals', 'drape', 'colliders', 'worn'].includes(key)) return `rig has an unknown field "${key}"; it takes joints, adjust, goals`;for (const [i, j] of (r.joints as Record<string, unknown>[]).entries()) {if (typeof j !== 'object' || j === null) return `rig joint ${i} must be an object`;for (const key of Object.keys(j)) if (!['name', 'at', 'parent', 'mirror'].includes(key)) return `rig joint ${i} has an unknown field "${key}"; a joint takes name, at, parent, mirror`;diff --git a/pipeline/tests/modeling-humanoid.test.ts b/pipeline/tests/modeling-humanoid.test.tsnew file mode 100644index 000000000..4872d6927--- /dev/null+++ b/pipeline/tests/modeling-humanoid.test.ts@@ -0,0 +1,371 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/** A person from a few numbers: whole from every side, on bones that fit, wearing clothes that move with them, and able to be held in a pose. */+import { describe, expect, it } from 'vitest';+import { bakeModel, buildPolyMesh, validateModelSource, type ModelStep } from '../src/modeling';+import { garment } from '../src/modeling/garment';+import { HUMANOID_TAGS, humanoidFrame, humanoidJoints } from '../src/modeling/humanoid';+import { organic, shapeField } from '../src/modeling/organic';+import { computeWornWeights, posedPositions, resolveJoints } from '../src/modeling/rig';+import type { PolyMesh, Vec3 } from '../src/modeling/polyMesh';++const build = (steps: ModelStep[]): PolyMesh => buildPolyMesh(validateModelSource({ version: 1, steps })).mesh;+const bounds = (m: PolyMesh, tag?: string): { min: number[]; max: number[] } => {+ const v = tag ? [...new Set(m.faces.filter((f) => f.tag === tag).flatMap((f) => [...f.v]))].map((i) => m.positions[i]!) : m.positions;+ return { min: [0, 1, 2].map((k) => Math.min(...v.map((p) => p[k]!))), max: [0, 1, 2].map((k) => Math.max(...v.map((p) => p[k]!))) };+};++/** Measured: 4e-5 as it is, 7e-4 with the rounded ends of neighbours left in, 6.6e-4 with no spline over the rows. */+const STRIPE_LIMIT = 1.5e-4;++describe('organic limb', () => {+ const limb = (extra: Record<string, unknown> = {}): PolyMesh => organic({ positions: [], faces: [] }, { resolution: 90, parts: [{+ shape: 'limb', curve: 4, sections: [{ at: [0, 0, 0], across: 0.2, front: 0.1, back: 0.3 }, { at: [0, 1, 0], across: 0.2, front: 0.1, back: 0.3 }], ...extra,+ }] as never });++ it('is an oval across, deeper behind than in front where it is told to be', () => {+ const b = bounds(limb());+ expect(b.max[0]).toBeCloseTo(0.2, 1);+ expect(b.min[0]).toBeCloseTo(-0.2, 1);+ expect(b.max[2]).toBeCloseTo(0.1, 1);+ expect(b.min[2]).toBeCloseTo(-0.3, 1);+ });++ it('rounds off past its ends, and passes through each section', () => {+ const b = bounds(limb());+ expect(b.max[1]).toBeGreaterThan(1.05);+ expect(b.max[1]).toBeLessThan(1.15);+ const taper = organic({ positions: [], faces: [] }, { resolution: 90, parts: [{ shape: 'limb', curve: 6, sections: [{ at: [0, 0, 0], across: 0.3, front: 0.3 }, { at: [0, 0.5, 0], across: 0.1, front: 0.1 }, { at: [0, 1, 0], across: 0.3, front: 0.3 }] }] });+ const waist = taper.positions.filter((p) => Math.abs(p[1] - 0.5) < 0.02).map((p) => Math.hypot(p[0], p[2]));+ expect(Math.max(...waist)).toBeLessThan(0.17);+ expect(Math.max(...waist)).toBeGreaterThan(0.08);+ });++ it('follows a path that is not straight, and `side` turns its width', () => {+ const flat = organic({ positions: [], faces: [] }, { resolution: 90, parts: [{ shape: 'limb', side: [0, 0, 1], sections: [{ at: [0, 0, 0], across: 0.3, front: 0.05 }, { at: [1, 0, 0], across: 0.3, front: 0.05 }] }] });+ const b = bounds(flat);+ expect(b.max[2]).toBeCloseTo(0.3, 1);+ expect(b.max[1]).toBeCloseTo(0.05, 1);+ });++ it('squares up with `power`', () => {+ const corner = (m: PolyMesh): number => Math.max(...m.positions.filter((p) => Math.abs(p[1] - 0.5) < 0.03).map((p) => Math.hypot(p[0], p[2])));+ const round = organic({ positions: [], faces: [] }, { resolution: 80, parts: [{ shape: 'limb', sections: [{ at: [0, 0, 0], across: 0.2, front: 0.2 }, { at: [0, 1, 0], across: 0.2, front: 0.2 }] }] });+ const square = organic({ positions: [], faces: [] }, { resolution: 80, parts: [{ shape: 'limb', power: 6, sections: [{ at: [0, 0, 0], across: 0.2, front: 0.2 }, { at: [0, 1, 0], across: 0.2, front: 0.2 }] }] });+ expect(corner(square)).toBeGreaterThan(corner(round) * 1.1);+ });++ it('has no stripe across it: the slope does not jump from one row of its table to the next', () => {+ // On the field itself: a mesh's grid is coarser than what is being asked. How far out the surface is, found by halving, at closely spaced heights.+ const { field } = shapeField({ shape: 'limb', curve: 4, sections: [{ at: [0, 0, 0], across: 0.3, front: 0.3 }, { at: [0, 0.4, 0], across: 0.2, front: 0.2 }, { at: [0, 0.8, 0], across: 0.32, front: 0.32 }, { at: [0, 1.2, 0], across: 0.2, front: 0.2 }] });+ const radiusAt = (y: number): number => {+ let [lo, hi] = [0, 1];+ for (let i = 0; i < 40; i++) { const mid = (lo + hi) / 2; if (field(mid, y, 0) < 0) lo = mid; else hi = mid; }+ return lo;+ };+ const profile: number[] = [];+ for (let y = 0.1; y < 1.1; y += 0.002) profile.push(radiusAt(y));+ let worst = 0;+ for (let i = 1; i + 1 < profile.length; i++) worst = Math.max(worst, Math.abs(profile[i - 1]! - 2 * profile[i]! + profile[i + 1]!));+ expect(worst).toBeLessThan(STRIPE_LIMIT);+ });++ it('refuses what cannot be drawn', () => {+ expect(() => organic({ positions: [], faces: [] }, { parts: [{ shape: 'limb', sections: [{ at: [0, 0, 0], across: 1, front: 1 }] }] })).toThrow(/at least 2 sections/);+ expect(() => organic({ positions: [], faces: [] }, { parts: [{ shape: 'limb', sections: [{ at: [0, 0, 0], across: 0, front: 1 }, { at: [0, 1, 0], across: 1, front: 1 }] }] })).toThrow(/positive/);+ expect(() => organic({ positions: [], faces: [] }, { parts: [{ shape: 'limb', power: 0.5, sections: [{ at: [0, 0, 0], across: 1, front: 1 }, { at: [0, 1, 0], across: 1, front: 1 }] }] })).toThrow(/power/);+ });+});++describe('organic fine', () => {+ const parts = [{ shape: 'sphere' as const, radius: 1 }];+ it('splits only where it is asked, and what it splits still lies on the surface, in one skin', () => {+ const plain = organic({ positions: [], faces: [] }, { resolution: 30, parts });+ const fine = organic({ positions: [], faces: [] }, { resolution: 30, parts, fine: [{ at: [0, 0, 1], radius: 0.5, longest: 0.02 }] });+ expect(fine.positions.length).toBeGreaterThan(plain.positions.length * 2);+ for (const p of fine.positions) expect(Math.hypot(p[0], p[1], p[2])).toBeCloseTo(1, 1);+ const edges = new Map<string, number>();+ for (const f of fine.faces) f.v.forEach((a, i) => { const b = f.v[(i + 1) % f.v.length]!; const k = a < b ? `${a}:${b}` : `${b}:${a}`; edges.set(k, (edges.get(k) ?? 0) + 1); });+ expect([...edges.values()].filter((n) => n !== 2).length).toBeLessThan(fine.faces.length * 0.01);+ const far = fine.positions.filter((p) => p[2] < -0.5).length, farPlain = plain.positions.filter((p) => p[2] < -0.5).length;+ expect(far).toBe(farPlain);+ });++ it('finds there what the grid was too coarse to see', () => {+ const bump = organic({ positions: [], faces: [] }, { resolution: 24, blend: 0.01, parts: [{ shape: 'sphere', radius: 1 }, { shape: 'sphere', radius: 0.05, at: [0, 0, 1] }], fine: [{ at: [0, 0, 1], radius: 0.3, longest: 0.01 }] });+ expect(bounds(bump).max[2]).toBeGreaterThan(1.03);+ });+});++describe('humanoid', () => {+ const body = build([{ op: 'humanoid', resolution: 120 } as ModelStep]);++ it('stands where it says: feet on the floor, crown at its height, facing +z', () => {+ const b = bounds(body);+ expect(b.max[1]).toBeCloseTo(1.6, 1);+ expect(b.min[1]).toBeLessThan(0.02);+ expect(b.min[1]).toBeGreaterThan(-0.02);+ // Toes forward of heels, and a nose ahead of a skull's middle.+ const foot = bounds(body, 'foot');+ expect(foot.max[2]).toBeGreaterThan(0.15);+ expect(foot.min[2]).toBeGreaterThan(-0.12);+ expect(bounds(body, 'face').max[2]).toBeGreaterThan(0.06);+ });++ it('is a whole body from every side: the same on both sides of it, deep as well as wide', () => {+ const b = bounds(body);+ expect(b.min[0]).toBeCloseTo(-b.max[0]!, 1);+ // A chest has a front and a back.+ const chest = body.positions.filter((p) => Math.abs(p[1] - 1.15) < 0.02 && Math.abs(p[0]) < 0.1);+ expect(Math.max(...chest.map((p) => p[2]))).toBeGreaterThan(0.06);+ expect(Math.min(...chest.map((p) => p[2]))).toBeLessThan(-0.06);+ });++ it('has a person\'s parts, each tagged', () => {+ const tags = new Set(body.faces.map((f) => f.tag));+ for (const t of ['torso', 'arm', 'hand', 'leg', 'foot', 'face', 'scalp', 'ear', 'lips', 'lid', 'eye', 'iris']) expect(tags.has(t), t).toBe(true);+ for (const t of tags) expect(HUMANOID_TAGS.includes(t), t).toBe(true);+ });++ it('takes a build: taller is taller, and wider hips are wider', () => {+ const tall = build([{ op: 'humanoid', resolution: 120, height: 1.9 } as ModelStep]);+ expect(bounds(tall).max[1]).toBeCloseTo(1.9, 1);+ const wide = build([{ op: 'humanoid', resolution: 120, hips: 1.4 } as ModelStep]);+ const hips = (m: PolyMesh): number => Math.max(...m.positions.filter((p) => Math.abs(p[1] - 0.86) < 0.02 && Math.abs(p[0]) < 0.35).map((p) => p[0]));+ expect(hips(wide)).toBeGreaterThan(hips(build([{ op: 'humanoid', resolution: 120 } as ModelStep])) * 1.15);+ });++ it('closes its eyes', () => {+ const shut = build([{ op: 'humanoid', resolution: 120, eyes: 'closed' } as ModelStep]);+ expect(shut.faces.some((f) => f.tag === 'eye')).toBe(false);+ expect(shut.faces.some((f) => f.tag === 'lid')).toBe(true);+ });++ it('says what is wrong', () => {+ expect(() => build([{ op: 'humanoid', resolution: 10 } as ModelStep])).toThrow(/resolution/);+ expect(() => build([{ op: 'humanoid', height: -1 } as ModelStep])).toThrow(/height/);+ expect(() => build([{ op: 'humanoid', eyes: 'shut' } as ModelStep])).toThrow(/eyes/);+ });+});++describe('a humanoid\'s bones', () => {+ it('are laid in the body they are for, one root, both sides', () => {+ const joints = resolveJoints({ joints: humanoidJoints() });+ expect(joints.filter((j) => j.parent < 0).map((j) => j.name)).toEqual(['hips']);+ const names = joints.map((j) => j.name);+ for (const n of ['head', 'upperArm.L', 'upperArm.R', 'hand.L', 'index3.R', 'thumb2.L', 'thigh.R', 'foot.L', 'toes.R']) expect(names).toContain(n);+ const at = (n: string): Vec3 => joints.find((j) => j.name === n)!.at;+ expect(at('upperArm.L')[0]).toBeGreaterThan(0);+ expect(at('upperArm.R')[0]).toBeCloseTo(-at('upperArm.L')[0], 6);+ expect(at('head')[1]).toBeGreaterThan(at('neck')[1]);+ });++ it('scale with the build', () => {+ const short = humanoidFrame({ height: 0.8 });+ expect(short.crown[1]).toBeCloseTo(0.8, 5);+ expect(humanoidFrame({ shoulders: 1.2 }).shoulder[0]).toBeGreaterThan(humanoidFrame().shoulder[0]);+ });++ it('come from `rig.humanoid`, and bend her: a raised arm goes up and a foot stays put', () => {+ const source = validateModelSource({+ version: 1, rig: { humanoid: true },+ animations: [{ name: 'wave', duration: 1, tracks: [{ joint: 'upperArm.L', rotate: [[0, 0, 0, 70]] }] }],+ steps: [{ op: 'humanoid', resolution: 120 }],+ });+ const baked = bakeModel(source);+ const rig = baked.rig!;+ expect(rig.joints.length).toBeGreaterThan(40);+ const moved = posedPositions(baked.poly, rig.joints, rig.skin, source.animations![0]!, 0);+ const hand = baked.poly.faces.filter((f) => f.tag === 'hand').flatMap((f) => [...f.v]).filter((v) => baked.poly.positions[v]![0] > 0.3);+ const wasUp = Math.max(...hand.map((v) => baked.poly.positions[v]![1]));+ expect(Math.max(...hand.map((v) => moved[v]![1]))).toBeGreaterThan(wasUp + 0.2);+ const foot = baked.poly.faces.filter((f) => f.tag === 'foot').flatMap((f) => [...f.v]);+ for (const v of foot.slice(0, 50)) expect(moved[v]![1]).toBeCloseTo(baked.poly.positions[v]![1], 3);+ });++ it('add to any given', () => {+ const source = validateModelSource({ version: 1, rig: { humanoid: true, joints: [{ name: 'bow', at: [0.6, 1, 0], parent: 'hand.L' }] }, steps: [{ op: 'box', size: 1 }] });+ expect(source.rig!.joints.some((j) => j.name === 'bow')).toBe(true);+ expect(source.rig!.joints.some((j) => j.name === 'hips')).toBe(true);+ });+});++describe('garment', () => {+ const ball: ModelStep = { op: 'sphere', radius: 1, rings: 24, sides: 32, tag: 'body' };++ it('stands off the surface by its ease, and keeps what it was made from', () => {+ const m = build([ball, { op: 'garment', faces: 'body', ease: 0.1, relax: 0, tag: 'coat' } as ModelStep]);+ expect(m.faces.some((f) => f.tag === 'body')).toBe(true);+ const coat = m.faces.filter((f) => f.tag === 'coat').flatMap((f) => [...f.v]);+ for (const v of coat.slice(0, 100)) expect(Math.hypot(...m.positions[v]!)).toBeCloseTo(1.1, 1);+ });++ it('relaxes across a hollow it would otherwise follow', () => {+ const dented = (relax: number): number => {+ const body: PolyMesh = organic({ positions: [], faces: [] }, { resolution: 60, tag: 'body', blend: 0.02, parts: [{ shape: 'sphere', radius: 1 }, { shape: 'sphere', radius: 0.3, at: [0, 0, 1], subtract: true }] });+ const m = garment(body, { faces: 'body', ease: 0.02, relax, tag: 'coat' });+ const near = m.faces.filter((f) => f.tag === 'coat').flatMap((f) => [...f.v]).map((v) => m.positions[v]!).filter((p) => Math.hypot(p[0], p[1]) < 0.05 && p[2] > 0);+ return Math.max(...near.map((p) => p[2]));+ };+ expect(dented(30)).toBeGreaterThan(dented(0) + 0.02);+ });++ it('is cut clean at a plane: the hem is a level line and nothing goes past it', () => {+ const m = build([ball, { op: 'garment', faces: 'body', ease: 0.05, relax: 0, tag: 'coat', cut: [{ at: [0, 0.2, 0], keep: [0, 1, 0] }] } as ModelStep]);+ const coat = m.faces.filter((f) => f.tag === 'coat').flatMap((f) => [...f.v]).map((v) => m.positions[v]!);+ expect(Math.min(...coat.map((p) => p[1]))).toBeCloseTo(0.2, 6);+ expect(coat.filter((p) => Math.abs(p[1] - 0.2) < 1e-6).length).toBeGreaterThan(8);+ });++ it('cuts both sides of a mirror', () => {+ const m = build([ball, { op: 'garment', faces: 'body', ease: 0.05, relax: 0, tag: 'coat', cut: [{ at: [0.5, 0, 0], keep: [-1, 0, 0], mirror: 'x' }] } as ModelStep]);+ const b = bounds(m, 'coat');+ expect(b.max[0]).toBeCloseTo(0.5, 6);+ expect(b.min[0]).toBeCloseTo(-0.5, 6);+ });++ it('has a thickness at its hem, and no inside a long way from one', () => {+ const m = build([ball, { op: 'garment', faces: 'body', ease: 0.05, relax: 0, tag: 'coat', thickness: 0.02, cut: [{ at: [0, 0.8, 0], keep: [0, -1, 0] }] } as ModelStep]);+ expect(m.faces.some((f) => f.tag === 'coatInside')).toBe(true);+ const outer = m.faces.filter((f) => f.tag === 'coat').length, inner = m.faces.filter((f) => f.tag === 'coatInside').length;+ expect(inner).toBeLessThan(outer);+ // A cloth with an edge is closed all the way round it.+ const edges = new Map<string, number>();+ for (const f of m.faces.filter((q) => q.tag === 'coat' || q.tag === 'coatInside')) f.v.forEach((a, i) => { const b = f.v[(i + 1) % f.v.length]!; const k = a < b ? `${a}:${b}` : `${b}:${a}`; edges.set(k, (edges.get(k) ?? 0) + 1); });+ const hem = [...edges.keys()].filter((k) => edges.get(k) === 1).map((k) => k.split(':').map(Number)).filter(([a]) => Math.abs(m.positions[a!]![1] - 0.8) < 1e-6);+ expect(hem).toHaveLength(0);+ });++ it('grows along a line with `loose`, more at the end asked, on both sides with a mirror', () => {+ const m = build([{ op: 'box', size: [4, 0.4, 0.4], tag: 'body' }, { op: 'subdivide', levels: 3 } as ModelStep, { op: 'garment', faces: { tag: 'body' }, ease: 0, relax: 0, tag: 'sleeve', loose: [{ from: [0, 0, 0], to: [2, 0, 0], ease: [0, 0.5], mirror: 'x' }] } as ModelStep]);+ const sleeve = m.faces.filter((f) => f.tag === 'sleeve').flatMap((f) => [...f.v]).map((v) => m.positions[v]!);+ const radius = (x: number): number => Math.max(...sleeve.filter((p) => Math.abs(p[0] - x) < 0.25).map((p) => Math.hypot(p[1], p[2])));+ expect(radius(1.4)).toBeGreaterThan(radius(0.4) + 0.1);+ expect(radius(-1.4)).toBeCloseTo(radius(1.4), 3);+ });++ it('hangs with `hang`, the underside the most', () => {+ const m = build([{ op: 'box', size: [2, 0.4, 0.4], tag: 'body', at: [1, 0, 0] }, { op: 'subdivide', levels: 3 } as ModelStep, { op: 'garment', faces: { tag: 'body' }, ease: 0, relax: 0, tag: 'sleeve', loose: [{ from: [0, 0, 0], to: [2, 0, 0], hang: [0, 0.3] }] } as ModelStep]);+ const low = (tag: string, x: number): number => Math.min(...m.faces.filter((f) => f.tag === tag).flatMap((f) => [...f.v]).map((v) => m.positions[v]!).filter((p) => Math.abs(p[0] - x) < 0.2).map((p) => p[1]));+ expect(low('sleeve', 1.7)).toBeLessThan(low('body', 1.7) - 0.1);+ expect(low('sleeve', 0.2)).toBeGreaterThan(low('sleeve', 1.7));+ });++ it('takes away what it covers when told to, and leaves a margin at its hem', () => {+ const before = build([ball]);+ const m = build([ball, { op: 'garment', faces: 'body', ease: 0.05, relax: 0, tag: 'coat', hide: true, cut: [{ at: [0, 0, 0], keep: [0, 1, 0] }] } as ModelStep]);+ const body = m.faces.filter((f) => f.tag === 'body');+ expect(body.length).toBeLessThan(before.faces.length);+ // The body past the hem is there, and a little way under it too.+ const lowest = Math.max(...body.flatMap((f) => [...f.v]).map((v) => m.positions[v]![1]));+ expect(lowest).toBeGreaterThan(0.05);+ });++ it('says what is wrong', () => {+ expect(() => build([ball, { op: 'garment', faces: 'nothing' } as ModelStep])).toThrow(/matched no face/);+ expect(() => build([ball, { op: 'garment', faces: 'body', thickness: 0 } as ModelStep])).toThrow(/thickness/);+ expect(() => build([ball, { op: 'garment', faces: 'body', cut: [{ at: [0, 5, 0], keep: [0, 1, 0] }] } as ModelStep])).toThrow(/leaves nothing/);+ expect(() => validateModelSource({ steps: [ball, { op: 'garment', faces: 'body', cut: [{ at: [0, 0] }] }] })).toThrow(/cut/);+ });+});++describe('what a body wears moves with it', () => {+ it('takes its weights from the nearest skin: arm and sleeve turn together, and the arm stays inside', () => {+ const mesh = build([+ { op: 'humanoid', resolution: 120 } as ModelStep,+ { op: 'garment', faces: { tag: 'arm' }, ease: 0.012, relax: 4, tag: 'sleeve' } as ModelStep,+ ]);+ const joints = resolveJoints({ joints: humanoidJoints() });+ const skin = computeWornWeights(mesh, joints, new Set(HUMANOID_TAGS));+ const moved = posedPositions(mesh, joints, skin, { name: 'p', duration: 1, tracks: [{ joint: 'forearm.L', rotate: [[0, 0, -90, 0]] }] }, 0);+ const verts = (tag: string): number[] => [...new Set(mesh.faces.filter((f) => f.tag === tag).flatMap((f) => [...f.v]))].filter((v) => mesh.positions[v]![0] > 0.3);+ const arm = verts('arm'), sleeve = verts('sleeve');+ // Each point of the sleeve keeps its distance from the arm it was around.+ const sample = sleeve.filter((_, i) => i % 7 === 0);+ let worst = 0;+ for (const s of sample) {+ let near = Infinity;+ for (const a of arm) {+ const [p, q] = [moved[s]!, moved[a]!];+ near = Math.min(near, Math.hypot(p[0] - q[0], p[1] - q[1], p[2] - q[2]));+ }+ worst = Math.max(worst, near);+ }+ expect(worst).toBeLessThan(0.07);+ }, 60000);++ it('falls back to finding them when nothing is a body', () => {+ const mesh = build([{ op: 'box', size: 1, tag: 'block' }]);+ const joints = resolveJoints({ joints: [{ name: 'a', at: [0, 0, 0] }, { name: 'b', at: [0, 1, 0], parent: 'a' }] });+ expect(computeWornWeights(mesh, joints, new Set(['torso'])).joints.length).toBe(mesh.positions.length * 4);+ });+});++describe('pose', () => {+ const steps = (pose: Record<string, unknown>): ModelStep[] => [{ op: 'humanoid', resolution: 120 } as ModelStep, { op: 'pose', humanoid: true, ...pose } as ModelStep];++ it('holds a body in a pose by angles: a thigh raised, the other foot where it was', () => {+ const m = build(steps({ rotate: { 'thigh.L': [-90, 0, 0] } }));+ const leftFoot = m.faces.filter((f) => f.tag === 'foot').flatMap((f) => [...f.v]).map((v) => m.positions[v]!);+ expect(Math.max(...leftFoot.filter((p) => p[0] > 0).map((p) => p[2]))).toBeGreaterThan(0.5);+ expect(Math.min(...leftFoot.filter((p) => p[0] < 0).map((p) => p[1]))).toBeLessThan(0.03);+ });++ it('puts a hand where it is told, with `reach`', () => {+ const target: Vec3 = [0.25, 1.1, 0.4];+ const m = build(steps({ reach: { 'hand.L': { at: target, pole: [1, -1, -0.5] } } }));+ const wrist = humanoidFrame().wrist;+ const near = m.faces.filter((f) => f.tag === 'hand').flatMap((f) => [...f.v]).map((v) => m.positions[v]!).filter((p) => p[0] > 0);+ const best = Math.min(...near.map((p) => Math.hypot(p[0] - target[0], p[1] - target[1], p[2] - target[2])));+ expect(best).toBeLessThan(0.05);+ expect(Math.max(...near.map((p) => p[2]))).toBeGreaterThan(wrist[2] + 0.3);+ });++ it('carries a whole mesh on one joint with `rigid`', () => {+ const before = build([{ op: 'box', size: 0.1, at: [0, 1.5, 0], tag: 'prop' }]);+ const m = build([{ op: 'box', size: 0.1, at: [0, 1.5, 0], tag: 'prop' }, { op: 'pose', humanoid: true, rigid: 'head', rotate: { head: [90, 0, 0] } } as ModelStep]);+ // Turned about the head's joint as one thing: every length in it is the same.+ const span = (q: PolyMesh): number => Math.hypot(q.positions[0]![0] - q.positions[6]![0], q.positions[0]![1] - q.positions[6]![1], q.positions[0]![2] - q.positions[6]![2]);+ expect(span(m)).toBeCloseTo(span(before), 5);+ expect(m.positions[0]).not.toEqual(before.positions[0]);+ });++ it('says what is wrong', () => {+ expect(() => build(steps({ rotate: { wing: [0, 0, 0] } }))).toThrow(/no joint "wing"/);+ expect(() => build(steps({ rigid: 'tail' }))).toThrow(/no joint "tail"/);+ expect(() => validateModelSource({ steps: [{ op: 'box', size: 1 }, { op: 'pose', humanoid: true, rotate: { head: [1] } }] })).toThrow(/rotate/);+ expect(() => validateModelSource({ steps: [{ op: 'box', size: 1 }, { op: 'pose', humanoid: true, reach: { 'hand.L': {} } }] })).toThrow(/reach/);+ expect(() => validateModelSource({ steps: [{ op: 'box', size: 1 }, { op: 'pose' }] })).toThrow(/humanoid/);+ });+});++describe('folds', () => {+ /** How much the height differs, on average, between two places this far apart on the sheet. */+ const difference = (m: PolyMesh, [dx, dz]: readonly [number, number]): number => {+ const cell = 0.03;+ const grid = new Map<string, number>();+ for (const p of m.positions) grid.set(`${Math.round(p[0] / cell)},${Math.round(p[2] / cell)}`, p[1]);+ let sum = 0, n = 0;+ for (let x = -0.8; x <= 0.7; x += 0.06) {+ for (let z = -0.8; z <= 0.7; z += 0.06) {+ const a = grid.get(`${Math.round(x / cell)},${Math.round(z / cell)}`);+ const b = grid.get(`${Math.round((x + dx) / cell)},${Math.round((z + dz) / cell)}`);+ if (a !== undefined && b !== undefined) { sum += Math.abs(a - b); n++; }+ }+ }+ return sum / Math.max(1, n);+ };+ const sheet = (along?: Vec3): PolyMesh => build([{ op: 'plane', size: 2, tag: 'cloth' }, { op: 'displace', faces: 'cloth', pattern: 'folds', scale: 0.2, amplitude: 0.05, long: 5, octaves: 1, detail: 0.02, ...(along ? { along } : { along: [1, 0, 0] }) } as ModelStep]);++ it('runs along the way it is told: smooth that way, and rising and falling across it', () => {+ const m = sheet([1, 0, 0]);+ expect(difference(m, [0, 0.1])).toBeGreaterThan(difference(m, [0.1, 0]) * 1.5);+ // Told the other way, the other way.+ const turned = sheet([0, 0, 1]);+ expect(difference(turned, [0.1, 0])).toBeGreaterThan(difference(turned, [0, 0.1]) * 1.5);+ });++ it('is the same every time', () => {+ expect(sheet().positions).toEqual(sheet().positions);+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 05178086d..0dedf3ce4 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -3884,6 +3884,10 @@ export const NOTED = {{"note":"A material's normal and metal-rough maps are read as data in the editor's Play."},"fix(minigame): no mini-game module needs BigInt64Array, so WeChat DevTools boots the game":{"note":"A WeChat mini-game opens in WeChat DevTools."},+ "feat(modeling): a whole person from a few numbers, clothes from the body's own surface, and a pose by where a hand should be":+ {"note":"An AI can build a person, and not a picture of one."},+ "feat(mcp): model_write describes a person, and scene_views looks round a subject without a shot's lens":+ {"note":"An AI can build a person, and not a picture of one."},"feat(look): a part of a picture traced as points, its edges as lines, and the colour of a patch":{"note":"An AI can read shapes and colours off a picture as numbers."},"feat(mcp): reference_trace, reference_probe, and the outline of one part on the reference":