Skip to content

Turn one illustration into an animated 2D mesh avatar with a coding agent and a local editor

Richer lighting: point light falloff, relief from strokes, gloss and rim

shinshin864beeda4719bd
diff --git a/src/engine/renderer.js b/src/engine/renderer.js
index 445ac4d..0eff4d0 100644
--- a/src/engine/renderer.js
+++ b/src/engine/renderer.js
@@ -1,6 +1,6 @@
import { layerNormals } from '../lighting/normals';
import { DEFAULT_LIGHTING, parseLighting } from '../lighting/settings';
-import { WRAP, DARKEN, BRIGHTEN, headRotation } from '../lighting/shading';
+import { TERMINATOR, DETAIL_SCALE, SHADOW_SATURATION, MAX_IRRADIANCE, headRotation } from '../lighting/shading';
import { DropShadow } from '../lighting/shadow';
/** @param {ReturnType<import('./rig.js').createRig>} engine
@@ -132,22 +132,43 @@ export function createRenderer(engine, rig) {
.replace('vUv = aUv;', 'vHeadWeight = aHeadWeight; vScreen = vec2((aPos.x * uScale.x + uOffset.x + 1.0) * 0.5, (1.0 - aPos.y * uScale.y - uOffset.y) * 0.5); vUv = aUv;');
const LIGHT_FS = FS.replace('uniform sampler2D uTex;', `uniform sampler2D uTex;
uniform sampler2D uNormal; in float vHeadWeight; in vec2 vScreen;
- uniform mat3 uHeadRotation; uniform vec3 uLight; uniform vec3 uLightColor;
- uniform vec4 uLighting; uniform float uAspect; uniform int uCel;`)
+ uniform mat3 uHeadRotation; uniform vec3 uLight; uniform vec3 uLightColor; uniform vec3 uAmbientColor;
+ uniform vec4 uLighting; uniform vec4 uSurface; uniform float uAspect; uniform int uCel;`)
.replace('outColor = c * uAlpha;', `
- vec3 n = normalize(texture(uNormal, vUv).rgb * 2.0 - 1.0);
+ // RG hold the smooth surface normal, BA the painting's relief (see lighting/normals.ts).
+ vec4 encoded = texture(uNormal, vUv);
+ vec2 base = encoded.rg * 2.0 - 1.0;
+ vec3 n = vec3(base, sqrt(max(0.0, 1.0 - dot(base, base))));
+ n = normalize(n + vec3((encoded.ba * 2.0 - 1.0) * uSurface.w * ${DETAIL_SCALE.toFixed(3)}, 0.0));
n = normalize(mix(n, uHeadRotation * n, vHeadWeight));
- vec3 light = normalize(vec3((uLight.xy - vScreen) * vec2(uAspect, 1.0), uLight.z));
- float diffuse = clamp((dot(n, light) + ${WRAP}) / (1.0 + ${WRAP}), 0.0, 1.0);
+ vec2 toLight = (uLight.xy - vScreen) * vec2(uAspect, 1.0);
+ vec3 light = normalize(vec3(toLight, uLight.z));
+ float ndl = dot(n, light);
+ float diffuse;
if (uCel == 1) {
- float edge = max(fwidth(diffuse), 0.001);
- diffuse = 0.18 + 0.37 * smoothstep(0.4 - edge, 0.4 + edge, diffuse) + 0.45 * smoothstep(0.75 - edge, 0.75 + edge, diffuse);
+ float w = 0.01 + uSurface.x * 0.08;
+ diffuse = 0.2 + 0.45 * smoothstep(${TERMINATOR.toFixed(3)} - w, ${TERMINATOR.toFixed(3)} + w, ndl) + 0.35 * smoothstep(0.55 - w, 0.55 + w, ndl);
+ } else {
+ float s = 0.05 + uSurface.x * 0.5;
+ diffuse = smoothstep(${TERMINATOR.toFixed(3)} - s, ${TERMINATOR.toFixed(3)} + s, ndl) * (0.35 + 0.65 * max(0.0, ndl));
}
- float amount = clamp(uLighting.z + uLighting.y * diffuse - 1.0, -1.0, 1.0) * uLighting.x;
- c.rgb *= 1.0 + min(0.0, amount) * ${DARKEN};
- c.rgb += (vec3(c.a) - c.rgb) * uLightColor * max(0.0, amount) * ${BRIGHTEN};
- // Tint only the illuminated side; preserve premultiplication and painted contrast.
- c.rgb *= mix(vec3(1.0), uLightColor, diffuse * uLighting.x * 0.25);
+ float reach = dot(toLight, toLight) / (uLighting.w * uLighting.w);
+ float attenuation = 1.0 / (1.0 + reach);
+ vec3 radiance = uLightColor * uLighting.y * attenuation;
+ // A light close to the surface may brighten a little, but must not bleach painted colours.
+ vec3 irradiance = min(uAmbientColor * uLighting.z + radiance * diffuse, vec3(${MAX_IRRADIANCE.toFixed(3)}));
+ // Painted shadows are deeper versions of the base colour, not grey: multiply by the colour
+ // itself as the surface turns away from the light.
+ vec3 albedo = c.rgb / max(c.a, 1e-4);
+ float dark = 1.0 - clamp(dot(irradiance, vec3(0.3333)), 0.0, 1.0);
+ vec3 shaded = c.rgb * mix(vec3(1.0), albedo, dark * ${SHADOW_SATURATION.toFixed(3)}) * irradiance;
+ float specular = pow(max(dot(n, normalize(light + vec3(0.0, 0.0, 1.0))), 0.0), 60.0) * uSurface.y;
+ if (uCel == 1) specular = smoothstep(0.3, 0.35, specular) * uSurface.y;
+ vec2 side = length(n.xy) > 0.001 ? normalize(n.xy) : vec2(0.0);
+ float rim = pow(1.0 - max(n.z, 0.0), 4.0) * smoothstep(-0.2, 0.7, dot(side, normalize(toLight + vec2(1e-4)))) * uSurface.z;
+ shaded += radiance * (specular * max(0.0, ndl) + rim) * c.a;
+ // Strength blends between the original painting and the relit result; alpha is unchanged.
+ c.rgb = clamp(mix(c.rgb, shaded, uLighting.x), vec3(0.0), vec3(c.a));
outColor = c * uAlpha;`);
const LINE_VS = `#version 300 es
@@ -356,7 +377,9 @@ export function createRenderer(engine, rig) {
gl.uniform1i(m.u.uNormal, 1);
gl.uniform3f(m.u.uLight, light.x, light.y, light.z);
gl.uniform3f(m.u.uLightColor, ((light.color >> 16) & 255) / 255, ((light.color >> 8) & 255) / 255, (light.color & 255) / 255);
- gl.uniform4f(m.u.uLighting, light.strength, light.intensity, light.ambient, 0);
+ gl.uniform3f(m.u.uAmbientColor, ((light.ambientColor >> 16) & 255) / 255, ((light.ambientColor >> 8) & 255) / 255, (light.ambientColor & 255) / 255);
+ gl.uniform4f(m.u.uLighting, light.strength, light.intensity, light.ambient, light.reach);
+ gl.uniform4f(m.u.uSurface, light.softness, light.specular, light.rim, light.detail);
gl.uniform1f(m.u.uAspect, this.canvas.width / this.canvas.height);
gl.uniform1i(m.u.uCel, light.mode === 'cel' ? 1 : 0);
gl.uniformMatrix3fv(m.u.uHeadRotation, false, headRotation(state.angleX ?? 0, state.angleY ?? 0, state.angleZ ?? 0, rig.head.maxRoll));
diff --git a/src/lighting/Controls.tsx b/src/lighting/Controls.tsx
index d40e8ad..20feb9e 100644
--- a/src/lighting/Controls.tsx
+++ b/src/lighting/Controls.tsx
@@ -3,20 +3,29 @@ import { colorHex, DEFAULT_LIGHTING, type LightingSettings } from './settings';
import './lighting.css';
export const lightingText = {
- en: { title: 'Lighting', enabled: 'Enable lighting', height: 'Light height', strength: 'Strength', intensity: 'Intensity', ambient: 'Ambient light', color: 'Light color', mode: 'Shading', soft: 'Soft', cel: 'Cel', shadow: 'Drop shadow', reset: 'Reset lighting', handle: 'Light position', hint: 'Drag the light over the preview. Arrow keys move it too.' },
- ja: { title: '光源と陰影', enabled: '照明を有効にする', height: '光源の高さ', strength: '陰影の強さ', intensity: '光の強さ', ambient: '環境光', color: '光の色', mode: '陰影の種類', soft: 'やわらかい陰影', cel: 'セル調', shadow: '背後の影', reset: '照明をリセット', handle: '光源の位置', hint: 'プレビュー上の光源をドラッグします。矢印キーでも移動できます。' },
- zh: { title: '光源与阴影', enabled: '启用光照', height: '光源高度', strength: '明暗强度', intensity: '光照强度', ambient: '环境光', color: '光源颜色', mode: '着色方式', soft: '柔和', cel: '赛璐璐', shadow: '投影', reset: '重置光照', handle: '光源位置', hint: '在预览上拖动光源,也可使用方向键移动。' },
+ en: { title: 'Lighting', enabled: 'Enable lighting', height: 'Light height', strength: 'Strength', intensity: 'Intensity', ambient: 'Ambient light', color: 'Light color', mode: 'Shading', soft: 'Soft', cel: 'Cel', shadow: 'Drop shadow', reset: 'Reset lighting', handle: 'Light position', hint: 'Drag the light over the preview. Arrow keys move it too.', reach: 'Light spread', ambientColor: 'Ambient color', softness: 'Shading smoothness', specular: 'Gloss', rim: 'Rim light', detail: 'Stroke relief', light: 'Light', surface: 'Shading' },
+ ja: { title: '光源と陰影', enabled: '照明を有効にする', height: '光源の高さ', strength: '陰影の強さ', intensity: '光の強さ', ambient: '環境光', color: '光の色', mode: '陰影の種類', soft: 'やわらかい陰影', cel: 'セル調', shadow: '背後の影', reset: '照明をリセット', handle: '光源の位置', hint: 'プレビュー上の光源をドラッグします。矢印キーでも移動できます。', reach: '光の広がり', ambientColor: '環境光の色', softness: '陰影のなめらかさ', specular: 'つや', rim: 'リムライト', detail: '描線の凹凸', light: '光源', surface: '陰影' },
+ zh: { title: '光源与阴影', enabled: '启用光照', height: '光源高度', strength: '明暗强度', intensity: '光照强度', ambient: '环境光', color: '光源颜色', mode: '着色方式', soft: '柔和', cel: '赛璐璐', shadow: '投影', reset: '重置光照', handle: '光源位置', hint: '在预览上拖动光源,也可使用方向键移动。', reach: '光照范围', ambientColor: '环境光颜色', softness: '明暗过渡', specular: '光泽', rim: '轮廓光', detail: '线条凹凸', light: '光源', surface: '明暗' },
};
type Props = { value: LightingSettings; onChange: (value: LightingSettings) => void; language: keyof typeof lightingText };
export function LightingControls({ value, onChange, language }: Props) {
const t = lightingText[language];
+ type Key = 'z' | 'reach' | 'intensity' | 'ambient' | 'strength' | 'softness' | 'specular' | 'rim' | 'detail';
+ const sliders = (items: { key: Key; label: keyof typeof t; min: number; max: number }[]) => items.map(({ key, label, min, max }) =>
+ <label className="lighting-slider" key={key}>{t[label]}<input aria-label={t[label]} type="range" min={min} max={max} step="0.01" value={value[key]} onChange={e => onChange({ ...value, [key]: Number(e.target.value) })} /><output>{value[key].toFixed(2)}</output></label>);
return <div className="lighting-controls">
<label className="lighting-check"><input type="checkbox" checked={value.enabled} onChange={e => onChange({ ...value, enabled: e.target.checked })} />{t.enabled}</label>
<fieldset disabled={!value.enabled}>
- {([{ key: 'z', label: 'height', min: 0.1, max: 2 }, { key: 'strength', label: 'strength', min: 0, max: 1 },
- { key: 'intensity', label: 'intensity', min: 0, max: 2 }, { key: 'ambient', label: 'ambient', min: 0, max: 1 }] as const).map(({ key, label, min, max }) =>
- <label className="lighting-slider" key={key}>{t[label]}<input aria-label={t[label]} type="range" min={min} max={max} step="0.01" value={value[key]} onChange={e => onChange({ ...value, [key]: Number(e.target.value) })} /><output>{value[key].toFixed(2)}</output></label>)}
+ <legend>{t.light}</legend>
+ {sliders([{ key: 'z', label: 'height', min: 0.1, max: 2 }, { key: 'reach', label: 'reach', min: 0.2, max: 3 },
+ { key: 'intensity', label: 'intensity', min: 0, max: 2 }, { key: 'ambient', label: 'ambient', min: 0, max: 1 }])}
<label className="lighting-color">{t.color}<input aria-label={t.color} type="color" value={colorHex(value.color)} onChange={e => onChange({ ...value, color: parseInt(e.target.value.slice(1), 16) })} /></label>
+ <label className="lighting-color">{t.ambientColor}<input aria-label={t.ambientColor} type="color" value={colorHex(value.ambientColor)} onChange={e => onChange({ ...value, ambientColor: parseInt(e.target.value.slice(1), 16) })} /></label>
+ </fieldset>
+ <fieldset disabled={!value.enabled}>
+ <legend>{t.surface}</legend>
+ {sliders([{ key: 'strength', label: 'strength', min: 0, max: 1 }, { key: 'softness', label: 'softness', min: 0, max: 1 },
+ { key: 'specular', label: 'specular', min: 0, max: 1 }, { key: 'rim', label: 'rim', min: 0, max: 1 }, { key: 'detail', label: 'detail', min: 0, max: 1 }])}
<label>{t.mode}<select aria-label={t.mode} value={value.mode} onChange={e => onChange({ ...value, mode: e.target.value as 'soft' | 'cel' })}><option value="soft">{t.soft}</option><option value="cel">{t.cel}</option></select></label>
<label className="lighting-check"><input type="checkbox" checked={value.shadow} onChange={e => onChange({ ...value, shadow: e.target.checked })} />{t.shadow}</label>
</fieldset>
diff --git a/src/lighting/lighting.css b/src/lighting/lighting.css
index f49489b..1c6d64b 100644
--- a/src/lighting/lighting.css
+++ b/src/lighting/lighting.css
@@ -24,3 +24,4 @@
.lighting-section > summary::-webkit-details-marker, .live-lighting > summary::-webkit-details-marker { display: none; }
.lighting-section > summary { list-style: none; } .live-lighting > summary { list-style: none; }
.lighting-on { margin-left: auto; padding: 1px 7px; border-radius: 999px; background: #fff4cc; color: #805000; font-size: 11px; font-weight: 600; }
+.lighting-controls legend { padding: 0; margin-bottom: 2px; font-weight: 600; color: #4a5a70; }
diff --git a/src/lighting/normals.ts b/src/lighting/normals.ts
index f305709..5733a91 100644
--- a/src/lighting/normals.ts
+++ b/src/lighting/normals.ts
@@ -23,13 +23,52 @@ export function silhouetteDistance(alpha: Uint8Array, width: number, height: num
}
function gaussian(x: number, y: number, e: Ellipse) { return Math.exp(-(((x - e.cx) / e.rx) ** 2 + ((y - e.cy) / e.ry) ** 2)); }
export function rigHeight(x: number, y: number, rig: Rig) {
- // Smooth domes have no crease at the ellipse border. Facial overlays share this field.
- let h = rig.head.rx * 0.55 * gaussian(x, y, rig.head) + rig.body.chest.rx * 0.23 * gaussian(x, y, rig.body.chest);
+ // Facial overlays share this field.
+ // The head is an ellipsoid so its sides turn away from a frontal light; the field is smoothed later.
+ const r2 = ((x - rig.head.cx) / rig.head.rx) ** 2 + ((y - rig.head.cy) / rig.head.ry) ** 2;
+ let h = rig.head.rx * 0.8 * Math.sqrt(Math.max(0, 1 - r2)) + rig.body.chest.rx * 0.23 * gaussian(x, y, rig.body.chest);
h += rig.face.nose.rx * 0.2 * gaussian(x, y, rig.face.nose);
for (const [cx, cy] of rig.cheeks) h += rig.head.rx * 0.012 * gaussian(x, y, { cx, cy, rx: rig.head.rx * 0.3, ry: rig.head.ry * 0.16 });
return h;
}
-export function generateNormals(alpha: Uint8Array, width: number, height: number, rect: readonly number[], rig?: Rig, inflate = true) {
+// Separable box blur with running sums; edges average only the pixels inside the image.
+function boxBlur(src: Float32Array, width: number, height: number, radius: number) {
+ const tmp = new Float32Array(src.length), out = new Float32Array(src.length);
+ const pass = (input: Float32Array, output: Float32Array, length: number, lines: number, step: number, stride: number) => {
+ for (let line = 0; line < lines; line++) {
+ const start = line * stride;
+ let sum = 0, count = 0;
+ for (let k = 0; k < Math.min(radius, length - 1) + 1; k++) { sum += input[start + k * step]; count++; }
+ for (let i = 0; i < length; i++) {
+ output[start + i * step] = sum / count;
+ const add = i + radius + 1, remove = i - radius;
+ if (add < length) { sum += input[start + add * step]; count++; }
+ if (remove >= 0) { sum -= input[start + remove * step]; count--; }
+ }
+ }
+ };
+ pass(src, tmp, width, height, 1, width);
+ pass(tmp, out, height, width, width, 1);
+ return out;
+}
+// Fine relief from the painting itself: dark strokes become shallow grooves, so hair strands and
+// folds catch the light. Only local contrast is kept; large painted shadows are not reinterpreted.
+export function detailGradient(luminance: Float32Array, alpha: Uint8Array, width: number, height: number) {
+ const fine = boxBlur(luminance, width, height, 1), coarse = boxBlur(luminance, width, height, 6);
+ const relief = new Float32Array(luminance.length);
+ for (let i = 0; i < relief.length; i++) relief[i] = alpha[i] > 128 ? fine[i] - coarse[i] : 0;
+ const gradient = new Float32Array(luminance.length * 2);
+ const at = (x: number, y: number) => relief[Math.max(0, Math.min(height - 1, y)) * width + Math.max(0, Math.min(width - 1, x))];
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
+ const i = y * width + x;
+ if (alpha[i] <= 128) continue;
+ gradient[2 * i] = Math.max(-1, Math.min(1, -(at(x + 1, y) - at(x - 1, y)) * 4));
+ gradient[2 * i + 1] = Math.max(-1, Math.min(1, -(at(x, y + 1) - at(x, y - 1)) * 4));
+ }
+ return gradient;
+}
+// RG: the smooth surface normal's x/y (z is rebuilt in the shader). BA: the painting's relief gradient.
+export function generateNormals(alpha: Uint8Array, width: number, height: number, rect: readonly number[], rig?: Rig, inflate = true, luminance?: Float32Array) {
const cropped = !!rig && rect[0] === 0 && rect[1] === 0 && rect[2] === rig.image.width && rect[3] === rig.image.height;
const distances = silhouetteDistance(alpha, width, height, cropped), heights = new Float32Array(alpha.length);
const dx = rect[2] / width, dy = rect[3] / height, unit = Math.min(dx, dy);
@@ -39,15 +78,21 @@ export function generateNormals(alpha: Uint8Array, width: number, height: number
heights[i] = (inflate ? Math.sqrt(distances[i] * unit * depth) * 0.55 : 0)
+ (rig ? rigHeight(rect[0] + (x + 0.5) * dx, rect[1] + (y + 0.5) * dy, rig) : 0);
}
+ // The distance field has creases along the silhouette's medial axis; smoothing removes the
+ // visible seams they would draw across large areas such as the face.
+ const radius = Math.max(1, Math.round(Math.min(width, height) * 0.02));
+ heights.set(boxBlur(boxBlur(heights, width, height, radius), width, height, radius));
+ const detail = luminance ? detailGradient(luminance, alpha, width, height) : null;
const normals = new Uint8Array(width * height * 4);
const sample = (x: number, y: number) => heights[Math.max(0, Math.min(height - 1, y)) * width + Math.max(0, Math.min(width - 1, x))];
for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
// A small derivative footprint suppresses staircase artifacts in the distance field.
const nx = -(sample(x + 2, y) - sample(x - 2, y)) / (4 * dx), ny = -(sample(x, y + 2) - sample(x, y - 2)) / (4 * dy);
- const len = Math.hypot(nx, ny, 1), i = (y * width + x) * 4;
+ const len = Math.hypot(nx, ny, 1), i = (y * width + x) * 4, j = y * width + x;
normals[i] = Math.round((nx / len * 0.5 + 0.5) * 255);
normals[i + 1] = Math.round((ny / len * 0.5 + 0.5) * 255);
- normals[i + 2] = Math.round((1 / len * 0.5 + 0.5) * 255); normals[i + 3] = 255;
+ normals[i + 2] = Math.round(((detail?.[2 * j] ?? 0) * 0.5 + 0.5) * 255);
+ normals[i + 3] = Math.round(((detail?.[2 * j + 1] ?? 0) * 0.5 + 0.5) * 255);
}
return normals;
}
@@ -63,8 +108,13 @@ export function layerNormals(image: HTMLImageElement, rect: number[], rig: Rig,
const context = canvas.getContext('2d', { willReadFrequently: true })!;
context.drawImage(image, 0, 0, width, height);
const pixels = context.getImageData(0, 0, width, height).data, alpha = new Uint8Array(width * height);
- for (let i = 0; i < alpha.length; i++) alpha[i] = pixels[4 * i + 3];
- const result = { key, data: generateNormals(alpha, width, height, rect, rig, inflate), width, height };
+ const luminance = new Float32Array(width * height);
+ for (let i = 0; i < alpha.length; i++) {
+ alpha[i] = pixels[4 * i + 3];
+ luminance[i] = (0.2126 * pixels[4 * i] + 0.7152 * pixels[4 * i + 1] + 0.0722 * pixels[4 * i + 2]) / 255;
+ }
+ // Eye and mouth layers are redrawn by the shader, so painted relief would not line up there.
+ const result = { key, data: generateNormals(alpha, width, height, rect, rig, inflate, inflate ? luminance : undefined), width, height };
cache.set(image, result);
return { ...result, computed: true, ms: performance.now() - start };
}
diff --git a/src/lighting/settings.ts b/src/lighting/settings.ts
index cf1f484..409f2c5 100644
--- a/src/lighting/settings.ts
+++ b/src/lighting/settings.ts
@@ -1,12 +1,19 @@
export interface LightingSettings {
enabled: boolean; x: number; y: number; z: number; color: number;
strength: number; intensity: number; ambient: number; mode: 'soft' | 'cel'; shadow: boolean;
+ reach: number; ambientColor: number; softness: number; specular: number; rim: number; detail: number;
}
export const DEFAULT_LIGHTING: Readonly<LightingSettings> = Object.freeze({
- enabled: false, x: 0.2, y: 0.2, z: 0.65, color: 0xffffff,
- strength: 0.35, intensity: 1, ambient: 0.6, mode: 'soft', shadow: false,
+ enabled: false, x: 0.2, y: 0.2, z: 0.45, color: 0xffffff,
+ strength: 0.8, intensity: 0.8, ambient: 0.4, mode: 'soft', shadow: false,
+ reach: 1.2, ambientColor: 0xeef0f8, softness: 0.45, specular: 0.12, rim: 0.3, detail: 0.4,
});
-const ranges = { x: [0, 1], y: [0, 1], z: [0.1, 2], color: [0, 0xffffff], strength: [0, 1], intensity: [0, 2], ambient: [0, 1] } as const;
+const ranges = { x: [0, 1], y: [0, 1], z: [0.1, 2], color: [0, 0xffffff], strength: [0, 1], intensity: [0, 2], ambient: [0, 1],
+ reach: [0.2, 3], ambientColor: [0, 0xffffff], softness: [0, 1], specular: [0, 1], rim: [0, 1], detail: [0, 1] } as const;
+const colors = new Set(['color', 'ambientColor']);
+// URL parameter names; colours are six hex digits without '#'.
+const params = { x: 'lx', y: 'ly', z: 'lz', strength: 'ls', intensity: 'li', ambient: 'la',
+ reach: 'lr', softness: 'lf', specular: 'lsp', rim: 'lrim', detail: 'ld' } as const;
// Strict wire format: only finite numbers and enumerated strings; no arbitrary payloads.
export function parseLighting(input: unknown): LightingSettings | null {
if (!input || typeof input !== 'object' || Array.isArray(input)) return null;
@@ -16,30 +23,36 @@ export function parseLighting(input: unknown): LightingSettings | null {
const result = { ...DEFAULT_LIGHTING, enabled: data.enabled, shadow: data.shadow, mode: data.mode } as LightingSettings;
for (const key of Object.keys(ranges) as (keyof typeof ranges)[]) {
const value = data[key], [min, max] = ranges[key];
- if (typeof value !== 'number' || !Number.isFinite(value) || (key === 'color' && !Number.isInteger(value))) return null;
+ if (typeof value !== 'number' || !Number.isFinite(value) || (colors.has(key) && !Number.isInteger(value))) return null;
result[key] = Math.max(min, Math.min(max, value));
}
return result;
}
export function lightingFromQuery(query: URLSearchParams): LightingSettings {
const value = { ...DEFAULT_LIGHTING, enabled: query.get('light') === '1', shadow: query.get('shadow') === '1', mode: query.get('lm') === 'cel' ? 'cel' : 'soft' } as LightingSettings;
- for (const [key, param] of Object.entries({ x: 'lx', y: 'ly', z: 'lz', strength: 'ls', intensity: 'li', ambient: 'la' })) {
+ for (const [key, param] of Object.entries(params)) {
const raw = query.get(param), n = Number(raw);
if (raw?.trim() && Number.isFinite(n)) (value as unknown as Record<string, unknown>)[key] = n;
}
- const color = query.get('lc');
- if (color && /^[0-9a-f]{6}$/i.test(color)) value.color = parseInt(color, 16);
+ for (const [key, param] of [['color', 'lc'], ['ambientColor', 'lac']] as const) {
+ const color = query.get(param);
+ if (color && /^[0-9a-f]{6}$/i.test(color)) value[key] = parseInt(color, 16);
+ }
return parseLighting(value)!;
}
export function writeLightingQuery(query: URLSearchParams, value: LightingSettings) {
- const pairs = { light: value.enabled ? '1' : '0', lx: value.x, ly: value.y, lz: value.z,
- lc: colorHex(value.color).slice(1), ls: value.strength, li: value.intensity, la: value.ambient,
- lm: value.mode, shadow: value.shadow ? '1' : '0' };
- for (const [key, v] of Object.entries(pairs)) query.set(key, String(v));
+ query.set('light', value.enabled ? '1' : '0');
+ for (const [key, param] of Object.entries(params)) query.set(param, String(value[key as keyof typeof params]));
+ query.set('lc', colorHex(value.color).slice(1)); query.set('lac', colorHex(value.ambientColor).slice(1));
+ query.set('lm', value.mode); query.set('shadow', value.shadow ? '1' : '0');
}
export function colorHex(color: number) { return `#${color.toString(16).padStart(6, '0')}`; }
export function loadLighting(project: string): LightingSettings {
- try { return parseLighting(JSON.parse(localStorage.getItem(`mesh-avatar:lighting:${project}`) ?? 'null')) ?? { ...DEFAULT_LIGHTING }; }
+ try {
+ const stored = JSON.parse(localStorage.getItem(`mesh-avatar:lighting:${project}`) ?? 'null');
+ // Settings saved before newer options existed keep their values; missing options use defaults.
+ return stored && typeof stored === 'object' && !Array.isArray(stored) ? parseLighting({ ...DEFAULT_LIGHTING, ...stored }) ?? { ...DEFAULT_LIGHTING } : { ...DEFAULT_LIGHTING };
+ }
catch { return { ...DEFAULT_LIGHTING }; }
}
export function saveLighting(project: string, value: LightingSettings) {
diff --git a/src/lighting/shading.ts b/src/lighting/shading.ts
index 7875068..f453346 100644
--- a/src/lighting/shading.ts
+++ b/src/lighting/shading.ts
@@ -1,12 +1,25 @@
-// Shared coefficients keep the reference math and shader in agreement.
-export const WRAP = 0.45;
-export const DARKEN = 0.55;
-export const BRIGHTEN = 0.3;
-export function shadeAmount(dot: number, mode: 'soft' | 'cel', ambient: number, intensity: number) {
- let diffuse = Math.max(0, Math.min(1, (dot + WRAP) / (1 + WRAP)));
- if (mode === 'cel') diffuse = diffuse < 0.4 ? 0.18 : diffuse < 0.75 ? 0.55 : 1;
- return Math.max(-1, Math.min(1, ambient + intensity * diffuse - 1));
+// Shared reference math; the shader in renderer.js follows the same formulas.
+const smoothstep = (a: number, b: number, x: number) => { const t = Math.max(0, Math.min(1, (x - a) / (b - a))); return t * t * (3 - 2 * t); };
+export const TERMINATOR = -0.1;
+export const DETAIL_SCALE = 0.9;
+export const SHADOW_SATURATION = 1.0;
+export const MAX_IRRADIANCE = 1.06;
+/** Colour of an unpremultiplied albedo under a grey irradiance level. */
+export function shadedColor(albedo: readonly number[], irradiance: number) {
+ const dark = 1 - Math.max(0, Math.min(1, irradiance));
+ return albedo.map(v => v * (1 + (v - 1) * dark * SHADOW_SATURATION) * irradiance);
}
+export function diffuseTerm(ndl: number, mode: 'soft' | 'cel', softness: number) {
+ if (mode === 'cel') {
+ const w = 0.01 + softness * 0.08;
+ return 0.2 + 0.45 * smoothstep(TERMINATOR - w, TERMINATOR + w, ndl) + 0.35 * smoothstep(0.55 - w, 0.55 + w, ndl);
+ }
+ const s = 0.05 + softness * 0.5;
+ // A soft terminator, then a gentle rise toward surfaces facing the light.
+ return smoothstep(TERMINATOR - s, TERMINATOR + s, ndl) * (0.35 + 0.65 * Math.max(0, ndl));
+}
+export function attenuation(distance: number, reach: number) { return 1 / (1 + (distance / reach) ** 2); }
+export function rimTerm(nz: number, facing: number) { return (1 - Math.max(0, nz)) ** 4 * smoothstep(-0.2, 0.7, facing); }
export function shadowOffset(x: number, y: number): [number, number] { return [(0.5 - x) * 0.12, (0.5 - y) * 0.12]; }
export function headRotation(angleX: number, angleY: number, angleZ: number, maxRoll: number) {
const yaw = angleX * Math.PI / 180, pitch = angleY * Math.PI / 180, roll = -angleZ / 30 * maxRoll;
diff --git a/tests/lighting.test.ts b/tests/lighting.test.ts
index 73078bd..0df2e61 100644
--- a/tests/lighting.test.ts
+++ b/tests/lighting.test.ts
@@ -1,7 +1,7 @@
import { expect, test } from 'vitest';
-import { DEFAULT_LIGHTING, lightingFromQuery, parseLighting, writeLightingQuery } from '../src/lighting/settings';
-import { generateNormals, silhouetteDistance } from '../src/lighting/normals';
-import { headRotation, shadeAmount, shadowOffset } from '../src/lighting/shading';
+import { DEFAULT_LIGHTING, lightingFromQuery, loadLighting, parseLighting, writeLightingQuery } from '../src/lighting/settings';
+import { detailGradient, generateNormals, silhouetteDistance } from '../src/lighting/normals';
+import { attenuation, diffuseTerm, shadedColor, headRotation, rimTerm, shadowOffset } from '../src/lighting/shading';
import { lightingMessage, lightingValue, lightingWire } from '../src/lighting/protocol';
import { viewSettings, streamUrl } from '../src/live/settings';
@@ -9,8 +9,10 @@ test('inflated disc normals face outward at the rim and forward at the centre',
const size = 65, alpha = new Uint8Array(size * size);
for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) if (Math.hypot(x - 32, y - 32) <= 28) alpha[y * size + x] = 255;
const data = generateNormals(alpha, size, size, [0, 0, size, size]);
- const normal = (x: number, y: number) => [...data.slice((y * size + x) * 4, (y * size + x) * 4 + 3)].map(v => v / 255 * 2 - 1);
- expect(normal(32, 32)[0]).toBeCloseTo(0, 2); expect(normal(32, 32)[1]).toBeCloseTo(0, 2); expect(normal(32, 32)[2]).toBe(1);
+ const normal = (x: number, y: number) => [...data.slice((y * size + x) * 4, (y * size + x) * 4 + 2)].map(v => v / 255 * 2 - 1);
+ expect(normal(32, 32)[0]).toBeCloseTo(0, 2); expect(normal(32, 32)[1]).toBeCloseTo(0, 2);
+ // Without painting data the relief channels stay neutral.
+ expect(data[(32 * size + 32) * 4 + 2]).toBe(128); expect(data[(32 * size + 32) * 4 + 3]).toBe(128);
expect(normal(58, 32)[0]).toBeGreaterThan(0.2); expect(normal(6, 32)[0]).toBeLessThan(-0.2);
expect(normal(32, 58)[1]).toBeGreaterThan(0.2); expect(normal(32, 6)[1]).toBeLessThan(-0.2);
expect(silhouetteDistance(alpha, size, size)[0]).toBe(0);
@@ -19,16 +21,27 @@ test('transparent and fully opaque rectangles produce finite normals', () => {
for (const alpha of [new Uint8Array(1), new Uint8Array(100).fill(255)]) {
const n = generateNormals(alpha, Math.sqrt(alpha.length), Math.sqrt(alpha.length), [0, 0, 100, 100]);
expect([...n].every(Number.isFinite)).toBe(true);
- for (let i = 3; i < n.length; i += 4) expect(n[i]).toBe(255);
+ for (let i = 3; i < n.length; i += 4) expect(n[i]).toBe(128);
}
});
-test('wrapped diffuse is brighter facing the source and cel has three bands', () => {
- for (const mode of ['soft', 'cel'] as const) expect(shadeAmount(1, mode, 0.6, 1)).toBeGreaterThan(shadeAmount(-1, mode, 0.6, 1));
- const levels = new Set(Array.from({length:201}, (_,i)=>shadeAmount(i / 100 - 1, 'cel', 0.6, 1)));
- expect(levels.size).toBe(3);
- expect(shadeAmount(1, 'soft', 1, 0)).toBe(0);
+test('diffuse is brighter facing the light, cel has three bands, and light fades with distance', () => {
+ for (const mode of ['soft', 'cel'] as const) expect(diffuseTerm(1, mode, 0.45)).toBeGreaterThan(diffuseTerm(-1, mode, 0.45));
+ const levels = new Set(Array.from({ length: 201 }, (_, i) => Math.round(diffuseTerm(i / 100 - 1, 'cel', 0) * 1000)));
+ expect(levels.size).toBeLessThanOrEqual(8); expect([...levels].filter(v => [200, 650, 1000].includes(v))).toHaveLength(3);
+ expect(diffuseTerm(-1, 'soft', 1)).toBe(0); expect(diffuseTerm(0.3, 'soft', 1)).toBeLessThan(diffuseTerm(0.3, 'soft', 0));
+ expect(attenuation(0, 1)).toBe(1); expect(attenuation(2, 1)).toBeLessThan(attenuation(1, 1)); expect(attenuation(1, 3)).toBeGreaterThan(attenuation(1, 1));
+ expect(rimTerm(1, 1)).toBe(0); expect(rimTerm(0, 1)).toBeGreaterThan(rimTerm(0, -1));
expect(shadowOffset(0, 0)).toEqual([0.06, 0.06]); expect(shadowOffset(1, 1)).toEqual([-0.06, -0.06]);
});
+test('painted strokes become grooves; flat paint and transparent pixels add no relief', () => {
+ const size = 21, alpha = new Uint8Array(size * size).fill(255), luminance = new Float32Array(size * size).fill(0.8);
+ for (let y = 0; y < size; y++) luminance[y * size + 10] = 0.1;
+ const g = detailGradient(luminance, alpha, size, size);
+ // Left of the dark line the surface tilts right (into the groove), right of it tilts left.
+ expect(g[2 * (10 * size + 9)]).toBeGreaterThan(0); expect(g[2 * (10 * size + 11)]).toBeLessThan(0);
+ expect(g[2 * (10 * size + 2)]).toBeCloseTo(0, 5);
+ alpha.fill(0); expect([...detailGradient(luminance, alpha, size, size)].every(v => v === 0)).toBe(true);
+});
test('head yaw rotates the front normal toward the new direction; roll uses the rig angle', () => {
const r = headRotation(30, 0, 0, 0.3);
expect(r[6]).toBeCloseTo(0.5); expect(r[7]).toBeCloseTo(0); expect(r[8]).toBeCloseTo(Math.sqrt(3)/2);
@@ -36,7 +49,8 @@ test('head yaw rotates the front normal toward the new direction; roll uses the
expect(roll[0]).toBeCloseTo(Math.cos(-0.3)); expect(roll[1]).toBeCloseTo(Math.sin(-0.3));
});
test('lighting URLs round trip every option and clamp malformed numbers', () => {
- const light = { ...DEFAULT_LIGHTING, enabled: true, x: 0.9, y: 0.8, z: 1.2, color: 0x1234ff, strength: 0.8, intensity: 1.5, ambient: 0.2, mode: 'cel' as const, shadow: true };
+ const light = { ...DEFAULT_LIGHTING, enabled: true, x: 0.9, y: 0.8, z: 1.2, color: 0x1234ff, strength: 0.8, intensity: 1.5, ambient: 0.2, mode: 'cel' as const, shadow: true,
+ reach: 2.5, ambientColor: 0x203040, softness: 0.1, specular: 0.6, rim: 0.9, detail: 0.7 };
const query = new URLSearchParams(); writeLightingQuery(query, light); expect(lightingFromQuery(query)).toEqual(light);
const view = { ...viewSettings(''), lighting: light };
expect(viewSettings(new URL(streamUrl(view, 'http://127.0.0.1:5173')).search)).toEqual(view);
@@ -46,7 +60,7 @@ test('relay accepts only complete, numeric or enumerated lighting settings', ()
const message = lightingWire('project-a', { ...DEFAULT_LIGHTING, enabled: true });
expect(lightingMessage(message)).toEqual(message);
expect(lightingValue(message)).toEqual({ ...DEFAULT_LIGHTING, enabled: true });
- for (const change of [{ z: Infinity }, { x: '0.5' }, { color: '#ffffff' }, { color: 1.2 }, { mode: 'other' }, { enabled: true }, { enabled: '1' }, { shadow: 2 }, { url: 'https://example.com' }]) {
+ for (const change of [{ ambientColor: 0.5 }, { reach: '1' }, { z: Infinity }, { x: '0.5' }, { color: '#ffffff' }, { color: 1.2 }, { mode: 'other' }, { enabled: true }, { enabled: '1' }, { shadow: 2 }, { url: 'https://example.com' }]) {
expect(lightingMessage({ ...message, lighting: { ...message.lighting, ...change } })).toBeNull();
}
for (const invalid of [null, [], { ...message, project: '../private' }, { ...message, params: {} }, { project: 'a', lighting: {} }]) expect(lightingMessage(invalid)).toBeNull();
@@ -60,3 +74,20 @@ test('cropped opaque borders do not bend toward an artificial outside silhouette
expect(distance[12]).toBe(distance[12 * size + 12]);
expect(distance[24 * size + 12]).toBe(distance[12 * size + 12]);
});
+
+test('settings saved before newer options existed keep their values', () => {
+ const store = new Map<string, string>();
+ Object.assign(globalThis, { localStorage: { getItem: (k: string) => store.get(k) ?? null, setItem: (k: string, v: string) => store.set(k, v) } });
+ const old = { enabled: true, x: 0.7, y: 0.3, z: 0.9, color: 0xffeedd, strength: 0.5, intensity: 1, ambient: 0.6, mode: 'cel', shadow: true };
+ store.set('mesh-avatar:lighting:old', JSON.stringify(old));
+ expect(loadLighting('old')).toEqual({ ...DEFAULT_LIGHTING, ...old });
+ store.set('mesh-avatar:lighting:bad', '[1]'); expect(loadLighting('bad')).toEqual(DEFAULT_LIGHTING);
+});
+
+test('shadows deepen the base colour instead of turning it grey', () => {
+ const skin = [1, 0.9, 0.85], lit = shadedColor(skin, 1), shadow = shadedColor(skin, 0.5);
+ expect(lit).toEqual(skin);
+ const saturation = (c: number[]) => (Math.max(...c) - Math.min(...c)) / Math.max(...c);
+ expect(saturation(shadow)).toBeGreaterThan(saturation(skin));
+ expect(shadedColor([0.5, 0.5, 0.5], 0.5)[0]).toBeCloseTo(0.1875);
+});