Skip to content

Code-first video & image, rendered natively on WebGPU.

feat(3d): glTF materials drive the layered lobes; energy-conserving skin scattering

okanaslec65a81a3d43
diff --git a/.changeset/gltf-material-lobes.md b/.changeset/gltf-material-lobes.md
new file mode 100644
index 00000000..dcf1c1d3
--- /dev/null
+++ b/.changeset/gltf-material-lobes.md
@@ -0,0 +1,7 @@
+---
+"framefields": minor
+---
+
+glTF models render their own layered materials: `KHR_materials_clearcoat`, `_sheen`, `_anisotropy` and `_iridescence` (and forge's `subsurface`, in `extras.framefields.subsurface`) feed the matching shading lobes, under any lobe props set on the layer.
+
+Subsurface scattering now conserves energy: each color channel's light wraps past the shadow edge by how far that channel scatters, instead of a near-white glow being added over the surface and an ambient tint across it. Skin keeps its form and only its shadow edges warm; previous `subsurface` looks render less washed out.
diff --git a/nodes/node-compositor/src/renderers/webgpu-renderer.ts b/nodes/node-compositor/src/renderers/webgpu-renderer.ts
index 1af94789..4fe13168 100644
--- a/nodes/node-compositor/src/renderers/webgpu-renderer.ts
+++ b/nodes/node-compositor/src/renderers/webgpu-renderer.ts
@@ -60,6 +60,7 @@ import {
Light3D,
type Light3DOptions,
type Mat4,
+ type MaterialSurface,
Matrix4Math,
type Mesh3DData,
type MeshCrowd,
@@ -587,7 +588,11 @@ function drawProjectedQuad(
function surfaceProps(
target: Partial<CompositionNodeBase> | undefined,
lop: Partial<CompositionNodeBase>,
- mat?: { emissive?: [number, number, number]; emissiveStrength?: number },
+ mat?: {
+ emissive?: [number, number, number];
+ emissiveStrength?: number;
+ surface?: MaterialSurface;
+ },
): {
emissive?: string | [number, number, number];
emissiveIntensity?: number;
@@ -599,9 +604,9 @@ function surfaceProps(
anisotropy?: number;
anisotropyRotation?: number;
subsurface?: number;
- subsurfaceColor?: string;
+ subsurfaceColor?: string | [number, number, number];
sheen?: number;
- sheenColor?: string;
+ sheenColor?: string | [number, number, number];
sheenRoughness?: number;
iridescence?: CompositionNodeBase["iridescence"];
iridescenceThickness?: number;
@@ -635,36 +640,39 @@ function surfaceProps(
if (lop.castShadow !== undefined) out.castShadow = lop.castShadow;
out.toon = target?.toon ?? lop.toon;
out.outline = target?.outline ?? lop.outline;
- const clearcoat = target?.clearcoat ?? lop.clearcoat;
- if (clearcoat !== undefined) out.clearcoat = clearcoat;
- const clearcoatRoughness =
- target?.clearcoatRoughness ?? lop.clearcoatRoughness;
- if (clearcoatRoughness !== undefined)
- out.clearcoatRoughness = clearcoatRoughness;
- const anisotropy = target?.anisotropy ?? lop.anisotropy;
- if (anisotropy !== undefined) out.anisotropy = anisotropy;
- const anisotropyRotation =
- target?.anisotropyRotation ?? lop.anisotropyRotation;
- if (anisotropyRotation !== undefined)
- out.anisotropyRotation = anisotropyRotation;
- const subsurface = target?.subsurface ?? lop.subsurface;
- if (subsurface !== undefined) out.subsurface = subsurface;
- const subsurfaceColor = target?.subsurfaceColor ?? lop.subsurfaceColor;
- if (subsurfaceColor !== undefined) out.subsurfaceColor = subsurfaceColor;
- const sheen = target?.sheen ?? lop.sheen;
- if (sheen !== undefined) out.sheen = sheen;
- const sheenColor = target?.sheenColor ?? lop.sheenColor;
- if (sheenColor !== undefined) out.sheenColor = sheenColor;
- const sheenRoughness = target?.sheenRoughness ?? lop.sheenRoughness;
- if (sheenRoughness !== undefined) out.sheenRoughness = sheenRoughness;
- const iridescence = target?.iridescence ?? lop.iridescence;
- if (iridescence !== undefined) out.iridescence = iridescence;
- const iridescenceThickness =
- target?.iridescenceThickness ?? lop.iridescenceThickness;
- if (iridescenceThickness !== undefined)
- out.iridescenceThickness = iridescenceThickness;
- const iridescenceIor = target?.iridescenceIor ?? lop.iridescenceIor;
- if (iridescenceIor !== undefined) out.iridescenceIor = iridescenceIor;
+ // Layer settings win; the model file's own material extensions fill in.
+ const file = mat?.surface;
+ const lobes = {
+ clearcoat: target?.clearcoat ?? lop.clearcoat ?? file?.clearcoat,
+ clearcoatRoughness:
+ target?.clearcoatRoughness ??
+ lop.clearcoatRoughness ??
+ file?.clearcoatRoughness,
+ anisotropy: target?.anisotropy ?? lop.anisotropy ?? file?.anisotropy,
+ anisotropyRotation:
+ target?.anisotropyRotation ??
+ lop.anisotropyRotation ??
+ file?.anisotropyRotation,
+ subsurface: target?.subsurface ?? lop.subsurface ?? file?.subsurface,
+ subsurfaceColor:
+ target?.subsurfaceColor ?? lop.subsurfaceColor ?? file?.subsurfaceColor,
+ sheen: target?.sheen ?? lop.sheen ?? file?.sheen,
+ sheenColor: target?.sheenColor ?? lop.sheenColor ?? file?.sheenColor,
+ sheenRoughness:
+ target?.sheenRoughness ?? lop.sheenRoughness ?? file?.sheenRoughness,
+ iridescence: target?.iridescence ?? lop.iridescence ?? file?.iridescence,
+ iridescenceThickness:
+ target?.iridescenceThickness ??
+ lop.iridescenceThickness ??
+ file?.iridescenceThickness,
+ iridescenceIor:
+ target?.iridescenceIor ?? lop.iridescenceIor ?? file?.iridescenceIor,
+ };
+ for (const [key, value] of Object.entries(lobes) as [
+ keyof typeof lobes,
+ never,
+ ][])
+ if (value !== undefined) out[key] = value;
const triplanar = target?.triplanar ?? lop.triplanar;
if (triplanar !== undefined) out.triplanar = triplanar;
const triplanarScale = target?.triplanarScale ?? lop.triplanarScale;
diff --git a/packages/forge/src/forge.test.ts b/packages/forge/src/forge.test.ts
index aea6fa98..c4e977ce 100644
--- a/packages/forge/src/forge.test.ts
+++ b/packages/forge/src/forge.test.ts
@@ -189,6 +189,32 @@ describe("GltfDocument", () => {
expect(report.errors).toBe(0);
});
+ it("writes layered lobes the engine loader reads back", () => {
+ const doc = new GltfDocument();
+ const material = doc.addMaterial({
+ color: "#e8cfb0",
+ clearcoat: { factor: 0.6, roughness: 0.1 },
+ sheen: { color: "#ffd9c0", roughness: 0.4 },
+ anisotropy: { strength: 0.5, rotation: 30 },
+ iridescence: { factor: 0.7, ior: 1.4, thickness: [100, 380] },
+ subsurface: { factor: 0.8, color: "#ff5040" },
+ });
+ doc.addNode({
+ mesh: doc.addMesh({ primitives: [{ ...strip(1, 10), material }] }),
+ });
+ const surface = Object.values(parseGLB(doc.toGlb()).materials)[0]?.surface;
+ expect(surface?.clearcoat).toBeCloseTo(0.6);
+ expect(surface?.clearcoatRoughness).toBeCloseTo(0.1);
+ expect(surface?.sheen).toBeCloseTo(1);
+ // Display colors come back as written.
+ expect(surface?.sheenColor?.[0]).toBeCloseTo(1, 2);
+ expect(surface?.sheenColor?.[1]).toBeCloseTo(0xd9 / 0xff, 2);
+ expect(surface?.anisotropyRotation).toBeCloseTo(30);
+ expect(surface?.iridescenceThickness).toBeCloseTo(380);
+ expect(surface?.subsurface).toBeCloseTo(0.8);
+ expect(surface?.subsurfaceColor?.[1]).toBeCloseTo(0x50 / 0xff, 2);
+ });
+
it("refuses inconsistent input where it is given", () => {
const doc = new GltfDocument();
expect(() =>
diff --git a/packages/forge/src/material.ts b/packages/forge/src/material.ts
index c78f11b8..eb89a29b 100644
--- a/packages/forge/src/material.ts
+++ b/packages/forge/src/material.ts
@@ -65,6 +65,13 @@ export interface MaterialSpec {
| { factor: number; ior?: number; thickness?: [number, number] };
/** Brushed / combed highlights: strength 0..1, rotation in degrees. */
anisotropy?: { strength: number; rotation?: number };
+ /**
+ * Light scattering under the surface (skin, wax, jade, leaves): strength
+ * 0..1 and the scattered color (display sRGB). glTF has no ratified
+ * lobe for it, so it is written to `extras.framefields.subsurface`,
+ * which framefields renders and other viewers ignore.
+ */
+ subsurface?: number | { factor: number; color?: ColorInput };
/** Free data for other tools (glTF `extras`). */
extras?: Record<string, unknown>;
}
@@ -146,7 +153,24 @@ export function materialJson(m: MaterialSpec): MaterialJson {
json.alphaCutoff = m.alphaCutoff;
}
if (m.doubleSided) json.doubleSided = true;
- if (m.extras) json.extras = m.extras;
+ const extras: Record<string, unknown> = { ...(m.extras ?? {}) };
+ if (m.subsurface !== undefined) {
+ const ss =
+ typeof m.subsurface === "number"
+ ? { factor: m.subsurface }
+ : m.subsurface;
+ check("subsurface", ss.factor);
+ const own =
+ (extras.framefields as Record<string, unknown> | undefined) ?? {};
+ extras.framefields = {
+ ...own,
+ subsurface: {
+ factor: ss.factor,
+ color: linearRgb(ss.color ?? "#ff6a4a"),
+ },
+ };
+ }
+ if (Object.keys(extras).length) json.extras = extras;
const ext: Record<string, Record<string, unknown>> = {};
if (m.unlit) ext.KHR_materials_unlit = {};
diff --git a/packages/framefields/src/substrate-materials-render.test.ts b/packages/framefields/src/substrate-materials-render.test.ts
index bbb05e19..c61ef8b4 100644
--- a/packages/framefields/src/substrate-materials-render.test.ts
+++ b/packages/framefields/src/substrate-materials-render.test.ts
@@ -29,6 +29,8 @@ interface SceneOptions {
sphere: SphereOptions;
/** Key light direction, from the light toward the sphere (y down). */
keyFrom?: [number, number, number];
+ /** Key light intensity. Default 2.2. */
+ keyIntensity?: number;
environment?: Parameters<typeof Layer.environment>;
}
@@ -58,7 +60,7 @@ async function render(o: SceneOptions): Promise<Uint8ClampedArray> {
targetX: CX,
targetY: CY,
targetZ: 0,
- intensity: 2.2,
+ intensity: o.keyIntensity ?? 2.2,
color: "#ffffff",
}),
Layer3D.sphere({
@@ -216,6 +218,25 @@ describe("Phase 2: Substrate multi-lobe materials", () => {
expect(after[0] - before[0]).toBeGreaterThan(after[2] - before[2]);
});
+ it("subsurface moves light past the terminator instead of adding it (front-lit)", async () => {
+ const skin: SphereOptions = { color: "#e2bfa5", roughness: 0.6 };
+ const keyFrom: [number, number, number] = [0.6, -0.4, -1];
+ // Dim enough that tone mapping stays linear: its highlight compression
+ // would otherwise couple the channels.
+ const keyIntensity = 0.7;
+ const opaque = await render({ sphere: skin, keyFrom, keyIntensity });
+ const sss = await render({
+ sphere: { ...skin, subsurface: 0.8, subsurfaceColor: "#ff5a3c" },
+ keyFrom,
+ keyIntensity,
+ });
+ const disc = silhouette(opaque, sss);
+ // The core facing the light gives a little up; it never brightens.
+ const core = (img: typeof opaque) => luma(ringMean(img, disc, 0, 0.35));
+ expect(core(sss)).toBeLessThanOrEqual(core(opaque) + 0.5);
+ expect(core(sss)).toBeGreaterThan(core(opaque) - 25);
+ });
+
it("sheen lifts grazing angles more than the center (velvet rim)", async () => {
const velvet: SphereOptions = { color: "#2a0a3a", roughness: 0.9 };
const plain = await render({ sphere: velvet });
diff --git a/packages/webgpu-renderers/src/loaders/gltf-loader.ts b/packages/webgpu-renderers/src/loaders/gltf-loader.ts
index 816027b2..132d229c 100644
--- a/packages/webgpu-renderers/src/loaders/gltf-loader.ts
+++ b/packages/webgpu-renderers/src/loaders/gltf-loader.ts
@@ -9,6 +9,7 @@ import type {
AnimationClip3D,
LoadModelOptions,
Material3D,
+ MaterialSurface,
Model3DData,
ModelNode3D,
NodeAnimationTrack3D,
@@ -176,6 +177,29 @@ interface GltfMaterial {
KHR_materials_emissive_strength?: { emissiveStrength?: number };
/** VRM 1.0 toon material: the base is lit flat, the shadowed side tinted by shadeColorFactor. */
VRMC_materials_mtoon?: { shadeColorFactor?: [number, number, number] };
+ KHR_materials_clearcoat?: {
+ clearcoatFactor?: number;
+ clearcoatRoughnessFactor?: number;
+ };
+ KHR_materials_sheen?: {
+ sheenColorFactor?: [number, number, number];
+ sheenRoughnessFactor?: number;
+ };
+ KHR_materials_anisotropy?: {
+ anisotropyStrength?: number;
+ anisotropyRotation?: number;
+ };
+ KHR_materials_iridescence?: {
+ iridescenceFactor?: number;
+ iridescenceIor?: number;
+ iridescenceThicknessMinimum?: number;
+ iridescenceThicknessMaximum?: number;
+ };
+ };
+ extras?: {
+ framefields?: {
+ subsurface?: { factor?: number; color?: [number, number, number] };
+ };
};
}
@@ -264,6 +288,10 @@ interface GltfDocument {
const SUPPORTED_REQUIRED_EXTENSIONS = new Set([
"KHR_materials_unlit",
"KHR_materials_emissive_strength",
+ "KHR_materials_clearcoat",
+ "KHR_materials_sheen",
+ "KHR_materials_anisotropy",
+ "KHR_materials_iridescence",
"KHR_texture_transform",
"KHR_texture_basisu",
"EXT_texture_webp",
@@ -891,6 +919,8 @@ export class GltfLoader {
material.emissiveStrength =
mat.extensions?.KHR_materials_emissive_strength?.emissiveStrength ?? 1;
}
+ const surface = materialSurface(mat);
+ if (surface) material.surface = surface;
const mtoon = mat.extensions?.VRMC_materials_mtoon;
if (mtoon) {
material.shading = "toon";
@@ -1392,6 +1422,50 @@ export function loadGLB(
return GltfLoader.load(srcOrData, options);
}
+/** The layered lobes a glTF material's extensions describe (display colors, degrees). */
+function materialSurface(mat: GltfMaterial): MaterialSurface | undefined {
+ const ext = mat.extensions;
+ const out: MaterialSurface = {};
+ const display = (c: [number, number, number]): [number, number, number] => [
+ linearToSrgb(c[0]),
+ linearToSrgb(c[1]),
+ linearToSrgb(c[2]),
+ ];
+ const cc = ext?.KHR_materials_clearcoat;
+ if (cc && (cc.clearcoatFactor ?? 0) > 0) {
+ out.clearcoat = cc.clearcoatFactor;
+ out.clearcoatRoughness = cc.clearcoatRoughnessFactor ?? 0;
+ }
+ const sh = ext?.KHR_materials_sheen;
+ if (sh) {
+ const c = sh.sheenColorFactor ?? [0, 0, 0];
+ const peak = Math.max(c[0], c[1], c[2]);
+ if (peak > 0) {
+ // The lobe takes a strength and a tint; glTF folds both into one color.
+ out.sheen = Math.min(1, peak);
+ out.sheenColor = display([c[0] / peak, c[1] / peak, c[2] / peak]);
+ out.sheenRoughness = sh.sheenRoughnessFactor ?? 0;
+ }
+ }
+ const an = ext?.KHR_materials_anisotropy;
+ if (an && (an.anisotropyStrength ?? 0) > 0) {
+ out.anisotropy = an.anisotropyStrength;
+ out.anisotropyRotation = ((an.anisotropyRotation ?? 0) * 180) / Math.PI;
+ }
+ const ir = ext?.KHR_materials_iridescence;
+ if (ir && (ir.iridescenceFactor ?? 0) > 0) {
+ out.iridescence = ir.iridescenceFactor;
+ out.iridescenceIor = ir.iridescenceIor ?? 1.3;
+ out.iridescenceThickness = ir.iridescenceThicknessMaximum ?? 400;
+ }
+ const ss = mat.extras?.framefields?.subsurface;
+ if (ss && (ss.factor ?? 0) > 0) {
+ out.subsurface = ss.factor;
+ out.subsurfaceColor = display(ss.color ?? [1, 0.2, 0.1]);
+ }
+ return Object.keys(out).length ? out : undefined;
+}
+
function linearToSrgb(c: number): number {
const x = Math.min(Math.max(c, 0), 1);
return x <= 0.0031308 ? x * 12.92 : 1.055 * x ** (1 / 2.4) - 0.055;
diff --git a/packages/webgpu-renderers/src/loaders/types.ts b/packages/webgpu-renderers/src/loaders/types.ts
index 16d8e6b9..0fb76ecb 100644
--- a/packages/webgpu-renderers/src/loaders/types.ts
+++ b/packages/webgpu-renderers/src/loaders/types.ts
@@ -77,6 +77,30 @@ export interface Material3D {
occlusionStrength?: number;
/** Encoded emissive color map (multiplies `emissive`). */
emissiveTextureBuffer?: Uint8Array;
+ /** Layered shading lobes from the file's material extensions (display colors, degrees). */
+ surface?: MaterialSurface;
+}
+
+/**
+ * Physical lobes a model file's material asks for, in the units layers use:
+ * KHR_materials_clearcoat / _sheen / _anisotropy / _iridescence, and
+ * subsurface from `extras.framefields.subsurface` (glTF has no skin lobe).
+ */
+export interface MaterialSurface {
+ clearcoat?: number;
+ clearcoatRoughness?: number;
+ sheen?: number;
+ sheenColor?: [number, number, number];
+ sheenRoughness?: number;
+ anisotropy?: number;
+ /** Degrees. */
+ anisotropyRotation?: number;
+ iridescence?: number;
+ iridescenceIor?: number;
+ /** Film thickness, nm. */
+ iridescenceThickness?: number;
+ subsurface?: number;
+ subsurfaceColor?: [number, number, number];
}
/** A scene-graph node: its rest transform and parent (glTF node semantics). */
diff --git a/packages/webgpu-renderers/src/shaders/lighting3d.ts b/packages/webgpu-renderers/src/shaders/lighting3d.ts
index 6a57642e..847ec7ab 100644
--- a/packages/webgpu-renderers/src/shaders/lighting3d.ts
+++ b/packages/webgpu-renderers/src/shaders/lighting3d.ts
@@ -831,22 +831,26 @@ fn shadePhysicalSubstrate(
var directLobe = diff * nDotL + spec * select(0.0, nDotLSpec, nDotL > 0.0);
- // Subsurface wrap diffuse + terminator bleed + translucent back-scattering
+ // Subsurface scattering (skin, wax, jade): light enters, scatters and
+ // leaves past where it entered. Each channel's lit region wraps past
+ // the terminator by how far that channel scatters (the subsurface
+ // color: red farthest in skin), normalized so the wrap moves energy
+ // rather than adding it: the form keeps its shading and only the
+ // shadow edge softens and warms.
if (sssWeight > 0.001) {
- let wrap = 0.45 * sssWeight;
- let wrapNdotL = max(0.0, (rawNdotL + wrap) / ((1.0 + wrap) * (1.0 + wrap)));
- let terminator = smoothstep(0.0, wrap + 0.3, max(0.0, rawNdotL + wrap)) * (1.0 - nDotL);
- let wrapDiff = diffuseColor * wrapNdotL + sssColor * (diffuseColor * 0.6 + vec3<f32>(0.4)) * terminator * sssWeight * 0.55;
- let backL = normalize(ls.L + N * 0.35);
+ let w = sssWeight * mix(vec3<f32>(0.06), vec3<f32>(0.75), sssColor);
+ let onePlusW = vec3<f32>(1.0) + w;
+ let wrapped = max(vec3<f32>(0.0), vec3<f32>(rawNdotL) + w) / (onePlusW * onePlusW);
// Light crossing a convex body travels far through its middle and
// briefly near its silhouette: how closely the exit normal follows
// the light's travel direction stands in for that chord length, so
- // back-lit solids glow at the rim and stay dense at the core.
+ // thin parts (ears, nostrils, fingers) glow when back-lit.
+ let backL = normalize(ls.L + N * 0.35);
let chord = clamp(dot(N, -ls.L), 0.0, 1.0);
- let transmittance = exp(-chord * mix(6.0, 1.5, sssWeight));
- let backTrans = pow(clamp(dot(V, -backL), 0.0, 1.0), 3.0) * transmittance * sssWeight * 0.65;
- let sssContrib = (wrapDiff + sssColor * backTrans) / PI;
- directLobe = mix(diff * nDotL, sssContrib, sssWeight) + spec * select(0.0, nDotLSpec, nDotL > 0.0);
+ let transmittance = exp(-chord * mix(8.0, 3.0, sssWeight));
+ let backTrans = pow(clamp(dot(V, -backL), 0.0, 1.0), 3.0) * transmittance * 0.35;
+ let sssDiff = (vec3<f32>(1.0) - F) * diffuseColor * (wrapped + sssColor * backTrans) / PI;
+ directLobe = mix(diff * nDotL, sssDiff, sssWeight) + spec * select(0.0, nDotLSpec, nDotL > 0.0);
}
// Charlie cloth / velvet sheen lobe (Estevez & Kulla)
@@ -891,11 +895,7 @@ fn shadePhysicalSubstrate(
let si = screenIndirectAt(worldPos);
let specOcclusion = screenSpecularOcclusion(si, nDotV, r);
let irradiance = screenAmbient(si, envIrradiance(N) + lights.ambientLinear.rgb);
- var diffAmbient = diffuseColor * irradiance;
- if (sssWeight > 0.001) {
- let backIrradiance = envIrradiance(-N) * 0.35 + irradiance * 0.25;
- diffAmbient += sssColor * (diffuseColor * 0.5 + vec3<f32>(0.5)) * backIrradiance * sssWeight * 0.45;
- }
+ let diffAmbient = diffuseColor * irradiance;
let specEnv = screenReflection(si, r, envRadiance(R_ibl, r) * specOcclusion) * envBrdfApprox(f0_ibl, r, nDotV);
var iblTotal = diffAmbient + specEnv;
diff --git a/plugins/framefields/skills/framefields-compose/SKILL.md b/plugins/framefields/skills/framefields-compose/SKILL.md
index c5cbaf1e..1e63af9a 100644
--- a/plugins/framefields/skills/framefields-compose/SKILL.md
+++ b/plugins/framefields/skills/framefields-compose/SKILL.md
@@ -459,7 +459,7 @@ Order of evaluation: clips, `pose`, `aim`, `lookAt`, `ik` (so IK can still plant
Rules: a crowd mesh keeps its own `rotateX` / `scale` under each instance (y-up glTF: `rotateX: 180`). Spring bones follow the clip's motion and the model's current orientation, not the layer's keyframed travel. Per-instance `clip`, `animOffset`, `animSpeed` in `transforms` / `instanceAt` override the crowd's seeded choices.
-**Building characters in code (`framefields/forge`)**: write rigged GLB files from TypeScript, then load them with `Layer.glb`. `humanoidSkeleton({ height, heads, shoulderWidth, hipWidth, armAngle, fingers, toes, prefix })` places Mixamo-named joints (feet on y = 0, facing +z, left at +x, A-pose by default) so `pose`, `aim` and `retarget({ rig: "mixamo" })` work unchanged; `new Skeleton().add(name, { at, parent }).chain(base, points).mirror()` builds any other rig. `GltfDocument` writes meshes (32-bit indices past 65,535 vertices, named morph targets in `extras.targetNames`), PBR materials with Khronos extensions (`clearcoat`, `sheen`, `specular`, `ior`, `transmission`, `volume`, `iridescence`, `anisotropy`, `emissiveStrength`, `unlit`, alpha `mask`), textures, skins and clips, and checks every input where it is given. Colors are display sRGB; the writer stores glTF's linear factors. `boneGizmo(skeleton)` draws the rig as octahedral bones for checking poses before there is a body.
+**Building characters in code (`framefields/forge`)**: write rigged GLB files from TypeScript, then load them with `Layer.glb`. `humanoidSkeleton({ height, heads, shoulderWidth, hipWidth, armAngle, fingers, toes, prefix })` places Mixamo-named joints (feet on y = 0, facing +z, left at +x, A-pose by default) so `pose`, `aim` and `retarget({ rig: "mixamo" })` work unchanged; `new Skeleton().add(name, { at, parent }).chain(base, points).mirror()` builds any other rig. `GltfDocument` writes meshes (32-bit indices past 65,535 vertices, named morph targets in `extras.targetNames`), PBR materials with Khronos extensions (`clearcoat`, `sheen`, `specular`, `ior`, `transmission`, `volume`, `iridescence`, `anisotropy`, `emissiveStrength`, `unlit`, alpha `mask`) plus `subsurface` for skin, textures, skins and clips, and checks every input where it is given. Colors are display sRGB; the writer stores glTF's linear factors. `boneGizmo(skeleton)` draws the rig as octahedral bones for checking poses before there is a body.
```ts
import { boneGizmo, GltfDocument, humanoidSkeleton } from "framefields/forge";
@@ -479,7 +479,7 @@ import { GltfDocument, human } from "framefields/forge";
const elf = await human({ sex: 0, age: 0.6, muscle: 0.55, weight: 0.35, height: 184 });
const doc = new GltfDocument();
const rig = doc.addSkeleton(elf.skeleton);
-const skin = doc.addMaterial({ color: "#e9d2b4", roughness: 0.5 });
+const skin = doc.addMaterial({ color: "#d9b29a", roughness: 0.5, subsurface: { factor: 0.8, color: "#ff5a3c" } });
doc.addNode({ mesh: doc.addMesh({ name: "Body", primitives: [{ ...elf.body, material: skin }] }), skin: rig.skin });
```
@@ -602,6 +602,7 @@ Layer3D.cylinder({ ..., height: 400, color: "#111", emissive: "#4da3ff", emissiv
- **Shadows:** `directional`, `spot`, `rect` (`Layer.rectLight` / `Light.rect`), and omnidirectional `point` (`Layer.pointLight` / `Light.point`, 6-face cube shadow map) 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.
- **Rect Area Lights (`Layer.rectLight` / `Light.rect`):** studio softbox / LED panel lights with `width`, `height`, `twoSided`, `rotation`, `x/y/z`, `targetX/Y/Z`, `intensity`, `radius`, `decay`, and `castShadow`. Uses solid-angle diffuse irradiance and representative-point GGX specular highlights that stretch across rough and glossy surfaces. Numeric light props accept `Signal`s directly (e.g. `Layer.rectLight({ intensity: bassSignal, width: 300, height: 120 })`).
- **Volumetric Fog & Light Shafts (`volumetricFog`):** `Layer.environment("night", { volumetricFog: true | { density, anisotropy, heightFalloff, baseHeight, color, lightIntensity, ambientIntensity, maxDistance, steps, noise: { scale, strength, speed, octaves } } })` raymarches participating media at half resolution with depth-aware bilateral upsampling. Any shadow-casting `directional`, `spot`, `rect`, or `point` light automatically carves volumetric light shafts (god rays) through the fog behind occluders. `density`, `anisotropy`, and `noise.strength` accept numbers or live `Signal` objects directly.
+- **Model files bring their own lobes:** glTF materials with `KHR_materials_clearcoat`, `_sheen`, `_anisotropy` or `_iridescence`, and forge's `subsurface` (written to `extras.framefields.subsurface`), render with those lobes; a layer's own lobe props override them. Subsurface scattering conserves energy: each channel's light wraps past the terminator by how far it scatters (`subsurfaceColor`; red farthest for skin, e.g. `"#ff5a3c"`), so form keeps its shading and only shadow edges warm; thin parts glow when back-lit.
- **Substrate lobes (physical shading, needs an environment):** every `Layer3D.*` mesh, `Layer.model` and 3D card accepts `clearcoat` / `clearcoatRoughness` (car paint, lacquer), `anisotropy` (-1..1) / `anisotropyRotation` (deg; brushed metal), `subsurface` / `subsurfaceColor` (wax, jade, skin), `sheen` / `sheenColor` / `sheenRoughness` (velvet, cloth), `iridescence` (0..1 or `{ intensity, thickness, ior }`; soap, oil, beetle shell) with `iridescenceThickness` (nm) / `iridescenceIor`, and `triplanar: true | { scale, sharpness }` for world-space textures on UV-less meshes. Numeric lobes take numbers or live `Signal`s (`clearcoat: bass`). Example: `Layer3D.sphere({ radius: 90, color: "#8a0f1c", metallic: 0.6, roughness: 0.35, clearcoat: 1, clearcoatRoughness: 0.05 })`.
- **HDRI environments:** pass a `.hdr` or `.exr` path instead of a preset: `Layer.environment("assets/hdri/studio.exr", { intensity: 1.2, rotation: 90 })` (or `{ hdri: path }`). The panorama lights and reflects every physical surface; preset names keep working; relative paths resolve from the working directory. EXR files must use lossless compression (NONE, RLE, ZIPS, ZIP, PIZ or PXR24); re-save B44/DWA files as ZIP.
- **Screen-space reflections & GI (`ssr`, `gi`):** `Layer.environment("night", { ssr: true, gi: true })`. `ssr` (`{ intensity, maxRoughness, thickness, steps }`) reflects nearby geometry and emissives in glossy surfaces: chrome, wet floors, lacquer, walls. `gi` (`{ intensity, radius, samples }`) adds contact occlusion and color bleeding from visible surfaces, e.g. a neon sign tinting the floor. Each costs a second 3D pass; only what is on screen can be reflected or bounce, so keep key reflected objects in frame. Use `floor` for a planar mirror that also shows off-screen objects.
diff --git a/specs/character-forge.md b/specs/character-forge.md
index d667b89b..74a66fce 100644
--- a/specs/character-forge.md
+++ b/specs/character-forge.md
@@ -1,6 +1,6 @@
# Character Forge: rigged characters built in code
-Status: Phases 1–2 done (GLB writer, skeleton, humanoid preset, bone gizmo; bound sculpting, manifold narrow-band meshing, simplification, smooth material borders, skin weights from the field; `packages/forge`, exposed as `framefields/forge`). Sharp-edge preservation for hard surfaces moves to Phase 7's hard-surface work. Human bodies and faces now start from MakeHuman's CC0 base (`human()`): realistic anatomy, edge loops and UVs, macro and feature targets, painted weights. `sculpt` stays for stylization, costume, armor and non-humans. The face rig (Phase 4) builds on MakeHuman's expression units and the ARKit 52 names. Phase 3 next. First character: **Ithrael Sunmourn** (`examples/36_emberwake/CHARACTERS.md`), an original hooded elven ranger with a long cloak, long hair, a sculpted face, real eyes, and a full set of expressions.
+Status: Phases 1–2 done (GLB writer, skeleton, humanoid preset, bone gizmo; bound sculpting, manifold narrow-band meshing, simplification, smooth material borders, skin weights from the field; `packages/forge`, exposed as `framefields/forge`). Sharp-edge preservation for hard surfaces moves to Phase 7's hard-surface work. Human bodies and faces now start from MakeHuman's CC0 base (`human()`): realistic anatomy, edge loops and UVs, macro and feature targets, painted weights. `sculpt` stays for stylization, costume, armor and non-humans. The face rig (Phase 4) builds on MakeHuman's expression units and the ARKit 52 names. Phase 3 in progress: the loader reads clearcoat, sheen, anisotropy and iridescence and forge's `extras.framefields.subsurface`, the compositor uses them under layer overrides, and the subsurface lobe was rewritten to conserve energy (per-channel wrap). Still to do in Phase 3: alpha-to-coverage for hair cards and morphs combined with skinning; the specular, IOR, transmission and volume extensions are written but not yet rendered. First character: **Ithrael Sunmourn** (`examples/36_emberwake/CHARACTERS.md`), an original hooded elven ranger with a long cloak, long hair, a sculpted face, real eyes, and a full set of expressions.
## Goal