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(look): painting across the picture, strokes along a line, values and colours read

yhh3326c31aac56
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8a30b085e..79b52c3ca 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -22,7 +22,7 @@ published separately; it ships inside the editor.
- **Glyphs can be put on the atlas before they are shown.** The first page of a novel is hundreds of new characters, all landing in one frame. `preloadGlyphs(app, label, text, { budgetMs })` makes them ahead of time, a slice a frame, drawn as that `Text` will draw them, and returns `progress`, `done` and `release()`. On a Snapdragon 8 Elite a book's 2992 characters at 28 px took 145 ms over 25 frames with the worst frame at 9.5 ms, after which the first page's frame went from 49 to 11 ms and no page made a new glyph. Preloaded glyphs hold their atlas pages (4 MB each, a few hundred characters at that size) until `release()`.
- **Voxel GI lights what the camera does not see, and bounces light more than once.** The cache now reads the sun's shadow map back into the world, so a surface the sun lights behind or beside the camera still sends light into the view. Each surface also gives off again the bounce light it received, so a corner or a floor in shade gets light that took two or more bounces to reach it. A ray now brings what it meets at full strength however far it went (it used to fade with distance, 40% at 4 m with 12 cm voxels). Each voxel is weighed by how much of it a surface covers, so a bright patch no longer lights like the whole voxel around it. Together these keep the result close to a path tracer's whatever the voxel size. In a sunlit test room the whole frame carries 0.95 of Cycles' light at the default size and 0.74 at 12 cm voxels; before, it was 0.54 at the default and darker the finer the grid. With the lit patch behind the camera, the walls went from no bounce light to 25–57%. A closed room the sun only lights from outside stays dark. Two inspector controls tune it: **Off-screen Sun Albedo** (the colour the shadow map cannot give, assumed) and **Multi-bounce**. A fine grid no longer drops every voxel: a count truncated by the cache's ageing had kept them below the two samples a ray asks for. The WebGL2 fallback does the same in its own passes: each voxel asks the sun's map whether a sunlit surface stands in it, and traces two rays through last frame's grid for the light it is given. In the test room it carries 1.00 of Cycles' light at the default size (it was 0.56) and 0.80 at 12 cm; with the lit patch behind the camera 0.20 (it was 0). Its voxel pass costs about 1.3 ms more at 720p on a desktop.
-- **An AI can draw 2D pictures.** `image_write` turns layers into a `.png` beside an `.esimage`: shapes and SVG paths, gradients, strokes, shadows and glows, clipping and cutting, or pixel art as rows of characters. It answers with the picture on a mid ground and a light check and at 96, 64, 48 and 32 pixels, to look at and correct; `image_edit` changes one layer, a row or a block of pixels without restating the rest, and moves layers or wraps them in a group. Strokes can keep sharp corners, and the reply measures where each layer ended up. A layer or group can be blurred, for depth of field, and a fill can be noise for cloud, texture and film grain, the same picture from the same seed. A `paint` layer is a canvas of brush strokes with pressure, softness, tapering, bristles and smudging, added to round by round, for what shapes cannot do; one `sweep` instruction lays a mass of hair gathered into locks, and one `field` covers a region in strokes along a flow. `image_read` enlarges a part, and `image_set` shows several together with the stroke widths and size of each. Drawn on the CPU, so a source makes the same picture on any machine.
+- **An AI can draw 2D pictures.** `image_write` turns layers into a `.png` beside an `.esimage`: shapes and SVG paths, gradients, strokes, shadows and glows, clipping and cutting, or pixel art as rows of characters. It answers with the picture on a mid ground and a light check and at 96, 64, 48 and 32 pixels, to look at and correct; `image_edit` changes one layer, a row or a block of pixels without restating the rest, and moves layers or wraps them in a group. Strokes can keep sharp corners, and the reply measures where each layer ended up. A layer or group can be blurred, for depth of field, and a fill can be noise for cloud, texture and film grain, the same picture from the same seed. A `paint` layer is a canvas of brush strokes with pressure, softness, tapering, bristles and smudging, added to round by round, for what shapes cannot do; one `sweep` instruction lays a mass of hair gathered into locks, one `field` covers a region in strokes along a flow, and one `along` repeats strokes along a line. A layer can work across everything under it, to fuse separate parts into one painting, and `image_read` shows lightness alone and reads colours. `image_read` enlarges a part, and `image_set` shows several together with the stroke widths and size of each. Drawn on the CPU, so a source makes the same picture on any machine.
- **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.
diff --git a/desktop b/desktop
index 11d4d63fc..b0652f84b 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 11d4d63fc644fa9cfff0300c5f3d5230cfc3ea10
+Subproject commit b0652f84b13824d1a5155b486f61719f07262726
diff --git a/pipeline/src/image/imageRaster.ts b/pipeline/src/image/imageRaster.ts
index 3d9b8e784..1c3de7daf 100644
--- a/pipeline/src/image/imageRaster.ts
+++ b/pipeline/src/image/imageRaster.ts
@@ -8,7 +8,7 @@
* On the CPU rather than through a canvas, so the same source makes the same bytes on any machine and a test can read them.
*/
import { MAX_MARK_STROKES } from './imageSource';
-import type { ImageFill, ImageLayer, ImageSource, ImageEffect, ImageField, ImageMark, ImageStroke, ImageSweep, ImageTransform } from './imageSource';
+import type { ImageFill, ImageLayer, ImageSource, ImageAlong, ImageEffect, ImageField, ImageMark, ImageStroke, ImageSweep, ImageTransform } from './imageSource';
export interface RgbaBitmap { width: number; height: number; rgba: Uint8Array }
@@ -557,7 +557,7 @@ function effectLayers(effects: readonly ImageEffect[] | undefined, under: boolea
}
}
-interface Drawn { masks: Map<string, Float32Array>; notes: string[]; bounds: Map<string, ImageBox> }
+interface Drawn { masks: Map<string, Float32Array>; notes: string[]; bounds: Map<string, ImageBox>; painted: Map<string, { entries: number; strokes: number }> }
/** x, y, width and height in the picture's pixels. */
export type ImageBox = readonly [number, number, number, number];
@@ -944,10 +944,23 @@ function sweepStrokes(s: ImageSweep): ImageStroke[] {
}
/** Strokes across a region, following the guides or an angle. Each takes its colour from `tone` where it starts. */
-function fieldStrokes(s: ImageField, w: number, h: number): ImageStroke[] {
+function fieldStrokes(s: ImageField, w: number, h: number, m: Matrix, drawn: Drawn, where: string): ImageStroke[] {
const seed = s.seed ?? 1;
- const regionRuns = s.region ? parsePath(s.region).map((r) => r.points) : null;
+ const named = s.region?.startsWith('@') ? s.region.slice(1) : null;
+ const mask = named ? drawn.masks.get(named) : undefined;
+ if (named && !mask) {
+ drawn.notes.push(`${where}: a field's region "@${named}" names no layer drawn before it, so it drew nothing`);
+ return [];
+ }
+ const box = mask ? boxOf(w, h, (i) => mask[i]! >= 0.5) : null;
+ if (mask && !box) return [];
+ const regionRuns = s.region && !named ? parsePath(s.region).map((r) => r.points) : null;
const inside = (x: number, y: number): boolean => {
+ if (mask) {
+ const p = apply(m, [x, y]);
+ const [px, py] = [Math.floor(p[0]), Math.floor(p[1])];
+ return px >= 0 && py >= 0 && px < w && py < h && mask[py * w + px]! >= 0.5;
+ }
if (!regionRuns) return true;
let winding = 0;
for (const run of regionRuns) {
@@ -960,7 +973,10 @@ function fieldStrokes(s: ImageField, w: number, h: number): ImageStroke[] {
}
return winding !== 0;
};
- const all = regionRuns ? regionRuns.flat() : [[0, 0], [w, h]] as Pt[];
+ const back = invert(m);
+ const all = box
+ ? ([[box[0], box[1]], [box[0] + box[2], box[1]], [box[0], box[1] + box[3]], [box[0] + box[2], box[1] + box[3]]] as Pt[]).map((p) => apply(back, p))
+ : regionRuns ? regionRuns.flat() : [[0, 0], [w, h]] as Pt[];
const [x0, x1] = [Math.min(...all.map((p) => p[0])), Math.max(...all.map((p) => p[0]))];
const [y0, y1] = [Math.min(...all.map((p) => p[1])), Math.max(...all.map((p) => p[1]))];
const flow = (s.guides ?? []).flatMap((g) => {
@@ -984,9 +1000,9 @@ function fieldStrokes(s: ImageField, w: number, h: number): ImageStroke[] {
const len = Math.hypot(dx, dy) || 1;
return [dx / len, dy / len];
};
- const paint = paintOf(s.tone, IDENTITY);
+ const paint = s.tone !== undefined ? paintOf(s.tone, IDENTITY) : null;
const length = s.length ?? s.size * 3;
- const count = Math.min(MAX_MARK_STROKES, Math.ceil(((s.coverage ?? 2.5) * Math.max(1, (x1 - x0) * (y1 - y0))) / (s.size * length)));
+ const count = Math.min(MAX_MARK_STROKES, Math.ceil(((s.coverage ?? 4) * Math.max(1, (x1 - x0) * (y1 - y0))) / (s.size * length)));
const spread = ((s.spread ?? 12) * Math.PI) / 180;
const vary = s.vary ?? 0.05;
const steps = 5;
@@ -1012,22 +1028,72 @@ function fieldStrokes(s: ImageField, w: number, h: number): ImageStroke[] {
x += rx * forward; y += ry * forward;
}
out.push({
- points, size: s.size * (0.75 + pick(4) * 0.5), hardness: s.hardness ?? 0.55, opacity: s.opacity ?? 0.85,
- color: toHex(paint(sx, sy), 1 + (pick(5) - 0.5) * 2 * vary), taper: [0.12, 0.3],
+ points, size: s.size * (0.75 + pick(4) * 0.5), hardness: s.hardness ?? 0.25, opacity: s.opacity ?? 0.6,
+ ...(s.smudge ? { smudge: s.smudge } : { color: toHex(paint!(sx, sy), 1 + (pick(5) - 0.5) * 2 * vary) }), taper: [0.12, 0.3],
});
}
return out;
}
-const expandMark = (mark: ImageMark, w: number, h: number): readonly ImageStroke[] => {
- if ('type' in mark) return mark.type === 'sweep' ? sweepStrokes(mark) : fieldStrokes(mark, w, h);
- return [mark];
+/** The strokes again along a line, each turned to the line's direction there and sized along it. */
+function alongStrokes(s: ImageAlong): ImageStroke[] {
+ const seed = s.seed ?? 1;
+ const line = resampled(s.line, Math.max(2, s.count));
+ const [from, to] = typeof s.scale === 'number' ? [s.scale, s.scale] : s.scale ?? [1, 1];
+ const jitter = s.jitter ?? 0;
+ const out: ImageStroke[] = [];
+ for (let i = 0; i < s.count; i++) {
+ const t = s.count === 1 ? 0 : i / (s.count - 1);
+ const p = line[i]!;
+ // Its direction from the next place along, and at the last from the one before.
+ const [from0, to0] = i + 1 < line.length ? [p, line[i + 1]!] : [line[i - 1]!, p];
+ const pick = (k: number): number => (hash01(seed * 89 + i, k) - 0.5) * 2 * jitter;
+ const scale = from + (to - from) * t;
+ const base = Math.atan2(to0.y - from0.y, to0.x - from0.x);
+ for (const side of s.both ? [1, -1] : [1]) {
+ const angle = base + (((s.turn ?? 0) * side + pick(1) * 0.1) * Math.PI) / 180;
+ const [cos, sin] = [Math.cos(angle), Math.sin(angle)];
+ const [ox, oy] = [p.x + pick(2), p.y + pick(3)];
+ for (const stroke of s.strokes) {
+ out.push({
+ ...stroke,
+ size: stroke.size * scale,
+ points: stroke.points.map((v) => {
+ const [x, y] = [v[0]! * scale, v[1]! * scale * side];
+ return [ox + x * cos - y * sin, oy + x * sin + y * cos, ...(v[2] !== undefined ? [v[2]] : [])];
+ }),
+ });
+ }
+ }
+ }
+ return out;
+}
+
+/** Hairs laid between lines closer than a few hairs' width do not read as hairs, and nothing else says so. */
+function sweepNote(s: ImageSweep, drawn: Drawn, where: string): void {
+ const size = s.size ?? 1.2;
+ const lines = s.guides.map((g) => resampled(g, 3)[1]!);
+ let span = 0;
+ for (let i = 0; i + 1 < lines.length; i++) span += Math.hypot(lines[i + 1]!.x - lines[i]!.x, lines[i + 1]!.y - lines[i]!.y);
+ if (span < size * 4 || s.count * size > span * 8 * Math.max(1, s.guides.length)) {
+ drawn.notes.push(`${where}: a sweep lays ${s.count} hairs of size ${size} across ${Math.round(span)} pixels, which fills it as a flat band; use fewer, thinner hairs or set the guides further apart`);
+ }
+}
+
+const expandMark = (mark: ImageMark, w: number, h: number, m: Matrix, drawn: Drawn, where: string): readonly ImageStroke[] => {
+ if (!('type' in mark)) return [mark];
+ if (mark.type === 'sweep') {
+ sweepNote(mark, drawn, where);
+ return sweepStrokes(mark);
+ }
+ return mark.type === 'along' ? alongStrokes(mark) : fieldStrokes(mark, w, h, m, drawn, where);
};
function drawPaint(c: Canvas, layer: ImageLayer, parent: Matrix, drawn: Drawn, opacity: number, blend: Blend, clip: Float32Array | undefined): void {
const { w, h } = c;
const m = times(parent, transformOf(layer.transform, [w / 2, h / 2]));
const inner = new Canvas(w, h);
+ if (layer.from === 'below') inner.px.set(c.px);
if (layer.fill !== undefined) {
const paint = paintOf(layer.fill, m);
for (let y = 0; y < h; y++) {
@@ -1040,12 +1106,21 @@ function drawPaint(c: Canvas, layer: ImageLayer, parent: Matrix, drawn: Drawn, o
const buffer: StrokeBuffer = { mask: new Float32Array(w * h), rgb: new Float32Array(w * h * 3), touched: [] };
let drawnStrokes = 0;
(layer.strokes ?? []).forEach((mark) => {
- for (const s of expandMark(mark, w, h)) paintStroke(inner, s, m, drawnScale(m), drawnStrokes++, buffer);
+ for (const s of expandMark(mark, w, h, m, drawn, `layer ${layer.id ?? 'paint'}`)) paintStroke(inner, s, m, drawnScale(m), drawnStrokes++, buffer);
});
+ if (layer.id) drawn.painted.set(layer.id, { entries: (layer.strokes ?? []).length, strokes: drawnStrokes });
const alpha = new Float32Array(w * h);
for (let i = 0; i < alpha.length; i++) alpha[i] = inner.px[i * 4 + 3]!;
if (layer.id) drawn.masks.set(layer.id, alpha);
noteBox(drawn, layer.id, alpha, w, h);
+ if (layer.from === 'below') {
+ // It already holds the picture, so it takes that picture's place and does not go over it.
+ for (let i = 0; i < alpha.length * 4; i++) {
+ const keep = opacity * (clip ? clip[Math.floor(i / 4)]! : 1);
+ c.px[i] = c.px[i]! + (inner.px[i]! - c.px[i]!) * keep;
+ }
+ return;
+ }
effectLayers(layer.effects, true, c, alpha);
for (let i = 0; i < alpha.length; i++) {
const a = alpha[i]!;
@@ -1090,6 +1165,8 @@ export interface RenderedImage extends RgbaBitmap {
covers: number;
/** The same box for each layer with an id, after every transform, without its effects. */
layerBounds: Record<string, ImageBox>;
+ /** For each paint layer with an id: its entries, which `drop` counts, and the strokes they came to. */
+ painted: Record<string, { entries: number; strokes: number }>;
}
/** Draws a source that has been validated. */
@@ -1100,7 +1177,7 @@ export function renderImage(source: ImageSource): RenderedImage {
const [r, g, b, a] = parseColor(source.background);
for (let i = 0; i < w * h; i++) put(canvas, i, r, g, b, a, 'normal');
}
- const drawn: Drawn = { masks: new Map(), notes: [], bounds: new Map() };
+ const drawn: Drawn = { masks: new Map(), notes: [], bounds: new Map(), painted: new Map() };
for (const layer of source.layers) drawLayer(canvas, layer, IDENTITY, drawn);
const rgba = new Uint8Array(w * h * 4);
for (let i = 0; i < w * h; i++) {
@@ -1118,6 +1195,7 @@ export function renderImage(source: ImageSource): RenderedImage {
bounds: boxOf(w, h, (i) => rgba[i * 4 + 3]! >= 128),
covers: Math.round((solid / (w * h)) * 1000) / 1000,
layerBounds: Object.fromEntries(drawn.bounds),
+ painted: Object.fromEntries(drawn.painted),
};
}
@@ -1199,7 +1277,7 @@ export function setSheet(images: readonly RgbaBitmap[], cell = 128): RgbaBitmap
}
/** A part of a picture enlarged with hard pixels on the check, to see what the whole hides: a seam one pixel wide. */
-export function zoomImage(image: RgbaBitmap, region: { x: number; y: number; w: number; h: number }, longest = 640): RgbaBitmap {
+export function zoomImage(image: RgbaBitmap, region: { x: number; y: number; w: number; h: number }, longest = 1024): RgbaBitmap {
const [x0, y0] = [Math.max(0, Math.floor(region.x)), Math.max(0, Math.floor(region.y))];
const [w, h] = [Math.min(image.width - x0, Math.round(region.w)), Math.min(image.height - y0, Math.round(region.h))];
if (!(w > 0 && h > 0)) throw new Error(`region ${JSON.stringify(region)} is outside the picture, ${image.width} by ${image.height}`);
@@ -1215,6 +1293,7 @@ export function zoomImage(image: RgbaBitmap, region: { x: number; y: number; w:
/** Something to look at: the picture on a mid ground and on a light check, as a transparent image needs both, and at the sizes an icon is really seen. */
export function imageSheet(image: RgbaBitmap, sizes: readonly number[] = [96, 64, 48, 32]): RgbaBitmap {
const big = Math.max(image.width, image.height);
+ if (big >= LARGE_PICTURE && isOpaque(image)) return largeSheet(image);
const k = big < 384 ? Math.max(1, Math.floor(384 / big)) : Math.min(1, 512 / big);
const [pw, ph] = [Math.round(image.width * k), Math.round(image.height * k)];
const gap = 8;
@@ -1236,6 +1315,55 @@ export function imageSheet(image: RgbaBitmap, sizes: readonly number[] = [96, 64
return { width: W, height: H, rgba };
}
+const LARGE_PICTURE = 512;
+
+export function isOpaque(image: RgbaBitmap): boolean {
+ for (let i = 3; i < image.rgba.length; i += 4) if (image.rgba[i] !== 255) return false;
+ return true;
+}
+
+/** What a full painting wants to be seen at: large, with nothing to judge against a ground, and small to check it still reads. */
+function largeSheet(image: RgbaBitmap): RgbaBitmap {
+ const k = Math.min(1, 1024 / Math.max(image.width, image.height));
+ const [pw, ph] = [Math.round(image.width * k), Math.round(image.height * k)];
+ const gap = 8;
+ const [W, H] = [pw + gap * 3 + 192, ph + gap * 2];
+ const rgba = solidSheet(W, H);
+ layOn(rgba, W, k < 1 ? shrink(image, pw, ph) : image, gap, gap, midGround);
+ let oy = gap;
+ for (const s of [192, 96]) {
+ const small = shrink(image, s, Math.max(1, Math.round((s * image.height) / image.width)));
+ if (oy + small.height > H) break;
+ layOn(rgba, W, small, gap * 2 + pw, oy, midGround);
+ oy += small.height + gap;
+ }
+ return { width: W, height: H, rgba };
+}
+
+/** The picture in lightness alone: whether it holds together in light and dark, before colour flatters it. */
+export function valuesImage(image: RgbaBitmap): RgbaBitmap {
+ const rgba = new Uint8Array(image.rgba.length);
+ for (let i = 0; i < rgba.length; i += 4) {
+ const v = Math.round(lightness(image.rgba[i]!, image.rgba[i + 1]!, image.rgba[i + 2]!) * 255);
+ rgba[i] = v; rgba[i + 1] = v; rgba[i + 2] = v; rgba[i + 3] = image.rgba[i + 3]!;
+ }
+ return { width: image.width, height: image.height, rgba };
+}
+
+const lightness = (r: number, g: number, b: number): number => (r * 0.2126 + g * 0.7152 + b * 0.0722) / 255;
+
+/** What is at each point: the colour, and how light it is 0..1. */
+export function pickColors(image: RgbaBitmap, points: readonly (readonly number[])[]): { at: readonly number[]; color: string; value: number }[] {
+ return points.map((at) => {
+ const [x, y] = [Math.floor(at[0]!), Math.floor(at[1]!)];
+ if (!(x >= 0 && y >= 0 && x < image.width && y < image.height)) throw new Error(`[${at.join(', ')}] is outside the picture, ${image.width} by ${image.height}`);
+ const i = (y * image.width + x) * 4;
+ const [r, g, b, a] = [image.rgba[i]!, image.rgba[i + 1]!, image.rgba[i + 2]!, image.rgba[i + 3]!];
+ const hex = (v: number): string => v.toString(16).padStart(2, '0');
+ return { at, color: `#${hex(r)}${hex(g)}${hex(b)}${a === 255 ? '' : hex(a)}`, value: Math.round(lightness(r, g, b) * 100) / 100 };
+ });
+}
+
function nearestScale(src: RgbaBitmap, width: number, height: number): RgbaBitmap {
const rgba = new Uint8Array(width * height * 4);
for (let y = 0; y < height; y++) {
diff --git a/pipeline/src/image/imageSource.ts b/pipeline/src/image/imageSource.ts
index f7d5e5ada..a0ed8d941 100644
--- a/pipeline/src/image/imageSource.ts
+++ b/pipeline/src/image/imageSource.ts
@@ -91,12 +91,15 @@ export interface ImageSweep {
/** A region covered in strokes that follow a flow, each its colour from `tone` where it starts. */
export interface ImageField {
type: 'field';
- /** An SVG path to start strokes in; the whole picture without it. Strokes may run over its edge. */
+ /** An SVG path to start strokes in, or "@id" for where an earlier layer drew; the whole picture without it. Strokes may run over its edge. */
region?: string;
/** Lines the strokes follow, nearest the most, or a direction in degrees clockwise from right. */
guides?: readonly (readonly (readonly number[])[])[];
angle?: number;
- tone: ImageFill;
+ /** Where each stroke takes its colour; left out when it smudges. */
+ tone?: ImageFill;
+ /** 0..1: the strokes drag what is there along the flow, and lay no colour. */
+ smudge?: number;
size: number;
length?: number;
/** How many times over the strokes cover the region. */
@@ -109,7 +112,25 @@ export interface ImageField {
seed?: number;
}
-export type ImageMark = ImageStroke | ImageSweep | ImageField;
+/** The same strokes again and again along a line: feathers, scales, leaves, beads. */
+export interface ImageAlong {
+ type: 'along';
+ line: readonly (readonly number[])[];
+ count: number;
+ /** Drawn with x along the line and y across it, about the point [0, 0]. */
+ strokes: readonly ImageStroke[];
+ /** How large they are at the start of the line and at the end. */
+ scale?: number | readonly [number, number];
+ /** Degrees, added to the line's direction. */
+ turn?: number;
+ /** Each one again, reflected across the line. */
+ both?: boolean;
+ /** Up to this far off their place, in pixels and a tenth as many degrees. */
+ jitter?: number;
+ seed?: number;
+}
+
+export type ImageMark = ImageStroke | ImageSweep | ImageField | ImageAlong;
export interface ImageLayer {
id?: string;
@@ -129,6 +150,8 @@ export interface ImageLayer {
scale?: number;
layers?: readonly ImageLayer[];
strokes?: readonly ImageMark[];
+ /** "below": a paint layer's canvas starts as the picture so far, so its strokes and smudges work across everything under it. */
+ from?: 'below';
fill?: ImageFill;
stroke?: { color: ImageFill; width: number; align?: 'center' | 'inside' | 'outside'; join?: 'round' | 'miter' | 'bevel'; cap?: 'round' | 'butt' | 'square' };
opacity?: number;
@@ -165,6 +188,7 @@ function checkFill(v: unknown): string | null {
if (f.seed !== undefined && !Number.isInteger(f.seed)) return 'noise seed must be a whole number';
}
if (f.type === 'linear' && !(isPair(f.from) && isPair(f.to))) return 'a linear gradient needs from and to, each [x, y]';
+ if (f.type === 'linear' && (f.from as number[])[0] === (f.to as number[])[0] && (f.from as number[])[1] === (f.to as number[])[1]) return 'a linear gradient needs from and to apart: at one point it draws a single flat colour';
if (f.type === 'radial' && !(isPair(f.at) && isNum(f.radius) && (f.radius as number) > 0)) return 'a radial gradient needs at: [x, y] and a positive radius';
if (!Array.isArray(f.stops) || f.stops.length < 2) return 'a gradient needs two stops or more, each [0..1, colour]';
for (const s of f.stops as unknown[]) {
@@ -173,12 +197,13 @@ function checkFill(v: unknown): string | null {
return null;
}
-const FIELDS = ['id', 'shape', 'at', 'size', 'radius', 'radii', 'inner', 'count', 'tooth', 'turn', 'points', 'd', 'rows', 'palette', 'scale', 'layers', 'fill', 'stroke', 'opacity', 'blend', 'transform', 'mirror', 'effects', 'clip', 'erase', 'visible', 'blur', 'strokes'];
+const FIELDS = ['id', 'shape', 'at', 'size', 'radius', 'radii', 'inner', 'count', 'tooth', 'turn', 'points', 'd', 'rows', 'palette', 'scale', 'layers', 'fill', 'stroke', 'opacity', 'blend', 'transform', 'mirror', 'effects', 'clip', 'erase', 'visible', 'blur', 'strokes', 'from'];
const SHAPES: readonly ImageShape[] = ['rect', 'circle', 'ellipse', 'ring', 'polygon', 'line', 'star', 'gear', 'path', 'pixels', 'paint', 'group'];
const STROKE_FIELDS = ['points', 'color', 'to', 'size', 'hardness', 'opacity', 'taper', 'bristles', 'strand', 'spread', 'vary', 'wobble', 'seed', 'smudge', 'erase', 'blend'];
const SWEEP_FIELDS = ['type', 'guides', 'colors', 'count', 'tip', 'size', 'clumps', 'gather', 'flyaway', 'vary', 'wobble', 'opacity', 'taper', 'seed'];
-const FIELD_FIELDS = ['type', 'region', 'guides', 'angle', 'tone', 'size', 'length', 'coverage', 'spread', 'vary', 'opacity', 'hardness', 'seed'];
+const ALONG_FIELDS = ['type', 'line', 'count', 'strokes', 'scale', 'turn', 'both', 'jitter', 'seed'];
+const FIELD_FIELDS = ['type', 'region', 'guides', 'angle', 'tone', 'smudge', 'size', 'length', 'coverage', 'spread', 'vary', 'opacity', 'hardness', 'seed'];
const isGuide = (g: unknown): boolean => Array.isArray(g) && g.length >= 2 && g.every((p) => Array.isArray(p) && (p.length === 2 || p.length === 3) && p.every(isNum));
export const MAX_MARK_STROKES = 30000;
@@ -187,7 +212,7 @@ function markProblem(s: Record<string, unknown>): string | null {
for (const key of keys) if (s[key] !== undefined && !(isNum(s[key]) && (s[key] as number) >= 0 && (s[key] as number) <= 1)) return `${key} must be 0..1`;
return null;
};
- const fields = s.type === 'sweep' ? SWEEP_FIELDS : FIELD_FIELDS;
+ const fields = s.type === 'sweep' ? SWEEP_FIELDS : s.type === 'along' ? ALONG_FIELDS : FIELD_FIELDS;
for (const key of Object.keys(s)) if (!fields.includes(key)) return `has unknown field "${key}"; a ${String(s.type)} takes ${fields.join(', ')}`;
if (s.seed !== undefined && !Number.isInteger(s.seed)) return 'seed must be a whole number';
if (s.type === 'sweep') {
@@ -200,26 +225,45 @@ function markProblem(s: Record<string, unknown>): string | null {
if (s.taper !== undefined && !(Array.isArray(s.taper) && s.taper.length === 2 && s.taper.every((t) => isNum(t) && t >= 0 && t <= 1))) return 'taper must be [start, end], each 0..1';
return zeroToOne(['gather', 'flyaway', 'vary', 'opacity']);
}
+ if (s.type === 'along') {
+ if (!isGuide(s.line)) return 'needs a line: two or more [x, y]';
+ if (!(Number.isInteger(s.count) && (s.count as number) >= 1 && (s.count as number) <= 2000)) return 'count must be a whole number from 1 to 2000';
+ if (!Array.isArray(s.strokes) || s.strokes.length === 0) return 'needs strokes, drawn about [0, 0]';
+ for (const [n, inner] of (s.strokes as Record<string, unknown>[]).entries()) {
+ if (inner?.type !== undefined) return `strokes[${n}] must be a plain stroke`;
+ const bad = strokeProblem(inner);
+ if (bad) return `strokes[${n}] ${bad}`;
+ }
+ const scale = s.scale;
+ if (scale !== undefined && !(isNum(scale) && scale > 0) && !(isPair(scale) && (scale as number[]).every((v) => v > 0))) return 'scale must be a positive number, or [start, end]';
+ for (const key of ['turn', 'jitter']) if (s[key] !== undefined && !isNum(s[key])) return `${key} must be a number`;
+ return null;
+ }
if (s.region !== undefined) {
- if (typeof s.region !== 'string') return 'region must be an SVG path';
- try { parsePath(s.region); } catch (e) { return `region: ${(e as Error).message}`; }
+ if (typeof s.region !== 'string') return 'region must be an SVG path or "@id"';
+ if (!s.region.startsWith('@')) {
+ try { parsePath(s.region); } catch (e) { return `region: ${(e as Error).message}`; }
+ }
}
if (s.guides !== undefined && !(Array.isArray(s.guides) && s.guides.length > 0 && s.guides.every(isGuide))) return 'guides must be one or more lines, each two or more [x, y]';
if (s.angle !== undefined && !isNum(s.angle)) return 'angle must be degrees';
- const bad = checkFill(s.tone);
- if (bad) return `tone ${bad}`;
+ if (s.tone === undefined && !s.smudge) return 'needs a tone, unless it smudges';
+ if (s.tone !== undefined) {
+ const bad = checkFill(s.tone);
+ if (bad) return `tone ${bad}`;
+ }
for (const key of ['size', 'length', 'coverage']) {
if (s[key] !== undefined && !(isNum(s[key]) && (s[key] as number) > 0)) return `${key} must be positive`;
}
if (s.size === undefined) return 'needs a positive size';
if (s.spread !== undefined && !(isNum(s.spread) && (s.spread as number) >= 0)) return 'spread must be 0 or more degrees';
- return zeroToOne(['vary', 'opacity', 'hardness']);
+ return zeroToOne(['vary', 'opacity', 'hardness', 'smudge']);
}
function strokeProblem(s: Record<string, unknown>): string | null {
if (typeof s !== 'object' || s === null) return 'must be an object';
- if (s.type === 'sweep' || s.type === 'field') return markProblem(s);
- if (s.type !== undefined) return `has type "${String(s.type)}"; there are sweep and field, or none for one stroke`;
+ if (s.type === 'sweep' || s.type === 'field' || s.type === 'along') return markProblem(s);
+ if (s.type !== undefined) return `has type "${String(s.type)}"; there are sweep, field and along, or none for one stroke`;
for (const key of Object.keys(s)) if (!STROKE_FIELDS.includes(key)) return `has unknown field "${key}"; a stroke takes ${STROKE_FIELDS.join(', ')}`;
if (!Array.isArray(s.points) || s.points.length === 0 || !s.points.every((p) => Array.isArray(p) && (p.length === 2 || p.length === 3) && p.every(isNum))) return 'needs points, each [x, y] or [x, y, pressure]';
if (!(isNum(s.size) && (s.size as number) > 0)) return 'needs a positive size';
@@ -269,6 +313,8 @@ function checkLayer(l: Record<string, unknown>, where: string, ids: Set<string>)
break;
case 'paint': {
if (!Array.isArray(l.strokes)) fail('strokes must be an array, which may start empty');
+ if (l.from !== undefined && l.from !== 'below') fail('from must be "below"');
+ if (l.from !== undefined && (l.fill !== undefined || l.effects !== undefined || l.blend !== undefined)) fail('from "below" works on the picture itself, and takes no fill, effects or blend');
(l.strokes as Record<string, unknown>[]).forEach((s, n) => {
const bad = strokeProblem(s);
if (bad) fail(`stroke ${n} ${bad}`);
@@ -310,6 +356,7 @@ function checkLayer(l: Record<string, unknown>, where: string, ids: Set<string>)
if (s.cap !== undefined && !['round', 'butt', 'square'].includes(s.cap as string)) fail('stroke cap must be round, butt or square');
}
if (!['group', 'pixels', 'paint', 'line'].includes(l.shape as string) && l.fill === undefined && l.stroke === undefined && !l.erase) fail('it needs a fill or a stroke, or it draws nothing');
+ if (l.from !== undefined && l.shape !== 'paint') fail('from is for a paint layer');
if (l.blur !== undefined && !(isNum(l.blur) && (l.blur as number) >= 0)) fail('blur must be 0 or more, in pixels');
if (l.blur && l.erase) fail('blur does not go with erase; put what cuts in a group with what it cuts, and blur the group');
if (l.opacity !== undefined && !(isNum(l.opacity) && l.opacity >= 0 && l.opacity <= 1)) fail('opacity must be 0..1');
diff --git a/pipeline/tests/image-raster.test.ts b/pipeline/tests/image-raster.test.ts
index d4ba74a78..ef6fef056 100644
--- a/pipeline/tests/image-raster.test.ts
+++ b/pipeline/tests/image-raster.test.ts
@@ -2,7 +2,7 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/** A picture from layers: each draws what it says and where, edges are antialiased, and what is wrong with a source is said before anything is drawn. */
import { describe, expect, it } from 'vitest';
-import { imageSheet, parseColor, parsePath, renderImage, setSheet, zoomImage } from '../src/image/imageRaster';
+import { imageSheet, parseColor, parsePath, pickColors, renderImage, setSheet, valuesImage, zoomImage } from '../src/image/imageRaster';
import { applyImageEdits, strokeWidths, validateImageSource, type ImageLayer } from '../src/image/imageSource';
const draw = (layers: unknown[], size: number | [number, number] = 64, background?: string): ReturnType<typeof renderImage> => renderImage(validateImageSource({ size, layers, ...(background ? { background } : {}) }));
@@ -838,7 +838,7 @@ describe('marks that are many strokes', () => {
it('says what is wrong with one', () => {
const bad = (mark: object): unknown => validateImageSource({ size: 8, layers: [{ id: 'p', shape: 'paint', strokes: [mark] }] });
- expect(() => bad({ type: 'wash' })).toThrow(/stroke 0 has type "wash"; there are sweep and field/);
+ expect(() => bad({ type: 'wash' })).toThrow(/stroke 0 has type "wash"; there are sweep, field and along/);
expect(() => bad({ type: 'sweep', guides: [[[0, 0], [1, 1]]], colors: [RED], count: 3 })).toThrow(/two or more lines/);
expect(() => bad(sweep({ colors: [] }))).toThrow(/needs colors/);
expect(() => bad(sweep({ count: 0 }))).toThrow(/count must be/);
@@ -850,6 +850,122 @@ describe('marks that are many strokes', () => {
});
});
+describe('working across the picture', () => {
+ const halves: ImageLayer[] = [{ id: 'l', shape: 'rect', at: [0, 0], size: [32, 64], fill: RED }, { id: 'r', shape: 'rect', at: [32, 0], size: [32, 64], fill: BLUE }];
+ const smear = { points: [[8, 32], [56, 32]], size: 12, smudge: 0.9 };
+
+ it('a layer that starts from below drags colour from one layer across another', () => {
+ const img = draw([...halves, { shape: 'paint', from: 'below', strokes: [smear] } as never]);
+ expect(px(img, 42, 32)[0]).toBeGreaterThan(40);
+ expect(px(img, 42, 4)).toEqual([0, 0, 255, 255]);
+ });
+
+ it('without it a smudge sees only its own layer', () => {
+ const img = draw([...halves, { shape: 'paint', strokes: [smear] } as never]);
+ expect(px(img, 42, 32)).toEqual([0, 0, 255, 255]);
+ });
+
+ it('leaves the picture exactly as it was until it does something', () => {
+ const under = draw(halves);
+ const same = draw([...halves, { shape: 'paint', from: 'below', strokes: [] } as never]);
+ let worst = 0;
+ for (let i = 0; i < under.rgba.length; i++) worst = Math.max(worst, Math.abs(under.rgba[i]! - same.rgba[i]!));
+ expect(worst).toBeLessThanOrEqual(1);
+ });
+
+ it('does not thicken what is see-through, and keeps to its clip and opacity', () => {
+ const clear = draw([{ shape: 'rect', at: [0, 0], size: [64, 64], fill: '#ff000080' }, { shape: 'paint', from: 'below', strokes: [] } as never]);
+ expect(Math.abs(px(clear, 32, 32)[3]! - 128)).toBeLessThanOrEqual(1);
+ const clipped = draw([...halves, { id: 'c', shape: 'rect', at: [0, 0], size: [64, 20], fill: '#ffffff00' }, { shape: 'paint', from: 'below', clip: 'c', strokes: [{ points: [[0, 32], [64, 32]], size: 12, color: '#ffffff' }] } as never]);
+ expect(px(clipped, 10, 32)).toEqual([255, 0, 0, 255]);
+ const half = draw([...halves, { shape: 'paint', from: 'below', opacity: 0.5, strokes: [{ points: [[0, 32], [64, 32]], size: 12, color: '#ffffff', hardness: 1 }] } as never]);
+ expect(px(half, 10, 32)[1]).toBeGreaterThan(110);
+ expect(px(half, 10, 32)[1]).toBeLessThan(140);
+ });
+
+ it('a field of smudges softens a hard edge, and takes no colour of its own', () => {
+ const img = draw([...halves, { shape: 'paint', from: 'below', strokes: [{ type: 'field', smudge: 0.8, size: 10, length: 30, angle: 0, seed: 1 }] } as never]);
+ const mixed = new Set<number>();
+ for (let x = 22; x < 42; x++) mixed.add(px(img, x, 30)[0]!);
+ expect(mixed.size).toBeGreaterThan(4);
+ for (let i = 0; i < img.rgba.length; i += 4) expect(img.rgba[i + 1]).toBeLessThanOrEqual(1);
+ });
+
+ it('takes a region from a layer drawn before it, through a transform too', () => {
+ const blob: ImageLayer = { id: 'b', shape: 'circle', at: [64, 64], radius: 30, fill: '#00000000' };
+ const img = draw([blob, { shape: 'paint', strokes: [{ type: 'field', region: '@b', tone: RED, size: 3, length: 6, angle: 0, hardness: 1, opacity: 1, vary: 0, seed: 1 }] } as never], [128, 128]);
+ expect(px(img, 64, 64)[0]).toBe(255);
+ expect(px(img, 64, 20)[3]).toBe(0);
+ const moved = draw([{ ...blob, fill: '#00000001' }, { shape: 'paint', transform: { translate: [40, 0], origin: [0, 0] }, strokes: [{ type: 'field', region: '@b', tone: RED, size: 3, length: 6, angle: 0, hardness: 1, opacity: 1, vary: 0, seed: 1 }] } as never], [128, 128]);
+ expect(px(moved, 64, 64)[0]).toBe(255);
+ const none = draw([{ shape: 'paint', strokes: [{ type: 'field', region: '@nope', tone: RED, size: 3 }] } as never]);
+ expect(none.notes.join()).toMatch(/"@nope" names no layer/);
+ });
+
+ it('repeats strokes along a line, turned and sized to it, and reflected when asked', () => {
+ const feather = { points: [[0, 0], [10, 0]], color: RED, size: 2, hardness: 1 };
+ const along = (fields: object): ReturnType<typeof draw> => draw([{ shape: 'paint', strokes: [{ type: 'along', line: [[10, 32], [50, 32]], count: 5, strokes: [feather], ...fields }] } as never]);
+ expect(px(along({}), 15, 32)[0]).toBe(255);
+ const up = along({ turn: -90, count: 3 });
+ expect(px(up, 30, 25)[0]).toBe(255);
+ expect(px(up, 30, 39)[3]).toBe(0);
+ expect(px(along({ turn: -90, count: 3, both: true }), 30, 39)[0]).toBe(255);
+ expect(px(along({ turn: -90, count: 3, scale: [1, 3] }), 50, 8)[0]).toBe(255);
+ expect(() => validateImageSource({ size: 8, layers: [{ shape: 'paint', strokes: [{ type: 'along', line: [[0, 0], [1, 1]], count: 2, strokes: [{ type: 'field', tone: RED, size: 2 }] }] }] })).toThrow(/plain stroke/);
+ });
+
+ it('says when a sweep will be a flat band, and is quiet when it will not', () => {
+ const sweep = (guides: number[][][], count: number): string[] => draw([{ id: 's', shape: 'paint', strokes: [{ type: 'sweep', guides, colors: [RED], count }] } as never], [128, 128]).notes;
+ expect(sweep([[[10, 10], [100, 10]], [[10, 11], [100, 11]]], 40).join()).toMatch(/flat band/);
+ expect(sweep([[[10, 10], [10, 110]], [[90, 10], [90, 110]]], 160)).toEqual([]);
+ });
+
+ it('reports entries and strokes for each paint layer', () => {
+ const img = draw([{ id: 'p', shape: 'paint', strokes: [{ points: [[1, 1], [9, 9]], color: RED, size: 1 }, { type: 'sweep', guides: [[[10, 10], [10, 50]], [[50, 10], [50, 50]]], colors: [RED], count: 40 }] } as never]);
+ expect(img.painted.p).toEqual({ entries: 2, strokes: 41 });
+ });
+
+ it('refuses a gradient at one point, and a below layer with what it cannot take', () => {
+ const bad = (l: object): unknown => validateImageSource({ size: 8, layers: [l] });
+ expect(() => bad({ shape: 'rect', at: [0, 0], size: [8, 8], fill: { type: 'linear', from: [2, 2], to: [2, 2], stops: [[0, RED], [1, BLUE]] } })).toThrow(/from and to apart/);
+ expect(() => bad({ shape: 'paint', from: 'below', fill: RED, strokes: [] })).toThrow(/takes no fill/);
+ expect(() => bad({ shape: 'paint', from: 'above', strokes: [] })).toThrow(/from must be "below"/);
+ expect(() => bad({ shape: 'circle', at: [1, 1], radius: 1, fill: RED, from: 'below' })).toThrow(/for a paint layer/);
+ expect(() => bad({ shape: 'paint', strokes: [{ type: 'field', size: 3 }] })).toThrow(/needs a tone/);
+ });
+
+ it('shows lightness alone and reads a colour', () => {
+ const pic = draw(halves);
+ const v = valuesImage(pic);
+ expect(px(v as never, 10, 10)[0]).toBe(px(v as never, 10, 10)[1]);
+ expect(px(v as never, 10, 10)[0]).toBeGreaterThan(px(v as never, 50, 10)[0]!);
+ expect(pickColors(pic, [[10, 10], [50, 10]])).toEqual([{ at: [10, 10], color: '#ff0000', value: 0.21 }, { at: [50, 10], color: '#0000ff', value: 0.07 }]);
+ expect(() => pickColors(pic, [[90, 0]])).toThrow(/outside the picture/);
+ });
+
+ it('sees a large opaque picture large, and any other as before', () => {
+ const big = renderImage(validateImageSource({ size: [800, 450], layers: [{ shape: 'rect', at: [0, 0], size: [800, 450], fill: RED }] }));
+ expect(imageSheet(big).width).toBe(800 + 24 + 192);
+ expect(imageSheet(big).height).toBe(450 + 16);
+ const clear = renderImage(validateImageSource({ size: [800, 450], layers: [{ shape: 'circle', at: [400, 225], radius: 100, fill: RED }] }));
+ expect(imageSheet(clear).width).toBeLessThan(1300);
+ expect(imageSheet(clear).width).toBeGreaterThan(1000);
+ });
+
+ it('zooms what is large as far as it fits', () => {
+ const big = renderImage(validateImageSource({ size: [960, 540], layers: [{ shape: 'rect', at: [0, 0], size: [960, 540], fill: RED }] }));
+ expect(zoomImage(big, { x: 0, y: 0, w: 480, h: 270 }).width).toBe(960);
+ expect(zoomImage(big, { x: 0, y: 0, w: 960, h: 540 }).width).toBe(960);
+ });
+
+ it('has most of its noise in the middle, as the text says', () => {
+ const img = draw([{ shape: 'rect', at: [0, 0], size: [64, 64], fill: { type: 'noise', scale: 16, stops: [[0, '#000000'], [1, '#ffffff']] } as never }]);
+ const v = Array.from({ length: 64 * 64 }, (_, i) => img.rgba[i * 4]! / 255).sort((a, b) => a - b);
+ expect(v[Math.floor(v.length * 0.1)]).toBeGreaterThan(0.2);
+ expect(v[Math.floor(v.length * 0.9)]).toBeLessThan(0.8);
+ });
+});
+
describe('what it measures', () => {
it('finds where the picture is solid and how much of it that is', () => {
const img = draw([{ shape: 'rect', at: [10, 20], size: [16, 8], fill: RED }]);
@@ -901,7 +1017,7 @@ describe('a set and a close look', () => {
it('enlarges a part with hard pixels, on the check where it is clear', () => {
const half = draw([{ shape: 'rect', at: [10, 0], size: [54, 64], fill: RED }]);
- const big = zoomImage(half, { x: 8, y: 8, w: 4, h: 4 });
+ const big = zoomImage(half, { x: 8, y: 8, w: 4, h: 4 }, 640);
expect(big.width).toBe(640);
const at = (x: number, y: number): number[] => Array.from(big.rgba.subarray((y * big.width + x) * 4, (y * big.width + x) * 4 + 3));
// Two pixels of nothing and two of red, each 160 wide, and no blur between.
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 41e964a60..737eb6953 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -3888,6 +3888,10 @@ export const NOTED = {
{"note":"An AI can draw 2D pictures."},
"feat(look): layers moved and wrapped, one pixel changed, a set and a close look drawn":
{"note":"An AI can draw 2D pictures."},
+ "feat(look): painting across the picture, strokes along a line, values and colours read":
+ {"note":"An AI can draw 2D pictures."},
+ "feat(mcp): image_read shows values and picks colours; the painting text in full":
+ {"note":"An AI can draw 2D pictures."},
"fix(look): a dab with a taper drew nothing":
{"internal":"the paint layer it fixes has not been released"},
"feat(look): one instruction, many strokes: sweep for hair, field for a region":