Code-first video & image, rendered natively on WebGPU.
feat(3d): geometry outlines and toon lighting; overflow visible by default
okanasl976c78275136
diff --git a/.changeset/overflow-visible-default.md b/.changeset/overflow-visible-default.mdnew file mode 100644index 00000000..f06d0fb5--- /dev/null+++ b/.changeset/overflow-visible-default.md@@ -0,0 +1,7 @@+---+"@framefields/compositions": minor+"@framefields/node-compositor": minor+"framefields": minor+---++Containers no longer clip their children by default: `overflow` defaults to `"visible"`, as in CSS, so tilted badges, outside strokes and shaking titles are not cut at a parent's edge. Set `overflow: "hidden"` where children must stay inside a box, such as a rounded card holding a square header or image. Text layers also make room for their own outside stroke and shadows, which used to be cut at the text box, and scale or rotate around their anchor within that room.diff --git a/.changeset/spatial-styling.md b/.changeset/spatial-styling.mdnew file mode 100644index 00000000..0c62b8f2--- /dev/null+++ b/.changeset/spatial-styling.md@@ -0,0 +1,11 @@+---+"@framefields/core": minor+"@framefields/compositions": minor+"@framefields/webgpu-renderers": minor+"@framefields/node-compositor": minor+"framefields": minor+---++Add opt-in geometry-aware scene outlines and art-directed toon lighting for meshes, 3D cards and native text. Outline widths scale with export resolution; exclusions retain occlusion, and ink follows fog before camera depth blur and bloom. Toon materials now use colored direct lights, point/spot attenuation and cast shadows, with configurable shadow/lit colors and terminators. Correct 3D card pivot transforms so changing an anchor does not move identity geometry.++Shade ink before the MSAA color resolve to preserve subpixel coverage between outlined surfaces. Custom cube-face artwork inherits surface settings while retaining explicit face overrides.diff --git a/.gitignore b/.gitignoreindex baf00440..7ff4e1bf 100644--- a/.gitignore+++ b/.gitignore@@ -97,3 +97,7 @@ packages/**/models/# Generated package README, built from the repo root README (scripts/sync-readme.mjs)packages/framefields/README.md++# Local examples, not tracked+examples/34_spatial_styling/+examples/35_robot_uprising/diff --git a/examples/19_framefields_film/src/scenes/effects.ts b/examples/19_framefields_film/src/scenes/effects.tsindex 01abe39d..9aedc521 100644--- a/examples/19_framefields_film/src/scenes/effects.ts+++ b/examples/19_framefields_film/src/scenes/effects.ts@@ -13,8 +13,28 @@ import {LayerAnimation,Vignette,} from "framefields";-import { CODE_FROM, CODE_TO, DANCER_TRIM_SEC, EMBER_STOPS, HALFTONE, PREVIEW_CLIP_START } from "./code.js";-import { EASE_OUT, EMBER, FPS, H, INK, PAPER, SANS, W, asset, beats, headline, scene } from "../theme.js";+import {+ asset,+ beats,+ EASE_OUT,+ EMBER,+ FPS,+ H,+ headline,+ INK,+ PAPER,+ SANS,+ scene,+ W,+} from "../theme.js";+import {+ CODE_FROM,+ CODE_TO,+ DANCER_TRIM_SEC,+ EMBER_STOPS,+ HALFTONE,+ PREVIEW_CLIP_START,+} from "./code.js";export const EFFECTS_FROM = CODE_TO;export const EFFECTS_TO = EFFECTS_FROM + beats(6);@@ -26,8 +46,18 @@ const warm = (c: Clip): Clip =>c.apply(new Curves({- master: [{ x: 0, y: 0.02 }, { x: 0.25, y: 0.18 }, { x: 0.5, y: 0.5 }, { x: 0.75, y: 0.82 }, { x: 1, y: 0.98 }],- blue: [{ x: 0, y: 0 }, { x: 0.5, y: 0.47 }, { x: 1, y: 0.93 }],+ master: [+ { x: 0, y: 0.02 },+ { x: 0.25, y: 0.18 },+ { x: 0.5, y: 0.5 },+ { x: 0.75, y: 0.82 },+ { x: 1, y: 0.98 },+ ],+ blue: [+ { x: 0, y: 0 },+ { x: 0.5, y: 0.47 },+ { x: 1, y: 0.93 },+ ],}),).apply(new ColorBalance({ midtones: { cyanRed: 8, yellowBlue: -12 } }));@@ -38,7 +68,17 @@ const FIRE_STOPS = [{ position: 1, color: PAPER },];-function clip(id: string, file: string, trimStartSec: number, frame: { x: number; y: number; w: number; h: number } = { x: 0, y: 0, w: W, h: H }): Clip {+function clip(+ id: string,+ file: string,+ trimStartSec: number,+ frame: { x: number; y: number; w: number; h: number } = {+ x: 0,+ y: 0,+ w: W,+ h: H,+ },+): Clip {return Layer.video(asset(file), {id,position: "absolute",@@ -69,7 +109,13 @@ function shot(id: string, from: number, to: number, children: unknown[]) {}/** Effect name chip (bottom-left by default): solid enough to read over any plate. */-function chip(id: string, name: string, from: number, to: number, at = { x: 96, y: H - 96 - 56 }) {+function chip(+ id: string,+ name: string,+ from: number,+ to: number,+ at = { x: 96, y: H - 96 - 56 },+) {const len = to - from;const anim = LayerAnimation.create().fadeIn(0, 6, "power2.out")@@ -77,6 +123,7 @@ function chip(id: string, name: string, from: number, to: number, at = { x: 96,if (len > 12) anim.fadeOut(len - 6, len, "power2.in");return Layer.flex({+ overflow: "hidden",id,position: "absolute",x: at.x,@@ -94,20 +141,46 @@ function chip(id: string, name: string, from: number, to: number, at = { x: 96,startFrame: from,durationFrames: len,children: [- Layer.box({ id: `${id}-dot`, width: 8, height: 8, borderRadius: 4, background: EMBER }),- Layer.text(name.toUpperCase(), { id: `${id}-t`, fontFamily: SANS, fontSize: 20, fontWeight: 500, letterSpacing: 4, fill: PAPER }),+ Layer.box({+ id: `${id}-dot`,+ width: 8,+ height: 8,+ borderRadius: 4,+ background: EMBER,+ }),+ Layer.text(name.toUpperCase(), {+ id: `${id}-t`,+ fontFamily: SANS,+ fontSize: 20,+ fontWeight: 500,+ letterSpacing: 4,+ fill: PAPER,+ }),],}).animate(anim);}export function effectsScene() {// Continue the code preview exactly where it was when it hit full frame.- const dancerIn = DANCER_TRIM_SEC + (CODE_TO - CODE_FROM - PREVIEW_CLIP_START) / FPS;+ const dancerIn =+ DANCER_TRIM_SEC + (CODE_TO - CODE_FROM - PREVIEW_CLIP_START) / FPS;// One beat per idea: halftone (0..45), pure smoke (36..72), the wall (63..108).const A = shot("fx-a", 0, 45, [- clip("fx-a-clip", "dancer.mp4", dancerIn).apply(new HalftoneScreen(HALFTONE)).apply(new GradientMap({ stops: EMBER_STOPS })),- headline({ id: "fx-title", text: "Transform it.", x: 96, y: 96, width: 1200, size: 124, color: INK, inAt: 4, outAt: 28 }),+ clip("fx-a-clip", "dancer.mp4", dancerIn)+ .apply(new HalftoneScreen(HALFTONE))+ .apply(new GradientMap({ stops: EMBER_STOPS })),+ headline({+ id: "fx-title",+ text: "Transform it.",+ x: 96,+ y: 96,+ width: 1200,+ size: 124,+ color: INK,+ inAt: 4,+ outAt: 28,+ }),]).animate(LayerAnimation.create().fadeOut(36, 44, "power2.inOut"));// Smoke blooms out of the fading dancer, stands alone for the gradient map,@@ -133,8 +206,9 @@ export function effectsScene() {durationFrames: smokeDur,blendMode: "screen",children: [- clip("fx-b-clip", "ink.mp4", 3.1)- .apply(new GradientMap({ stops: FIRE_STOPS })),+ clip("fx-b-clip", "ink.mp4", 3.1).apply(+ new GradientMap({ stops: FIRE_STOPS }),+ ),],}).animate(smokeAnim);@@ -143,16 +217,45 @@ export function effectsScene() {const cw = (W - GAP * 3) / 2;const ch = (H - GAP * 3) / 2;const cells: { name: string; title: string; fx: (c: Clip) => Clip }[] = [- { name: "grade", title: "Graded", fx: (c) => warm(c).apply(new Vignette({ strength: 0.4 })) },- { name: "halftone", title: "Halftone", fx: (c) => c.apply(new HalftoneScreen(HALFTONE)) },- { name: "map", title: "Gradient map", fx: (c) => c.apply(new GradientMap({ stops: FIRE_STOPS })) },+ {+ name: "grade",+ title: "Graded",+ fx: (c) => warm(c).apply(new Vignette({ strength: 0.4 })),+ },+ {+ name: "halftone",+ title: "Halftone",+ fx: (c) => c.apply(new HalftoneScreen(HALFTONE)),+ },+ {+ name: "map",+ title: "Gradient map",+ fx: (c) => c.apply(new GradientMap({ stops: FIRE_STOPS })),+ },{name: "bleach",title: "Bleach bypass",fx: (c) =>c- .apply(new GradientMap({ stops: [{ position: 0, color: INK }, { position: 1, color: PAPER }], opacity: 0.6 }))- .apply(new Curves({ master: [{ x: 0, y: 0 }, { x: 0.3, y: 0.16 }, { x: 0.7, y: 0.86 }, { x: 1, y: 1 }] }))+ .apply(+ new GradientMap({+ stops: [+ { position: 0, color: INK },+ { position: 1, color: PAPER },+ ],+ opacity: 0.6,+ }),+ )+ .apply(+ new Curves({+ master: [+ { x: 0, y: 0 },+ { x: 0.3, y: 0.16 },+ { x: 0.7, y: 0.86 },+ { x: 1, y: 1 },+ ],+ }),+ ).apply(new FilmGrain({ strength: 45, size: 1.6 })),},];@@ -164,6 +267,7 @@ export function effectsScene() {const x = GAP + (i % 2) * (cw + GAP);const y = GAP + Math.floor(i / 2) * (ch + GAP);return Layer.box({+ overflow: "hidden",id: `fx-e-cell-${name}`,position: "absolute",x,@@ -172,13 +276,24 @@ export function effectsScene() {height: ch,borderRadius: 10,children: [- fx(clip(`fx-e-${name}`, "dancer.mp4", 1.0, { x: 0, y: 0, w: cw, h: ch })),+ fx(+ clip(`fx-e-${name}`, "dancer.mp4", 1.0, {+ x: 0,+ y: 0,+ w: cw,+ h: ch,+ }),+ ),chip(`fx-e-tag-${name}`, title, i * 4 + 6, 45, { x: 20, y: 20 }),],}).animate(LayerAnimation.create().fadeIn(i * 4, i * 4 + 3)- .fromTo("scale", 1.12, 1, { start: i * 4, end: i * 4 + 16, ease: EASE_OUT }),+ .fromTo("scale", 1.12, 1, {+ start: i * 4,+ end: i * 4 + 16,+ ease: EASE_OUT,+ }),);}),);diff --git a/examples/19_framefields_film/src/scenes/grade.ts b/examples/19_framefields_film/src/scenes/grade.tsindex 743974cf..b8161dec 100644--- a/examples/19_framefields_film/src/scenes/grade.ts+++ b/examples/19_framefields_film/src/scenes/grade.ts@@ -3,21 +3,28 @@* grade on top. An ember split-line sweeps across with the riser while the RGB* curve draws itself in the corner — the grade lands on the downbeat.*/-import { ColorBalance, Curves, GradientMap, Layer, LayerAnimation, Vignette } from "framefields";import {+ ColorBalance,+ Curves,+ GradientMap,+ Layer,+ LayerAnimation,+ Vignette,+} from "framefields";+import {+ asset,+ chapter,EASE_OUT,EMBER,H,- PAPER,- STONE,- W,- asset,- chapter,headline,keys,label,+ PAPER,+ STONE,scene,scrim,+ W,} from "../theme.js";export const GRADE_FROM = 198;@@ -37,10 +44,19 @@ const WIPE_END = WIPE[WIPE.length - 1][0];/** Everything that rides the line shares one track. */const wipe = (offset = 0, prop: "x" | "width" = "x") =>- keys(prop, WIPE.map(([f, u, e]) => [f, offset + u * W, e] as [number, number, string?]));+ keys(+ prop,+ WIPE.map(+ ([f, u, e]) => [f, offset + u * W, e] as [number, number, string?],+ ),+ );/** Slow push shared by both passes so they stay pixel-aligned. */-const push = () => keys("scale", [[0, 1.0], [GRADE_TO - GRADE_FROM, 1.05, "sine.inOut"]]);+const push = () =>+ keys("scale", [+ [0, 1.0],+ [GRADE_TO - GRADE_FROM, 1.05, "sine.inOut"],+ ]);function plate(id: string) {return Layer.video(asset("portrait.mp4"), {@@ -58,15 +74,41 @@ function plate(id: string) {export function gradeScene() {const log = plate("grade-log")- .apply(new GradientMap({ stops: [{ position: 0, color: "#000000" }, { position: 1, color: "#FFFFFF" }], opacity: 0.6 }))- .apply(new Curves({ master: [{ x: 0, y: 0.13 }, { x: 0.5, y: 0.52 }, { x: 1, y: 0.84 }] }))+ .apply(+ new GradientMap({+ stops: [+ { position: 0, color: "#000000" },+ { position: 1, color: "#FFFFFF" },+ ],+ opacity: 0.6,+ }),+ )+ .apply(+ new Curves({+ master: [+ { x: 0, y: 0.13 },+ { x: 0.5, y: 0.52 },+ { x: 1, y: 0.84 },+ ],+ }),+ ).animate(push());const graded = plate("grade-final").apply(new Curves({- master: [{ x: 0, y: 0.02 }, { x: 0.25, y: 0.17 }, { x: 0.5, y: 0.5 }, { x: 0.75, y: 0.83 }, { x: 1, y: 0.98 }],- blue: [{ x: 0, y: 0 }, { x: 0.5, y: 0.47 }, { x: 1, y: 0.93 }],+ master: [+ { x: 0, y: 0.02 },+ { x: 0.25, y: 0.17 },+ { x: 0.5, y: 0.5 },+ { x: 0.75, y: 0.83 },+ { x: 1, y: 0.98 },+ ],+ blue: [+ { x: 0, y: 0 },+ { x: 0.5, y: 0.47 },+ { x: 1, y: 0.93 },+ ],}),).apply(@@ -119,17 +161,49 @@ export function gradeScene() {inAt: 6,outAt: 90,}),- ...chapter({ id: "grade-ch", index: "02", name: "Color", color: PAPER, accent: PAPER, inAt: 12, outAt: 92 }),+ ...chapter({+ id: "grade-ch",+ index: "02",+ name: "Color",+ color: PAPER,+ accent: PAPER,+ inAt: 12,+ outAt: 92,+ }),curvesCard(),],});}/** A caption glued to the split-line. */-function rider(id: string, text: string, offset: number, align: "start" | "end", inAt: number) {- const node = label({ id, text, x: offset, y: 88, width: 300, align, color: PAPER, inAt, outAt: WIPE_END - 6 });- return Layer.box({ id: `${id}-rail`, position: "absolute", x: 0, y: 0, width: W, height: 140, overflow: "visible", children: [node] })- .animate(wipe(0));+function rider(+ id: string,+ text: string,+ offset: number,+ align: "start" | "end",+ inAt: number,+) {+ const node = label({+ id,+ text,+ x: offset,+ y: 88,+ width: 300,+ align,+ color: PAPER,+ inAt,+ outAt: WIPE_END - 6,+ });+ return Layer.box({+ id: `${id}-rail`,+ position: "absolute",+ x: 0,+ y: 0,+ width: W,+ height: 140,+ overflow: "visible",+ children: [node],+ }).animate(wipe(0));}/** RGB curve readout: the neutral log line, then the S-curve drawing in with the wipe. */@@ -141,10 +215,27 @@ function curvesCard() {const y = H - 96 - size;// Strokes are clipped to their layer, so curve layers get a little bleed.const bleed = 6;- const pt = (u: number, v: number) => `${(bleed + u * plot).toFixed(1)} ${(bleed + (1 - v) * plot).toFixed(1)}`;+ const pt = (u: number, v: number) =>+ `${(bleed + u * plot).toFixed(1)} ${(bleed + (1 - v) * plot).toFixed(1)}`;const grid = [0.25, 0.5, 0.75].flatMap((t, i) => [- Layer.shape("rect", { id: `grade-grid-v${i}`, position: "absolute", x: pad + t * plot, y: pad, width: 1, height: plot, fillColor: "rgba(238,233,224,0.10)" }),- Layer.shape("rect", { id: `grade-grid-h${i}`, position: "absolute", x: pad, y: pad + t * plot, width: plot, height: 1, fillColor: "rgba(238,233,224,0.10)" }),+ Layer.shape("rect", {+ id: `grade-grid-v${i}`,+ position: "absolute",+ x: pad + t * plot,+ y: pad,+ width: 1,+ height: plot,+ fillColor: "rgba(238,233,224,0.10)",+ }),+ Layer.shape("rect", {+ id: `grade-grid-h${i}`,+ position: "absolute",+ x: pad,+ y: pad + t * plot,+ width: plot,+ height: 1,+ fillColor: "rgba(238,233,224,0.10)",+ }),]);const curve = (id: string, d: string, color: string, width: number) =>Layer.shape("path", {@@ -162,6 +253,7 @@ function curvesCard() {});return Layer.box({+ overflow: "hidden",id: "grade-card",position: "absolute",x,@@ -175,9 +267,12 @@ function curvesCard() {children: [...grid,curve("grade-curve-log", `M${pt(0, 0.13)} L${pt(1, 0.84)}`, STONE, 2),- curve("grade-curve-s", `M${pt(0, 0.02)} C${pt(0.42, 0.0)} ${pt(0.58, 1.0)} ${pt(1, 0.98)}`, EMBER, 3).animate(- keys("trimEnd", WIPE),- ),+ curve(+ "grade-curve-s",+ `M${pt(0, 0.02)} C${pt(0.42, 0.0)} ${pt(0.58, 1.0)} ${pt(1, 0.98)}`,+ EMBER,+ 3,+ ).animate(keys("trimEnd", WIPE)),],}).animate(LayerAnimation.create()diff --git a/examples/22_framefields_launch/src/scenes/tools.ts b/examples/22_framefields_launch/src/scenes/tools.tsindex 4b545e5d..099f5797 100644--- a/examples/22_framefields_launch/src/scenes/tools.ts+++ b/examples/22_framefields_launch/src/scenes/tools.ts@@ -105,6 +105,7 @@ function tile(const { x, y } = slot(i);return [Layer.box({+ overflow: "hidden",id: `tools-tile-${i}`,position: "absolute",x: x - TILE / 2,@@ -203,6 +204,7 @@ export function toolsScene() {outAt: light.at - from - 6,}),Layer.box({+ overflow: "hidden",id: "tools-import",position: "absolute",x: CX - 520,diff --git a/examples/22_framefields_launch/src/scenes/world.ts b/examples/22_framefields_launch/src/scenes/world.tsindex 019d224a..b71a3364 100644--- a/examples/22_framefields_launch/src/scenes/world.ts+++ b/examples/22_framefields_launch/src/scenes/world.ts@@ -281,6 +281,7 @@ function carousel(at: number, len: number) {faceInward: true,items: CARDS.map((name, i) =>Layer.box({+ overflow: "hidden",id: `world-card-${i}`,width: 420,height: 280,diff --git a/examples/24_audio_capabilities/src/audio-pipeline.ts b/examples/24_audio_capabilities/src/audio-pipeline.tsindex fa072d62..f55cfb8b 100644--- a/examples/24_audio_capabilities/src/audio-pipeline.ts+++ b/examples/24_audio_capabilities/src/audio-pipeline.ts@@ -26,6 +26,7 @@ function createCard(title: string, subtitle: string, badge: string) {gap: 20,children: [Layer.box({+ overflow: "hidden",padding: 16,background: "#1e232d",borderRadius: 20,diff --git a/examples/29_capabilities_reel/src/scenes/finale.ts b/examples/29_capabilities_reel/src/scenes/finale.tsindex d1017bb4..39bdeeca 100644--- a/examples/29_capabilities_reel/src/scenes/finale.ts+++ b/examples/29_capabilities_reel/src/scenes/finale.ts@@ -230,6 +230,7 @@ export async function finaleScene(): Promise<Node> {]),),Layer.box({+ overflow: "hidden",id: "finale-install",position: "absolute",x: CX - 250,diff --git a/examples/29_capabilities_reel/src/scenes/fluid.ts b/examples/29_capabilities_reel/src/scenes/fluid.tsindex 6ea4cfd5..e4610f8f 100644--- a/examples/29_capabilities_reel/src/scenes/fluid.ts+++ b/examples/29_capabilities_reel/src/scenes/fluid.ts@@ -66,6 +66,7 @@ function panel(children: [...children,Layer.box({+ overflow: "hidden",position: "absolute",x: 16,y: h - 50,diff --git a/examples/29_capabilities_reel/src/scenes/nodes.ts b/examples/29_capabilities_reel/src/scenes/nodes.tsindex 76f19897..9d9a6309 100644--- a/examples/29_capabilities_reel/src/scenes/nodes.ts+++ b/examples/29_capabilities_reel/src/scenes/nodes.ts@@ -255,6 +255,7 @@ export function nodesScene(): Node {trimStartSec: 1 + at / 30,}).withEffects(fx as never),Layer.box({+ overflow: "hidden",position: "absolute",x: 70,y: 70,diff --git a/examples/29_capabilities_reel/src/scenes/stylize.ts b/examples/29_capabilities_reel/src/scenes/stylize.tsindex ef0d0ed5..536246f6 100644--- a/examples/29_capabilities_reel/src/scenes/stylize.ts+++ b/examples/29_capabilities_reel/src/scenes/stylize.ts@@ -144,6 +144,7 @@ export function stylizeScene(): Node {]),),Layer.box({+ overflow: "hidden",position: "absolute",x: 12,y: TH - 44,diff --git a/examples/30_product_demo/src/film.ts b/examples/30_product_demo/src/film.tsindex 88ea5988..f327d5bc 100644--- a/examples/30_product_demo/src/film.ts+++ b/examples/30_product_demo/src/film.ts@@ -78,6 +78,7 @@ function lockup(at: number): LayoutNode {startFrame: at,children: [Layer.box({+ overflow: "hidden",position: "absolute",x: W / 2 - mark / 2,y: H / 2 - 120,diff --git a/examples/30_product_demo/src/ui.ts b/examples/30_product_demo/src/ui.tsindex 2a0210be..e732b446 100644--- a/examples/30_product_demo/src/ui.ts+++ b/examples/30_product_demo/src/ui.ts@@ -147,6 +147,7 @@ function sidebar(t: Timeline): LayoutNode {];const children: LayoutNode[] = [Layer.box({+ overflow: "hidden",position: "absolute",x: 24,y: 24,@@ -204,6 +205,7 @@ function sidebar(t: Timeline): LayoutNode {});children.push(Layer.box({+ overflow: "hidden",position: "absolute",x: 24,y: CH - 64,@@ -256,6 +258,7 @@ function sidebar(t: Timeline): LayoutNode {function header(t: Timeline): LayoutNode[] {const at = t.loaded;const deploy = Layer.box({+ overflow: "hidden",id: "deploy-button",position: "absolute",...DEPLOY_BUTTON,@@ -298,6 +301,7 @@ function header(t: Timeline): LayoutNode[] {rise(60, at + 2),),Layer.box({+ overflow: "hidden",position: "absolute",...VISIT_BUTTON,borderRadius: 11,@@ -512,6 +516,7 @@ const ROWS: Row[] = [function pill(label: string, color: string, x: number, y: number, w = 96) {return Layer.box({+ overflow: "hidden",position: "absolute",x,y,@@ -615,6 +620,7 @@ function table(t: Timeline): LayoutNode {]),);const promote = Layer.box({+ overflow: "hidden",id: "promote-button",position: "absolute",x: PROMOTE_BUTTON.x - TABLE.x,@@ -649,6 +655,7 @@ function table(t: Timeline): LayoutNode {.animate(press(t.promoteDown, t.promoteUp));// Promoting swaps the Ready pill for a Production badge in its place.const production = Layer.box({+ overflow: "hidden",position: "absolute",x: statusX - 20,y: (ROW_H - 28) / 2,@@ -747,6 +754,7 @@ function toast(t: Timeline): LayoutNode {const show = t.promoteUp + sec(0.3);const hide = show + sec(2.6);return Layer.box({+ overflow: "hidden",position: "absolute",x,y,diff --git a/examples/32_relay/src/titles.ts b/examples/32_relay/src/titles.tsindex fbf249a1..afbc649b 100644--- a/examples/32_relay/src/titles.ts+++ b/examples/32_relay/src/titles.ts@@ -96,6 +96,7 @@ export function opening(fly: number, landed: number, row: Rect): LayoutNode[] {);const card = raise(Layer.box({+ overflow: "hidden",position: "absolute",x,y,diff --git a/examples/32_relay/src/ui/board.ts b/examples/32_relay/src/ui/board.tsindex 06fa5a1c..948aceba 100644--- a/examples/32_relay/src/ui/board.ts+++ b/examples/32_relay/src/ui/board.ts@@ -58,6 +58,7 @@ function card(c: Card, x: number, y: number, contents?: LayerAnimation) {];return raise(Layer.box({+ overflow: "hidden",position: "absolute",x,y,@@ -93,6 +94,7 @@ function header(): LayoutNode[] {[MAYA, LEO, AVA].forEach((p, i) => {nodes.push(Layer.box({+ overflow: "hidden",position: "absolute",x: CW - space(4) - 28 - (2 - i) * 22 - 2,y: 22,diff --git a/examples/32_relay/src/ui/brand.ts b/examples/32_relay/src/ui/brand.tsindex 6bfcb971..868f62eb 100644--- a/examples/32_relay/src/ui/brand.ts+++ b/examples/32_relay/src/ui/brand.ts@@ -50,6 +50,7 @@ export function relayMark(o: {);}return Layer.box({+ overflow: "hidden",...(o.id && { id: o.id }),position: "absolute",x: o.x,diff --git a/examples/32_relay/src/ui/inbox.ts b/examples/32_relay/src/ui/inbox.tsindex 7367f215..e7930c34 100644--- a/examples/32_relay/src/ui/inbox.ts+++ b/examples/32_relay/src/ui/inbox.ts@@ -196,6 +196,7 @@ function button(glyph: "plus" | "reply",) {return Layer.box({+ overflow: "hidden",position: "absolute",...r,borderRadius: space(1),diff --git a/examples/32_relay/src/ui/kit.ts b/examples/32_relay/src/ui/kit.tsindex 01f66a35..4c7deb24 100644--- a/examples/32_relay/src/ui/kit.ts+++ b/examples/32_relay/src/ui/kit.ts@@ -137,6 +137,7 @@ export interface Person {export function avatar(p: Person, o: { x: number; y: number; size: number }) {return Layer.box({+ overflow: "hidden",position: "absolute",x: o.x,y: o.y,diff --git a/examples/32_relay/src/ui/sidebar.ts b/examples/32_relay/src/ui/sidebar.tsindex b6de70da..681765ac 100644--- a/examples/32_relay/src/ui/sidebar.ts+++ b/examples/32_relay/src/ui/sidebar.ts@@ -61,6 +61,7 @@ function row(function unreadBadge(t: Timeline): LayoutNode {const size = 20;return Layer.box({+ overflow: "hidden",position: "absolute",x: ROW_X + ROW_W - space(1.5) - size,y: NAV_Y + (ROW_H - size) / 2,@@ -119,6 +120,7 @@ export function sidebar(t: Timeline): LayoutNode {text("Fieldwork", { x: 60, y: 25, size: 15, strong: true }),icon("chevron", { x: 140, y: 27, size: 16 }),Layer.box({+ overflow: "hidden",position: "absolute",x: space(2),y: 64,diff --git a/examples/32_relay/src/ui/task-modal.ts b/examples/32_relay/src/ui/task-modal.tsindex 0340eb44..d6f7e60c 100644--- a/examples/32_relay/src/ui/task-modal.ts+++ b/examples/32_relay/src/ui/task-modal.ts@@ -74,6 +74,7 @@ function field(): LayoutNode[] {const nodes: LayoutNode[] = [Layer.box({+ overflow: "hidden",position: "absolute",...r,borderRadius: space(1),@@ -202,6 +203,7 @@ function checklist(t: Timeline): LayoutNode[] {}).animate(rise(y, checklistItemAt(t, i), 8, sec(0.35)));});const add = Layer.box({+ overflow: "hidden",position: "absolute",...ADD_CHECKLIST,borderRadius: space(1),@@ -235,6 +237,7 @@ function footer(t: Timeline): LayoutNode[] {return [rule(0, FOOTER_Y, MODAL.width, { color: LINE }),Layer.box({+ overflow: "hidden",position: "absolute",...CANCEL_BUTTON,borderRadius: space(1),@@ -252,6 +255,7 @@ function footer(t: Timeline): LayoutNode[] {],}),Layer.box({+ overflow: "hidden",position: "absolute",...SAVE_BUTTON,borderRadius: space(1),@@ -283,6 +287,7 @@ function menu(const highlight = local(optionIn(r, hover.index));return raise(Layer.box({+ overflow: "hidden",position: "absolute",...r,anchorY: 0,@@ -398,6 +403,7 @@ export function taskModal(t: Timeline): LayoutNode[] {rule(0, 72, MODAL.width, { color: LINE }),text(REQUEST.subject, { x: PAD, y: 92, size: 26, strong: true }),Layer.box({+ overflow: "hidden",position: "absolute",x: PAD,y: 136,@@ -437,6 +443,7 @@ export function taskModal(t: Timeline): LayoutNode[] {);const modal = raise(Layer.box({+ overflow: "hidden",id: "task-modal",position: "absolute",...MODAL,diff --git a/examples/33_news_explainer/src/paper.ts b/examples/33_news_explainer/src/paper.tsindex 603800ec..cc5d92aa 100644--- a/examples/33_news_explainer/src/paper.ts+++ b/examples/33_news_explainer/src/paper.ts@@ -219,6 +219,7 @@ export function stamp(o: {const size = o.fontSize ?? 30;const pad = size * 0.45;return Layer.box({+ overflow: "hidden",id: o.id,position: "absolute",x: o.x,diff --git a/nodes/node-compositor/SKILL.md b/nodes/node-compositor/SKILL.mdindex 2094abb8..e6302c9c 100644--- a/nodes/node-compositor/SKILL.md+++ b/nodes/node-compositor/SKILL.md@@ -105,7 +105,7 @@ Container styles (flex/block/box with children):- **`justify`** (flex only): `start` (default) | `center` | `end` | `space-between` | `space-around`.- **`align`** (flex/block): `start` (default) | `center` | `end` | `stretch`.- **`wrap`** (flex only, boolean): Allow main-axis wrapping.-- **`overflow`** (`"hidden"` (default) | `"visible"`): Clip children to container bounds (`hidden`) or allow drawing outside (`visible`). A hidden container with a `borderRadius` clips to its rounded corners, animated radius and size included (an iris mask is a box closing its `width`, `height` and `borderRadius`).+- **`overflow`** (`"visible"` (default) | `"hidden"`): Children draw past the container's edges unless it is `hidden`, which clips them to its bounds (a rounded card that must keep a square header or image inside its corners needs `hidden`). A text node's own outside stroke and shadows are never cut at its box. A hidden container with a `borderRadius` clips to its rounded corners, animated radius and size included (an iris mask is a box closing its `width`, `height` and `borderRadius`).- **`staggerFrames`** (number, optional, default 0): Automatic frame offset sequentially applied to child nodes.- **`staggerDirection`** (`"forward"` | `"reverse"` | `"center-out"`, default `"forward"`): Traversal order when computing child stagger delays.@@ -212,6 +212,9 @@ Each track represents animatable property modifications:- **Audio-Reactive 3D Models:** a `kind: "model3d"` node loading an OBJ/FBX/GLTF/STL/PLY mesh with `audioDeform: { audioTrackId, mode: "normal_extrusion" | "radial_pulse" | "harmonic_wave" | "twist" | "ripple", amplitudeMultiplier, damping }`, deformed directly in VRAM via WebGPU compute shaders driven by audio frequency spectra and transient energies. `twist` turns each slice about Y by its height (harder on the bass); `ripple` runs concentric waves across XY, struck by the drums. `audioTrackId` may be an audio layer's id or an audio file path.- **Several 3D scenes:** a `box`/`flex`/`block` with a numeric `width` and `height` that holds a `camera` and the layers it films renders as its own scene (one holding only a camera stays a shot in a camera cut list): a nested composition with only its own camera, lights and environment, on its own clock (children start from the box's frame 0), placed in its parent like a media layer. Transitions, opacity and mattes on the box then blend finished pictures. Without that, every 3D layer shares one world and the active camera (the latest to start).- **3D scene capacity:** direct lights and skin joints use dynamically sized GPU storage; directional and spot lights can each cast shadows, up to the device texture-array layer limit.+- **Art-directed 3D lighting:** `material: "toon"` on meshes, flat 3D cards and native 3D text uses the shared direct lights, colors, point/spot attenuation, cast shadows, environment fog and tone mapping. Optional `toon: { shadowColor, lightColor, threshold, softness, diffuse }` controls the shadow/lit albedo multipliers, terminator cosine/width and Lambert modelling (defaults: model shade color or `#80808c`, white, 0.075, 0.25, 0). Lit/physical materials retain their own shading.+- **Geometry outlines:** an environment light's optional `outlines: true | { color, width, referenceHeight, creaseAngle, depthThreshold, opacity }` runs a depth/normal ink pass before camera depth blur and bloom (defaults: `#16131c`, 1.5 px at height 1080, 45°, 0.01, 1). It reuses the linear-depth attachment's spare channels for octahedral surface normals and outline participation. Inverse-depth curvature avoids false contours on perspective planes; normal discontinuities find creases without inking texture/shadow/triangulation seams. `outline: false` on a layer/model opts out while retaining depth occlusion; `creaseAngle: 180` disables creases. Ink fades into the environment fog. 3D `anchorX/Y` pivots remain fixed under scale/rotation and leave identity placement unchanged.+ With MSAA enabled, retain original scene color and geometry samples and shade ink per sample before resolving color. A single-sample ink pass after the scene resolve loses subpixel coverage between outlined surfaces. Lens blur uses a separate nearest-sample geometry resolve. The scene's geometry is still drawn once.- **Transparent meshes:** glTF `BLEND` materials and meshes with reduced layer, material, tint, or vertex alpha draw after opaque items, back to front by the camera-space center of each mesh’s transformed bounds, without writing depth. This is object-level sorting: intersecting meshes, self-overlap, skinned/deformed bounds, translucent flat layers, glass, and transparent shadows have separate limitations.- **Mesh wireframe:** `wireframe: true` on a `model3d` draws triangle edges as one-pixel lines, including triangulation and back edges; it also applies to skinned and audio-deformed meshes and their shadows.- **glTF scenes:** a glTF/GLB `model3d` keeps its node hierarchy, every skin and its animation clips (translation, rotation, scale and morph weights; linear, step and cubic-spline). Draco and meshopt compressed geometry and all seven core primitive modes are supported; per-map UV sets and texture transforms are independent. Basis KTX2 (ETC1S/UASTC) textures transcode offline to RGBA8 with their mip levels. Unsupported required extensions fail clearly. Morph targets run on the GPU before skinning and audio deformation. Skinned meshes are posed per frame from the clip (`animationName`, `animationTime`/`animationProgress`, `loop`); base-colour textures (with mipmaps), alpha `MASK`/`BLEND` and VRM MToon materials (`material: "toon"`, picked automatically when `material` is unset) render as authored. `center`/`normalizeSize` apply above the scene graph, so skinning stays intact.diff --git a/nodes/node-compositor/src/renderers/webgpu-renderer.ts b/nodes/node-compositor/src/renderers/webgpu-renderer.tsindex a6b0ab7b..37d3a0a1 100644--- a/nodes/node-compositor/src/renderers/webgpu-renderer.ts+++ b/nodes/node-compositor/src/renderers/webgpu-renderer.ts@@ -3,6 +3,7 @@import { resolveMediaSourceUrl } from "@framefields/client-utils";import { decodeAudioSource } from "@framefields/compositions";import {+ type CompositionNodeBase,collectNodeOps,computeLayout,initLayout,@@ -93,6 +94,41 @@ import { has3DTransform, type Quad2D, Transform3DMath } from "./transform3d.js";// Mesh vertex buffers are cached by identity, so their alpha classification can// also be computed once instead of scanning large models on every frame.const meshHasAlpha = new WeakMap<Mesh3DData, boolean>();+/**+ * How far a text node's ink can reach past its layout box, in px: an outside+ * stroke reaches its full width past the outline (any other alignment, half),+ * a shadow its offset plus blur. One px of slack covers antialiasing.+ */+function textInkOutset(+ target: Record<string, unknown> | undefined,+ lop: Record<string, unknown>,+): number {+ const num = (v: unknown) => (typeof v === "number" && v > 0 ? v : 0);+ const width = num(target?.strokeWidth ?? lop.strokeWidth);+ const hasStroke = Boolean(+ target?.stroke ?? target?.strokeColor ?? lop.stroke,+ );+ const stroke = hasStroke+ ? lop.strokeAlign === "outside"+ ? width+ : width / 2+ : 0;+ let shadow = 0;+ const shadows = lop.shadows;+ if (Array.isArray(shadows))+ for (const s of shadows as {+ offset?: { x?: number; y?: number };+ blurRadius?: number;+ }[])+ shadow = Math.max(+ shadow,+ Math.max(Math.abs(s.offset?.x ?? 0), Math.abs(s.offset?.y ?? 0)) ++ 2 * num(s.blurRadius),+ );+ const reach = stroke + shadow;+ return reach > 0 ? Math.ceil(reach) + 1 : 0;+}+function hasVertexAlpha(mesh: Mesh3DData): boolean {const cached = meshHasAlpha.get(mesh);if (cached !== undefined) return cached;@@ -523,13 +559,15 @@ function drawProjectedQuad(* then the node's own, then (meshes) the model file's material.*/function surfaceProps(- target: any,- lop: any,+ target: Partial<CompositionNodeBase> | undefined,+ lop: Partial<CompositionNodeBase>,mat?: { emissive?: [number, number, number]; emissiveStrength?: number },): {emissive?: string | [number, number, number];emissiveIntensity?: number;castShadow?: boolean;+ toon?: CompositionNodeBase["toon"];+ outline?: boolean;} {// glTF emissiveFactor is linear; draws take display (sRGB) colors.const toSrgb = (v: number) =>@@ -554,6 +592,8 @@ function surfaceProps(1;}if (lop.castShadow !== undefined) out.castShadow = lop.castShadow;+ out.toon = target?.toon ?? lop.toon;+ out.outline = target?.outline ?? lop.outline;return out;}@@ -1343,6 +1383,7 @@ export const CompositorWebGPURenderer: WebGPUNodeRenderer = async (args) => {toneMapping: lop.toneMapping,fog: lop.fog,floor: lop.floor,+ outlines: lop.outlines,...(intensity !== undefined && { intensity }),};sceneBloom =@@ -1484,9 +1525,12 @@ export const CompositorWebGPURenderer: WebGPUNodeRenderer = async (args) => {);const scene3dView = scene3dTex.createView();+ const outlineSetting = sceneEnvironment?.outlines;+ const outlines = outlineSetting === true ? {} : outlineSetting || null;+ const geometryEnabled = dofEnabled || Boolean(outlines);let linearDepthTex: GPUTexture | undefined;let linearDepthView: GPUTextureView | undefined;- if (dofEnabled) {+ if (geometryEnabled) {linearDepthTex = r3d.getOrCreateLinearDepthTexture(nativeWidth,nativeHeight,@@ -1736,7 +1780,7 @@ export const CompositorWebGPURenderer: WebGPUNodeRenderer = async (args) => {lightsBindGroup,blurredReflectionTex,floorSpec,- dofEnabled,+ geometryEnabled,Boolean(sceneBloom),);}@@ -1748,7 +1792,7 @@ export const CompositorWebGPURenderer: WebGPUNodeRenderer = async (args) => {lightsBindGroup,item.texture,item.opts,- dofEnabled,+ geometryEnabled,);} else if (item.kind === "slug") {r3d.drawSlugText(@@ -1758,7 +1802,7 @@ export const CompositorWebGPURenderer: WebGPUNodeRenderer = async (args) => {item.batches,item.opts,item.stackBase,- dofEnabled,+ geometryEnabled,);} else if (item.kind === "mesh") {r3d.drawMesh3D(@@ -1768,7 +1812,7 @@ export const CompositorWebGPURenderer: WebGPUNodeRenderer = async (args) => {item.meshBuffers ?? item.mesh,item.texture,isGlass(item) ? { ...item.opts, backdrop: curTex } : item.opts,- dofEnabled,+ geometryEnabled,);}}@@ -1776,15 +1820,33 @@ export const CompositorWebGPURenderer: WebGPUNodeRenderer = async (args) => {pass3d.end();let final3dTex = scene3dTex;+ if (outlines && linearDepthTex) {+ if (dofEnabled) r3d.resolveGeometry(encoder, linearDepthTex);+ const outlinedTex = ctx.renderer.getTemporaryTexture(+ nativeWidth,+ nativeHeight,+ [curTex, targetTexture, scene3dTex, linearDepthTex, ...curExcludes],+ );+ r3d.applyOutlines(+ encoder,+ scene3dTex,+ linearDepthTex,+ outlinedTex.createView(),+ camera,+ outlines,+ sceneEnvironment?.fog,+ );+ final3dTex = outlinedTex;+ }if (dofEnabled && linearDepthTex) {const dofResultTex = ctx.renderer.getTemporaryTexture(nativeWidth,nativeHeight,- [curTex, targetTexture, scene3dTex, ...curExcludes],+ [curTex, targetTexture, scene3dTex, final3dTex, ...curExcludes],);r3d.applyDepthOfField(encoder,- scene3dTex,+ final3dTex,linearDepthTex,dofResultTex.createView(),cameraBuffer,@@ -3573,22 +3635,31 @@ export const CompositorWebGPURenderer: WebGPUNodeRenderer = async (args) => {padX = Math.max(80, Math.ceil(rect.width * 0.2));padY = Math.max(50, Math.ceil(rect.height * 0.5));}+ // Text ink may reach past its box: an outside stroke, a shadow. The+ // layer grows to hold it, so nothing is cut at the node's edge.+ if (kind === "text" && !isPathText) {+ const ink = textInkOutset(target, lop);+ padX = Math.max(padX, ink);+ padY = Math.max(padY, ink);+ }// Path text draws into a canvas-sized layer so glyphs following a path// beyond the node box aren't clipped. Path coordinates stay local to// the node (like every other child), so the layer still sits at the// node's layout position.const layerW = isPathText ? targetW : rect.width + padX * 2;const layerH = isPathText ? targetH : rect.height + padY * 2;- if (!isPathText && hasKineticAnimators) {- localX -= padX;- localY -= padY;- }+ localX -= padX;+ localY -= padY;// Anchor-aware pivot (H2): scale/rotation happen AROUND the node's// anchor point (0.5/0.5 = center) instead of its top-left corner.- // For path text the anchor is a point of the node box, not of the- // oversized layer, so a badge spins around its own centre.- const anchorX = lop.anchorX ?? 0.5;- const anchorY = lop.anchorY ?? 0.5;+ // The anchor is a point of the node box, not of an oversized or+ // padded layer, so a badge spins around its own centre.+ const anchorX = isPathText+ ? ((lop.anchorX ?? 0.5) * rect.width) / layerW+ : (padX + (lop.anchorX ?? 0.5) * rect.width) / layerW;+ const anchorY = isPathText+ ? ((lop.anchorY ?? 0.5) * rect.height) / layerH+ : (padY + (lop.anchorY ?? 0.5) * rect.height) / layerH;const localMatrix = toDOMMatrix(buildLayerMatrix({x: localX,@@ -3599,8 +3670,8 @@ export const CompositorWebGPURenderer: WebGPUNodeRenderer = async (args) => {scale,scaleX,scaleY,- anchorX: isPathText ? (anchorX * rect.width) / layerW : anchorX,- anchorY: isPathText ? (anchorY * rect.height) / layerH : anchorY,+ anchorX,+ anchorY,}),);const layerMatrix = parentMatrix.multiply(localMatrix);@@ -3616,15 +3687,9 @@ export const CompositorWebGPURenderer: WebGPUNodeRenderer = async (args) => {const translateZ = target?.translateZ ?? lop.translateZ ?? 0;const perspective = target?.perspective ?? lop.perspective ?? 0;const perspectiveOriginX =- target?.perspectiveOriginX ??- lop.perspectiveOriginX ??- lop.anchorX ??- 0.5;+ target?.perspectiveOriginX ?? lop.perspectiveOriginX ?? anchorX;const perspectiveOriginY =- target?.perspectiveOriginY ??- lop.perspectiveOriginY ??- lop.anchorY ??- 0.5;+ target?.perspectiveOriginY ?? lop.perspectiveOriginY ?? anchorY;const backfaceVisibility =target?.backfaceVisibility ?? lop.backfaceVisibility ?? "visible";@@ -3862,54 +3927,6 @@ export const CompositorWebGPURenderer: WebGPUNodeRenderer = async (args) => {borderPass.end();}- let modelMatrix: Mat4 | undefined;- if (parent3DMatrix) {- let localM = Matrix4Math.identity();- const childX = target?.x ?? lop.x ?? 0;- const childY = target?.y ?? lop.y ?? 0;- const childZ = target?.z ?? lop.z ?? 0;- localM = Matrix4Math.multiply(- localM,- Matrix4Math.translate(childX, childY, childZ),- );- const rxRad =- ((target?.rotateX ?? lop.rotateX ?? 0) * Math.PI) / 180;- const ryRad =- ((target?.rotateY ?? lop.rotateY ?? 0) * Math.PI) / 180;- const rzRad =- ((target?.rotateZ ?? lop.rotateZ ?? 0) !== 0- ? (target?.rotateZ ?? lop.rotateZ ?? 0)- : rotation) *- (Math.PI / 180);- if (rzRad !== 0)- localM = Matrix4Math.multiply(localM, Matrix4Math.rotateZ(rzRad));- if (ryRad !== 0)- localM = Matrix4Math.multiply(localM, Matrix4Math.rotateY(ryRad));- if (rxRad !== 0)- localM = Matrix4Math.multiply(localM, Matrix4Math.rotateX(rxRad));-- const sx = layerW * scale * scaleX;- const sy = layerH * scale * scaleY;- const sz = target?.scaleZ ?? lop.scaleZ ?? 1;- localM = Matrix4Math.multiply(- localM,- Matrix4Math.scale(sx, sy, sz),- );-- const ax = lop.anchorX ?? 0.5;- const ay = lop.anchorY ?? 0.5;- const pivotX = 0.5 - ax;- const pivotY = 0.5 - ay;- if (pivotX !== 0 || pivotY !== 0) {- localM = Matrix4Math.multiply(- localM,- Matrix4Math.translate(pivotX, pivotY, 0),- );- }-- modelMatrix = Matrix4Math.multiply(parent3DMatrix, localM);- }-const quadOpts: DrawQuad3DOpts = {position: [localX + layerW * 0.5,@@ -3948,9 +3965,27 @@ export const CompositorWebGPURenderer: WebGPUNodeRenderer = async (args) => {ambientIntensity: target?.ambientIntensity ?? lop.ambientIntensity,metallic: target?.metallic ?? lop.metallic,...surfaceProps(target, lop),- ...(modelMatrix && { modelMatrix }),+...reliefOpts(lop.id, localX, localY, layerW, layerH),};+ if (parent3DMatrix) {+ const r3d = getRenderer3D(+ ctx.device,+ ctx.renderer.format ?? "rgba8unorm",+ sampleCount3d,+ );+ quadOpts.modelMatrix = Matrix4Math.multiply(+ parent3DMatrix,+ r3d.quadModelMatrix({+ ...quadOpts,+ position: [+ target?.x ?? lop.x ?? 0,+ target?.y ?? lop.y ?? 0,+ target?.z ?? lop.z ?? 0,+ ],+ }),+ );+ }pending3DItems.push({kind: "quad",@@ -4148,7 +4183,7 @@ export const CompositorWebGPURenderer: WebGPUNodeRenderer = async (args) => {return { finalTex: activeTex, finalView: activeView };}- const shouldClip = lop.overflow !== "visible";+ const shouldClip = (target?.overflow ?? lop.overflow) === "hidden";const scissorRect = shouldClip? computeContainerScissor(layerMatrix, layerW, layerH): null;@@ -5596,49 +5631,6 @@ export const CompositorWebGPURenderer: WebGPUNodeRenderer = async (args) => {borderPass.end();}- let modelMatrix: Mat4 | undefined;- if (parent3DMatrix) {- let localM = Matrix4Math.identity();- const childX = target?.x ?? lop.x ?? 0;- const childY = target?.y ?? lop.y ?? 0;- const childZ = target?.z ?? lop.z ?? 0;- localM = Matrix4Math.multiply(- localM,- Matrix4Math.translate(childX, childY, childZ),- );- const rxRad = ((target?.rotateX ?? lop.rotateX ?? 0) * Math.PI) / 180;- const ryRad = ((target?.rotateY ?? lop.rotateY ?? 0) * Math.PI) / 180;- const rzRad =- ((target?.rotateZ ?? lop.rotateZ ?? 0) !== 0- ? (target?.rotateZ ?? lop.rotateZ ?? 0)- : rotation) *- (Math.PI / 180);- if (rzRad !== 0)- localM = Matrix4Math.multiply(localM, Matrix4Math.rotateZ(rzRad));- if (ryRad !== 0)- localM = Matrix4Math.multiply(localM, Matrix4Math.rotateY(ryRad));- if (rxRad !== 0)- localM = Matrix4Math.multiply(localM, Matrix4Math.rotateX(rxRad));-- const sx = layerW * scale * scaleX;- const sy = layerH * scale * scaleY;- const sz = target?.scaleZ ?? lop.scaleZ ?? 1;- localM = Matrix4Math.multiply(localM, Matrix4Math.scale(sx, sy, sz));-- const ax = lop.anchorX ?? 0.5;- const ay = lop.anchorY ?? 0.5;- const pivotX = 0.5 - ax;- const pivotY = 0.5 - ay;- if (pivotX !== 0 || pivotY !== 0) {- localM = Matrix4Math.multiply(- localM,- Matrix4Math.translate(pivotX, pivotY, 0),- );- }-- modelMatrix = Matrix4Math.multiply(parent3DMatrix, localM);- }-const quadOpts: DrawQuad3DOpts = {position: [localX + layerW * 0.5,@@ -5676,9 +5668,27 @@ export const CompositorWebGPURenderer: WebGPUNodeRenderer = async (args) => {ambientIntensity: target?.ambientIntensity ?? lop.ambientIntensity,metallic: target?.metallic ?? lop.metallic,...surfaceProps(target, lop),- ...(modelMatrix && { modelMatrix }),+...reliefOpts(lop.id, localX, localY, layerW, layerH),};+ if (parent3DMatrix) {+ const r3d = getRenderer3D(+ ctx.device,+ ctx.renderer.format ?? "rgba8unorm",+ sampleCount3d,+ );+ quadOpts.modelMatrix = Matrix4Math.multiply(+ parent3DMatrix,+ r3d.quadModelMatrix({+ ...quadOpts,+ position: [+ target?.x ?? lop.x ?? 0,+ target?.y ?? lop.y ?? 0,+ target?.z ?? lop.z ?? 0,+ ],+ }),+ );+ }// The texture quad carries the layer's backdrop and border; a// text layer that drew neither needs only its glyphs.diff --git a/packages/compositions/src/program/schema.test.ts b/packages/compositions/src/program/schema.test.tsindex d269ad41..e645f88b 100644--- a/packages/compositions/src/program/schema.test.ts+++ b/packages/compositions/src/program/schema.test.ts@@ -1189,3 +1189,27 @@ describe("media time remapping schema", () => {);});});++describe("container overflow", () => {+ it("lets children draw past the container unless it is hidden", () => {+ for (const node of [+ { id: "f", kind: "flex", children: [] },+ { id: "k", kind: "block", children: [] },+ { id: "b", kind: "box", background: "#000", children: [] },+ ])+ expect(+ (LayoutNodeSchema.parse(node) as { overflow?: string }).overflow,+ ).toBe("visible");+ expect(+ (+ LayoutNodeSchema.parse({+ id: "h",+ kind: "box",+ background: "#000",+ overflow: "hidden",+ children: [],+ }) as { overflow?: string }+ ).overflow,+ ).toBe("hidden");+ });+});diff --git a/packages/compositions/src/program/schema.ts b/packages/compositions/src/program/schema.tsindex 0f9d1fc2..6f061b55 100644--- a/packages/compositions/src/program/schema.ts+++ b/packages/compositions/src/program/schema.ts@@ -17,15 +17,18 @@import {Effect,type EffectDomain,+ type GeometryOutlineOptions,type MediaTimeRemapInput,MediaTimeRemapInputSchema,type MeshAudioDeformConfig,type TextSpan,type TextSpanMark,+ type ToonShading,validateMediaTimeRemap,} from "@framefields/core";import { ColorSchema } from "@framefields/node-sdk";export type { TextSpan, TextSpanMark };+export type { ToonShading, GeometryOutlineOptions };import {type AdvancedTextAnimator,@@ -687,6 +690,27 @@ export type LayerAnimationSpec<TProp extends AnimatableProp = AnimatableProp> =// Container `children` fields use z.lazy closures; the union schema is// cast to z.ZodType<LayoutNode> — the documented pattern (zod-recursion).+export const ToonShadingSchema: z.ZodType<ToonShading> = z+ .object({+ shadowColor: ColorSchema.optional(),+ lightColor: ColorSchema.optional(),+ threshold: z.number().min(-1).max(1).optional(),+ softness: z.number().min(0).max(2).optional(),+ diffuse: z.number().min(0).max(1).optional(),+ })+ .strict();++export const GeometryOutlineOptionsSchema: z.ZodType<GeometryOutlineOptions> = z+ .object({+ color: ColorSchema.optional(),+ width: z.number().min(0).max(32).optional(),+ referenceHeight: z.number().positive().optional(),+ creaseAngle: z.number().min(0).max(180).optional(),+ depthThreshold: z.number().positive().max(1).optional(),+ opacity: z.number().min(0).max(1).optional(),+ })+ .strict();+const BaseNodeFields = {id: z.string().min(1),/** Graph binding — which connected input this node renders (for text/media nodes). */@@ -781,6 +805,10 @@ const BaseNodeFields = {emissiveIntensity: z.number().min(0).optional(),/** Falls into a `castShadow` light's shadow map. Meshes default on, flat layers off. */castShadow: z.boolean().optional(),+ /** Art-directed toon lighting, including cast shadows and colored lights. */+ toon: ToonShadingSchema.optional(),+ /** Participate in scene geometry outlines (default true). Excluded surfaces still occlude. */+ outline: z.boolean().optional(),/*** Track matte: another layer whose alpha or brightness masks this one.* Laid out like a sibling (same parent), timed with this node; with no@@ -871,6 +899,8 @@ export interface CompositionNodeBase {emissive?: string;emissiveIntensity?: number;castShadow?: boolean;+ toon?: ToonShading;+ outline?: boolean;matte?: { node: unknown; mode?: MatteMode };matteId?: string;matteOf?: string;@@ -1409,6 +1439,8 @@ export interface LightNode {toneMapping?: ToneMapping;fog?: EnvironmentFog;floor?: EnvironmentFloor;+ /** Optional depth/normal outlines, before depth of field and bloom. */+ outlines?: boolean | GeometryOutlineOptions;/** Glow around emissive surfaces and hot highlights: `true` or settings. */bloom?: boolean | BloomConfig;startFrame?: number;@@ -1448,6 +1480,7 @@ export const LightNodeSchema: z.ZodType<LightNode> = ztoneMapping: ToneMappingSchema.optional(),fog: EnvironmentFogSchema.optional(),floor: EnvironmentFloorSchema.optional(),+ outlines: z.union([z.boolean(), GeometryOutlineOptionsSchema]).optional(),bloom: z.union([z.boolean(), BloomConfigSchema]).optional(),startFrame: z.number().int().min(0).default(0),durationFrames: z.number().int().min(1).optional(),@@ -1544,7 +1577,7 @@ export const FlexNodeSchema: z.ZodType<FlexNode> = zstaggerDirection: z.enum(["forward", "reverse", "center-out"]).default("forward"),- overflow: z.enum(["visible", "hidden"]).default("hidden"),+ overflow: z.enum(["visible", "hidden"]).default("visible"),background: ColorSchema.optional(),borderRadius: z.number().min(0).optional(),borderColor: ColorSchema.optional(),@@ -1566,7 +1599,7 @@ export const BlockNodeSchema: z.ZodType<BlockNode> = zstaggerDirection: z.enum(["forward", "reverse", "center-out"]).default("forward"),- overflow: z.enum(["visible", "hidden"]).default("hidden"),+ overflow: z.enum(["visible", "hidden"]).default("visible"),background: ColorSchema.optional(),borderRadius: z.number().min(0).optional(),borderColor: ColorSchema.optional(),@@ -1589,7 +1622,7 @@ export const BoxNodeSchema: z.ZodType<BoxNode> = zstaggerDirection: z.enum(["forward", "reverse", "center-out"]).default("forward"),- overflow: z.enum(["visible", "hidden"]).default("hidden"),+ overflow: z.enum(["visible", "hidden"]).default("visible"),borderColor: ColorSchema.optional(),borderWidth: z.number().min(0).optional(),strokeAlign: z.enum(["inside", "center", "outside"]).optional(),diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 86006ec2..b393a726 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -7,6 +7,7 @@ export * from "./media-time-signal.js";export * from "./node-metadata.js";export * from "./render-diagnostics.js";export * from "./signals/index.js";+export * from "./spatial-styling.js";export * from "./types/index.js";export * from "./utils/assert.js";export * from "./utils/color.js";diff --git a/packages/core/src/spatial-styling.ts b/packages/core/src/spatial-styling.tsnew file mode 100644index 00000000..a17e0335--- /dev/null+++ b/packages/core/src/spatial-styling.ts@@ -0,0 +1,29 @@+/** Art-directed lighting for `material: "toon"`, on meshes, cards and text. */+export interface ToonShading {+ /** Shadow-side albedo multiplier. Defaults to the model's shade color or #80808c. */+ shadowColor?: string;+ /** Lit-side albedo multiplier, in addition to the scene light's color. Default white. */+ lightColor?: string;+ /** Cosine of the light angle at the middle of the light/shade transition. Default 0.075. */+ threshold?: number;+ /** Width of the light/shade transition in cosine space. Default 0.25. */+ softness?: number;+ /** Cosine modelling within the lit region: 0 flat, 1 Lambert. Default 0. */+ diffuse?: number;+}++/** Geometry outlines use surface depth and normals, independently of texture or lighting. */+export interface GeometryOutlineOptions {+ /** Ink color. Default #16131c. */+ color?: string;+ /** Line width in pixels at `referenceHeight`. Default 1.5. */+ width?: number;+ /** Height at which width is specified; exports scale it proportionally. Default 1080. */+ referenceHeight?: number;+ /** Normal discontinuity in degrees that starts a crease. 180 disables creases. Default 45. */+ creaseAngle?: number;+ /** Relative inverse-depth curvature that starts a silhouette/depth edge. Default 0.01. */+ depthThreshold?: number;+ /** Overall ink opacity. Default 1. */+ opacity?: number;+}diff --git a/packages/framefields/src/index.ts b/packages/framefields/src/index.tsindex 28b2482b..9852e646 100644--- a/packages/framefields/src/index.ts+++ b/packages/framefields/src/index.ts@@ -558,6 +558,8 @@ export {type FlexNode,FlexNodeSchema,type FromToOptions,+ type GeometryOutlineOptions,+ GeometryOutlineOptionsSchema,type GlyphAnchorGrouping,GlyphAnchorGroupingSchema,type GlyphAnchorPoint,@@ -657,6 +659,8 @@ export {TextWigglySelectorSchema,type ToneMapping,ToneMappingSchema,+ type ToonShading,+ ToonShadingSchema,type TrackSource,type TypewriterAnimator,TypewriterAnimatorSchema,@@ -3501,6 +3505,7 @@ export type EnvironmentOptions = Partial<| "toneMapping"| "fog"| "floor"+ | "outlines"| "bloom"| "startFrame"| "durationFrames"diff --git a/packages/framefields/src/shapes3d.ts b/packages/framefields/src/shapes3d.tsindex 49e78f44..f886bbf1 100644--- a/packages/framefields/src/shapes3d.ts+++ b/packages/framefields/src/shapes3d.ts@@ -3,6 +3,7 @@ import type {LayoutNode,MaterialType,Model3DNode,+ ToonShading,} from "@framefields/compositions/program";import {type CapsuleGeometryOptions,@@ -33,6 +34,10 @@ import { createSwarm3D, type Swarm3DOptions } from "./swarm3d.js";/** Physically based surface options every 3D builder accepts. */export interface Surface3DOptions {+ /** Art-directed lighting for material: "toon". */+ toon?: ToonShading;+ /** Opt out of the scene's geometry outlines while retaining depth occlusion. */+ outline?: boolean;/** Light the surface gives off: a CSS color added on top of lighting. */emissive?: string;/** Emissive multiplier; above 1 glows past white and blooms. Default 1. */@@ -42,6 +47,8 @@ export interface Surface3DOptions {}const MATERIAL_KEYS = [+ "toon",+ "outline","material","shininess","roughness",@@ -646,7 +653,11 @@ export const Layer3D = {) {node.ambientIntensity = options.ambientIntensity;}- Object.assign(node, faceProps);+ Object.assign(+ node,+ { ...materialProps(options), ...materialProps(node) },+ faceProps,+ );return node;}const cfg: CubeFaceConfig =diff --git a/packages/framefields/src/spatial-styling-render.test.ts b/packages/framefields/src/spatial-styling-render.test.tsnew file mode 100644index 00000000..ba161619--- /dev/null+++ b/packages/framefields/src/spatial-styling-render.test.ts@@ -0,0 +1,666 @@+import { describe, expect, it } from "vitest";+import {+ Composition,+ CompositorProgramSchema,+ type GeometryOutlineOptions,+ Layer,+ Layer3D,+} from "./index.js";+import {+ computeMse,+ type DecodedImage,+ decodePngPixels,+ getPixel,+} from "./test-utils/pixels.js";++function stage(+ outlines: boolean | GeometryOutlineOptions = true,+ size = 256,+): Composition {+ const comp = new Composition({+ width: size,+ height: size,+ fps: 30,+ durationMs: 1000,+ backgroundColor: "#c5d8ed",+ });+ comp.add(+ Layer.environment("neutral", {+ intensity: 0,+ toneMapping: "none",+ outlines,+ }),+ );+ return comp;+}++async function render(comp: Composition): Promise<DecodedImage> {+ return decodePngPixels(await comp.renderFrame({ frame: 0 }));+}++function darkPixels(image: DecodedImage): number {+ let count = 0;+ for (let i = 0; i < image.pixels.length; i += 4) {+ if (+ image.pixels[i] < 50 &&+ image.pixels[i + 1] < 50 &&+ image.pixels[i + 2] < 50+ )+ count++;+ }+ return count;+}++describe("geometry outlines and art-directed lighting", () => {+ it("preserves MSAA coverage where two outlined surfaces meet", async () => {+ const draw = (antialias3d: boolean) => {+ const comp = stage({+ width: 2,+ referenceHeight: 256,+ color: "#000000",+ creaseAngle: 180,+ });+ comp.antialias3d = antialias3d;+ comp.add(+ Layer.box({+ position: "absolute",+ x: 0,+ y: 0,+ z: 100,+ width: 256,+ height: 256,+ is3D: true,+ background: "#ffffff",+ material: "unlit",+ }),+ );+ comp.add(+ Layer3D.sphere({+ x: 128.35,+ y: 128.35,+ radius: 61,+ segments: 128,+ color: "#ffffff",+ material: "unlit",+ }),+ );+ return render(comp);+ };+ const countCoverage = (image: DecodedImage) => {+ let count = 0;+ for (let y = 40; y < 216; y++)+ for (let x = 40; x < 216; x++) {+ const r = image.pixels[(y * image.width + x) * 4];+ if (r > 8 && r < 247) count++;+ }+ return count;+ };+ const hard = countCoverage(await draw(false));+ const smooth = countCoverage(await draw(true));+ expect(smooth).toBeGreaterThan(hard + 40);+ });+ it("inherits cube surface settings on custom artwork and preserves face overrides", () => {+ const front = Layer.box({ width: 80, height: 120, background: "#ffffff" });+ const back = Layer.box({+ width: 80,+ height: 120,+ outline: true,+ toon: { shadowColor: "#996655" },+ });+ const cube = Layer3D.cube({+ size: [80, 120, 60],+ material: "toon",+ toon: { shadowColor: "#778899", diffuse: 0.6 },+ outline: false,+ castShadow: true,+ faces: { front, back },+ });+ expect(cube.faces?.[0]).toMatchObject({+ toon: { shadowColor: "#778899", diffuse: 0.6 },+ outline: false,+ castShadow: true,+ });+ expect(cube.faces?.[1]).toMatchObject({+ toon: { shadowColor: "#996655" },+ outline: true,+ });+ });+ it("never makes diffuse toon light darker than its shadow floor", async () => {+ const draw = async (angle: number) => {+ const comp = new Composition({+ width: 128,+ height: 128,+ fps: 30,+ durationMs: 1000,+ });+ const radians = (angle * Math.PI) / 180;+ comp.add(+ Layer.directionalLight({+ x: 64 + Math.sin(radians) * 400,+ y: 64,+ z: -Math.cos(radians) * 400,+ targetX: 64,+ targetY: 64,+ targetZ: 0,+ color: "#ffffff",+ intensity: 1,+ }),+ );+ comp.add(+ Layer.box({+ position: "absolute",+ x: 32,+ y: 32,+ width: 64,+ height: 64,+ is3D: true,+ background: "#ffffff",+ material: "toon",+ toon: {+ shadowColor: "#cccccc",+ threshold: 0,+ softness: 0.25,+ diffuse: 1,+ },+ }),+ );+ return getPixel(await render(comp), 64, 64).r;+ };+ const shadow = await draw(120);+ const grazing = await draw(80);+ const angled = await draw(60);+ const front = await draw(0);+ expect(grazing).toBeGreaterThanOrEqual(shadow);+ expect(angled).toBeGreaterThanOrEqual(grazing);+ expect(front).toBeGreaterThanOrEqual(angled);+ });+ it("keeps an authored 3D pivot fixed and leaves identity placement unchanged", async () => {+ const draw = (anchorY: number, scale = 1) => {+ const comp = stage(false);+ comp.add(+ Layer.box({+ position: "absolute",+ is3D: true,+ x: 80,+ y: 60,+ width: 96,+ height: 96,+ anchorY,+ scale,+ background: "#ff3300",+ material: "unlit",+ }),+ );+ return render(comp);+ };+ const centered = await draw(0.5);+ const bottom = await draw(1);+ expect(computeMse(centered.pixels, bottom.pixels)).toBeLessThan(0.01);+ const scaled = await draw(1, 2);+ expect(getPixel(scaled, 128, 150).g).toBeLessThan(60);+ expect(getPixel(scaled, 128, 165).g).toBeGreaterThan(150);+ });+ it("round-trips the public material and scene options and rejects invalid settings", () => {+ const comp = stage({ width: 3, creaseAngle: 55, referenceHeight: 256 });+ comp.add(+ Layer3D.sphere({+ radius: 50,+ material: "toon",+ toon: { shadowColor: "#433966", softness: 0.1 },+ outline: false,+ }),+ );+ const parsed = CompositorProgramSchema.parse(comp.toSpec());+ expect(parsed.layout.find((node) => node.kind === "light")).toMatchObject({+ outlines: { width: 3, creaseAngle: 55, referenceHeight: 256 },+ });+ expect(parsed.layout.find((node) => node.kind === "model3d")).toMatchObject(+ { outline: false, toon: { shadowColor: "#433966", softness: 0.1 } },+ );+ const invalid = comp.toSpec();+ const environment = invalid.layout.find((node) => node.kind === "light");+ if (environment?.kind !== "light") throw new Error("Missing environment");+ environment.outlines = { width: -1 };+ expect(CompositorProgramSchema.safeParse(invalid).success).toBe(false);+ });++ it("keeps off-center pivots stable inside preserve-3d containers", async () => {+ const draw = (anchorY: number) => {+ const comp = stage(false);+ comp.add(+ Layer.box({+ position: "absolute",+ x: 0,+ y: 0,+ width: 256,+ height: 256,+ is3D: true,+ transformStyle: "preserve-3d",+ children: [+ Layer.box({+ position: "absolute",+ x: 0,+ y: 0,+ width: 96,+ height: 96,+ is3D: true,+ anchorY,+ background: "#ff3300",+ material: "unlit",+ }),+ ],+ }),+ );+ return render(comp);+ };+ const centered = await draw(0.5);+ const bottom = await draw(1);+ let painted = 0;+ for (let i = 0; i < centered.pixels.length; i += 4) {+ if (centered.pixels[i] > 240 && centered.pixels[i + 1] < 90) painted++;+ }+ expect(painted).toBeGreaterThan(500);+ expect(computeMse(centered.pixels, bottom.pixels)).toBeLessThan(0.01);+ });++ it("finds silhouettes and normal creases between identically colored faces", async () => {+ const draw = (creaseAngle: number, enabled: boolean) => {+ const comp = stage(+ enabled && { width: 2, referenceHeight: 256, creaseAngle },+ );+ comp.add(+ Layer3D.roundedBox({+ width: 110,+ height: 110,+ depth: 110,+ radius: 0,+ x: 128,+ y: 128,+ rotateY: 30,+ rotateX: 15,+ color: "#ffffff",+ material: "unlit",+ }),+ );+ return render(comp);+ };+ const plain = await draw(45, false);+ const silhouettes = await draw(180, true);+ const creases = await draw(45, true);+ expect(darkPixels(plain)).toBe(0);+ expect(darkPixels(silhouettes)).toBeGreaterThan(200);+ expect(darkPixels(creases)).toBeGreaterThan(darkPixels(silhouettes) + 60);+ });++ it("ignores artwork edges on a plane and preserves excluded foreground occlusion", async () => {+ const draw = (enabled: boolean) => {+ const comp = stage(enabled && { width: 3, referenceHeight: 256 });+ comp.add(+ Layer3D.roundedBox({+ width: 130,+ height: 130,+ depth: 100,+ radius: 0,+ x: 128,+ y: 128,+ rotateY: 30,+ color: "#ffffff",+ material: "unlit",+ }),+ );+ comp.add(+ Layer.box({+ position: "absolute",+ x: 85,+ y: 80,+ z: -120,+ width: 86,+ height: 96,+ is3D: true,+ material: "unlit",+ outline: false,+ background: "#f7e8ca",+ children: [+ Layer.box({+ position: "absolute",+ x: 40,+ y: 0,+ width: 5,+ height: 96,+ background: "#ee3311",+ }),+ ],+ }),+ );+ return render(comp);+ };+ const plain = await draw(false);+ const ink = await draw(true);+ for (let y = 90; y <= 165; y += 5) {+ for (let x = 100; x <= 155; x += 5)+ expect(getPixel(ink, x, y)).toEqual(getPixel(plain, x, y));+ }+ expect(darkPixels(ink)).toBeGreaterThan(100);+ });++ it("scales line width with export resolution without inking texture seams", async () => {+ const line = async (scale: number) => {+ const comp = stage({ width: 3, referenceHeight: 256 }, 256 * scale);+ comp.add(+ Layer.box({+ position: "absolute",+ is3D: true,+ x: 64 * scale,+ y: 64 * scale,+ width: 128 * scale,+ height: 128 * scale,+ background: "#ffffff",+ material: "unlit",+ children: [+ Layer.box({+ position: "absolute",+ x: 60 * scale,+ y: 0,+ width: 8 * scale,+ height: 128 * scale,+ background: "#ff4422",+ }),+ ],+ }),+ );+ const image = await render(comp);+ let width = 0;+ for (let x = 60 * scale; x < 80 * scale; x++)+ if (getPixel(image, x, 128 * scale).r < 50) width++;+ expect(getPixel(image, 123 * scale, 128 * scale).r).toBeGreaterThan(240);+ return width;+ };+ const small = await line(1);+ const large = await line(2);+ expect(small).toBeGreaterThanOrEqual(2);+ expect(large).toBeGreaterThanOrEqual(small * 2 - 1);+ expect(large).toBeLessThanOrEqual(small * 2 + 1);+ });++ it("does not draw false contours on a grazing plane", async () => {+ const comp = stage({+ width: 3,+ referenceHeight: 256,+ depthThreshold: 0.01,+ });+ comp.add(+ Layer.box({+ position: "absolute",+ is3D: true,+ x: -250,+ y: -250,+ width: 750,+ height: 750,+ background: "#ffffff",+ material: "unlit",+ rotateY: 55,+ }),+ );+ const image = await render(comp);+ for (let y = 90; y < 170; y += 10)+ for (let x = 90; x < 170; x += 10)+ expect(getPixel(image, x, y).r).toBeGreaterThan(240);+ });++ it("renders geometry ink without MSAA and makes zero-width outlines a no-op", async () => {+ const draw = (+ outlines: boolean | GeometryOutlineOptions,+ antialias3d: boolean,+ ) => {+ const comp = stage(outlines);+ comp.antialias3d = antialias3d;+ comp.add(+ Layer3D.sphere({+ x: 128,+ y: 128,+ radius: 65,+ color: "#ffffff",+ material: "unlit",+ }),+ );+ return render(comp);+ };+ const plain = await draw(false, true);+ const zero = await draw({ width: 0 }, true);+ expect(computeMse(plain.pixels, zero.pixels)).toBeLessThan(0.01);+ const ink = await draw({ width: 3, referenceHeight: 256 }, false);+ expect(darkPixels(ink)).toBeGreaterThan(200);+ });++ it("applies point-light falloff and spot cones to toon surfaces", async () => {+ const draw = (spot: boolean) => {+ const comp = new Composition({+ width: 256,+ height: 256,+ fps: 30,+ durationMs: 1000,+ });+ const light = {+ x: 128,+ y: 128,+ z: -80,+ targetX: 128,+ targetY: 128,+ targetZ: 0,+ intensity: 1,+ radius: 250,+ decay: 1,+ color: "#ffffff",+ angle: 20,+ penumbra: 0.1,+ };+ comp.add(spot ? Layer.spotLight(light) : Layer.pointLight(light));+ comp.add(+ Layer.box({+ position: "absolute",+ x: 0,+ y: 0,+ width: 256,+ height: 256,+ is3D: true,+ background: "#ffffff",+ material: "toon",+ toon: { shadowColor: "#202040" },+ }),+ );+ return render(comp);+ };+ const point = await draw(false);+ const spot = await draw(true);+ expect(getPixel(point, 128, 128).r).toBeGreaterThan(+ getPixel(point, 220, 128).r + 20,+ );+ expect(getPixel(spot, 220, 128).r).toBeLessThan(+ getPixel(point, 220, 128).r - 50,+ );+ expect(getPixel(spot, 128, 128).r).toBeGreaterThan(150);+ });++ it("lights toon cards with colored direct lights beyond the eighth", async () => {+ const comp = new Composition({+ width: 256,+ height: 256,+ fps: 30,+ durationMs: 1000,+ });+ for (let i = 0; i < 9; i++)+ comp.add(+ Layer.directionalLight({+ x: 128,+ y: 128,+ z: -400,+ targetX: 128,+ targetY: 128,+ targetZ: 0,+ intensity: i === 8 ? 1 : 0,+ color: "#ff2200",+ }),+ );+ comp.add(+ Layer.box({+ position: "absolute",+ is3D: true,+ x: 64,+ y: 64,+ width: 128,+ height: 128,+ background: "#ffffff",+ material: "toon",+ }),+ );+ const pixel = getPixel(await render(comp), 128, 128);+ expect(pixel.r).toBeGreaterThan(230);+ expect(pixel.g).toBeLessThan(50);+ expect(pixel.b).toBeLessThan(10);+ });++ it("receives real cast shadows on toon cards with a controlled shadow tint", async () => {+ const draw = (castShadow: boolean) => {+ const comp = stage(false);+ comp.add(+ Layer.directionalLight({+ x: -150,+ y: -150,+ z: -450,+ targetX: 128,+ targetY: 128,+ targetZ: 0,+ intensity: 1,+ castShadow,+ shadowSoftness: 0,+ shadowMapSize: 1024,+ }),+ );+ comp.add(+ Layer.box({+ position: "absolute",+ x: 0,+ y: 0,+ z: 100,+ width: 256,+ height: 256,+ is3D: true,+ background: "#ffffff",+ material: "toon",+ toon: { shadowColor: "#303060" },+ }),+ );+ comp.add(+ Layer3D.roundedBox({+ x: 100,+ y: 100,+ z: 0,+ width: 55,+ height: 55,+ depth: 30,+ radius: 0,+ color: "#ff5555",+ material: "toon",+ }),+ );+ return render(comp);+ };+ const plain = await draw(false);+ const shadow = await draw(true);+ expect(computeMse(plain.pixels, shadow.pixels)).toBeGreaterThan(100);+ let tinted = 0;+ for (let i = 0; i < plain.pixels.length; i += 4)+ if (+ plain.pixels[i] > 240 &&+ shadow.pixels[i] < 160 &&+ shadow.pixels[i + 2] > shadow.pixels[i] * 1.5+ )+ tinted++;+ expect(tinted).toBeGreaterThan(100);+ });++ it("fogs toon materials and their outlines into the same environment", async () => {+ const comp = new Composition({+ width: 256,+ height: 256,+ fps: 30,+ durationMs: 1000,+ backgroundColor: "#b9cdea",+ });+ comp.add(+ Layer.environment("neutral", {+ intensity: 0,+ toneMapping: "none",+ outlines: { width: 3, referenceHeight: 256 },+ fog: { color: "#b9cdea", start: 0, end: 100 },+ }),+ );+ comp.add(+ Layer.directionalLight({+ x: 128,+ y: 128,+ z: -500,+ targetX: 128,+ targetY: 128,+ }),+ );+ comp.add(+ Layer3D.roundedBox({+ width: 100,+ height: 100,+ depth: 50,+ radius: 0,+ x: 128,+ y: 128,+ color: "#ff0000",+ material: "toon",+ }),+ );+ const image = await render(comp);+ expect(darkPixels(image)).toBe(0);+ const pixel = getPixel(image, 128, 128);+ expect(pixel.r).toBeCloseTo(185, -1);+ expect(pixel.b).toBeCloseTo(234, -1);+ });++ it("blends outline fog in the same linear-light space as surface fog", async () => {+ const draw = (outlines: boolean) => {+ const comp = new Composition({+ width: 256,+ height: 256,+ fps: 30,+ durationMs: 1000,+ backgroundColor: "#c8daf0",+ });+ comp.add(+ Layer.environment("neutral", {+ intensity: 0,+ toneMapping: "none",+ outlines: outlines && {+ color: "#1c438c",+ width: 3,+ referenceHeight: 256,+ },+ fog: { color: "#c8daf0", start: 100, end: 1000 },+ }),+ );+ comp.add(+ Layer.box({+ position: "absolute",+ x: 64,+ y: 64,+ width: 128,+ height: 128,+ is3D: true,+ material: "unlit",+ background: "#1c438c",+ }),+ );+ return render(comp);+ };+ const plain = await draw(false);+ const ink = await draw(true);+ // With ink the same color as the surface, fog must not reveal a seam.+ expect(computeMse(plain.pixels, ink.pixels)).toBeLessThan(0.1);+ });+});diff --git a/packages/webgpu-renderers/src/math3d/environment3d.ts b/packages/webgpu-renderers/src/math3d/environment3d.tsindex b37ab8d5..189555a0 100644--- a/packages/webgpu-renderers/src/math3d/environment3d.ts+++ b/packages/webgpu-renderers/src/math3d/environment3d.ts@@ -4,7 +4,7 @@* with an environment is shaded physically; one without keeps the original* Blinn-Phong look.*/-import { parseCssColor } from "@framefields/core";+import { type GeometryOutlineOptions, parseCssColor } from "@framefields/core";/*** "neutral" (default, Khronos PBR Neutral): colors as authored, highlights@@ -64,6 +64,7 @@ export interface Environment3DOptions {toneMapping?: ToneMapping;fog?: Environment3DFog;floor?: Environment3DFloor;+ outlines?: boolean | GeometryOutlineOptions;}interface PresetDef {diff --git a/packages/webgpu-renderers/src/renderer3d/floor-reflection-pipeline.ts b/packages/webgpu-renderers/src/renderer3d/floor-reflection-pipeline.tsindex 3fd3a5a3..12335188 100644--- a/packages/webgpu-renderers/src/renderer3d/floor-reflection-pipeline.ts+++ b/packages/webgpu-renderers/src/renderer3d/floor-reflection-pipeline.ts@@ -220,7 +220,7 @@ fn fs_mrt(in: VsOut) -> FsOutputMrt {var out: FsOutputMrt;let s = shadeFloor(in);out.color = vec4<f32>(s.display * s.alpha, s.alpha);- out.linearDepth = vec4<f32>(s.linearDepth, 0.0, 0.0, 1.0);+ out.linearDepth = geometryPixel(s.linearDepth, vec3<f32>(0.0, -1.0, 0.0), 1.0);out.depth = s.depth;return out;}@@ -240,7 +240,7 @@ fn fs_mrt_bloom(in: VsOut) -> FsOutputMrtBloom {var out: FsOutputMrtBloom;let s = shadeFloor(in);out.color = vec4<f32>(s.display * s.alpha, s.alpha);- out.linearDepth = vec4<f32>(s.linearDepth, 0.0, 0.0, 1.0);+ out.linearDepth = geometryPixel(s.linearDepth, vec3<f32>(0.0, -1.0, 0.0), 1.0);out.hdr = vec4<f32>(s.hdr * s.alpha, 1.0);out.depth = s.depth;return out;diff --git a/packages/webgpu-renderers/src/renderer3d/geometry-outline-pipeline.ts b/packages/webgpu-renderers/src/renderer3d/geometry-outline-pipeline.tsnew file mode 100644index 00000000..1e13b370--- /dev/null+++ b/packages/webgpu-renderers/src/renderer3d/geometry-outline-pipeline.ts@@ -0,0 +1,226 @@+import type { GeometryOutlineOptions } from "@framefields/core";+import { parseColor } from "../color.js";+import { Camera3D, type Camera3DPose } from "../math3d/camera3d.js";+import type { Environment3DFog } from "../math3d/environment3d.js";+import { BufferPool } from "../renderer2d/buffer-pool.js";++function outlineShader(sampleCount: number): string {+ const multisampled = sampleCount > 1;+ const textureType = multisampled+ ? "texture_multisampled_2d<f32>"+ : "texture_2d<f32>";+ return /* wgsl */ `+struct Uniforms {+ params : vec4<f32>, // width, cosine(crease angle), relative depth threshold, opacity+ ink : vec4<f32>,+ fog : vec4<f32>,+ fogRange : vec4<f32>,+ projection : vec4<f32>, // inverse projection x/y scale, far depth+};+@group(0) @binding(0) var<uniform> u : Uniforms;+@group(0) @binding(1) var colorTex : ${textureType};+@group(0) @binding(2) var geometryTex : ${textureType};++@vertex fn vs(@builtin(vertex_index) i : u32) -> @builtin(position) vec4<f32> {+ let p = vec2<f32>(f32((i << 1u) & 2u), f32(i & 2u));+ return vec4<f32>(p * 2.0 - 1.0, 0.0, 1.0);+}++fn geometry(p : vec2<i32>, sample : i32) -> vec4<f32> {+ let size = vec2<i32>(textureDimensions(geometryTex));+ // Beyond the viewport is the same surface: never ink the canvas border.+ return textureLoad(geometryTex, clamp(p, vec2<i32>(0), size - 1), sample);+}++fn normal(oct : vec2<f32>) -> vec3<f32> {+ let p = oct * 2.0 - 1.0;+ var n = vec3<f32>(p, 1.0 - abs(p.x) - abs(p.y));+ let t = max(-n.z, 0.0);+ n = vec3<f32>(n.xy + select(vec2<f32>(t), vec2<f32>(-t), n.xy >= vec2<f32>(0.0)), n.z);+ return normalize(n);+}++fn srgbToLinear(c : vec3<f32>) -> vec3<f32> {+ return select(pow((max(c, vec3<f32>(0.0)) + 0.055) / 1.055, vec3<f32>(2.4)), c / 12.92, c <= vec3<f32>(0.04045));+}+fn linearToSrgb(c : vec3<f32>) -> vec3<f32> {+ let x = max(c, vec3<f32>(0.0));+ return select(1.055 * pow(x, vec3<f32>(1.0 / 2.4)) - 0.055, x * 12.92, x <= vec3<f32>(0.0031308));+}++fn edge(center : vec4<f32>, next : vec4<f32>, previous : vec4<f32>) -> f32 {+ let z = 1.0 / max(center.r, 0.0001);+ let a = 1.0 / max(next.r, 0.0001);+ let b = 1.0 / max(previous.r, 0.0001);+ // Inverse depth is affine on a perspective-projected plane. Its signed+ // second difference suppresses grazing surfaces and inks only the near+ // side of an occlusion, including thin geometry with background both sides.+ let curvature = (2.0 * z - a - b) / z;+ let depthEdge = smoothstep(u.params.z, u.params.z * 2.0, curvature);+ let sameDepth = abs(center.r - next.r) / max(center.r, 0.0001) < 0.03;+ let crease = select(0.0, 1.0, next.a > 0.5 && sameDepth && dot(normal(center.gb), normal(next.gb)) < u.params.y);+ return max(depthEdge, crease);+}++@fragment fn fs(@builtin(position) pos : vec4<f32>${multisampled ? ", @builtin(sample_index) sampleIndex : u32" : ""}) -> @location(0) vec4<f32> {+ let sample = ${multisampled ? "i32(sampleIndex)" : "0"};+ let pixel = vec2<i32>(pos.xy);+ let source = textureLoad(colorTex, pixel, sample);+ let c = geometry(pixel, sample);+ if (c.a <= 0.0 || u.params.x <= 0.0 || u.params.w <= 0.0) { return source; }+ var coverage = 0.0;+ let directions = array<vec2<f32>, 8>(+ vec2<f32>(1.0, 0.0), vec2<f32>(-1.0, 0.0), vec2<f32>(0.0, 1.0), vec2<f32>(0.0, -1.0),+ vec2<f32>(0.707107, 0.707107), vec2<f32>(-0.707107, 0.707107), vec2<f32>(0.707107, -0.707107), vec2<f32>(-0.707107, -0.707107));+ for (var r = 1; r <= i32(ceil(u.params.x)); r++) {+ let weight = clamp(u.params.x - f32(r) + 1.0, 0.0, 1.0);+ for (var d = 0; d < 8; d++) {+ let offset = vec2<i32>(round(directions[d] * f32(r)));+ coverage = max(coverage, edge(c, geometry(pixel + offset, sample), geometry(pixel - offset, sample)) * weight);+ }+ }+ var ink = u.ink.rgb;+ if (u.fog.w > 0.5) {+ let uv = pos.xy / vec2<f32>(textureDimensions(colorTex));+ let ray = vec3<f32>((uv * 2.0 - 1.0) * u.projection.xy, 1.0);+ let distance = c.r * length(ray);+ let fog = smoothstep(u.fogRange.x, max(u.fogRange.y, u.fogRange.x + 1.0), distance) * u.fogRange.z;+ // Match surface fog's linear-light blend; display-space interpolation+ // would darken outlines halfway into a light-colored atmosphere.+ ink = linearToSrgb(mix(srgbToLinear(ink), srgbToLinear(u.fog.rgb), fog));+ }+ let visibleCoverage = min(c.a / max(source.a, 0.0001), 1.0);+ return vec4<f32>(mix(source.rgb, ink * source.a, coverage * visibleCoverage * u.params.w * u.ink.a), source.a);+}+`;+}++/** Ink shades original color/depth/normal samples, then resolves color with MSAA. */+export class GeometryOutlinePipeline {+ private layout: GPUBindGroupLayout;+ private pipeline: GPURenderPipeline;+ private multisampledOutput: GPUTexture | null = null;+ private pool = new BufferPool(+ 80,+ GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,+ );++ constructor(+ private device: GPUDevice,+ private format: GPUTextureFormat,+ private sampleCount = 1,+ ) {+ this.layout = device.createBindGroupLayout({+ label: "GeometryOutlineLayout",+ entries: [+ {+ binding: 0,+ visibility: GPUShaderStage.FRAGMENT,+ buffer: { type: "uniform" },+ },+ ...[1, 2].map((binding) => ({+ binding,+ visibility: GPUShaderStage.FRAGMENT,+ texture: {+ sampleType: "unfilterable-float" as const,+ multisampled: sampleCount > 1,+ },+ })),+ ],+ });+ const module = device.createShaderModule({+ label: "geometry-outlines.wgsl",+ code: outlineShader(sampleCount),+ });+ this.pipeline = device.createRenderPipeline({+ label: "GeometryOutlines",+ layout: device.createPipelineLayout({ bindGroupLayouts: [this.layout] }),+ vertex: { module, entryPoint: "vs" },+ fragment: { module, entryPoint: "fs", targets: [{ format }] },+ primitive: { topology: "triangle-list" },+ multisample: { count: sampleCount },+ });+ }++ reset(): void {+ this.pool.reset();+ }+ destroy(): void {+ this.pool.destroy();+ this.multisampledOutput?.destroy();+ }++ private attachment(+ source: GPUTexture,+ dest: GPUTextureView,+ ): GPURenderPassColorAttachment {+ if (this.sampleCount <= 1)+ return { view: dest, loadOp: "clear", storeOp: "store" };+ if (+ !this.multisampledOutput ||+ this.multisampledOutput.width !== source.width ||+ this.multisampledOutput.height !== source.height+ ) {+ this.multisampledOutput?.destroy();+ this.multisampledOutput = this.device.createTexture({+ label: "GeometryOutlineMsaaOutput",+ size: { width: source.width, height: source.height },+ format: this.format,+ sampleCount: this.sampleCount,+ usage: GPUTextureUsage.RENDER_ATTACHMENT,+ });+ }+ return {+ view: this.multisampledOutput.createView(),+ resolveTarget: dest,+ loadOp: "clear",+ storeOp: "discard",+ };+ }++ render(+ encoder: GPUCommandEncoder,+ source: GPUTexture,+ geometry: GPUTexture,+ dest: GPUTextureView,+ camera: Camera3DPose,+ options: GeometryOutlineOptions,+ fog?: Environment3DFog,+ ): void {+ const data = new Float32Array(20);+ data.set([+ ((options.width ?? 1.5) * source.height) /+ (options.referenceHeight ?? 1080),+ Math.cos(((options.creaseAngle ?? 45) * Math.PI) / 180),+ options.depthThreshold ?? 0.01,+ options.opacity ?? 1,+ ]);+ const color = parseColor(options.color ?? "#16131c");+ data.set([color.r, color.g, color.b, color.a], 4);+ if (fog) {+ const tint = parseColor(fog.color);+ data.set([tint.r, tint.g, tint.b, 1], 8);+ data.set([fog.start, fog.end, fog.opacity ?? 1, 0], 12);+ }+ const projection = Camera3D.computeProjectionMatrix(camera);+ data.set([1 / projection[0], 1 / projection[5], camera.far, 0], 16);+ const bindGroup = this.device.createBindGroup({+ layout: this.layout,+ entries: [+ {+ binding: 0,+ resource: { buffer: this.pool.getBuffer(this.device, data) },+ },+ { binding: 1, resource: source.createView() },+ { binding: 2, resource: geometry.createView() },+ ],+ });+ const pass = encoder.beginRenderPass({+ colorAttachments: [this.attachment(source, dest)],+ });+ pass.setPipeline(this.pipeline);+ pass.setBindGroup(0, bindGroup);+ pass.draw(3);+ pass.end();+ }+}diff --git a/packages/webgpu-renderers/src/renderer3d/geometry-resolve-pipeline.ts b/packages/webgpu-renderers/src/renderer3d/geometry-resolve-pipeline.tsnew file mode 100644index 00000000..96d4c264--- /dev/null+++ b/packages/webgpu-renderers/src/renderer3d/geometry-resolve-pipeline.ts@@ -0,0 +1,75 @@+/**+ * Color MSAA resolves average samples. Depth and octahedral normals cannot+ * be averaged across silhouettes: that invents a distant surface and a+ * normal that belongs to neither object. Keep the nearest visible sample+ * and carry outline coverage separately, without re-rendering geometry.+ */+const shader = /* wgsl */ `+@group(0) @binding(0) var geometry : texture_multisampled_2d<f32>;+@vertex fn vs(@builtin(vertex_index) i : u32) -> @builtin(position) vec4<f32> {+ let p = vec2<f32>(f32((i << 1u) & 2u), f32(i & 2u));+ return vec4<f32>(p * 2.0 - 1.0, 0.0, 1.0);+}+@fragment fn fs(@builtin(position) pos : vec4<f32>) -> @location(0) vec4<f32> {+ let pixel = vec2<i32>(pos.xy);+ let samples = i32(textureNumSamples(geometry));+ var nearest = textureLoad(geometry, pixel, 0);+ var coverage = 0.0;+ for (var i = 0; i < samples; i++) {+ let s = textureLoad(geometry, pixel, i);+ if (s.r < nearest.r) { nearest = s; }+ coverage += s.a;+ }+ return vec4<f32>(nearest.rgb, nearest.a * coverage / f32(samples));+}+`;++export class GeometryResolvePipeline {+ private layout: GPUBindGroupLayout;+ private pipeline: GPURenderPipeline;++ constructor(private device: GPUDevice) {+ this.layout = device.createBindGroupLayout({+ entries: [+ {+ binding: 0,+ visibility: GPUShaderStage.FRAGMENT,+ texture: { sampleType: "unfilterable-float", multisampled: true },+ },+ ],+ });+ const module = device.createShaderModule({+ label: "geometry-resolve.wgsl",+ code: shader,+ });+ this.pipeline = device.createRenderPipeline({+ label: "GeometryResolve",+ layout: device.createPipelineLayout({ bindGroupLayouts: [this.layout] }),+ vertex: { module, entryPoint: "vs" },+ fragment: {+ module,+ entryPoint: "fs",+ targets: [{ format: "rgba16float" }],+ },+ primitive: { topology: "triangle-list" },+ });+ }++ render(+ encoder: GPUCommandEncoder,+ source: GPUTexture,+ dest: GPUTextureView,+ ): void {+ const bindGroup = this.device.createBindGroup({+ layout: this.layout,+ entries: [{ binding: 0, resource: source.createView() }],+ });+ const pass = encoder.beginRenderPass({+ colorAttachments: [{ view: dest, loadOp: "clear", storeOp: "store" }],+ });+ pass.setPipeline(this.pipeline);+ pass.setBindGroup(0, bindGroup);+ pass.draw(3);+ pass.end();+ }+}diff --git a/packages/webgpu-renderers/src/renderer3d/mesh3d-pipeline.ts b/packages/webgpu-renderers/src/renderer3d/mesh3d-pipeline.tsindex f8cfc13b..b4e38844 100644--- a/packages/webgpu-renderers/src/renderer3d/mesh3d-pipeline.ts+++ b/packages/webgpu-renderers/src/renderer3d/mesh3d-pipeline.ts@@ -144,7 +144,7 @@ export class Mesh3DPipeline {/** Outgrown white buffers: earlier draws this frame may still read them. */private retiredColorBuffers: GPUBuffer[] = [];- // 16 (model) + 16 (normal) + 4 (tint) + 4 (params) + 4 (materialParams) + 4 (shade) + 8 (pbr, emissive) + 4 (maps) = 60 floats (240 bytes)+ // Transform, tint, draw/material params, shade, shared surface block, maps.private modelData = new Float32Array(52 + SURFACE_PARAMS_FLOATS);constructor(@@ -480,12 +480,15 @@ export class Mesh3DPipeline {this.modelData[45] = shade[1];this.modelData[46] = shade[2];this.modelData[47] = data.alphaCutoff ?? 0;- packSurfaceParams(data, this.modelData, 48);+ packSurfaceParams(data, this.modelData, 48, data.shadeColor);const maps = data.maps;- this.modelData[56] = maps?.normal ? (maps.normalScale ?? 1) : 0;- this.modelData[57] = maps?.occlusion ? (maps.occlusionStrength ?? 1) : 0;- this.modelData[58] = maps?.metallicRoughness ? 1 : 0;- this.modelData[59] = maps?.emissive ? 1 : 0;+ const mapsOffset = 48 + SURFACE_PARAMS_FLOATS;+ this.modelData[mapsOffset] = maps?.normal ? (maps.normalScale ?? 1) : 0;+ this.modelData[mapsOffset + 1] = maps?.occlusion+ ? (maps.occlusionStrength ?? 1)+ : 0;+ this.modelData[mapsOffset + 2] = maps?.metallicRoughness ? 1 : 0;+ this.modelData[mapsOffset + 3] = maps?.emissive ? 1 : 0;const glass = data.glass;if (glass) {// shade.rgb and pbr.zw are unused outside toon: glass parameters.diff --git a/packages/webgpu-renderers/src/renderer3d/quad3d-pipeline.ts b/packages/webgpu-renderers/src/renderer3d/quad3d-pipeline.tsindex cea99b80..26dc9c8d 100644--- a/packages/webgpu-renderers/src/renderer3d/quad3d-pipeline.ts+++ b/packages/webgpu-renderers/src/renderer3d/quad3d-pipeline.ts@@ -84,7 +84,7 @@ export interface ModelUniformData extends SurfaceParams {height?: number;/** Fraction of the texture the layer covers, [u, v] (default the whole texture) */textureExtent?: [number, number];- material?: "lit" | "unlit";+ material?: "lit" | "unlit" | "toon";/** Screen-space track matte: the layer shows where this texture's alpha does. */matte?: GPUTexture;/** Turns the flat quad into a surface lifted by another picture's brightness. */@@ -106,6 +106,8 @@ export type MaterialUniformData = Pick<| "metallic"| "emissive"| "emissiveIntensity"+ | "toon"+ | "outline">;/** [shininess, specularIntensity, ambientIntensity, materialMode] as the 3D shaders' lighting reads them. */@@ -121,7 +123,8 @@ export function packMaterialParams(? data.metallic: (data.specularIntensity ?? 0.5);const ambientInt = data.ambientIntensity ?? 1.0;- const materialMode = data.material === "unlit" ? 0.0 : 1.0;+ const materialMode =+ data.material === "unlit" ? 0.0 : data.material === "toon" ? 2.0 : 1.0;return [shininess, specInt, ambientInt, materialMode];}@@ -145,7 +148,7 @@ export class Quad3DPipeline {indices: GPUBuffer;count: number;};- // 16 (model) + 16 (normal) + 4 (tint) + 4 (borderColor) + 4 (params) + 4 (dimensions) + 4 (materialParams) + 8 (pbr, emissive) + 12 (relief) = 72 floats (288 bytes)+ // Transform, colors, draw/dimensions/material params, shared surface block, relief.private modelData = new Float32Array(MODEL_FLOATS);constructor(diff --git a/packages/webgpu-renderers/src/renderer3d/renderer3d.ts b/packages/webgpu-renderers/src/renderer3d/renderer3d.tsindex 166d7cf2..3f28422f 100644--- a/packages/webgpu-renderers/src/renderer3d/renderer3d.ts+++ b/packages/webgpu-renderers/src/renderer3d/renderer3d.ts@@ -1,4 +1,7 @@-import type { MeshAudioDeformConfig } from "@framefields/core";+import type {+ GeometryOutlineOptions,+ MeshAudioDeformConfig,+} from "@framefields/core";import { type Color, parseColor } from "../color.js";import {FbxLoader,@@ -25,6 +28,7 @@ import type {} from "../loaders/types.js";import type {Environment3DFloor,+ Environment3DFog,Environment3DOptions,ShadowUniformInfo,} from "../math3d/environment3d.js";@@ -47,6 +51,8 @@ import type { SlugGlyphBatch } from "../slug/slug-pipeline.js";import { AudioMeshDeformPipeline } from "./audio-mesh-deform-pipeline.js";import { type BloomOptions, BloomPipeline } from "./bloom-pipeline.js";import { FloorReflectionPipeline } from "./floor-reflection-pipeline.js";+import { GeometryOutlinePipeline } from "./geometry-outline-pipeline.js";+import { GeometryResolvePipeline } from "./geometry-resolve-pipeline.js";import { decodeKtx2, isKtx2 } from "./ktx2.js";import {type GPUMeshBuffers,@@ -103,7 +109,7 @@ export interface DrawQuad3DOpts extends SurfaceParams {/** Pre-computed normal matrix */normalMatrix?: Mat4;/** Material shading mode ("lit" vs "unlit") */- material?: "lit" | "unlit";+ material?: "lit" | "unlit" | "toon";/** Blinn-Phong specular shininess exponent */shininess?: number;/** Roughness factor [0, 1] */@@ -299,6 +305,8 @@ export class Renderer3D {private shadowSampler: GPUSampler | null = null;private meshBounds = new WeakMap<Mesh3DData, Aabb>();private bloomPipeline: BloomPipeline | null = null;+ private outlinePipeline: GeometryOutlinePipeline | null = null;+ private geometryResolvePipeline: GeometryResolvePipeline | null = null;private lastCameraBuffer: GPUBuffer | null = null;/**@@ -453,6 +461,7 @@ export class Renderer3D {this.attachments.delete(key);}this.attachmentsUsed.clear();+ this.outlinePipeline?.reset();this.bloomPipeline?.resetPools();this.cameraPool.reset();// The cached camera buffer goes back to the pool and may be handed@@ -490,11 +499,14 @@ export class Renderer3D {format: GPUTextureFormat,width: number,height: number,+ sampled = false,): GPUTexture {return this.attachment(label, width, height, {format,sampleCount: this.sampleCount,- usage: GPUTextureUsage.RENDER_ATTACHMENT,+ usage:+ GPUTextureUsage.RENDER_ATTACHMENT |+ (sampled ? GPUTextureUsage.TEXTURE_BINDING : 0),});}@@ -1001,6 +1013,7 @@ export class Renderer3D {this.format,surfaceWidth,surfaceHeight,+ Boolean(world?.environment?.outlines),);}const colorAttachments: GPURenderPassColorAttachment[] = [@@ -1011,6 +1024,10 @@ export class Renderer3D {loadOp,),];+ if (msaa && world?.environment?.outlines) {+ // Ink shades the original color and geometry samples before resolving.+ colorAttachments[0].storeOp = "store";+ }if (linearDepthTargetView) {if (msaa) {@@ -1020,16 +1037,21 @@ export class Renderer3D {"rgba16float",surfaceWidth,surfaceHeight,+ true,);}- colorAttachments.push(- attach(- linearDepthTargetView,- msaa ? this.msaaLinearDepthTexture : null,- { r: camera.far, g: 0, b: 0, a: 1 },- "clear",- ),+ const geometryAttachment = attach(+ linearDepthTargetView,+ msaa ? this.msaaLinearDepthTexture : null,+ { r: Math.min(camera.far, 65504), g: 0.5, b: 0.5, a: 0 },+ "clear",);+ // Outline metadata needs a nearest-sample resolve, not a color average.+ if (msaa && world?.environment?.outlines) {+ geometryAttachment.resolveTarget = undefined;+ geometryAttachment.storeOp = "store";+ }+ colorAttachments.push(geometryAttachment);}this.passWritesHdr = writeHdr;@@ -1197,10 +1219,11 @@ export class Renderer3D {}/**- * A layer's unit quad ([-0.5, 0.5] square) in world space:- * T(pos) * Rz * Ry * Rx * S(w * sx, h * sy, sz) * T(0.5 - ax, 0.5 - ay, 0).+ * A centered unit quad in world space. Translate to the authored pivot,+ * rotate and scale, then offset the unit quad back from that pivot.+ * Shared with children in preserve-3d containers.*/- private quadModelMatrix(opts: DrawQuad3DOpts): Mat4 {+ quadModelMatrix(opts: DrawQuad3DOpts): Mat4 {if (opts.modelMatrix) return opts.modelMatrix;const {position,@@ -1213,7 +1236,13 @@ export class Renderer3D {let m = Matrix4Math.identity();m = Matrix4Math.multiply(m,- Matrix4Math.translate(position[0], position[1], position[2]),+ // Position is the untransformed center. Move to the authored pivot+ // before rotating/scaling, then move back in unit-quad space below.+ Matrix4Math.translate(+ position[0] + (anchor[0] - 0.5) * width,+ position[1] + (anchor[1] - 0.5) * height,+ position[2],+ ),);const rxRad = (rotation[0] * Math.PI) / 180;@@ -1310,6 +1339,8 @@ export class Renderer3D {metallic: opts.metallic,emissive: opts.emissive,emissiveIntensity: opts.emissiveIntensity,+ toon: opts.toon,+ outline: opts.outline,matte: opts.matte,},useMrt,@@ -1383,6 +1414,8 @@ export class Renderer3D {metallic,emissive: opts.emissive,emissiveIntensity: opts.emissiveIntensity,+ toon: opts.toon,+ outline: opts.outline,matte: opts.matte,relief: opts.relief,},@@ -1731,6 +1764,8 @@ export class Renderer3D {metallic,emissive: opts.emissive,emissiveIntensity: opts.emissiveIntensity,+ toon: opts.toon,+ outline: opts.outline,matte: opts.matte,maps: opts.maps,isInstanced: Boolean(@@ -1949,6 +1984,52 @@ export class Renderer3D {);}+ /** Geometry ink is applied before lens blur, independently of material shading. */+ resolveGeometry(encoder: GPUCommandEncoder, geometry: GPUTexture): void {+ if (this.sampleCount <= 1 || !this.msaaLinearDepthTexture) return;+ this.geometryResolvePipeline ??= new GeometryResolvePipeline(this.device);+ this.geometryResolvePipeline.render(+ encoder,+ this.msaaLinearDepthTexture,+ geometry.createView(),+ );+ }++ applyOutlines(+ encoder: GPUCommandEncoder,+ source: GPUTexture,+ geometry: GPUTexture,+ dest: GPUTextureView,+ camera: Camera3DPose,+ options: GeometryOutlineOptions,+ fog?: Environment3DFog,+ ): void {+ let colorSource = source;+ let geometrySource = geometry;+ if (this.sampleCount > 1) {+ if (!this.msaaColorTexture || !this.msaaLinearDepthTexture)+ throw new Error(+ "Geometry outlines require the scene's retained MSAA color and geometry samples",+ );+ colorSource = this.msaaColorTexture;+ geometrySource = this.msaaLinearDepthTexture;+ }+ this.outlinePipeline ??= new GeometryOutlinePipeline(+ this.device,+ this.format,+ this.sampleCount,+ );+ this.outlinePipeline.render(+ encoder,+ colorSource,+ geometrySource,+ dest,+ camera,+ options,+ fog,+ );+ }+applyDepthOfField(encoder: GPUCommandEncoder,sourceColorTex: GPUTexture,@@ -2020,6 +2101,7 @@ export class Renderer3D {for (const texture of this.attachments.values()) texture.destroy();this.attachments.clear();this.bloomPipeline?.destroy();+ this.outlinePipeline?.destroy();this.depthTexture?.destroy();for (const texture of this.shadowTextures.values()) texture.destroy();this.shadowTextures.clear();diff --git a/packages/webgpu-renderers/src/renderer3d/slug3d-pipeline.ts b/packages/webgpu-renderers/src/renderer3d/slug3d-pipeline.tsindex 23a136d1..aaa5f78e 100644--- a/packages/webgpu-renderers/src/renderer3d/slug3d-pipeline.ts+++ b/packages/webgpu-renderers/src/renderer3d/slug3d-pipeline.ts@@ -41,7 +41,7 @@ export class Slug3DPipeline {private modelPool: BufferPool;private instancePool: BufferPool;private fontBindGroups = new WeakMap<GPUTexture, GPUBindGroup>();- // 16 (model) + 16 (normal) + 4 (params) + 4 (materialParams) + 8 (pbr, emissive) = 48 floats (192 bytes)+ // Transform, draw/material params and the shared surface block.private modelData = new Float32Array(40 + SURFACE_PARAMS_FLOATS);constructor(diff --git a/packages/webgpu-renderers/src/renderer3d/surface-params.ts b/packages/webgpu-renderers/src/renderer3d/surface-params.tsindex 2afaf3c1..3c69cbce 100644--- a/packages/webgpu-renderers/src/renderer3d/surface-params.ts+++ b/packages/webgpu-renderers/src/renderer3d/surface-params.ts@@ -1,8 +1,11 @@+import type { ToonShading } from "@framefields/core";import { parseColor } from "../color.js";import type { Color } from "../renderer2d/index.js";/** Physically based surface inputs every 3D draw (quad, text, mesh) accepts. */export interface SurfaceParams {+ toon?: ToonShading;+ outline?: boolean;/** Microsurface roughness 0 (mirror) .. 1 (chalk). Physical scenes default to 0.5. */roughness?: number;/** 0 = dielectric (plastic, paint, wood), 1 = metal. */@@ -15,18 +18,36 @@ export interface SurfaceParams {castShadow?: boolean;}-/** Floats appended to each 3D model uniform block: pbr vec4 + emissive vec4. */-export const SURFACE_PARAMS_FLOATS = 8;+/** Shared model uniforms: PBR, emissive, and three art-direction vec4s. */+export const SURFACE_PARAMS_FLOATS = 20;export function packSurfaceParams(data: SurfaceParams,out: Float32Array,offset: number,+ modelShade?: [number, number, number],): void {out[offset] = data.roughness ?? -1;out[offset + 1] = data.metallic ?? 0;out[offset + 2] = 0;out[offset + 3] = 0;+ const shadow = data.toon?.shadowColor+ ? parseColor(data.toon.shadowColor)+ : null;+ out.set(+ shadow ? [shadow.r, shadow.g, shadow.b] : (modelShade ?? [0.5, 0.5, 0.55]),+ offset + 8,+ );+ out[offset + 11] = data.toon?.diffuse ?? 0;+ const light = parseColor(data.toon?.lightColor ?? "#ffffff");+ out.set(+ [light.r, light.g, light.b, data.toon?.threshold ?? 0.075],+ offset + 12,+ );+ out.set(+ [data.toon?.softness ?? 0.25, data.outline === false ? 0 : 1, 0, 0],+ offset + 16,+ );const e = data.emissive;if (e === undefined || e === null) {out.fill(0, offset + 4, offset + 8);diff --git a/packages/webgpu-renderers/src/shaders/lighting3d.ts b/packages/webgpu-renderers/src/shaders/lighting3d.tsindex c240c097..0173462d 100644--- a/packages/webgpu-renderers/src/shaders/lighting3d.ts+++ b/packages/webgpu-renderers/src/shaders/lighting3d.ts@@ -382,15 +382,56 @@ struct Shaded {hdr : vec3<f32>,};+// Two-sided, art-directed diffuse lighting. Shares the full direct-light+// storage, range/spot attenuation and PCF shadows with the physical renderer.+fn shadeToon(worldPos: vec3<f32>, worldNormal: vec3<f32>, base: vec3<f32>, ambient: f32, shade: vec4<f32>, lightTint: vec4<f32>, params: vec4<f32>) -> vec3<f32> {+ if (lights.params.y < 0.5) { return base; }+ var N = normalize(worldNormal);+ let V = normalize(cam.cameraPos.xyz - worldPos);+ if (dot(N, V) < 0.0) { N = -N; }+ var illumination = lights.ambientColor.rgb * ambient * lightTint.rgb;+ var visibility = clamp(max(illumination.r, max(illumination.g, illumination.b)), 0.0, 1.0);+ for (var i = 0; i < i32(lights.params.x); i++) {+ let ls = sampleLight(i, worldPos);+ if (!ls.valid) { continue; }+ let cosine = dot(N, ls.L);+ let softness = max(params.x, 0.0001);+ let band = smoothstep(lightTint.w - softness * 0.5, lightTint.w + softness * 0.5, cosine);+ let light = directLights[i];+ let strength = band * ls.attenuation * light.colorIntensity.w * shadowFactor(worldPos, N, i);+ let contribution = light.colorIntensity.rgb * lightTint.rgb * strength * mix(1.0, max(cosine, 0.0), shade.w);+ // Remove the shadow floor only as actual modeled light arrives.+ // Using the pre-diffuse band here creates a dark ring between the+ // shadow floor and the lit region, which slides as a surface turns.+ let energy = max(contribution.r, max(contribution.g, contribution.b));+ visibility = max(visibility, clamp(energy, 0.0, 1.0));+ illumination += contribution;+ }+ return base * (shade.rgb * (1.0 - visibility) + illumination);+}++// The existing linear-depth attachment doubles as a geometry buffer:+// r = optical depth, gb = octahedral world normal, a = outline participation.+// Geometric normals deliberately ignore normal maps and texture seams.+fn geometryPixel(depth: f32, normal: vec3<f32>, outlined: f32) -> vec4<f32> {+ let n = normalize(normal);+ let p = n.xy / max(abs(n.x) + abs(n.y) + abs(n.z), 1e-6);+ let signs = select(vec2<f32>(-1.0), vec2<f32>(1.0), p >= vec2<f32>(0.0));+ let oct = select((1.0 - abs(p.yx)) * signs, p, n.z >= 0.0);+ return vec4<f32>(depth, oct * 0.5 + 0.5, outlined);+}+/// Shades a surface for the scene's mode./// material: x shininess, y specularIntensity, z ambientIntensity, w mode (0 unlit)./// pbr: x roughness (<0 = default), y metallic, z/w unused./// emissive: rgb sRGB color, w strength.-fn shadeSurfaceFull(worldPos: vec3<f32>, worldNormal: vec3<f32>, baseColor: vec3<f32>, material: vec4<f32>, pbr: vec4<f32>, emissive: vec4<f32>) -> Shaded {+fn shadeSurfaceFull(worldPos: vec3<f32>, worldNormal: vec3<f32>, baseColor: vec3<f32>, material: vec4<f32>, pbr: vec4<f32>, emissive: vec4<f32>, toonShadow: vec4<f32>, toonLight: vec4<f32>, toonParams: vec4<f32>) -> Shaded {var out: Shaded;if (lights.params.z < 0.5) {var c = baseColor;- if (material.w >= 0.5) {+ if (material.w > 1.5) {+ c = shadeToon(worldPos, worldNormal, baseColor, material.z, toonShadow, toonLight, toonParams);+ } else if (material.w >= 0.5) {c = applyLighting3D(worldPos, worldNormal, baseColor, material);}c += emissive.rgb * emissive.w;@@ -401,6 +442,8 @@ fn shadeSurfaceFull(worldPos: vec3<f32>, worldNormal: vec3<f32>, baseColor: vec3var radiance: vec3<f32>;if (material.w < 0.5) {radiance = srgbToLinear(baseColor);+ } else if (material.w > 1.5) {+ radiance = srgbToLinear(shadeToon(worldPos, worldNormal, baseColor, material.z, toonShadow, toonLight, toonParams));} else {let rough = select(pbr.x, 0.5, pbr.x < 0.0);radiance = shadePhysical(worldPos, worldNormal, srgbToLinear(baseColor), rough, clamp(pbr.y, 0.0, 1.0), material.z);@@ -436,9 +479,6 @@ fn shadeSurfaceFull(worldPos: vec3<f32>, worldNormal: vec3<f32>, baseColor: vec3return out;}-fn shadeSurface(worldPos: vec3<f32>, worldNormal: vec3<f32>, baseColor: vec3<f32>, material: vec4<f32>, pbr: vec4<f32>, emissive: vec4<f32>) -> vec3<f32> {- return shadeSurfaceFull(worldPos, worldNormal, baseColor, material, pbr, emissive).display;-}`;/** Group-3 bindings every lit 3D shader declares. */diff --git a/packages/webgpu-renderers/src/shaders/mesh3d.ts b/packages/webgpu-renderers/src/shaders/mesh3d.tsindex d027b98a..26fc7a81 100644--- a/packages/webgpu-renderers/src/shaders/mesh3d.ts+++ b/packages/webgpu-renderers/src/shaders/mesh3d.ts@@ -22,6 +22,9 @@ struct ModelUniforms {shade : vec4<f32>, // rgb = toon shadow-side color multiplier, a = alpha cutoff (0 = none)pbr : vec4<f32>, // x = roughness (<0 = default), y = metallicemissive : vec4<f32>, // rgb = sRGB emissive color, w = strength+ toonShadow : vec4<f32>, // rgb shadow-side multiplier, w diffuse modelling+ toonLight : vec4<f32>, // rgb lit-side multiplier, w terminator threshold+ toonParams : vec4<f32>, // x terminator softness, y outline participationmaps : vec4<f32>, // x = normal scale (0 = no map), y = occlusion strength, z = has metallic-roughness map, w = has emissive map};@@ -162,37 +165,6 @@ fn vs_main(return out;}-// Toon (MToon-style): the base color as authored where the light reaches,-// the shade color past a soft terminator. Highlights stay out: the texture-// already paints them.-fn toonLighting(in: VertexOutput, baseColor: vec3<f32>) -> vec3<f32> {- var N = normalize(in.worldNormal);- let V = normalize(cam.cameraPos.xyz - in.worldPos);- if (dot(N, V) < 0.0) {- N = -N;- }- var lit = 0.0;- let numLights = i32(lights.params.x);- for (var i = 0; i < 8; i++) {- if (i >= numLights) {- break;- }- let light = lights.lights[i];- let lightType = light.posType.w;- var L = vec3<f32>(0.0, 0.0, 1.0);- if (lightType > 0.5 && lightType < 1.5) {- L = normalize(-light.dirRadius.xyz);- } else if (lightType >= 1.5) {- L = normalize(light.posType.xyz - in.worldPos);- } else {- continue;- }- let terminator = smoothstep(-0.05, 0.2, dot(N, L));- lit = max(lit, terminator * min(light.colorIntensity.w, 1.0));- }- return baseColor * mix(model.shade.rgb, vec3<f32>(1.0), lit);-}-struct MeshFragment {color : vec4<f32>, // premultiplied display colorhdr : vec4<f32>, // premultiplied scene radiance (bloom source)@@ -260,7 +232,7 @@ fn shadeGlass(in: VertexOutput, Nin: vec3<f32>, tint: vec3<f32>, alpha: f32, rimlet transmitted = col * depthTint * (1.0 - 0.45 * rim * rim);let f0 = pow((ior - 1.0) / (ior + 1.0), 2.0);let F = f0 + (1.0 - f0) * pow(rim, 5.0);- let lit = shadeSurfaceFull(in.worldPos, N, vec3<f32>(0.0), model.materialParams, vec4<f32>(model.pbr.x, 0.0, 0.0, 0.0), vec4<f32>(0.0));+ let lit = shadeSurfaceFull(in.worldPos, N, vec3<f32>(0.0), model.materialParams, vec4<f32>(model.pbr.x, 0.0, 0.0, 0.0), vec4<f32>(0.0), model.toonShadow, model.toonLight, model.toonParams);// Grazing faces mirror the room; keep that faint so dark scenes stay dark// and the studio highlights below carry the shape.let sheen = vec3<f32>(0.9, 0.94, 1.0) * F * 0.22 + tint * 0.05 * (0.4 + rim);@@ -308,19 +280,6 @@ fn shadeMesh(in: VertexOutput, isFront: bool) -> MeshFragment {let baseRgb = texColor.rgb * in.color.rgb * model.colorTint.rgb;var out: MeshFragment;- if (model.materialParams.w > 1.5) {- var toon = baseRgb;- if (lights.params.y >= 0.5) {- toon = toonLighting(in, baseRgb);- }- if (model.params.w > 0.5 && (in.emissive.w > 0.0 || dot(in.emissive.rgb, in.emissive.rgb) > 0.0)) {- toon += in.emissive.rgb * in.emissive.w;- }- out.color = vec4<f32>(toon * alpha, alpha);- out.hdr = vec4<f32>(srgbToLinear(toon) * alpha, alpha);- return out;- }-var N = normalize(in.worldNormal);if (model.maps.x > 0.0) {var tn = normalSample * 2.0 - 1.0;@@ -350,7 +309,7 @@ fn shadeMesh(in: VertexOutput, isFront: bool) -> MeshFragment {if (model.params.w > 0.5 && (in.emissive.w > 0.0 || dot(in.emissive.rgb, in.emissive.rgb) > 0.0)) {emissive = in.emissive;}- let shaded = shadeSurfaceFull(in.worldPos, N, baseRgb, material, pbr, emissive);+ let shaded = shadeSurfaceFull(in.worldPos, N, baseRgb, material, pbr, emissive, model.toonShadow, model.toonLight, model.toonParams);out.color = vec4<f32>(shaded.display * alpha, alpha);out.hdr = vec4<f32>(shaded.hdr * alpha, alpha);return out;@@ -381,7 +340,7 @@ fn fs_single(in: VertexOutput, @builtin(front_facing) isFront: bool) -> @locatiofn fs_mrt(in: VertexOutput, @builtin(front_facing) isFront: bool) -> MrtOutput {var out: MrtOutput;out.color = shadeMesh(in, isFront).color;- out.depth = vec4<f32>(in.linearDepth, 0.0, 0.0, 1.0);+ out.depth = geometryPixel(in.linearDepth, in.worldNormal, model.toonParams.y);return out;}@@ -399,7 +358,7 @@ fn fs_mrt_bloom(in: VertexOutput, @builtin(front_facing) isFront: bool) -> MrtBllet f = shadeMesh(in, isFront);var out: MrtBloomOutput;out.color = f.color;- out.depth = vec4<f32>(in.linearDepth, 0.0, 0.0, 1.0);+ out.depth = geometryPixel(in.linearDepth, in.worldNormal, model.toonParams.y);out.hdr = f.hdr;return out;}diff --git a/packages/webgpu-renderers/src/shaders/quad3d.ts b/packages/webgpu-renderers/src/shaders/quad3d.tsindex 746c8353..fb1dd6ff 100644--- a/packages/webgpu-renderers/src/shaders/quad3d.ts+++ b/packages/webgpu-renderers/src/shaders/quad3d.ts@@ -22,6 +22,9 @@ struct ModelUniforms {materialParams : vec4<f32>, // x = shininess, y = specularIntensity, z = ambientIntensity, w = materialMode (0=unlit, 1=lit)pbr : vec4<f32>, // x = roughness (<0 = default), y = metallicemissive : vec4<f32>, // rgb = sRGB emissive color, w = strength+ toonShadow : vec4<f32>, // rgb shadow-side multiplier, w diffuse modelling+ toonLight : vec4<f32>, // rgb lit-side multiplier, w terminator threshold+ toonParams : vec4<f32>, // x terminator softness, y outline participationrelief : vec4<f32>, // x = amount (px), y = on, w = grid cells per sidereliefRect : vec4<f32>, // xy = where the layer's box starts in reliefTex (0..1), zw = its sizereliefEye : vec4<f32>, // xyz = the eye the surface keeps its look from (the default camera)@@ -216,7 +219,7 @@ fn shadeQuad(in: VertexOutput, isFront: bool) -> QuadFragment {discard;}- let shaded = shadeSurfaceFull(in.worldPos, in.worldNormal, baseRgb, model.materialParams, model.pbr, model.emissive);+ let shaded = shadeSurfaceFull(in.worldPos, in.worldNormal, baseRgb, model.materialParams, model.pbr, model.emissive, model.toonShadow, model.toonLight, model.toonParams);var out: QuadFragment;out.color = vec4<f32>(shaded.display * alpha, alpha);out.hdr = vec4<f32>(shaded.hdr * alpha, alpha);@@ -248,7 +251,7 @@ fn fs_single(in: VertexOutput, @builtin(front_facing) isFront: bool) -> @locatiofn fs_mrt(in: VertexOutput, @builtin(front_facing) isFront: bool) -> MrtOutput {var out: MrtOutput;out.color = shadeQuad(in, isFront).color;- out.depth = vec4<f32>(in.linearDepth, 0.0, 0.0, 1.0);+ out.depth = geometryPixel(in.linearDepth, in.worldNormal, model.toonParams.y);return out;}@@ -266,7 +269,7 @@ fn fs_mrt_bloom(in: VertexOutput, @builtin(front_facing) isFront: bool) -> MrtBllet f = shadeQuad(in, isFront);var out: MrtBloomOutput;out.color = f.color;- out.depth = vec4<f32>(in.linearDepth, 0.0, 0.0, 1.0);+ out.depth = geometryPixel(in.linearDepth, in.worldNormal, model.toonParams.y);out.hdr = f.hdr;return out;}diff --git a/packages/webgpu-renderers/src/shaders/slug3d.ts b/packages/webgpu-renderers/src/shaders/slug3d.tsindex 0a5f5993..e74f8b46 100644--- a/packages/webgpu-renderers/src/shaders/slug3d.ts+++ b/packages/webgpu-renderers/src/shaders/slug3d.ts@@ -19,6 +19,9 @@ struct TextModelUniforms {materialParams : vec4<f32>, // x = shininess, y = specularIntensity, z = ambientIntensity, w = materialMode (0=unlit, 1=lit)pbr : vec4<f32>, // x = roughness (<0 = default), y = metallicemissive : vec4<f32>, // rgb = sRGB emissive color, w = strength+ toonShadow : vec4<f32>, // rgb shadow-side multiplier, w diffuse modelling+ toonLight : vec4<f32>, // rgb lit-side multiplier, w terminator threshold+ toonParams : vec4<f32>, // x terminator softness, y outline participation};@group(0) @binding(0) var<uniform> cam : CameraUniforms;@@ -151,7 +154,7 @@ fn shadeText(in : VSOut, fw : vec2<f32>) -> TextFragment {if (shaded.a < 0.0001) {return out;}- let lit = shadeSurfaceFull(in.worldPos, in.worldNormal, shaded.rgb / shaded.a, model.materialParams, model.pbr, model.emissive);+ let lit = shadeSurfaceFull(in.worldPos, in.worldNormal, shaded.rgb / shaded.a, model.materialParams, model.pbr, model.emissive, model.toonShadow, model.toonLight, model.toonParams);out.color = vec4<f32>(lit.display * shaded.a, shaded.a);out.hdr = vec4<f32>(lit.hdr * shaded.a, shaded.a);return out;@@ -192,7 +195,7 @@ struct MrtBloomOutput {@fragment fn fs_mrt(in : VSOut) -> MrtOutput {var out : MrtOutput;out.color = textFragment(in).color;- out.depth = vec4<f32>(in.linearDepth, 0.0, 0.0, 1.0);+ out.depth = geometryPixel(in.linearDepth, in.worldNormal, model.toonParams.y);return out;}@@ -208,7 +211,7 @@ struct MrtBloomOutput {let f = textFragment(in);var out : MrtBloomOutput;out.color = f.color;- out.depth = vec4<f32>(in.linearDepth, 0.0, 0.0, 1.0);+ out.depth = geometryPixel(in.linearDepth, in.worldNormal, model.toonParams.y);out.hdr = f.hdr;return out;}diff --git a/plugins/framefields/skills/framefields-compose/SKILL.md b/plugins/framefields/skills/framefields-compose/SKILL.mdindex a181dac1..000d3558 100644--- a/plugins/framefields/skills/framefields-compose/SKILL.md+++ b/plugins/framefields/skills/framefields-compose/SKILL.md@@ -87,7 +87,7 @@ All `Layer.*` builders return `AnimatableNode<T>` instances with chainable `.ani| Builder | Node `kind` | Description & Key Options ||---|---|---|| `Layer.text(content, options)` | `"text"` | Slug GPU vector text. Options: `fontSize`, `fontFamily`, `fill`, `letterSpacing`, `lineHeight`, `align`, `direction`, `animators`, `spans`. Arabic, Hebrew and Persian are shaped and laid out right to left automatically (`direction: "auto"`); set `"rtl"`/`"ltr"` to force it. `align: "start"`/`"end"` follow the direction. |-| `Layer.box(options)` | `"box"` | Rectangular container / card. Options: `background`, `borderRadius`, `borderColor`, `borderWidth`, `overflow: "hidden"`, `padding`, `children`. |+| `Layer.box(options)` | `"box"` | Rectangular container / card. Options: `background`, `borderRadius`, `borderColor`, `borderWidth`, `overflow` (`"visible"` by default; `"hidden"` clips children to the box and its rounded corners), `padding`, `children`. || `Layer.flex(options)` | `"flex"` | Auto-layout container (Yoga). Options: `dir: "row" \| "column"`, `gap`, `justify`, `align`, `padding`, `wrap`, `children`. || `Layer.video(src, options)` | `"media"` | Video layer decoded via mediabunny. Options: `fit: "cover" \| "contain"`, `trimStartSec`, `muted`, `volume`. || `Layer.image(src, options)` | `"media"` | Static raster image (`.png`, `.jpg`, `.webp`). Options: `fit: "cover" \| "contain"`. For vector animations (`.json`, `.lottie`), use `Layer.lottie`. |@@ -474,6 +474,13 @@ Layer3D.cylinder({ ..., color: "#111", emissive: "#4da3ff", emissiveIntensity: 3- **Tone mapping `"neutral"` (default) keeps brand colors as authored**: orange stays orange. Use `"agx"` for a filmic roll-off.- **Bloom only takes light well past white** (emissive ≳ 3, hot speculars), so ordinary bright surfaces don't glow. Raise `emissiveIntensity` to make something glow.- **Shadows:** directional and spot lights can each cast shadows, subject to device texture-array limits. Meshes cast by default (`castShadow: false` opts out); flat layers (planes, cards) cast only with `castShadow: true`. Everything receives.+- **Art-directed materials:** `material: "toon"` works on meshes, flat 3D cards and native 3D text. Its `toon` options are `shadowColor` (shadow-side albedo multiplier; model shade color or `#80808c`), `lightColor` (lit-side multiplier; white), `threshold` (terminator cosine; 0.075), `softness` (transition width; 0.25) and `diffuse` (0 flat through 1 Lambert; 0). Toon surfaces use all scene lights, their colors, point/spot attenuation and real cast shadows; environment exposure, tone mapping, fog and emissive bloom still apply. Lower `threshold` to wrap light around a surface, or raise `shadowColor` for a bright shadow floor on illustrated cards. Physical and unlit materials are independent of these options.+- **Geometry outlines:** `Layer.environment("neutral", { outlines: true })`, or `outlines: { color: "#191721", width: 2, referenceHeight: 1080, creaseAngle: 45, depthThreshold: 0.01, opacity: 1 }`. Width is in pixels at `referenceHeight` (default 1080), scaled with output height. Silhouettes/depth jumps use inverse-depth curvature; creases use surface normals, so textures, shadows and coplanar triangle seams do not acquire ink. `creaseAngle: 180` keeps only silhouettes/depth edges; `width: 0`, `opacity: 0` or `outlines: false` hides ink. Set `outline: false` on a 3D layer/model to exclude it while preserving its occlusion of outlines behind it (useful for already-outlined character artwork). Ink follows scene fog and runs **before** camera depth blur and bloom. This is a scene geometry pass, separate from the image-based `Toon` effect.+- **3D pivots:** `anchorX/Y` choose the point held fixed during scale/rotation; changing an anchor at identity transform leaves the layer in place. Use `anchorY: 1` to keep a character's feet planted while scaling.++With MSAA enabled, geometry ink shades the original color/depth/normal samples and then resolves color. Detecting contours only after the scene resolves loses subpixel coverage, especially where two outlined surfaces meet. Lens blur receives a separate nearest-sample depth resolve; normals and depths are never color-averaged for ink detection. Already-inked character artwork can remain excluded without losing occlusion. See `examples/34_spatial_styling` in the engine repository for daylight and firelit native scenes using these controls.++Custom `Layer3D.cube({ faces: { front: Layer.box(...) } })` artwork inherits the cube's surface settings (including `toon`, `outline`, emissive and shadow casting), while explicit face settings take precedence. For delicate illustrated scenes, start near a one-pixel outline at the export height and use moderate lens blur: heavy defocus can spread a dark contour into a wide band on distant architecture.- **Fog** fades to `fog.color` exactly, so set it to the composition background for a seamless horizon.- **Models:** glTF materials bring base color, normal, metallic-roughness, occlusion and emissive maps; OBJ (`map_Kd`, `norm` in the `.mtl`) and FBX bring diffuse and normal maps, looked up next to the model. Textures can be PNG, JPEG, WebP, GIF, TIFF, AVIF or Basis KTX2 (ETC1S/UASTC, transcoded offline to RGBA8); TGA, PSD and DDS are skipped with a warning. Draco and meshopt-compressed glTF geometry is decoded by the asynchronous compositor loader; individual maps retain their own UV sets and texture transforms. glTF morph weights animate on the GPU before skinning. Unknown required glTF extensions fail clearly. Vertex colors (VOX, PLY, OFF, glTF `COLOR_0`) multiply the base color.- **Model orientation:** the world is y-down, so a y-up model (most glTF, OBJ and FBX files) needs `rotateX: 180` to stand upright.diff --git a/plugins/framefields/skills/framefields-effects/SKILL.md b/plugins/framefields/skills/framefields-effects/SKILL.mdindex 0c685f06..f99891c2 100644--- a/plugins/framefields/skills/framefields-effects/SKILL.md+++ b/plugins/framefields/skills/framefields-effects/SKILL.md@@ -146,6 +146,7 @@ The effects behind them, for finer control:- **`Dither`**: `bayer` / `noise` / `halftone`; 1-bit duotone (`dark` / `light`) or per-channel `levels`.- **`Ascii`**: glyphs by brightness; `colorMode: "mono" | "source" | "green"`, `cellSize`, `fg` / `bg`, `invert`.- **`Toon`**: brightness bands plus Sobel ink lines (`edgeColor`, `edgeWidth`, `edgeThreshold`).+- **Geometry outlines for 3D:** use `Layer.environment(..., { outlines: { width: 2, referenceHeight: 1080, color: "#16131c", creaseAngle: 45 } })`. These use depth and surface normals rather than image contrast, ignore painted textures and lighting boundaries, follow scene fog, and render before camera depth blur and bloom. A layer/model with `outline: false` still occludes ink behind it. `material: "toon"` plus `toon: { shadowColor, lightColor, threshold, softness, diffuse }` controls actual surface lighting, including colored lights and cast shadows. These scene/material capabilities are independent of the 2D `Toon` effect and do not change the default physical look; see `framefields-compose` for defaults and ranges.- **`RGBSplit`**: chromatic aberration along `angle` or `radial`.- **`CRT`**: curvature, scanlines, aperture mask, noise, flicker, vignette; `tracking` and `chroma` give VHS wobble and colour bleed.- **`Painterly`**: Kuwahara `oil` / `watercolor` (pigment edges, paper grain).