Skip to content

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.

feat(modeling): hair follows guides over the head, stain draws lines, scatter lays out copies, and a material gives off light

yhh516073d25f80
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e8ea9983d..0ce71b947 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 model a character's hair by where it goes, and draw on a surface.** `hair` takes `guides`, lines the cards follow over the head rather than through it, with `gather` closing them into a ponytail. `stain` draws along a `line`: an eyelid, a lip, a seam. `scatter` puts hundreds of copies of a shape across a surface, along a path or through a box. `material.emissive` makes a model give off light, past 1 for what glows and blooms. `apply_scene_ops` now says which field a component does not have, where it used to drop it without a word.
+
- **An AI can put the game beside the pictures it is imitating.** The `look` tool group takes pictures or a video's frames, and `reference_compare` sets a frame of the game beside one with the reference's outline drawn over it and the exact colours of both. `field_sweep` shows a field at several values on one sheet, so what a number does is seen before it is chosen. `motion_sheet` lays the running game out over time, under a video's frames. `scene_views` shows the scene as the engine draws it from every side, in clay, paint and wireframe.
- **An AI building a model can dress it in clothes that swing.** `rig.drape` turns a skirt or a cape into a ring of chains that swing as the game runs, blended so it moves as one sheet, `rig.colliders` keeps it out of the legs, and a `pleats` pattern presses folds into it.
diff --git a/desktop b/desktop
index 9cd6eabef..fc2d9925f 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 9cd6eabef552c544c7879a4efb3a5128d7c089f7
+Subproject commit fc2d9925f0cce7478608ef2aa102dfa62c58c040
diff --git a/pipeline/src/modeling/hair.ts b/pipeline/src/modeling/hair.ts
index 913ab5c92..44eed3fd9 100644
--- a/pipeline/src/modeling/hair.ts
+++ b/pipeline/src/modeling/hair.ts
@@ -20,8 +20,12 @@ export interface HairParams {
faces: FaceSelector;
/** How many. Default 300. */
count?: number;
- /** How long a card is, in model units. */
- length: number;
+ /** How long a card is, in model units. Required unless `guides` say. */
+ length?: number;
+ /** Lines the hair follows, each from near the scalp to its ends: a ponytail, a fringe, a parting. A card takes the line starting nearest its root, and runs as long as it, in place of `droop` and `comb`. */
+ guides?: readonly (readonly Vec3[])[];
+ /** Along `guides`, how far cards close up onto the line by the end, 0..1: 1 gathers them into a lock. Default 0. */
+ gather?: number;
/** How wide at the root, in model units. Default a tenth of its length. */
width?: number;
/** Quads along a card: more follows a curve better. Default 6. */
@@ -51,10 +55,42 @@ const unit = (a: number, b: number, c: number, seed: number): number => hash3(a,
const MAX_CARDS = 20000;
const MAX_SEGMENTS = 24;
+const distance = (a: Vec3, b: Vec3): number => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
+
+interface Guide { points: readonly Vec3[]; size: number; at(t: number): Vec3; way(t: number): Vec3 }
+
+/** A line with its points rounded off, and read by the share of its length: a card has more rows than a guide has points. */
+function guideOf(line: readonly Vec3[]): Guide {
+ if (line.length < 2) throw new Error('each of `guides` needs two points or more');
+ const round = (t: number): Vec3 => {
+ const place = Math.max(0, Math.min(line.length - 1 - 1e-6, t * (line.length - 1)));
+ const i = Math.floor(place);
+ const w = place - i;
+ const [p0, p1, p2, p3] = [line[Math.max(0, i - 1)]!, line[i]!, line[i + 1]!, line[Math.min(line.length - 1, i + 2)]!];
+ const k = (a: number, b: number, c: number, e: number): number => 0.5 * (2 * b + (c - a) * w + (2 * a - 5 * b + 4 * c - e) * w * w + (3 * b - a - 3 * c + e) * w * w * w);
+ return [k(p0[0], p1[0], p2[0], p3[0]), k(p0[1], p1[1], p2[1], p3[1]), k(p0[2], p1[2], p2[2], p3[2])];
+ };
+ const SAMPLES = 48;
+ const lengths = [0];
+ for (let i = 1; i <= SAMPLES; i++) lengths.push(lengths[i - 1]! + distance(round((i - 1) / SAMPLES), round(i / SAMPLES)));
+ const size = lengths[SAMPLES]!;
+ if (!(size > 0)) throw new Error('one of `guides` has no length');
+ const at = (t: number): Vec3 => {
+ const wanted = Math.max(0, Math.min(1, t)) * size;
+ let i = 1;
+ while (i < SAMPLES && lengths[i]! < wanted) i++;
+ const span = lengths[i]! - lengths[i - 1]!;
+ return round((i - 1 + (span > 0 ? (wanted - lengths[i - 1]!) / span : 0)) / SAMPLES);
+ };
+ return { points: line, size, at, way: (t) => normalize(sub(at(Math.min(1, t + 0.02)), at(Math.max(0, t - 0.02)))) };
+}
+
export function hair(mesh: PolyMesh, p: HairParams): PolyMesh {
const count = p.count ?? 300;
const segments = p.segments ?? 6;
- if (!(p.length > 0)) throw new Error(`length ${p.length} must be positive`);
+ const guides = p.guides?.length ? p.guides.map(guideOf) : null;
+ if (!guides && !(p.length! > 0)) throw new Error(`length ${p.length} must be positive, or \`guides\` must say how far it runs`);
+ if (p.gather !== undefined && !(p.gather >= 0 && p.gather <= 1)) throw new Error(`gather ${p.gather} must be 0..1`);
if (!Number.isInteger(count) || count < 1 || count > MAX_CARDS) throw new Error(`count ${count} must be 1..${MAX_CARDS}`);
if (!Number.isInteger(segments) || segments < 1 || segments > MAX_SEGMENTS) throw new Error(`segments ${segments} must be 1..${MAX_SEGMENTS}`);
for (const [name, v] of [['droop', p.droop], ['spread', p.spread], ['uneven', p.uneven], ['taper', p.taper]] as const) {
@@ -66,7 +102,7 @@ export function hair(mesh: PolyMesh, p: HairParams): PolyMesh {
const seed = p.seed ?? 1;
const droop = p.droop ?? 0.7, spread = p.spread ?? 0.15, uneven = p.uneven ?? 0.3, taper = p.taper ?? 0.6;
- const width = p.width ?? p.length * 0.1;
+ const width = p.width ?? (guides ? guides[0]!.size : p.length!) * 0.1;
const comb: Vec3 = p.comb ?? [0, 0, 0];
const color = p.color ?? [0.25, 0.14, 0.07];
const tip = p.tipColor ?? color;
@@ -74,6 +110,7 @@ export function hair(mesh: PolyMesh, p: HairParams): PolyMesh {
const surface = compact({ positions: mesh.positions, faces: mesh.faces.filter((f) => f.card === undefined) });
const { min, max } = boundsOf(surface);
const middle: Vec3 = [(min[0] + max[0]) / 2, (min[1] + max[1]) / 2, (min[2] + max[2]) / 2];
+ const reach = Math.hypot(max[0] - min[0], max[1] - min[1], max[2] - min[2]) * 0.006;
// The head and not the layers before: cards lie over each other, and hair does not push hair away.
const tree = new TriangleTree(trianglesOf(surface));
const firstCard = mesh.faces.reduce((next, f) => Math.max(next, (f.card ?? -1) + 1), 0);
@@ -107,8 +144,10 @@ export function hair(mesh: PolyMesh, p: HairParams): PolyMesh {
const root = add(add(scale(piece.a, 1 - u - v), scale(piece.b, u)), scale(piece.c, v));
const out = piece.n;
const stray: Vec3 = [(r(3) - 0.5) * 2 * spread, (r(4) - 0.5) * 2 * spread, (r(5) - 0.5) * 2 * spread];
- const size = p.length * (1 - uneven * r(6));
+ const nearest = guides ? guides.reduce((best, g) => (distance(g.points[0]!, root) < distance(best.points[0]!, root) ? g : best)) : null;
+ const size = (nearest ? nearest.size : p.length!) * (1 - uneven * r(6));
const step = size / segments;
+ const fromLine = nearest ? sub(root, nearest.points[0]!) : ([0, 0, 0] as Vec3);
// Each step leans further toward the ground, by as much as `droop` asks over the card's whole length.
const pull = droop * 2.4 / segments;
let d = normalize(add(add(out, comb), stray));
@@ -120,6 +159,20 @@ export function hair(mesh: PolyMesh, p: HairParams): PolyMesh {
const phase = r(9) * Math.PI * 2;
const rows: { at: Vec3; side: Vec3 }[] = [];
for (let s = 0; s <= segments; s++) {
+ if (nearest) {
+ const along = (s / segments) * (size / nearest.size);
+ const closing = 1 - (p.gather ?? 0) * along;
+ at = add(add(nearest.at(along), scale(fromLine, closing)), scale(stray, along * size));
+ d = nearest.way(along);
+ // Over the head, not through it: a line from behind the ear to the tie is a chord of the skull.
+ // Outside is where the surface lies between a point and the middle of what it grew from.
+ for (let tries = 0; tries < 100; tries++) {
+ const way = sub(middle, at);
+ const far = Math.hypot(way[0], way[1], way[2]);
+ if (far < 1e-9 || tree.blocked(at[0], at[1], at[2], way[0] / far, way[1] / far, way[2] / far, far)) break;
+ at = add(at, scale(way, -reach / far));
+ }
+ }
const away = normalize(sub(at, middle));
let across = cross(d, add(scale(out, 0.5), scale(away, 0.5)));
if (dot(across, across) < 1e-8) across = cross(d, [0.3, 0.2, 0.9]);
@@ -127,7 +180,7 @@ export function hair(mesh: PolyMesh, p: HairParams): PolyMesh {
const t = s / segments;
const sway = p.wave ? scale(across, Math.sin(t * 7 + phase) * p.wave * t) : [0, 0, 0] as Vec3;
rows.push({ at: add(at, sway), side: scale(across, (width * (1 - taper * t)) / 2) });
- if (s === segments) break;
+ if (s === segments || nearest) continue;
d = normalize(add(scale(d, 1 - pull), add(scale([0, -1, 0], pull), scale(comb, pull * 0.5))));
// Turned aside rather than through: it slides over what it grows from.
for (let tries = 0; tries < 6 && tree.blocked(at[0], at[1], at[2], d[0], d[1], d[2], step * 1.2); tries++) {
diff --git a/pipeline/src/modeling/modelBake.ts b/pipeline/src/modeling/modelBake.ts
index ebc4e5dc9..83f1e3199 100644
--- a/pipeline/src/modeling/modelBake.ts
+++ b/pipeline/src/modeling/modelBake.ts
@@ -276,7 +276,7 @@ function withTangents(mesh: MeshData): MeshData {
}
/** What a material has to say about a model, or null where a plain MeshRenderer says all of it. */
-export function modelMaterialDoc(source: ModelSource, cullBackfaces: boolean, maps: { normal?: string | null; surface?: string | null; occlusion?: string | null; hair?: { flow: string; shift: string } | null }): Record<string, unknown> | null {
+export function modelMaterialDoc(source: ModelSource, cullBackfaces: boolean, maps: { normal?: string | null; surface?: string | null; occlusion?: string | null; color?: string | null; hair?: { flow: string; shift: string } | null }): Record<string, unknown> | null {
const { material } = source;
if (maps.hair) {
return {
@@ -311,6 +311,10 @@ export function modelMaterialDoc(source: ModelSource, cullBackfaces: boolean, ma
cull: cullBackfaces && !material?.alpha ? CullMode.Back : CullMode.None,
properties: {
...(material?.alpha === 'cutout' ? { u_alphaCutoff: material.cutoff ?? 0.5 } : {}),
+ ...(material?.emissive ? {
+ u_emissive: { r: material.emissive[0]!, g: material.emissive[1]!, b: material.emissive[2]!, a: 1 },
+ ...(maps.color ? { u_emissiveMap: maps.color } : {}),
+ } : {}),
...(maps.normal ? { u_normalMap: maps.normal } : {}),
...(maps.occlusion ? {
u_occlusionMap: maps.occlusion,
diff --git a/pipeline/src/modeling/modelSource.ts b/pipeline/src/modeling/modelSource.ts
index 97b320f29..9880d4502 100644
--- a/pipeline/src/modeling/modelSource.ts
+++ b/pipeline/src/modeling/modelSource.ts
@@ -22,6 +22,7 @@ import { decimate, triangleCount } from './decimate';
import { displace, DISPLACE_PATTERNS } from './displace';
import { stain } from './stain';
import { cardsOnly, hair, hasCards, type HairSway } from './hair';
+import { scatter } from './scatter';
import { checkAnimations, checkController, checkRig, checkShapes, resolveJoints, type AnimationSource, type ControllerSource, type RigSource, type ShapeSource } from './rig';
import { compact, type Face, type FaceSelector, type PolyMesh, type Vec3 } from './polyMesh';
@@ -71,6 +72,8 @@ export interface ModelMaterial {
alpha?: 'cutout' | 'blend';
/** Below this a `cutout` is a hole. Default 0.5. */
cutoff?: number;
+ /** Light it gives off, linear [r, g, b], past 1 for what glows and blooms: fire, a lit window. With a colour bake, multiplied by the paint. */
+ emissive?: readonly number[];
}
export interface ModelAttachment {
@@ -107,7 +110,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';
+ | 'color' | 'points' | 'faces' | 'edges' | 'axis' | 'pivot' | 'parts' | 'noise' | 'sections' | 'section' | 'vec3s' | 'numbers' | 'operation' | 'uvmode' | 'number|vec2only' | 'vec2' | 'pattern' | 'near' | 'where' | 'guides' | 'line';
interface OpSpec {
params: Record<string, Kind>;
@@ -140,8 +143,9 @@ export const MODEL_OPS: Record<string, OpSpec> = {
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' },
- hair: { params: { faces: 'faces', count: 'integer', length: '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', 'length'], run: hair as unknown as OpSpec['run'], says: 'grows cards of hair from these faces, falling around what is there; run it again for another layer, and only the cards are kept' },
- stain: { params: { faces: 'faces', near: 'near', 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, or around a spot: pupils, moss, grime' },
+ 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' },
decimate: { params: { from: 'string', faces: 'faces', ratio: 'number', triangles: 'integer', error: 'number' }, required: [], run: decimate as unknown as OpSpec['run'], says: 'leaves fewer triangles over the same surface: `ratio` to keep or `triangles` to end with, stopping sooner if the surface would move more than `error` (default 0.02) of its size; `from` thins the surface as it stood after that step, before its fine detail' },
uv: { params: { faces: 'faces', mode: 'uvmode', axis: 'string', at: 'vec3', scale: 'number|vec2only', repeat: 'number|vec2only', offset: 'vec2', rotate: 'number' }, required: ['mode'], run: uvStep as unknown as OpSpec['run'], says: 'sets how faces take a texture: box, planar, cylinder or sphere' },
delete: { params: { faces: 'faces' }, required: ['faces'], run: ops.deleteFaces as OpSpec['run'], says: 'removes faces, leaving a hole' },
@@ -299,6 +303,11 @@ const KIND_CHECK: Record<Kind, (v: unknown) => string | null> = {
uvmode: (v) => (['box', 'planar', 'cylinder', 'sphere'].includes(v as string) ? null : 'must be box, planar, cylinder or sphere'),
'number|vec2only': (v) => (isNum(v) || isNums(v, 2) ? null : 'must be a number or [u, v]'),
vec2: (v) => (isNums(v, 2) ? null : 'must be [u, v]'),
+ line: (v) => {
+ const n = v as { points?: unknown; width?: unknown } | null;
+ return typeof n === 'object' && n !== null && Array.isArray(n.points) && n.points.length >= 2 && n.points.every((q) => isNums(q, 3)) && isNum(n.width) && Object.keys(n).every((k) => k === 'points' || k === 'width') ? null : 'must be { points: [[x, y, z], ...], width }';
+ },
+ 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]'),
pattern: (v) => (DISPLACE_PATTERNS.includes(v as never) ? null : `must be one of ${DISPLACE_PATTERNS.join(', ')}`),
where: (v) => (v === 'cavity' || v === 'edges' ? null : 'must be cavity or edges'),
near: (v) => {
@@ -389,16 +398,23 @@ export function validateModelSource(raw: unknown): ModelSource {
if (!Array.isArray(source.steps)) throw new ModelBuildError('`steps` must be an array', null, null, null);
if (source.material !== undefined) {
const m = source.material as Record<string, unknown> | null;
- if (typeof m !== 'object' || m === null || Array.isArray(m)) throw new ModelBuildError('material must be { roughness?, metallic?, alpha?, cutoff? }', null, null, null);
+ if (typeof m !== 'object' || m === null || Array.isArray(m)) throw new ModelBuildError('material must be { roughness?, metallic?, alpha?, cutoff?, emissive? }', null, null, null);
for (const [key, value] of Object.entries(m)) {
if (key === 'alpha') {
if (value !== 'cutout' && value !== 'blend') throw new ModelBuildError('material.alpha must be cutout or blend', null, null, null);
continue;
}
- if (!['roughness', 'metallic', 'cutoff'].includes(key)) throw new ModelBuildError(`material has an unknown field "${key}"; it takes roughness, metallic, alpha, cutoff`, null, null, null);
+ if (key === 'emissive') {
+ if (!(isNums(value, 3) && (value as number[]).every((c) => c >= 0))) throw new ModelBuildError('material.emissive must be [r, g, b], none below 0', null, null, null);
+ continue;
+ }
+ if (!['roughness', 'metallic', 'cutoff'].includes(key)) throw new ModelBuildError(`material has an unknown field "${key}"; it takes roughness, metallic, alpha, cutoff, emissive`, null, null, null);
if (!(isNum(value) && value >= 0 && value <= 1)) throw new ModelBuildError(`material.${key} must be 0..1`, null, null, null);
}
}
+ (source.steps as Partial<ModelStep>[]).forEach((s, i) => {
+ if (s?.op === 'hair' && s.length === undefined && s.guides === undefined) throw new ModelBuildError(`${stepLabel(s, i)}: needs \`length\` or \`guides\``, i, s.id ?? null, 'hair');
+ });
if (Array.isArray(source.steps) && (source.steps as Partial<ModelStep>[]).some((s) => s?.op === 'hair')) {
if (source.normalBake !== undefined || source.uvAtlas) throw new ModelBuildError('a hair model\'s cards take their texture where the step puts them, so it has no normalBake or uvAtlas', null, null, null);
if (source.rig !== undefined || source.shapes !== undefined) throw new ModelBuildError('a hair model has no rig or shapes of its own: `hairSway` gives it bones, and placed under a head joint it follows that', null, null, null);
diff --git a/pipeline/src/modeling/scatter.ts b/pipeline/src/modeling/scatter.ts
new file mode 100644
index 000000000..cd8a1672b
--- /dev/null
+++ b/pipeline/src/modeling/scatter.ts
@@ -0,0 +1,164 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file scatter.ts — the `scatter` step: many copies of a shape, across a surface, along a path or through a box.
+ *
+ * Feathers along a limb, rivets on a plate, the lights of a far city: each is one small shape and a rule for where
+ * the rest go, where writing them out step by step would run to hundreds. The same seed lays them out the same way.
+ */
+import { hash3 } from './organic';
+import { triangulateFace } from './triangulate';
+import { add, boundsOf, compact, cross, dot, faceNormal, length, normalize, scale, selectFaces, sub, type Face, type FaceSelector, type PolyMesh, type Vec3 } from './polyMesh';
+
+export interface ScatterParams {
+ /** The shape to copy, which goes on standing as one of nothing: it is taken away unless `keep`. Its lowest point sits on the place it lands, and its +y points away. */
+ source: FaceSelector;
+ /** How many copies. */
+ count: number;
+ /** Across a surface, by area, each standing on it. */
+ faces?: FaceSelector;
+ /** Along a line of points, evenly with a little jitter, each pointing along it. */
+ path?: readonly Vec3[];
+ /** Through a box [min, max], upright. */
+ within?: readonly Vec3[];
+ /** Size of a copy, or [smallest, largest]. Default 1. */
+ scale?: number | readonly number[];
+ /** Along a `path`, the size at its end as a share of its start. Default 1. */
+ taper?: number;
+ /** How far each is turned about its own +y at random, in degrees. Default 180. */
+ spin?: number;
+ /** How far each leans off where it would point at random, in degrees. Default 0. */
+ tilt?: number;
+ /** Each copy takes one of these at random, in place of its own paint. */
+ colors?: readonly (readonly number[])[];
+ keep?: boolean;
+ seed?: number;
+ tag?: string;
+}
+
+const MAX_COPIES = 20000;
+const unit = (a: number, b: number, seed: number): number => hash3(a, b, 37, seed) * 0.5 + 0.5;
+
+/** Turns about an axis through the origin. */
+function turned(v: Vec3, axis: Vec3, radians: number): Vec3 {
+ const [c, s] = [Math.cos(radians), Math.sin(radians)];
+ return add(add(scale(v, c), scale(cross(axis, v), s)), scale(axis, dot(axis, v) * (1 - c)));
+}
+
+/** A frame whose +y is @p up, as the shortest turn from upright. */
+function frameFor(up: Vec3): (v: Vec3) => Vec3 {
+ const axis = cross([0, 1, 0], up);
+ const size = length(axis);
+ if (size < 1e-6) return up[1] > 0 ? (v) => v : (v) => [v[0], -v[1], -v[2]];
+ const unitAxis = scale(axis, 1 / size);
+ const angle = Math.atan2(size, up[1]);
+ return (v) => turned(v, unitAxis, angle);
+}
+
+interface Spot { at: Vec3; up: Vec3; along: number }
+
+function surfaceSpots(mesh: PolyMesh, picked: readonly number[], count: number, seed: number): Spot[] {
+ const pieces: { a: Vec3; b: Vec3; c: Vec3; n: Vec3 }[] = [];
+ const running: number[] = [];
+ let total = 0;
+ for (const f of picked) {
+ const face = mesh.faces[f]!;
+ const n = faceNormal(mesh, face);
+ for (const [a, b, c] of triangulateFace(mesh, face)) {
+ const [pa, pb, pc] = [mesh.positions[a]!, mesh.positions[b]!, mesh.positions[c]!];
+ total += length(cross(sub(pb, pa), sub(pc, pa))) / 2;
+ pieces.push({ a: pa, b: pb, c: pc, n });
+ running.push(total);
+ }
+ }
+ if (!(total > 0)) throw new Error('`faces` have no area to scatter over');
+ return Array.from({ length: count }, (_, i) => {
+ const wanted = unit(i, 0, seed) * total;
+ let lo = 0, hi = pieces.length - 1;
+ while (lo < hi) { const m = (lo + hi) >> 1; if (running[m]! < wanted) lo = m + 1; else hi = m; }
+ const p = pieces[lo]!;
+ let [u, v] = [unit(i, 1, seed), unit(i, 2, seed)];
+ if (u + v > 1) { u = 1 - u; v = 1 - v; }
+ return { at: add(add(scale(p.a, 1 - u - v), scale(p.b, u)), scale(p.c, v)), up: p.n, along: 0 };
+ });
+}
+
+function pathSpots(path: readonly Vec3[], count: number, seed: number): Spot[] {
+ if (path.length < 2) throw new Error('`path` needs two points or more');
+ const lengths = [0];
+ for (let i = 1; i < path.length; i++) lengths.push(lengths[i - 1]! + length(sub(path[i]!, path[i - 1]!)));
+ const whole = lengths.at(-1)!;
+ if (!(whole > 0)) throw new Error('`path` has no length');
+ return Array.from({ length: count }, (_, i) => {
+ const t = count === 1 ? 0.5 : Math.min(1, Math.max(0, (i + (unit(i, 1, seed) - 0.5) * 0.4) / (count - 1)));
+ let k = 1;
+ while (k < path.length - 1 && lengths[k]! < t * whole) k++;
+ const span = lengths[k]! - lengths[k - 1]!;
+ const w = span > 0 ? (t * whole - lengths[k - 1]!) / span : 0;
+ return { at: add(scale(path[k - 1]!, 1 - w), scale(path[k]!, w)), up: normalize(sub(path[k]!, path[k - 1]!)), along: t };
+ });
+}
+
+export function scatter(mesh: PolyMesh, p: ScatterParams): PolyMesh {
+ if (!Number.isInteger(p.count) || p.count < 1 || p.count > MAX_COPIES) throw new Error(`count ${p.count} must be 1..${MAX_COPIES}`);
+ const places = [p.faces, p.path, p.within].filter((v) => v !== undefined).length;
+ if (places !== 1) throw new Error('say where they go with one of `faces`, `path` or `within`');
+ const taken = selectFaces(mesh, p.source);
+ if (taken.length === 0) throw new Error(`\`source\` ${JSON.stringify(p.source)} matched no face`);
+ const seed = p.seed ?? 1;
+ const isTaken = new Set(taken);
+ const shape = taken.map((f) => mesh.faces[f]!);
+ const { min, max } = boundsOf(mesh, shape.flatMap((f) => [...f.v]));
+ const foot: Vec3 = [(min[0] + max[0]) / 2, min[1], (min[2] + max[2]) / 2];
+
+ let spots: Spot[];
+ if (p.faces !== undefined) {
+ const picked = selectFaces(mesh, p.faces).filter((f) => !isTaken.has(f));
+ if (picked.length === 0) throw new Error(`\`faces\` ${JSON.stringify(p.faces)} matched nothing but the source`);
+ spots = surfaceSpots(mesh, picked, p.count, seed);
+ } else if (p.path !== undefined) {
+ spots = pathSpots(p.path, p.count, seed);
+ } else {
+ const [lo, hi] = p.within as readonly [Vec3, Vec3];
+ if (!lo || !hi || p.within!.length !== 2) throw new Error('`within` must be [min, max]');
+ spots = Array.from({ length: p.count }, (_, i) => ({
+ at: [0, 1, 2].map((k) => lo[k]! + (hi[k]! - lo[k]!) * unit(i, 3 + k, seed)) as unknown as Vec3,
+ up: [0, 1, 0] as Vec3,
+ along: 0,
+ }));
+ }
+
+ const [smallest, largest] = typeof p.scale === 'number' ? [p.scale, p.scale] : p.scale ? [p.scale[0] ?? 1, p.scale[1] ?? p.scale[0] ?? 1] : [1, 1];
+ const spin = ((p.spin ?? 180) * Math.PI) / 180;
+ const tilt = ((p.tilt ?? 0) * Math.PI) / 180;
+ const keep = mesh.faces.filter((_, f) => p.keep || !isTaken.has(f));
+ const positions: Vec3[] = [...mesh.positions];
+ const faces: Face[] = [...keep];
+ spots.forEach((spot, i) => {
+ const size = (smallest + (largest - smallest) * unit(i, 6, seed)) * (1 + ((p.taper ?? 1) - 1) * spot.along);
+ const lean = (unit(i, 7, seed) - 0.5) * 2 * tilt;
+ const leanAbout = normalize(cross(spot.up, [unit(i, 8, seed) - 0.5, unit(i, 9, seed) - 0.5, unit(i, 10, seed) - 0.5 + 1e-3]));
+ const up = lean === 0 ? spot.up : normalize(turned(spot.up, leanAbout, lean));
+ const toFrame = frameFor(up);
+ const about = (unit(i, 11, seed) - 0.5) * 2 * spin;
+ const colour = p.colors?.length ? p.colors[Math.min(p.colors.length - 1, Math.floor(unit(i, 12, seed) * p.colors.length))] : undefined;
+ const seen = new Map<number, number>();
+ const place = (v: number): number => {
+ const had = seen.get(v);
+ if (had !== undefined) return had;
+ const local = scale(sub(mesh.positions[v]!, foot), size);
+ const spun: Vec3 = [local[0] * Math.cos(about) + local[2] * Math.sin(about), local[1], -local[0] * Math.sin(about) + local[2] * Math.cos(about)];
+ positions.push(add(spot.at, toFrame(spun)));
+ seen.set(v, positions.length - 1);
+ return positions.length - 1;
+ };
+ for (const face of shape) {
+ const copy: Face = { ...face, v: face.v.map(place) };
+ delete copy.uv;
+ if (p.tag) copy.tag = p.tag;
+ if (colour) copy.color = [colour[0]!, colour[1]!, colour[2]!, face.color?.[3] ?? 1];
+ faces.push(copy);
+ }
+ });
+ return compact({ positions, faces });
+}
diff --git a/pipeline/src/modeling/stain.ts b/pipeline/src/modeling/stain.ts
index 7033df72a..8036552c4 100644
--- a/pipeline/src/modeling/stain.ts
+++ b/pipeline/src/modeling/stain.ts
@@ -11,10 +11,25 @@
import { DISPLACE_PATTERNS, finestShare, mirroredPoint, nearWeight, patternField, reachedFaces, refine, MAX_DISPLACE_TRIANGLES, type DisplaceParams, type DisplacePattern } from './displace';
import { compact, faceArea, faceNormal, normalize, selectFaces, type Face, type FaceSelector, type PolyMesh, type Vec3 } from './polyMesh';
+/** How far a mirrored point is from a line of points. */
+function toLine(points: readonly Vec3[], mirror: StainParams['mirror'], x: number, y: number, z: number): number {
+ let best = Infinity;
+ for (let i = 1; i < points.length; i++) {
+ const a = mirroredPoint(mirror, points[i - 1]!), b = mirroredPoint(mirror, points[i]!);
+ const [dx, dy, dz] = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
+ const span = dx * dx + dy * dy + dz * dz;
+ const t = span > 0 ? Math.max(0, Math.min(1, ((x - a[0]) * dx + (y - a[1]) * dy + (z - a[2]) * dz) / span)) : 0;
+ best = Math.min(best, Math.hypot(x - a[0] - dx * t, y - a[1] - dy * t, z - a[2] - dz * t));
+ }
+ return best;
+}
+
export interface StainParams {
faces?: FaceSelector;
/** Only around here. Fades to its edge, or with `hard` stops there: a pupil. */
near?: { at: Vec3; radius: number };
+ /** Only along a line drawn on the surface, its points on or near it: an eyelid, a lip, a seam. Fades to `width` either side, or with `hard` stops there. */
+ line?: { points: readonly Vec3[]; width: number };
hard?: boolean;
/** Linear [r, g, b], over what is there. */
color?: readonly number[];
@@ -118,7 +133,9 @@ export function stain(mesh: PolyMesh, p: StainParams, budget = MAX_DISPLACE_TRIA
if (p.amount !== undefined && !(p.amount >= 0 && p.amount <= 1)) throw new Error(`amount ${p.amount} must be 0..1`);
if (p.softness !== undefined && !(p.softness > 0)) throw new Error(`softness ${p.softness} must be positive`);
if (p.near && !(p.near.radius > 0)) throw new Error(`near.radius ${p.near.radius} must be positive`);
- if (p.pattern === undefined && p.where === undefined && p.facing === undefined && p.near === undefined) throw new Error('say where: give at least one of pattern, where, facing, near; `paint` is for all of a set of faces');
+ if (p.line && !(p.line.width > 0)) throw new Error(`line.width ${p.line.width} must be positive`);
+ if (p.line && p.line.points.length < 2) throw new Error('line.points needs two points or more');
+ if (p.pattern === undefined && p.where === undefined && p.facing === undefined && p.near === undefined && p.line === undefined) throw new Error('say where: give at least one of pattern, where, facing, near, line; `paint` is for all of a set of faces');
const selector = p.faces ?? 'all';
let hit = selectFaces(mesh, selector);
@@ -127,11 +144,20 @@ export function stain(mesh: PolyMesh, p: StainParams, budget = MAX_DISPLACE_TRIA
hit = reachedFaces(mesh, hit, p.near, p.mirror);
if (hit.length === 0) throw new Error(`no surface of \`faces\` within ${p.near.radius} of ${JSON.stringify(p.near.at)}`);
}
+ if (p.line) {
+ const { points, width } = p.line;
+ const [lo, hi] = [[0, 1, 2].map((k) => Math.min(...points.map((q) => q[k]!))), [0, 1, 2].map((k) => Math.max(...points.map((q) => q[k]!)))];
+ const around = { at: [0, 1, 2].map((k) => (lo[k]! + hi[k]!) / 2) as unknown as Vec3, radius: Math.hypot(hi[0]! - lo[0]!, hi[1]! - lo[1]!, hi[2]! - lo[2]!) / 2 + width };
+ hit = reachedFaces(mesh, hit, around, p.mirror);
+ if (hit.length === 0) throw new Error(`no surface of \`faces\` within ${width} of the line`);
+ }
const asPattern = { ...p, pattern: p.pattern ?? 'bumps', amplitude: 1, scale: p.scale ?? 1 } as DisplaceParams;
const longest = p.detail
?? (p.pattern ? Math.min(...(p.stretch ?? [1, 1, 1])) * p.scale! * finestShare(asPattern)
// A hard edge is as clean as the faces it runs along.
- : p.near && p.hard ? p.near.radius / 8 : null);
+ : p.near && p.hard ? p.near.radius / 8
+ // A line is as fine as the faces under it, whatever those happen to be.
+ : p.line ? p.line.width / 3 : null);
const { mesh: fine, short } = longest === null ? { mesh, short: false } : refine(mesh, new Set(hit), longest, budget);
const chosen = new Set(hit);
@@ -163,6 +189,11 @@ export function stain(mesh: PolyMesh, p: StainParams, budget = MAX_DISPLACE_TRIA
m *= p.hard ? (w > 0 ? 1 : 0) : w;
if (m === 0) return 0;
}
+ if (p.line) {
+ const t = 1 - toLine(p.line.points, p.mirror, x, y, z) / p.line.width;
+ m *= t <= 0 ? 0 : p.hard ? 1 : t * t * (3 - 2 * t);
+ if (m === 0) return 0;
+ }
const n: Vec3 = [normals[v * 3]!, normals[v * 3 + 1]!, normals[v * 3 + 2]!];
if (facing) {
m *= smooth(0.2, 0.75, n[0] * facing[0] + n[1] * facing[1] + n[2] * facing[2]);
diff --git a/pipeline/tests/modeling-hair.test.ts b/pipeline/tests/modeling-hair.test.ts
index e6fe81a47..1a672d576 100644
--- a/pipeline/tests/modeling-hair.test.ts
+++ b/pipeline/tests/modeling-hair.test.ts
@@ -109,7 +109,7 @@ describe('hair', () => {
expect(() => bakeModel({ version: 1, steps: [head, { op: 'hair', faces: 'nothing', length: 1 }] })).toThrow(/matched no face/);
expect(() => bakeModel({ version: 1, steps: [head, { op: 'hair', faces: scalp, length: -1 }] })).toThrow(/length -1 must be positive/);
expect(() => bakeModel({ version: 1, steps: [head, { op: 'hair', faces: scalp, length: 1, droop: 2 }] })).toThrow(/droop 2 must be 0..1/);
- expect(() => validateModelSource({ steps: [head, { op: 'hair', faces: scalp }] })).toThrow(/length is required/);
+ expect(() => validateModelSource({ steps: [head, { op: 'hair', faces: scalp }] })).toThrow(/needs `length` or `guides`/);
expect(() => validateModelSource({ steps, normalBake: { from: 'x' } })).toThrow(/no normalBake or uvAtlas/);
expect(() => validateModelSource({ steps, rig: { joints: [{ name: 'a', at: [0, 0, 0] }] } })).toThrow(/no rig or shapes/);
});
@@ -271,3 +271,68 @@ describe('see-through', () => {
expect(() => validateModelSource({ steps: [plane], material: { cutoff: 2 } })).toThrow(/cutoff must be 0..1/);
});
});
+
+describe('hair along guides', () => {
+ const line: [number, number, number][] = [[0, 1, -1], [0, 0.5, -2], [0.2, -0.5, -2.4], [0.1, -1.5, -2.2]];
+ const tail = (extra: Record<string, unknown> = {}): BakedModel => bakeModel({ version: 1, steps: [head, { op: 'hair', faces: { within: { min: [-0.3, 0.8, -1.1], max: [0.3, 1.1, -0.2] } }, count: 40, guides: [line], segments: 8, uneven: 0, ...extra }] });
+ const tips = (m: BakedModel): number[][] => {
+ const cards = new Map<number, number[]>();
+ for (const f of m.poly.faces) cards.set(f.card!, [...f.v]);
+ return [...cards.values()].map((v) => { const [a, b] = [m.poly.positions[v[1]!]!, m.poly.positions[v[2]!]!]; return [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2, (a[2] + b[2]) / 2]; });
+ };
+ const spreadOf = (points: number[][]): number => {
+ const mid = [0, 1, 2].map((k) => points.reduce((sum, p) => sum + p[k]!, 0) / points.length);
+ return Math.max(...points.map((p) => Math.hypot(p[0]! - mid[0]!, p[1]! - mid[1]!, p[2]! - mid[2]!)));
+ };
+
+ it('runs along the line to its end, wherever gravity would have taken it', () => {
+ for (const tip of tips(tail({ spread: 0 }))) expect(Math.hypot(tip[0]! - 0.1, tip[1]! + 1.5, tip[2]! + 2.2)).toBeLessThan(0.95);
+ });
+
+ it('takes the line that starts nearest its root', () => {
+ const other: [number, number, number][] = [[0, 1, 1], [0, 0, 3]];
+ const m = bakeModel({ version: 1, steps: [head, { op: 'hair', faces: scalp, count: 60, guides: [line, other], segments: 4, uneven: 0, spread: 0 }] });
+ const ends = tips(m);
+ expect(ends.some((t) => t[2]! < -1.5)).toBe(true);
+ expect(ends.some((t) => t[2]! > 2)).toBe(true);
+ });
+
+ it('closes up onto the line as far as `gather` asks', () => {
+ expect(spreadOf(tips(tail({ spread: 0, gather: 1 })))).toBeLessThan(spreadOf(tips(tail({ spread: 0 }))) * 0.2);
+ });
+
+ it('flies apart toward the ends by `spread`', () => {
+ expect(spreadOf(tips(tail({ spread: 0.3, gather: 1 })))).toBeGreaterThan(spreadOf(tips(tail({ spread: 0, gather: 1 }))) + 0.2);
+ });
+
+ it('goes over the head rather than through it', () => {
+ const across: [number, number, number][] = [[0.9, 0.4, 0], [0, 0.4, 0], [-0.9, 0.4, -0.3]];
+ const m = bakeModel({ version: 1, steps: [head, { op: 'hair', faces: { within: { min: [0.5, 0.2, -0.5], max: [null, 0.6, 0.5] } }, count: 30, guides: [across], gather: 1, spread: 0, uneven: 0, segments: 12 }] });
+ const nearest = Math.min(...m.poly.positions.map((q) => Math.hypot(q[0]!, q[1]!, q[2]!)));
+ expect(nearest).toBeGreaterThan(0.9);
+ });
+
+ it('needs a length or guides, and says so', () => {
+ expect(() => validateModelSource({ steps: [head, { op: 'hair', faces: scalp, guides: [[[0, 0, 0]]] }] })).toThrow(/guides/);
+ expect(() => validateModelSource({ steps: [head, { op: 'hair', faces: scalp }] })).toThrow(/length/);
+ });
+});
+
+describe('material.emissive', () => {
+ const box: ModelStep = { op: 'box', size: 1 };
+ it('gives off that light, past 1 if asked', () => {
+ const doc = modelMaterialDoc({ version: 1, material: { emissive: [8, 3, 0.5] }, steps: [box] }, true, {}) as { properties: Record<string, unknown> };
+ expect(doc.properties.u_emissive).toEqual({ r: 8, g: 3, b: 0.5, a: 1 });
+ expect(doc.properties.u_emissiveMap).toBeUndefined();
+ });
+
+ it('takes its colours from the paint when the paint is baked', () => {
+ const doc = modelMaterialDoc({ version: 1, material: { emissive: [4, 4, 4] }, steps: [box] }, true, { color: 'm_color.png' }) as { properties: Record<string, unknown> };
+ expect(doc.properties.u_emissiveMap).toBe('m_color.png');
+ });
+
+ it('refuses what is not light', () => {
+ expect(() => validateModelSource({ material: { emissive: [1, -1, 0] }, steps: [box] })).toThrow(/emissive/);
+ expect(() => validateModelSource({ material: { emissive: 3 }, steps: [box] })).toThrow(/emissive/);
+ });
+});
diff --git a/pipeline/tests/modeling-scatter.test.ts b/pipeline/tests/modeling-scatter.test.ts
new file mode 100644
index 000000000..d1764c3b5
--- /dev/null
+++ b/pipeline/tests/modeling-scatter.test.ts
@@ -0,0 +1,86 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/** Many copies of a shape: where each lands, which way it stands, and that the same seed lays them out the same way. */
+import { describe, expect, it } from 'vitest';
+import { bakeModel, validateModelSource, type ModelStep } from '../src/modeling';
+
+const seed: ModelStep = { op: 'box', size: [0.1, 0.4, 0.1], tag: 'seed', at: [50, 50, 50] };
+const build = (scatter: Record<string, unknown>, extra: ModelStep[] = []) =>
+ bakeModel({ version: 1, smoothAngle: 0, steps: [...extra, seed, { op: 'scatter', source: 'seed', tag: 'copy', ...scatter }] }).poly;
+const copyPoints = (m: ReturnType<typeof build>): number[][] => {
+ const used = new Set(m.faces.filter((f) => f.tag === 'copy').flatMap((f) => [...f.v]));
+ return [...used].map((v) => [...m.positions[v]!]);
+};
+
+describe('scatter', () => {
+ it('takes the source away and leaves as many copies as asked', () => {
+ const m = build({ within: [[-1, -1, -1], [1, 1, 1]], count: 7 });
+ expect(m.faces.filter((f) => f.tag === 'seed')).toHaveLength(0);
+ expect(m.faces.filter((f) => f.tag === 'copy')).toHaveLength(7 * 6);
+ });
+
+ it('keeps the source when told to', () => {
+ expect(build({ within: [[-1, -1, -1], [1, 1, 1]], count: 2, keep: true }).faces.length).toBe(18);
+ });
+
+ it('fills the box and goes no further', () => {
+ const pts = copyPoints(build({ within: [[0, 0, 0], [10, 1, 10]], count: 200, spin: 0 }));
+ expect(Math.min(...pts.map((p) => p[0]!))).toBeGreaterThan(-0.1);
+ expect(Math.max(...pts.map((p) => p[0]!))).toBeLessThan(10.1);
+ expect(Math.max(...pts.map((p) => p[0]!))).toBeGreaterThan(8);
+ expect(Math.max(...pts.map((p) => p[2]!))).toBeGreaterThan(8);
+ });
+
+ it('stands each on a surface, pointing away from it', () => {
+ const ground: ModelStep = { op: 'box', size: [4, 1, 4], at: [0, 0, 0], tag: 'ground' };
+ const m = build({ faces: { tag: 'ground', facing: '+x' }, count: 20, spin: 0 }, [ground]);
+ const pts = copyPoints(m);
+ expect(Math.min(...pts.map((p) => p[0]!))).toBeGreaterThan(1.9);
+ expect(Math.max(...pts.map((p) => p[0]!))).toBeCloseTo(2.4, 1);
+ });
+
+ it('goes along a path, in order, pointing the way it runs', () => {
+ const m = build({ path: [[0, 0, 0], [10, 0, 0]], count: 11, spin: 0 });
+ const pts = copyPoints(m);
+ expect(Math.max(...pts.map((p) => p[0]!))).toBeGreaterThan(10);
+ expect(Math.max(...pts.map((p) => Math.abs(p[1]!)))).toBeLessThan(0.1);
+ for (let x = 1; x < 9; x++) expect(pts.some((p) => Math.abs(p[0]! - x) < 0.8)).toBe(true);
+ });
+
+ it('sizes them between the two it is given, and tapers along a path', () => {
+ const sizes = (scatter: Record<string, unknown>): number[] => {
+ const m = build({ count: 6, spin: 0, ...scatter });
+ const faces = m.faces.filter((f) => f.tag === 'copy');
+ return Array.from({ length: 6 }, (_, i) => {
+ const vs = faces.slice(i * 6, (i + 1) * 6).flatMap((f) => [...f.v]);
+ const ys = vs.map((v) => m.positions[v]!);
+ return Math.max(...ys.map((p) => Math.hypot(p[0]! - ys[0]![0]!, p[1]! - ys[0]![1]!, p[2]! - ys[0]![2]!)));
+ });
+ };
+ const ranged = sizes({ within: [[0, 0, 0], [9, 9, 9]], scale: [1, 3] });
+ expect(Math.max(...ranged)).toBeGreaterThan(Math.min(...ranged) * 1.2);
+ const tapered = sizes({ path: [[0, 0, 0], [10, 0, 0]], taper: 0.1 });
+ expect(tapered[5]!).toBeLessThan(tapered[0]! * 0.2);
+ });
+
+ it('gives each one of the colours', () => {
+ const colors = [[1, 0, 0], [0, 0, 1]];
+ const m = build({ within: [[0, 0, 0], [1, 1, 1]], count: 30, colors });
+ const seen = new Set(m.faces.filter((f) => f.tag === 'copy').map((f) => `${f.color?.[0]},${f.color?.[2]}`));
+ expect(seen).toEqual(new Set(['1,0', '0,1']));
+ });
+
+ it('lays them out the same way for a seed, and another way for another', () => {
+ const place = (s: number): number[][] => copyPoints(build({ within: [[0, 0, 0], [5, 5, 5]], count: 12, seed: s }));
+ expect(place(3)).toEqual(place(3));
+ expect(place(3)).not.toEqual(place(4));
+ });
+
+ it('asks for one place to go, and says what is wrong', () => {
+ expect(() => build({ count: 3 })).toThrow(/one of/);
+ expect(() => build({ count: 3, within: [[0, 0, 0], [1, 1, 1]], path: [[0, 0, 0], [1, 0, 0]] })).toThrow(/one of/);
+ expect(() => build({ source: 'nothing', count: 3, within: [[0, 0, 0], [1, 1, 1]] })).toThrow(/matched no face/);
+ expect(() => build({ count: 0, within: [[0, 0, 0], [1, 1, 1]] })).toThrow(/count/);
+ expect(() => validateModelSource({ steps: [seed, { op: 'scatter', source: 'seed' }] })).toThrow(/count/);
+ });
+});
diff --git a/pipeline/tests/modeling-stain.test.ts b/pipeline/tests/modeling-stain.test.ts
index d99df4f8a..fbb5071e3 100644
--- a/pipeline/tests/modeling-stain.test.ts
+++ b/pipeline/tests/modeling-stain.test.ts
@@ -203,3 +203,30 @@ describe('normalBake color', () => {
expect(applyModelEdits(source, [{ op: 'settings', fields: { normalBake: { size: 64 } } }]).normalBake?.color).toBeUndefined();
});
});
+
+describe('a stain along a line', () => {
+ const ball: ModelStep = { op: 'sphere', radius: 1, rings: 24, sides: 48, tag: 'ball', color: [1, 1, 1] };
+ const lid: [number, number, number][] = [[-0.5, 0, 0.866], [0, 0.1, 0.995], [0.5, 0, 0.866]];
+ const stained = (extra: Record<string, unknown> = {}) => bakeModel({ version: 1, steps: [ball, { op: 'stain', line: { points: lid, width: 0.04 }, color: [0, 0, 0], ...extra }] }).poly;
+ const dark = (m: ReturnType<typeof stained>): number[][] => m.faces.filter((f) => (f.color?.[0] ?? 1) < 0.5).map((f) => [...m.positions[f.v[0]!]!]);
+
+ it('darkens along the whole of it and nowhere else', () => {
+ const hit = dark(stained());
+ expect(hit.length).toBeGreaterThan(20);
+ expect(Math.min(...hit.map((q) => q[0]!))).toBeLessThan(-0.4);
+ expect(Math.max(...hit.map((q) => q[0]!))).toBeGreaterThan(0.4);
+ for (const q of hit) expect(Math.abs(q[1]! - (0.1 - Math.abs(q[0]!) * 0.2))).toBeLessThan(0.08);
+ });
+
+ it('draws on both sides across a mirror', () => {
+ const hit = dark(stained({ mirror: 'z' }));
+ expect(hit.some((q) => q[2]! > 0.5)).toBe(true);
+ expect(hit.some((q) => q[2]! < -0.5)).toBe(true);
+ });
+
+ it('says what is wrong', () => {
+ expect(() => validateModelSource({ steps: [ball, { op: 'stain', line: { points: [[0, 0, 0]], width: 1 } }] })).toThrow(/line/);
+ expect(() => bakeModel({ version: 1, steps: [ball, { op: 'stain', line: { points: lid, width: -1 }, color: [0, 0, 0] }] })).toThrow(/width/);
+ expect(() => bakeModel({ version: 1, steps: [ball, { op: 'stain', line: { points: [[9, 9, 9], [9, 9, 10]], width: 0.1 }, color: [0, 0, 0] }] })).toThrow(/no surface/);
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 1260c3890..47c51c6c0 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): hair follows guides over the head, stain draws lines, scatter lays out copies, and a material gives off light":
+ {"note":"An AI can model a character's hair by where it goes, and draw on a surface."},
+ "feat(mcp): model_write describes the new steps, and apply_scene_ops says which field a component does not have":
+ {"note":"An AI can model a character's hair by where it goes, and draw on a surface."},
"fix(postprocess): Color Grade contrast keeps a dark scene in a linear project":
{"note":"Color Grade contrast no longer blacks out a dark scene in a linear project."},
"feat(look): pictures laid side by side, one outlined over another, and their exact colours":