Turn one illustration into an animated 2D mesh avatar with a coding agent and a local editor
Add optional avatar lighting and drop shadows
shinshin863ed174ae8308
diff --git a/e2e/lighting.spec.ts b/e2e/lighting.spec.tsnew file mode 100644index 0000000..7c116a0--- /dev/null+++ b/e2e/lighting.spec.ts@@ -0,0 +1,145 @@+import { expect, test, type BrowserContext, type Page } from '@playwright/test';+import { createHash } from 'node:crypto';+import { existsSync, readFileSync, readdirSync } from 'node:fs';+import { PNG } from 'pngjs';+import { dismissGuide, samplePresent, sampleSkipReason } from './sample';++test.beforeEach(() => test.skip(!samplePresent, sampleSkipReason));+async function guard(context: BrowserContext) {+ const outside: string[] = [];+ await context.route('**/*', route => { const url = route.request().url(); if (new URL(url).hostname !== '127.0.0.1') { outside.push(url); return route.abort(); } return route.continue(); });+ const watch = (page: Page) => page.on('websocket', socket => { if (new URL(socket.url()).hostname !== '127.0.0.1') outside.push(socket.url()); });+ context.pages().forEach(watch); context.on('page', watch);+ return outside;+}+async function freeze(page: Page) {+ await page.addInitScript(() => {+ let clock = 0, next = 0; const frames = new Map<number, FrameRequestCallback>();+ performance.now = () => clock;+ window.requestAnimationFrame = fn => { frames.set(++next, fn); return next; }; window.cancelAnimationFrame = id => { frames.delete(id); };+ Object.assign(window, { stepFrames: (count: number) => { for (let i = 0; i < count; i++) { clock += 1000 / 60; const batch = [...frames.values()]; frames.clear(); batch.forEach(fn => fn(clock)); } } });+ });+}+const image = async (page: Page, selector: string) => PNG.sync.read(Buffer.from(await page.locator(selector).evaluate(c => (c as HTMLCanvasElement).toDataURL().split(',')[1]), 'base64'));+const hash = (png: PNG) => createHash('sha256').update(png.data).digest('hex');++test('off preview and stream hashes match the local pre-lighting capture', async ({ context, page }) => {+ const baseline = 'projects/.lighting-review/before-preview.png';+ test.skip(!existsSync(baseline), 'Local visual baseline is intentionally excluded from version control.');+ const outside = await guard(context); await freeze(page);+ for (const file of readdirSync('projects/.lighting-review').filter(name => /^before-stream-[A-Za-z0-9][A-Za-z0-9._-]*\.png$/.test(name))) {+ const project = file.slice('before-stream-'.length, -4);+ const path = `projects/.lighting-review/before-stream-${project}.png`;+ if (!existsSync(path)) continue;+ await page.goto(`/stream.html?project=${project}&idle=0`);+ await expect(page.locator('canvas')).toHaveAttribute('data-state', 'ready');+ await page.evaluate(() => (window as unknown as { stepFrames: (n: number) => void }).stepFrames(120));+ expect(hash(await image(page, 'canvas'))).toBe(hash(PNG.sync.read(readFileSync(path))));+ }+ await page.goto('/'); await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready'); await dismissGuide(page);+ await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');+ const revision = await page.getByTestId('preview').getAttribute('data-revision');+ await page.getByTestId('idle-toggle').click();+ await expect(page.getByTestId('preview')).not.toHaveAttribute('data-revision', revision!);+ await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');+ expect(hash(await image(page, '[data-testid="preview"]'))).toBe(hash(PNG.sync.read(readFileSync(baseline))));+ expect(outside).toEqual([]);+});++test('lighting is lazy, changes brightness with position, preserves alpha, shadows opposite, and off restores pixels', async ({ context, page }) => {+ const outside = await guard(context), errors: string[] = []; page.on('pageerror', e => errors.push(e.message));+ await page.addInitScript(() => { window.requestAnimationFrame = () => 0; });+ await page.goto('/stream.html?idle=0'); await expect(page.locator('canvas')).toHaveAttribute('data-state', 'ready');+ await page.evaluate(async () => {+ const path = '/src/live/avatar-view.ts', { createAvatarView, neutralParameters } = await import(path);+ const settingsPath = '/src/lighting/settings.ts', { DEFAULT_LIGHTING } = await import(settingsPath);+ const canvas = document.createElement('canvas'); canvas.id = 'test-avatar'; canvas.style.cssText = 'width:640px;height:640px'; document.body.append(canvas);+ const view = await createAvatarView(canvas, { project: 'sample-miko-qipao', fit: 'contain', idle: false });+ view.avatar.setParameters(neutralParameters); view.avatar.advance(1);+ Object.assign(window, { testAvatar: view.avatar, defaultLight: DEFAULT_LIGHTING });+ });+ const light = (settings: Record<string, unknown>) => page.evaluate(settings => {+ const w = window as unknown as { testAvatar: import('../src/engine').MeshAvatar; defaultLight: import('../src/lighting/settings').LightingSettings };+ w.testAvatar.setLighting({ ...w.defaultLight, ...settings }); w.testAvatar.advance(0); return w.testAvatar.getLightingStats();+ }, settings);+ const off = await image(page, '#test-avatar');+ expect(await light({ enabled: false })).toEqual({ computedLayers: 0, cachedLayers: 0, normalMs: 0 });+ const initial = await light({ enabled: true, x: 0, y: 0.5, strength: 0.8 });+ expect(initial.computedLayers).toBeGreaterThan(1);+ const left = await image(page, '#test-avatar');+ await light({ enabled: true, x: 1, y: 0.5, strength: 0.8 }); const right = await image(page, '#test-avatar');+ const delta = [0, 0], count = [0, 0]; let alphaChanged = 0;+ for (let y = 0; y < left.height; y++) for (let x = 0; x < left.width; x++) {+ const i = (y * left.width + x) * 4;+ if (left.data[i + 3] !== off.data[i + 3]) alphaChanged++;+ if (left.data[i + 3] < 250) continue;+ const half = x < left.width / 2 ? 0 : 1;+ delta[half] += left.data[i] + left.data[i + 1] + left.data[i + 2] - right.data[i] - right.data[i + 1] - right.data[i + 2]; count[half]++;+ }+ expect(alphaChanged).toBe(0);+ expect(delta[0] / count[0]).toBeGreaterThan(1); expect(delta[1] / count[1]).toBeLessThan(-1);+ const shadowCentres = [];+ for (const x of [0, 1]) {+ await light({ enabled: true, x, y: 0.5, shadow: true }); const shadow = await image(page, '#test-avatar');+ let mass = 0, centre = 0;+ for (let y = 0; y < shadow.height; y++) for (let px = 0; px < shadow.width; px++) {+ const i = (y * shadow.width + px) * 4;+ if (off.data[i + 3] > 0) continue;+ const alpha = shadow.data[i + 3]; mass += alpha; centre += alpha * px;+ }+ expect(mass).toBeGreaterThan(1000); shadowCentres.push(centre / mass);+ }+ expect(shadowCentres[0]).toBeGreaterThan(shadowCentres[1] + 50);+ expect(await light({ enabled: false })).toEqual(initial);+ expect(hash(await image(page, '#test-avatar'))).toBe(hash(off));+ expect(errors).toEqual([]); expect(outside).toEqual([]);+});++test('editor remembers lighting, hides the handle outside its tab, and resets in all languages', async ({ context, page }) => {+ const outside = await guard(context);+ await page.goto('/'); await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready'); await dismissGuide(page);+ await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');+ await expect(page.getByRole('button', { name: 'Light position', exact: true })).toHaveCount(0);+ await page.getByRole('tab', { name: 'Lighting', exact: true }).click();+ await page.getByRole('checkbox', { name: 'Enable lighting' }).check();+ const handle = page.getByRole('button', { name: 'Light position', exact: true });+ await handle.focus(); await handle.press('ArrowRight');+ await expect(handle).toHaveCSS('left', /px$/);+ await page.getByLabel('Shading', { exact: true }).selectOption('cel');+ await page.reload(); await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');+ await page.getByRole('tab', { name: 'Lighting', exact: true }).click();+ await expect(page.getByRole('checkbox', { name: 'Enable lighting' })).toBeChecked();+ await expect(page.getByLabel('Shading', { exact: true })).toHaveValue('cel');+ await page.getByRole('button', { name: '日本語', exact: true }).click();+ await expect(page.getByRole('checkbox', { name: '照明を有効にする' })).toBeVisible();+ await page.getByRole('button', { name: '简体中文', exact: true }).click();+ await page.getByRole('button', { name: '重置光照', exact: true }).click();+ await expect(page.getByRole('checkbox', { name: '启用光照' })).not.toBeChecked();+ expect(outside).toEqual([]);+});++test('live drag updates matching streams without a camera, and OBS URLs carry every lighting option', async ({ context, page }) => {+ const outside = await guard(context);+ await page.goto('/live.html'); await expect(page.locator('canvas')).toHaveAttribute('data-state', 'ready');+ const stream = await context.newPage(); await stream.goto('/stream.html?idle=0'); await expect(stream.locator('canvas')).toHaveAttribute('data-state', 'ready');+ await stream.evaluate(async () => {+ const path = '/src/live/relay.ts', { receiveLighting } = await import(path);+ Object.assign(window, { latestLighting: null, wrongProject: false });+ receiveLighting('sample-miko-qipao', (value: unknown) => Object.assign(window, { latestLighting: value }));+ receiveLighting('unrelated-project', () => Object.assign(window, { wrongProject: true }));+ });+ const before = hash(await image(stream, 'canvas'));+ await page.getByRole('checkbox', { name: 'Enable lighting' }).check();+ const handle = page.getByRole('button', { name: 'Light position', exact: true }), bounds = await page.locator('canvas').boundingBox();+ await handle.hover(); await page.mouse.down();+ await page.mouse.move(bounds!.x + bounds!.width * 0.9, bounds!.y + bounds!.height * 0.3, { steps: 12 }); await page.mouse.up();+ await page.getByLabel('Shading', { exact: true }).selectOption('cel');+ await page.getByRole('checkbox', { name: 'Drop shadow' }).check();+ await expect.poll(() => stream.evaluate(() => (window as unknown as { latestLighting: unknown }).latestLighting)).toMatchObject({ enabled: true, mode: 'cel', shadow: true });+ await expect.poll(async () => hash(await image(stream, 'canvas'))).not.toBe(before);+ expect(await stream.evaluate(() => (window as unknown as { wrongProject: boolean }).wrongProject)).toBe(false);+ const url = new URL(await page.getByRole('textbox', { name: 'Copy OBS URL' }).inputValue());+ expect(url.searchParams.get('light')).toBe('1'); expect(Number(url.searchParams.get('lx'))).toBeCloseTo(0.9, 2); expect(url.searchParams.get('lm')).toBe('cel'); expect(url.searchParams.get('shadow')).toBe('1');+ expect(await page.getByRole('link', { name: 'Open stream view' }).getAttribute('href')).toBe(url.href);+ expect(outside).toEqual([]);+});diff --git a/src/editor/App.tsx b/src/editor/App.tsxindex 02dfd06..16aa2c8 100644--- a/src/editor/App.tsx+++ b/src/editor/App.tsx@@ -395,7 +395,7 @@ function Workspace() {</div></section><div className="right-column">- <Preview rig={rig} assets={assets} hasMouthSprites={mouthSprites} onDrawMouth={() => setMouthRequest(value => value + 1)} />+ <Preview key={localProject?.name ?? (pickedName || 'sample-miko-qipao')} projectKey={localProject?.name ?? (pickedName || 'sample-miko-qipao')} rig={rig} assets={assets} hasMouthSprites={mouthSprites} onDrawMouth={() => setMouthRequest(value => value + 1)} /><VariantsPanel project={localProject} projectPath={localProject?.relativePath ?? (pickedName ? `<${pickedName}>` : 'samples/miko-qipao')} assets={assets} rootPath={rootPath} busy={job !== null || saving} stale={changed.length > 0} onRun={runJob} mouthRequest={mouthRequest} onMouthPresence={setMouthSprites} />{!localProject && !pickedName && <details className="panel new-illustration"><summary>{t.newIllustration}</summary><AskAgent newProject rootPath={rootPath} /></details>}<aside className="panel inspector" inert={job !== null || opening}>diff --git a/src/editor/Preview.tsx b/src/editor/Preview.tsxindex 01641d3..771ca37 100644--- a/src/editor/Preview.tsx+++ b/src/editor/Preview.tsx@@ -1,3 +1,5 @@+import { LightingControls, LightHandle, lightingText } from '../lighting/Controls';+import { loadLighting, saveLighting } from '../lighting/settings';import { useEffect, useRef, useState } from 'react';import { createMeshAvatar, type MeshAvatar } from '../engine';import { PARAMS } from '../engine/rig.js';@@ -17,8 +19,10 @@ const sliders = [] as const;type Vowel = 'a' | 'i' | 'u' | 'e' | 'o' | 'n';type Lip = { kind: 'hold'; vowel: Vowel } | { kind: 'text'; text: string; speed: number; loop: boolean } | null;-export function Preview({ rig, assets, hasMouthSprites, onDrawMouth }: { rig: Rig; assets?: Record<string, string>; hasMouthSprites: boolean; onDrawMouth: () => void }) {- const { t } = useI18n();+export function Preview({ projectKey, rig, assets, hasMouthSprites, onDrawMouth }: { projectKey: string; rig: Rig; assets?: Record<string, string>; hasMouthSprites: boolean; onDrawMouth: () => void }) {+ const { t, language } = useI18n();+ const [lighting, setLighting] = useState(() => loadLighting(projectKey));+ const lightRef = useRef(lighting); lightRef.current = lighting;const canvas = useRef<HTMLCanvasElement>(null);const avatar = useRef<MeshAvatar | null>(null);const [status, setStatus] = useState<'loading' | 'updating' | 'ready' | 'previewError'>('loading');@@ -31,7 +35,7 @@ export function Preview({ rig, assets, hasMouthSprites, onDrawMouth }: { rig: Riconst [speed, setSpeed] = useState(7);const [loop, setLoop] = useState(false);const [liveMouth, setLiveMouth] = useState(0);- const [tab, setTab] = useState<'pose' | 'lip'>('pose');+ const [tab, setTab] = useState<'pose' | 'lip' | 'lighting'>('pose');const skipped = skippedKanaCharacters(text).join(' ');const controls = useRef({ idle, stress, parameters });controls.current = { idle, stress, parameters };@@ -44,6 +48,7 @@ export function Preview({ rig, assets, hasMouthSprites, onDrawMouth }: { rig: Riif (cancelled) { value.destroy(); return; }instance = value;avatar.current = value;+ value.setLighting(lightRef.current);const control = controls.current;value.setAutoIdle(control.idle && !control.stress);value.setAutoMotion(control.idle && !control.stress);@@ -96,11 +101,18 @@ export function Preview({ rig, assets, hasMouthSprites, onDrawMouth }: { rig: Riraf = requestAnimationFrame(frame);return () => cancelAnimationFrame(raf);}, [rig, assets, idle, stress, parameters, revision, lip]);+ useEffect(() => {+ saveLighting(projectKey, lighting);+ avatar.current?.setLighting(lighting);+ avatar.current?.advance(0);+ }, [lighting, projectKey]);return (<section className="panel preview-panel"><div className="panel-title"><h2>{t.preview}</h2><span role="status" data-testid="preview-status" data-state={status}>{t[status]}</span></div>- <canvas ref={canvas} data-testid="preview" data-revision={revision} className="preview-canvas"+ <div className="lighting-preview"><canvas ref={canvas} data-testid="preview" data-revision={revision} className="preview-canvas"style={{ aspectRatio: `${rig.image.width * (1 + 2 * rig.view.padSide)} / ${rig.image.height * (1 + rig.view.padTop)}` }} />+ {tab === 'lighting' && <LightHandle value={lighting} onChange={setLighting} language={language} />}+ </div><div className="preview-tools"><button className="icon-button" aria-label={idle ? t.pause : t.play} title={idle ? t.pause : t.play}data-testid="idle-toggle" aria-pressed={idle} onClick={() => setIdle(current => !current)}><Icon name={idle ? 'pause' : 'play'} /></button><span>{t.idle}</span>@@ -108,7 +120,9 @@ export function Preview({ rig, assets, hasMouthSprites, onDrawMouth }: { rig: Ri<div className="preview-tabs" role="tablist" aria-label={t.preview}><button id="pose-tab" role="tab" aria-selected={tab === 'pose'} aria-controls="pose-panel" onClick={() => setTab('pose')}>{t.pose}</button><button id="lip-tab" role="tab" aria-selected={tab === 'lip'} aria-controls="lip-panel" onClick={() => setTab('lip')}>{t.lipSync}</button>+ <button id="lighting-tab" role="tab" aria-selected={tab === 'lighting'} aria-controls="lighting-panel" onClick={() => setTab('lighting')}>{lightingText[language].title}</button></div>+ <div id="lighting-panel" role="tabpanel" aria-labelledby="lighting-tab" hidden={tab !== 'lighting'}><LightingControls value={lighting} onChange={setLighting} language={language} /></div><div className="pose-test" id="pose-panel" role="tabpanel" aria-labelledby="pose-tab" hidden={tab !== 'pose'}><div className="sliders">{sliders.map(slider => (diff --git a/src/engine/createMeshAvatar.js b/src/engine/createMeshAvatar.jsindex c8614cd..9f93848 100644--- a/src/engine/createMeshAvatar.js+++ b/src/engine/createMeshAvatar.js@@ -186,6 +186,7 @@ export async function createMeshAvatarImpl(canvas, options) {const ball = 7; // px of iris travelR.draw({+ angleX: P.angleX, angleY: P.angleY, angleZ: P.angleZ,eyes: [eyeOpenFor(P.eyeROpen), P.eyeSmile, P.gazeX * ball, -P.gazeY * ball * 0.6,eyeOpenFor(P.eyeLOpen), P.eyeSmileL ?? P.eyeSmile, P.gazeX * ball * 0.85, -P.gazeY * ball * 0.6,@@ -232,6 +233,8 @@ export async function createMeshAvatarImpl(canvas, options) {stopLipSync() { motion.stopLipSync(); },getLipSyncState() { return motion.getLipSyncState(); },setAutoIdle(on) { motion.autoIdle = !!on; },+ setLighting(value) { R.setLighting(value); },+ getLightingStats() { return { ...R.lightingStats }; },setAutoMotion(on) { motion.autoMotion = !!on; },/** Hair / tassel sway multiplier (1 = default). */setSwayGain(g) { physics.gain = g; },diff --git a/src/engine/index.ts b/src/engine/index.tsindex c40956f..0db242c 100644--- a/src/engine/index.ts+++ b/src/engine/index.ts@@ -1,3 +1,4 @@+import type { LightingSettings } from '../lighting/settings';import type { Rig } from '../rig/types';import { parseRig } from '../rig/validate';import { createMeshAvatarImpl } from './createMeshAvatar.js';@@ -14,6 +15,8 @@ export interface MeshAvatarOptions {}export interface MeshAvatar {readonly motions: { id: string; label: string; idle: boolean }[];+ setLighting(settings: Partial<LightingSettings>): void;+ getLightingStats(): { normalMs: number; computedLayers: number; cachedLayers: number };setParameters(parameters: Record<string, number>, weight?: number): void;getParameters(): Record<string, number>;setVoiceLevel(value: number): void;diff --git a/src/engine/renderer.js b/src/engine/renderer.jsindex 1343c9c..445ac4d 100644--- a/src/engine/renderer.js+++ b/src/engine/renderer.js@@ -1,6 +1,11 @@+import { layerNormals } from '../lighting/normals';+import { DEFAULT_LIGHTING, parseLighting } from '../lighting/settings';+import { WRAP, DARKEN, BRIGHTEN, headRotation } from '../lighting/shading';+import { DropShadow } from '../lighting/shadow';+/** @param {ReturnType<import('./rig.js').createRig>} engine* @param {import('../rig/types').Rig} rig */-export function createRenderer(engine, _rig) {+export function createRenderer(engine, rig) {const { IMG, EYES, MOUTH, CHEEKS } = engine;// WebGL2 renderer: textured grid meshes whose vertices are deformed on the CPU,// plus a fragment-shader pass for eyelids, eye balls, mouth and blush on the base layer.@@ -122,6 +127,29 @@ export function createRenderer(engine, _rig) {outColor = c * uAlpha;}`;+ // Compile only when lighting is first enabled. The original off program is untouched.+ const LIGHT_VS = VS.replace('out vec2 vUv;', 'in float aHeadWeight; out float vHeadWeight; out vec2 vScreen; out vec2 vUv;')+ .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;`)+ .replace('outColor = c * uAlpha;', `+ vec3 n = normalize(texture(uNormal, vUv).rgb * 2.0 - 1.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);+ 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 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);+ outColor = c * uAlpha;`);+const LINE_VS = `#version 300 esin vec2 aPos; uniform vec2 uScale; uniform vec2 uOffset;void main() { gl_Position = vec4(aPos * uScale + uOffset, 0.0, 1.0); gl_PointSize = 7.0; }`;@@ -137,6 +165,7 @@ export function createRenderer(engine, _rig) {gl.attachShader(prog, sh);gl.deleteShader(sh);}+ gl.bindAttribLocation(prog, 0, 'aPos'); gl.bindAttribLocation(prog, 1, 'aUv'); gl.bindAttribLocation(prog, 2, 'aHeadWeight');gl.linkProgram(prog);if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(prog));const u = {};@@ -207,6 +236,8 @@ export function createRenderer(engine, _rig) {this.main = compile(gl, VS, FS);this.line = compile(gl, LINE_VS, LINE_FS);this.layers = [];+ this.lighting = DEFAULT_LIGHTING;+ this.lightingStats = { normalMs: 0, computedLayers: 0, cachedLayers: 0 };gl.enable(gl.BLEND);gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);}@@ -247,7 +278,7 @@ export function createRenderer(engine, _rig) {const lineBuf = gl.createBuffer();gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, lineBuf);gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, mesh.lines, gl.STATIC_DRAW);- const layer = { name, mesh, tex: this.texture(img), vao, posBuf, uvBuf, triBuf, lineBuf, visible: true, face: !!opts.face, eyeBall: opts.eyeBall, color: opts.color || [1, 1, 1, 1] };+ const layer = { name, image: img, mesh, tex: this.texture(img), vao, posBuf, uvBuf, triBuf, lineBuf, visible: true, face: !!opts.face, eyeBall: opts.eyeBall, color: opts.color || [1, 1, 1, 1] };this.layers.push(layer);return layer;}@@ -256,14 +287,47 @@ export function createRenderer(engine, _rig) {const gl = this.gl;for (const layer of this.layers) {gl.deleteTexture(layer.tex);+ if (layer.normal) gl.deleteTexture(layer.normal);+ if (layer.headBuf) gl.deleteBuffer(layer.headBuf);gl.deleteVertexArray(layer.vao);for (const buffer of [layer.posBuf, layer.uvBuf, layer.triBuf, layer.lineBuf]) gl.deleteBuffer(buffer);}gl.deleteProgram(this.main.prog);gl.deleteProgram(this.line.prog);+ if (this.lit) gl.deleteProgram(this.lit.prog);+ this.shadow?.destroy();this.layers.length = 0;}+ setLighting(value) {+ this.lighting = parseLighting({ ...DEFAULT_LIGHTING, ...value }) ?? DEFAULT_LIGHTING;+ if (!this.lighting.enabled) return;+ const gl = this.gl;+ if (!this.lit) this.lit = compile(gl, LIGHT_VS, LIGHT_FS);+ for (const layer of this.layers) {+ if (layer.normal || layer.overlay) continue;+ const data = layerNormals(layer.image, layer.mesh.rect, rig, !/^(eye|mouth)/.test(layer.name));+ this.lightingStats.normalMs += data.ms;+ this.lightingStats[data.computed ? 'computedLayers' : 'cachedLayers']++;+ layer.normal = gl.createTexture();+ gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, layer.normal);+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, data.width, data.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data.data);+ gl.generateMipmap(gl.TEXTURE_2D);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);+ const weights = new Float32Array(layer.mesh.rest.length / 2);+ for (let i = 0; i < weights.length; i++) weights[i] = engine.headWeight(layer.mesh.rest[i * 2], layer.mesh.rest[i * 2 + 1]);+ layer.headBuf = gl.createBuffer(); gl.bindVertexArray(layer.vao);+ gl.bindBuffer(gl.ARRAY_BUFFER, layer.headBuf); gl.bufferData(gl.ARRAY_BUFFER, weights, gl.STATIC_DRAW);+ gl.enableVertexAttribArray(2); gl.vertexAttribPointer(2, 1, gl.FLOAT, false, 0, 0);+ }+ gl.bindVertexArray(null);+ if (this.lighting.shadow && !this.shadow) this.shadow = new DropShadow(gl, compile);+ }+resize() {const c = this.canvas, dpr = Math.min(window.devicePixelRatio || 1, 2);const w = Math.round(c.clientWidth * dpr), h = Math.round(c.clientHeight * dpr);@@ -282,8 +346,21 @@ export function createRenderer(engine, _rig) {gl.viewport(0, 0, this.canvas.width, this.canvas.height);gl.clearColor(0, 0, 0, 0);gl.clear(gl.COLOR_BUFFER_BIT);- const m = this.main;+ const lit = this.lighting.enabled, shadow = lit && this.lighting.shadow;+ if (shadow) this.shadow.begin(this.canvas.width, this.canvas.height);+ const m = lit ? this.lit : this.main;+ this.current = m;gl.useProgram(m.prog);+ if (lit) {+ const light = this.lighting;+ 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.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));+ }gl.uniform2fv(m.u.uScale, this.scale); gl.uniform2fv(m.u.uOffset, this.offset);gl.uniform1i(m.u.uTex, 0);gl.uniform4fv(m.u.uEyeBox, EYES.flatMap(e => [e.x0, e.x1, 0, 0]));@@ -302,6 +379,8 @@ export function createRenderer(engine, _rig) {}if (this.original && state.originalAlpha > 0) this.drawLayer(this.original, state.originalAlpha);+ if (shadow) this.shadow.composite(this.lighting);+if (state.showMesh) {const l = this.line;gl.useProgram(l.prog);@@ -320,11 +399,12 @@ export function createRenderer(engine, _rig) {}drawLayer(L, alpha) {- const gl = this.gl, m = this.main;+ const gl = this.gl, m = this.current;gl.useProgram(m.prog);gl.bindVertexArray(L.vao);gl.bindBuffer(gl.ARRAY_BUFFER, L.posBuf);gl.bufferSubData(gl.ARRAY_BUFFER, 0, L.mesh.pos);+ if (this.lighting.enabled) { gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, L.normal); gl.activeTexture(gl.TEXTURE0); }gl.bindTexture(gl.TEXTURE_2D, L.tex);gl.uniform4fv(m.u.uRect, L.mesh.rect);gl.uniform1i(m.u.uFace, L.eyeBall !== undefined ? 2 + L.eyeBall : L.face ? 1 : 0);diff --git a/src/lighting/Controls.tsx b/src/lighting/Controls.tsxnew file mode 100644index 0000000..d40e8ad--- /dev/null+++ b/src/lighting/Controls.tsx@@ -0,0 +1,52 @@+import { useLayoutEffect, useRef, useState, type KeyboardEvent, type PointerEvent } from 'react';+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: '在预览上拖动光源,也可使用方向键移动。' },+};+type Props = { value: LightingSettings; onChange: (value: LightingSettings) => void; language: keyof typeof lightingText };+export function LightingControls({ value, onChange, language }: Props) {+ const t = lightingText[language];+ 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>)}+ <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>{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>+ <button type="button" onClick={() => onChange({ ...DEFAULT_LIGHTING })}>{t.reset}</button><p className="lighting-hint">{t.hint}</p>+ </div>;+}+export function LightHandle({ value, onChange, language }: Props) {+ const handle = useRef<HTMLButtonElement>(null);+ const [area, setArea] = useState<{ left: number; top: number; width: number; height: number } | null>(null);+ useLayoutEffect(() => {+ const canvas = handle.current?.parentElement?.querySelector('canvas');+ if (!canvas) return;+ const update = () => setArea({ left: canvas.offsetLeft, top: canvas.offsetTop, width: canvas.clientWidth, height: canvas.clientHeight });+ const observer = new ResizeObserver(update); observer.observe(canvas); observer.observe(canvas.parentElement!); update();+ return () => observer.disconnect();+ }, []);+ const position = (e: PointerEvent<HTMLButtonElement>) => {+ const bounds = e.currentTarget.parentElement!.querySelector('canvas')!.getBoundingClientRect();+ onChange({ ...value, x: Math.max(0, Math.min(1, (e.clientX - bounds.left) / bounds.width)), y: Math.max(0, Math.min(1, (e.clientY - bounds.top) / bounds.height)) });+ };+ const move = (e: KeyboardEvent) => {+ const step = e.shiftKey ? 0.1 : 0.02;+ const offsets: Record<string, [number, number]> = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] };+ if (!offsets[e.key]) return;+ e.preventDefault();+ onChange({ ...value, x: Math.max(0, Math.min(1, value.x + offsets[e.key][0])), y: Math.max(0, Math.min(1, value.y + offsets[e.key][1])) });+ };+ return <button ref={handle} type="button" className="light-handle" aria-label={lightingText[language].handle} title={lightingText[language].hint}+ disabled={!value.enabled} style={{ left: area ? area.left + value.x * area.width : `${value.x * 100}%`, top: area ? area.top + value.y * area.height : `${value.y * 100}%` }}+ onPointerDown={e => { e.currentTarget.setPointerCapture(e.pointerId); position(e); }}+ onPointerMove={e => { if (e.currentTarget.hasPointerCapture(e.pointerId)) position(e); }}+ onPointerUp={e => { if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId); }} onKeyDown={move}>☀</button>;+}diff --git a/src/lighting/lighting.css b/src/lighting/lighting.cssnew file mode 100644index 0000000..94e545d--- /dev/null+++ b/src/lighting/lighting.css@@ -0,0 +1,18 @@+.lighting-preview { position: relative; }+.lighting-preview > canvas { display: block; }+.light-handle { position: absolute; z-index: 2; transform: translate(-50%, -50%); border: 2px solid #a66109; border-radius: 50%; width: 32px; height: 32px; padding: 0; background: #fff4cc; color: #805000; box-shadow: 0 1px 5px #0004; font-size: 22px; line-height: 26px; cursor: grab; touch-action: none; }+.light-handle:active { cursor: grabbing; }+.light-handle:disabled { opacity: .5; cursor: default; }+.lighting-controls { padding: 12px; font-size: 12px; }+.lighting-controls fieldset { border: 0; padding: 0; margin: 10px 0; min-width: 0; }+.lighting-controls fieldset:disabled { opacity: .55; }+.lighting-controls label { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin: 8px 0; }+.lighting-controls .lighting-check { flex-direction: row; justify-content: flex-start; }+.lighting-controls .lighting-slider { display: grid; grid-template-columns: 100px minmax(60px, 1fr) 34px; gap: 6px; }+.lighting-controls input[type="range"] { width: 100%; min-width: 0; }+.lighting-controls input[type="checkbox"] { margin: 0; width: auto; }+.lighting-controls input[type="color"] { width: 58px; height: 28px; padding: 1px; }+.lighting-controls select { max-width: 60%; }+.lighting-hint { margin: 10px 0 0; color: #546a87; line-height: 1.5; }+.live-controls .lighting-controls { padding: 0; }+.live-preview.lighting-preview { overflow: visible; }diff --git a/src/lighting/normals.ts b/src/lighting/normals.tsnew file mode 100644index 0000000..f305709--- /dev/null+++ b/src/lighting/normals.ts@@ -0,0 +1,70 @@+import type { Ellipse, Rig } from '../rig/types';++// Two-pass chamfer distance. Full-image borders may cut through the artwork;+// do not curl those crop edges as if they were part of the visible silhouette.+export function silhouetteDistance(alpha: Uint8Array, width: number, height: number, cropped = false) {+ const boundary = cropped ? Math.max(width, height) * 2 : 1;+ const d = new Float32Array(alpha.length), diagonal = Math.SQRT2;+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {+ const i = y * width + x;+ if (alpha[i] <= 3) continue;+ d[i] = Math.min(x ? d[i - 1] + 1 : boundary, y ? d[i - width] + 1 : boundary,+ x && y ? d[i - width - 1] + diagonal : boundary, y && x + 1 < width ? d[i - width + 1] + diagonal : boundary);+ // The upper-right pixel is already on the previous row; all distances there are final for this pass.+ }+ for (let y = height - 1; y >= 0; y--) for (let x = width - 1; x >= 0; x--) {+ const i = y * width + x;+ if (!alpha[i] || alpha[i] <= 3) continue;+ d[i] = Math.min(d[i], x + 1 < width ? d[i + 1] + 1 : boundary, y + 1 < height ? d[i + width] + 1 : boundary,+ x && y + 1 < height ? d[i + width - 1] + diagonal : boundary,+ x + 1 < width && y + 1 < height ? d[i + width + 1] + diagonal : boundary);+ }+ return d;+}+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);+ 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) {+ 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);+ const depth = Math.min(rect[2], rect[3]) * 0.08;+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {+ const i = y * width + x;+ 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);+ }+ 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;+ 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;+ }+ return normals;+}+// CPU data survives preview renderer rebuilds; weak image keys release closed projects.+const cache = new WeakMap<HTMLImageElement, { key: string; data: Uint8Array; width: number; height: number }>();+export function layerNormals(image: HTMLImageElement, rect: number[], rig: Rig, inflate: boolean) {+ const key = JSON.stringify([rect, rig.head, rig.body.chest, rig.face.nose, rig.cheeks, inflate]);+ const cached = cache.get(image);+ if (cached?.key === key) return { ...cached, computed: false, ms: 0 };+ const start = performance.now(), scale = Math.min(1, 512 / Math.max(image.width, image.height));+ const width = Math.max(1, Math.round(image.width * scale)), height = Math.max(1, Math.round(image.height * scale));+ const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height;+ 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 };+ cache.set(image, result);+ return { ...result, computed: true, ms: performance.now() - start };+}diff --git a/src/lighting/protocol.ts b/src/lighting/protocol.tsnew file mode 100644index 0000000..0959195--- /dev/null+++ b/src/lighting/protocol.ts@@ -0,0 +1,18 @@+import { parseLighting, type LightingSettings } from './settings';+export const LIGHTING_EVENT = 'studio:lighting';+export interface LightingMessage { project: string; lighting: Omit<LightingSettings, 'enabled' | 'shadow'> & { enabled: 0 | 1; shadow: 0 | 1 } }+export function lightingMessage(input: unknown): LightingMessage | null {+ if (!input || typeof input !== 'object' || Array.isArray(input)) return null;+ const data = input as Record<string, unknown>;+ if (Object.keys(data).length !== 2 || typeof data.project !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(data.project) || !data.lighting || typeof data.lighting !== 'object') return null;+ const value = data.lighting as Record<string, unknown>;+ if (![0, 1].includes(value.enabled as number) || ![0, 1].includes(value.shadow as number)) return null;+ const parsed = parseLighting({ ...value, enabled: value.enabled === 1, shadow: value.shadow === 1 });+ return parsed ? { project: data.project, lighting: { ...parsed, enabled: parsed.enabled ? 1 : 0, shadow: parsed.shadow ? 1 : 0 } } : null;+}+export function lightingWire(project: string, value: LightingSettings): LightingMessage {+ return { project, lighting: { ...value, enabled: value.enabled ? 1 : 0, shadow: value.shadow ? 1 : 0 } };+}+export function lightingValue(message: LightingMessage): LightingSettings {+ return { ...message.lighting, enabled: message.lighting.enabled === 1, shadow: message.lighting.shadow === 1 };+}diff --git a/src/lighting/settings.ts b/src/lighting/settings.tsnew file mode 100644index 0000000..cf1f484--- /dev/null+++ b/src/lighting/settings.ts@@ -0,0 +1,47 @@+export interface LightingSettings {+ enabled: boolean; x: number; y: number; z: number; color: number;+ strength: number; intensity: number; ambient: number; mode: 'soft' | 'cel'; shadow: boolean;+}+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,+});+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;+// 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;+ const data = input as Record<string, unknown>;+ if (Object.keys(data).length !== Object.keys(DEFAULT_LIGHTING).length || Object.keys(data).some(k => !(k in DEFAULT_LIGHTING))) return null;+ if (![true, false].includes(data.enabled as boolean) || ![true, false].includes(data.shadow as boolean) || !['soft', 'cel'].includes(data.mode as string)) return 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;+ 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' })) {+ 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);+ 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));+}+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 }; }+ catch { return { ...DEFAULT_LIGHTING }; }+}+export function saveLighting(project: string, value: LightingSettings) {+ try { localStorage.setItem(`mesh-avatar:lighting:${project}`, JSON.stringify(value)); } catch { /* Storage is optional. */ }+}diff --git a/src/lighting/shading.ts b/src/lighting/shading.tsnew file mode 100644index 0000000..7875068--- /dev/null+++ b/src/lighting/shading.ts@@ -0,0 +1,17 @@+// 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));+}+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;+ const cy = Math.cos(yaw), sy = Math.sin(yaw), cp = Math.cos(pitch), sp = Math.sin(pitch), cr = Math.cos(roll), sr = Math.sin(roll);+ // Column-major Rz * Ry * Rx, in image coordinates (y points down).+ return [cr * cy, sr * cy, -sy, cr * sy * sp - sr * cp, sr * sy * sp + cr * cp, cy * sp,+ cr * sy * cp + sr * sp, sr * sy * cp - cr * sp, cy * cp];+}diff --git a/src/lighting/shadow.js b/src/lighting/shadow.jsnew file mode 100644index 0000000..06bd3a8--- /dev/null+++ b/src/lighting/shadow.js@@ -0,0 +1,64 @@+import { shadowOffset } from './shading';++// Render the avatar once into a transparent target. Two separable blur passes operate+// only on its alpha; the original premultiplied color is then composited over the shadow.+export class DropShadow {+ constructor(gl, compile) {+ this.gl = gl;+ this.program = compile(gl, `#version 300 es+ out vec2 vUv;+ void main() { vec2 p = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2)); vUv = p; gl_Position = vec4(p * 2.0 - 1.0, 0, 1); }`, `#version 300 es+ precision highp float; in vec2 vUv; out vec4 o;+ uniform sampler2D uTex; uniform vec2 uStep; uniform vec2 uShift; uniform int uPass;+ float alphaAt(vec2 p) { if (any(lessThan(p, vec2(0))) || any(greaterThan(p, vec2(1)))) return 0.0; return texture(uTex, p).a; }+ void main() {+ if (uPass == 2) { o = texture(uTex, vUv); return; }+ vec2 p = vUv - uShift;+ float a = alphaAt(p) * 0.227027;+ a += (alphaAt(p + uStep * 1.384615) + alphaAt(p - uStep * 1.384615)) * 0.316216;+ a += (alphaAt(p + uStep * 3.230769) + alphaAt(p - uStep * 3.230769)) * 0.070270;+ o = uPass == 0 ? vec4(0, 0, 0, a) : vec4(vec3(0.035, 0.045, 0.065) * a * 0.28, a * 0.28);+ }`);+ this.vao = gl.createVertexArray(); this.targets = [];+ }+ target(w, h) {+ const gl = this.gl, texture = gl.createTexture(), framebuffer = gl.createFramebuffer();+ gl.bindTexture(gl.TEXTURE_2D, texture);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);+ gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);+ if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) throw new Error('Shadow framebuffer unavailable');+ return { texture, framebuffer };+ }+ begin(w, h) {+ const gl = this.gl;+ if (this.width !== w || this.height !== h) {+ this.clearTargets(); this.width = w; this.height = h;+ this.targets = [this.target(w, h), this.target(Math.ceil(w / 2), Math.ceil(h / 2))];+ }+ gl.bindFramebuffer(gl.FRAMEBUFFER, this.targets[0].framebuffer);+ gl.viewport(0, 0, w, h); gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT);+ }+ composite(light) {+ const gl = this.gl, { prog, u } = this.program, w = this.width, h = this.height;+ gl.useProgram(prog); gl.bindVertexArray(this.vao); gl.activeTexture(gl.TEXTURE0); gl.uniform1i(u.uTex, 0);+ gl.disable(gl.BLEND);+ gl.bindFramebuffer(gl.FRAMEBUFFER, this.targets[1].framebuffer); gl.viewport(0, 0, Math.ceil(w / 2), Math.ceil(h / 2));+ gl.bindTexture(gl.TEXTURE_2D, this.targets[0].texture);+ gl.uniform1i(u.uPass, 0); gl.uniform2f(u.uShift, 0, 0); gl.uniform2f(u.uStep, 3 / w, 0); gl.drawArrays(gl.TRIANGLES, 0, 3);+ gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.viewport(0, 0, w, h);+ gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT); gl.enable(gl.BLEND);+ gl.bindTexture(gl.TEXTURE_2D, this.targets[1].texture);+ const offset = shadowOffset(light.x, light.y);+ gl.uniform1i(u.uPass, 1); gl.uniform2f(u.uShift, offset[0], -offset[1]); gl.uniform2f(u.uStep, 0, 3 / h); gl.drawArrays(gl.TRIANGLES, 0, 3);+ gl.bindTexture(gl.TEXTURE_2D, this.targets[0].texture);+ gl.uniform1i(u.uPass, 2); gl.drawArrays(gl.TRIANGLES, 0, 3);+ gl.bindVertexArray(null);+ }+ clearTargets() { for (const t of this.targets) { this.gl.deleteTexture(t.texture); this.gl.deleteFramebuffer(t.framebuffer); } this.targets = []; }+ destroy() { this.clearTargets(); this.gl.deleteProgram(this.program.prog); this.gl.deleteVertexArray(this.vao); }+}diff --git a/src/live/LiveApp.tsx b/src/live/LiveApp.tsxindex 789960a..518ab85 100644--- a/src/live/LiveApp.tsx+++ b/src/live/LiveApp.tsx@@ -1,3 +1,6 @@+import { LightingControls, LightHandle, lightingText } from '../lighting/Controls';+import { loadLighting, saveLighting } from '../lighting/settings';+import type { MeshAvatar } from '../engine';import { useEffect, useRef, useState } from 'react';import { useI18n } from '../editor/i18n';import { createAvatarView } from './avatar-view';@@ -5,11 +8,11 @@ import { viewSettings, streamUrl, backgroundColor } from './settings';import { FacePose, type TrackingOptions } from './tracking';import { CameraCapture, MicrophoneCapture, type CameraState, type MicState, type BackgroundTracking } from './media';import { liveText } from './i18n';-import { createLiveSender } from './relay';+import { createLiveSender, sendLighting } from './relay';export function LiveApp() {const { language, setLanguage } = useI18n(), t = liveText[language];- const [settings, setSettings] = useState(() => viewSettings(location.search));+ const [settings, setSettings] = useState(() => { const view = viewSettings(location.search); return { ...view, lighting: view.lighting ?? loadLighting(view.project) }; });const [options, setOptions] = useState<TrackingOptions>({ mirror: true, sensitivity: 1, smoothing: 0.35 });const [cameraState, setCameraState] = useState<CameraState>('stopped');const [micState, setMicState] = useState<MicState>('micOff');@@ -21,6 +24,8 @@ export function LiveApp() {const [backgroundStatus, setBackgroundStatus] = useState<BackgroundTracking>(null);const canvas = useRef<HTMLCanvasElement>(null), video = useRef<HTMLVideoElement>(null);const camera = useRef<CameraCapture | null>(null), microphone = useRef<MicrophoneCapture | null>(null);+ const avatarRef = useRef<MeshAvatar | null>(null);+ const lightRef = useRef(settings.lighting); lightRef.current = settings.lighting;const pose = useRef(new FacePose());const controls = useRef({ options, gain, micState, cameraState }); controls.current = { options, gain, micState, cameraState };const refreshDevices = () => { void navigator.mediaDevices?.enumerateDevices().then(setDevices).catch(() => undefined); };@@ -52,9 +57,23 @@ export function LiveApp() {avatar.setSpeaking(micOn); avatar.setVoiceLevel(micOn ? microphone.current?.level(control.gain) ?? 0 : 0);}, (avatar, now) => {if (controls.current.cameraState === 'running' || controls.current.micState === 'micOn') send(avatar.getParameters(), now);- }).then(value => { if (cancelled) value.destroy(); else { view = value; setViewState('ready'); } }).catch(() => { if (!cancelled) setViewState('projectError'); });- return () => { cancelled = true; clock.terminate(); view?.destroy(); };+ }).then(value => { if (cancelled) value.destroy(); else { view = value; avatarRef.current = value.avatar; value.avatar.setLighting(lightRef.current); setViewState('ready'); } }).catch(() => { if (!cancelled) setViewState('projectError'); });+ return () => { cancelled = true; clock.terminate(); view?.destroy(); avatarRef.current = null; };}, [settings.project, settings.fit]);+ useEffect(() => {+ saveLighting(settings.project, settings.lighting);+ avatarRef.current?.setLighting(settings.lighting);+ }, [settings.project, settings.lighting]);+ useEffect(() => {+ let sent: typeof settings.lighting | undefined;+ // Throttle continuous drags and deliver the final position even after dragging stops.+ const timer = setInterval(() => {+ if (sent === lightRef.current) return;+ sent = lightRef.current; sendLighting(settings.project, sent);+ }, 34);+ return () => clearInterval(timer);+ }, [settings.project]);+ const changeLighting = (lighting: typeof settings.lighting) => setSettings(current => ({ ...current, lighting }));const cameraActive = cameraState === 'starting' || cameraState === 'running';const micActive = micState === 'micStarting' || micState === 'micOn';const url = streamUrl(settings, location.origin);@@ -63,10 +82,12 @@ export function LiveApp() {<header className="live-header"><div><a href="/">{t.back}</a><h1>Mesh Avatar Studio <span>{t.title}</span></h1></div><div className="live-languages">{(['en', 'ja', 'zh'] as const).map(lang => <button key={lang} aria-pressed={language === lang} onClick={() => setLanguage(lang)}>{({ en: 'English', ja: '日本語', zh: '简体中文' })[lang]}</button>)}</div></header>- <div className="live-layout"><section className="live-view"><div className="live-preview checkerboard" style={{ backgroundColor: settings.background, backgroundImage: settings.background === 'transparent' ? undefined : 'none' }}>+ <div className="live-layout"><section className="live-view"><div className="live-preview checkerboard lighting-preview" style={{ backgroundColor: settings.background, backgroundImage: settings.background === 'transparent' ? undefined : 'none' }}><canvas ref={canvas} data-testid="live-avatar" />+ <LightHandle value={settings.lighting} onChange={changeLighting} language={language} /></div><p role="status" className={viewState === 'projectError' ? 'live-error' : ''}>{t[viewState]} · {settings.project}</p></section><aside className="live-controls">+ <section><h2>{lightingText[language].title}</h2><LightingControls value={settings.lighting} onChange={changeLighting} language={language} /></section><section><h2>{t.camera}</h2><label>{t.device}<select aria-label={t.camera} value={cameraId} disabled={cameraActive} onChange={event => setCameraId(event.target.value)}><option value="">{t.defaultDevice}</option>{devices.filter(device => device.kind === 'videoinput' && device.deviceId).map((device, i) => <option key={device.deviceId} value={device.deviceId}>{device.label || `${t.camera} ${i + 1}`}</option>)}</select></label><div className="live-buttons"><button className="live-primary" disabled={!cameraActive && viewState !== 'ready'} onClick={() => {setCalibrated(false); pose.current.reset();diff --git a/src/live/avatar-view.ts b/src/live/avatar-view.tsindex e4c6420..b67ce29 100644--- a/src/live/avatar-view.ts+++ b/src/live/avatar-view.ts@@ -14,6 +14,7 @@ export async function createAvatarView(canvas: HTMLCanvasElement, settings: Viewif (project?.error || (!project && settings.project !== SAMPLE_PROJECT)) throw new Error('Project unavailable');const loaded = project ? await openLocalProject(project) : { rig: fixture, assets: undefined };const avatar = await createMeshAvatar(canvas, { rig: loaded.rig!, assets: loaded.assets, manual: true, fit: settings.fit, preserveMouthForm: true });+ if (settings.lighting) avatar.setLighting(settings.lighting);avatar.setAutoIdle(settings.idle); avatar.setAutoMotion(settings.idle);if (!settings.idle) avatar.setParameters(neutralParameters);canvas.dataset.state = 'ready';diff --git a/src/live/relay.ts b/src/live/relay.tsindex c7e8bcc..b3a2fb0 100644--- a/src/live/relay.ts+++ b/src/live/relay.ts@@ -1,3 +1,5 @@+import { LIGHTING_EVENT, lightingWire, lightingMessage, lightingValue } from '../lighting/protocol';+import type { LightingSettings } from '../lighting/settings';import { LIVE_EVENT, liveMessage } from './protocol';export function createLiveSender(project: string) {@@ -12,3 +14,13 @@ export function receiveLiveParameters(callback: (data: unknown) => void) {import.meta.hot?.on(LIVE_EVENT, callback);return () => import.meta.hot?.off(LIVE_EVENT, callback);}++export function sendLighting(project: string, value: LightingSettings) {+ const message = lightingMessage(lightingWire(project, value));+ if (message) import.meta.hot?.send(LIGHTING_EVENT, message);+}+export function receiveLighting(project: string, callback: (value: LightingSettings) => void) {+ const receive = (data: unknown) => { const message = lightingMessage(data); if (message?.project === project) callback(lightingValue(message)); };+ import.meta.hot?.on(LIGHTING_EVENT, receive);+ return () => import.meta.hot?.off(LIGHTING_EVENT, receive);+}diff --git a/src/live/settings.ts b/src/live/settings.tsindex 2e3707a..b09d7c2 100644--- a/src/live/settings.ts+++ b/src/live/settings.ts@@ -1,9 +1,11 @@+import { lightingFromQuery, writeLightingQuery, type LightingSettings } from '../lighting/settings';export const SAMPLE_PROJECT = 'sample-miko-qipao';export interface ViewSettings {project: string;background: string;fit: 'contain' | 'cover';idle: boolean;+ lighting?: LightingSettings;}export function backgroundColor(value: string | null): string {if (value === 'green') return '#00ff00';@@ -14,10 +16,11 @@ export function backgroundColor(value: string | null): string {export function viewSettings(search: string): ViewSettings {const query = new URLSearchParams(search), project = query.get('project');return { project: project && /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(project) ? project : SAMPLE_PROJECT,- background: backgroundColor(query.get('bg')), fit: query.get('fit') === 'cover' ? 'cover' : 'contain', idle: query.get('idle') !== '0' };+ background: backgroundColor(query.get('bg')), fit: query.get('fit') === 'cover' ? 'cover' : 'contain', idle: query.get('idle') !== '0', ...(query.has('light') ? { lighting: lightingFromQuery(query) } : {}) };}export function streamUrl(settings: ViewSettings, origin: string): string {const url = new URL('/stream.html', origin);url.search = new URLSearchParams({ project: settings.project, bg: settings.background, fit: settings.fit, idle: settings.idle ? '1' : '0' }).toString();+ if (settings.lighting) writeLightingQuery(url.searchParams, settings.lighting);return url.href;}diff --git a/src/live/stream.ts b/src/live/stream.tsindex aa8c3fa..59ea361 100644--- a/src/live/stream.ts+++ b/src/live/stream.ts@@ -1,13 +1,15 @@import { createAvatarView, neutralParameters } from './avatar-view';import { viewSettings } from './settings';import { LivePose } from './protocol';-import { receiveLiveParameters } from './relay';+import { receiveLighting, receiveLiveParameters } from './relay';import './stream.css';const settings = viewSettings(location.search);document.documentElement.style.background = settings.background;const canvas = document.querySelector<HTMLCanvasElement>('#avatar')!;const pose = new LivePose(settings.project);+let avatarInstance: import('../engine').MeshAvatar | undefined;+const unsubscribeLighting = receiveLighting(settings.project, value => { settings.lighting = value; avatarInstance?.setLighting(value); });const unsubscribe = receiveLiveParameters(data => pose.receive(data, performance.now()));void createAvatarView(canvas, settings, (avatar, now, dt) => {const sampled = pose.sample(now, dt);@@ -20,7 +22,9 @@ void createAvatarView(canvas, settings, (avatar, now, dt) => {avatar.setParameters(params);}}).then(view => {- const destroy = () => { unsubscribe(); view.destroy(); };+ avatarInstance = view.avatar;+ if (settings.lighting) view.avatar.setLighting(settings.lighting);+ const destroy = () => { unsubscribe(); unsubscribeLighting(); avatarInstance = undefined; view.destroy(); };window.addEventListener('pagehide', destroy, { once: true });import.meta.hot?.dispose(destroy);-}).catch(() => { unsubscribe(); canvas.dataset.state = 'error'; });+}).catch(() => { unsubscribe(); unsubscribeLighting(); canvas.dataset.state = 'error'; });diff --git a/src/server/live-relay.ts b/src/server/live-relay.tsindex 91bbab7..502f90f 100644--- a/src/server/live-relay.ts+++ b/src/server/live-relay.ts@@ -1,3 +1,4 @@+import { LIGHTING_EVENT, lightingMessage } from '../lighting/protocol';import type { Plugin, WebSocketClient } from 'vite';import { LIVE_EVENT, liveMessage } from '../live/protocol';@@ -5,6 +6,13 @@ export function liveRelay(): Plugin {return {name: 'local-live-relay',configureServer(server) {+ const lastLighting = new WeakMap<WebSocketClient['socket'], number>();+ server.ws.on(LIGHTING_EVENT, (data, client) => {+ const message = lightingMessage(data), now = performance.now();+ if (!message || now - (lastLighting.get(client.socket) ?? -Infinity) < 1000 / 60) return;+ lastLighting.set(client.socket, now);+ server.ws.send(LIGHTING_EVENT, message);+ });const lastSent = new WeakMap<WebSocketClient['socket'], number>();server.ws.on(LIVE_EVENT, (data, client) => {const now = performance.now();diff --git a/tests/lighting.test.ts b/tests/lighting.test.tsnew file mode 100644index 0000000..73078bd--- /dev/null+++ b/tests/lighting.test.ts@@ -0,0 +1,62 @@+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 { lightingMessage, lightingValue, lightingWire } from '../src/lighting/protocol';+import { viewSettings, streamUrl } from '../src/live/settings';++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);+ 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);+});+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);+ }+});+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);+ expect(shadowOffset(0, 0)).toEqual([0.06, 0.06]); expect(shadowOffset(1, 1)).toEqual([-0.06, -0.06]);+});+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);+ const roll = headRotation(0, 0, 30, 0.3);+ 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 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);+ expect(lightingFromQuery(new URLSearchParams('light=true&lx=999&ly=NaN&lz=&lc=javascript&ls=-2&lm=unknown'))).toEqual({ ...DEFAULT_LIGHTING, x: 1, strength: 0 });+});+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' }]) {+ 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();+ expect(parseLighting({ ...DEFAULT_LIGHTING, x: NaN })).toBeNull();+});++test('cropped opaque borders do not bend toward an artificial outside silhouette', () => {+ const size = 25, alpha = new Uint8Array(size * size);+ for (let y = 0; y < size; y++) for (let x = 5; x < 20; x++) alpha[y * size + x] = 255;+ const distance = silhouetteDistance(alpha, size, size, true);+ expect(distance[12]).toBe(distance[12 * size + 12]);+ expect(distance[24 * size + 12]).toBe(distance[12 * size + 12]);+});