3D engine that AI agents drive
Add local point lights and authored lighting controls
Nguyen Xuan An7988ea049344
diff --git a/README.md b/README.mdindex 733000bb..14307c86 100644--- a/README.md+++ b/README.md@@ -156,6 +156,7 @@ renderer.render({ eye: [4, 3, 7], target: [0, 1.5, 0], assemblyAmount: 0.5 });The core exports animation helpers, camera views and effect presets. `renderer.updateParts(parts)` uploads changes without replacing geometry buffers.The current source adds [camera paths](docs/camera-path.md) with cubic moves, target tracking, roll and focal-length conversion.+It also adds [local lighting](docs/lighting.md) with eight point lights and separate key, fill and ambient controls. These controls remain source-only until the next package release.These camera helpers are not included in the published `0.3.3` package yet.The current source also adds [GPU skinning](docs/skinning.md) and skeletal GLB import, with four influences per vertex.The optional [physics addon](docs/physics.md) records Rapier contacts and articulated joints into a timeline for repeatable film seeks.diff --git a/docs/capability-audit.md b/docs/capability-audit.mdindex 1b29f494..20398b83 100644--- a/docs/capability-audit.md+++ b/docs/capability-audit.md@@ -26,7 +26,7 @@ The Blender references describe authoring capabilities. Their interpolation and| Film authoring | Scene-specific shot list and player | Shared timeline, shot editing, transitions, audio cues | Edited timeline seeks and exports deterministically || Asset import | Opaque glTF meshes, five material maps, rigid and skeletal animation integrated in source | Morphs, transparency, compression, streaming, package release | Blender fixtures preserve geometry, materials, and animation || Materials | Factors and five PBR texture channels integrated in source | Layered materials, advanced extensions, authored tangents, package verification | Reference material scenes and texture budget checks |-| Lighting | Directional shadows and procedural studio illumination | Configurable lights, HDR environments, baked lighting, reflection probes | Reference lighting scenes, stable shadows, and measured render cost |+| Lighting | Directional shadows, configurable key/fill/ambient strength and eight local point lights integrated in source | Local shadows, spot/area lights, HDR environments, baked lighting, reflection probes; package release | Reference lighting scenes, stable shadows, and measured render cost || Image rendering | HDR, bloom, grading, MSAA, FXAA | Depth of field, motion blur, temporal sampling, render passes | Reviewed stills and moving previews with measured artifacts || Simulation | Recorded Rapier rigid-body contacts, impulses, kinematics and articulated joints integrated in source; demo-specific wind, water, sparks and ignition | Joint limits, motors, worker baking, bone binding, shared particles, cloth, hair and volumetric tools; package release | Repeatable simulations, contact tests, and bounded resource usage || Interaction | Demo-specific orbit, zoom, and sliders | Picking, transform gizmos, reusable controls | Pointer, keyboard, and mobile interaction checks |diff --git a/docs/lighting.md b/docs/lighting.mdnew file mode 100644index 00000000..acf041f9--- /dev/null+++ b/docs/lighting.md@@ -0,0 +1,73 @@+# Local lighting++These controls exist in the source checkout and next library build. Published version `0.3.3` does not include them yet.++`Renderer67` accepts lighting in its existing `environment` option. `frame.environment` overrides selected fields for each frame. Lights use world-space positions and linear RGB colors. Use meters consistently when authoring a physically scaled scene.++```js+const renderer = new Renderer67(canvas, parts, {+ ground: false,+ world: true,+ hdr: true,+ environment: {+ lightDirection: [-0.8, 0.5, 0.3],+ keyIntensity: 0.7,+ fillIntensity: 0.35,+ ambientIntensity: 0.45,+ pointLights: [{+ position: [0, 3.34, -1],+ color: [1, 0.71, 0.43],+ intensity: 18,+ radius: 0.08,+ range: 9,+ }],+ },+});++renderer.render({ eye: [0, 2, 5], target: [0, 1, 0], fov: 40 });+```++## Light controls++`keyIntensity` scales the existing shadowed directional light. `keyColor` optionally replaces its linear RGB radiance color. `fillIntensity` scales the two existing fill/rim lights. `ambientIntensity` scales procedural reflection and hemisphere fill. Each intensity defaults to one, preserving previous lighting when no controls are supplied. Set all three to zero to isolate local lights on standard PBR surfaces.++These controls do not disable the sky, emission, fog or special procedural floor/fire/smoke shading. They also scale foliage transmission, water reflection and the directional water glint. Environment reflections remain the existing procedural studio approximation, not a loaded HDR environment.++## Point lights++At most eight lights are supported per frame. Each light supplies `position`. Optional fields default to white `color`, `intensity: 1`, `radius: 0.05` and unlimited `range: 0`.++The light uses inverse-square falloff outside its radius. Doubling distance reduces incoming illumination to one quarter before material response. Intensity follows the candela convention for a point source, but the renderer's existing exposure and environment are not a calibrated photographic pipeline.++Radius limits near-source attenuation to avoid a singularity. It does not create an area emitter or soften shadows. Range zero preserves unlimited falloff. A positive range smoothly fades the light to zero using `(max(1 - (distance / range)^4, 0))^2`. This artistic cutoff changes physical falloff near the range boundary.++Inputs must be finite numbers. Positions are within ±1,000,000 scene units. Colors are within zero and one. Intensity is within zero and 100,000. Radius is between 0.001 and 1,000,000. Range is zero or between 0.001 and 1,000,000.++Key/fill/ambient intensity is between zero and 100. Key color components are between zero and 1,000. Large coordinates still inherit Float32 rendering precision limits.++Lights currently cast no local shadows and can illuminate through opaque walls. The original directional shadow map remains in use. Point-light shadows, spotlights, area lights, indirect bounces and volumetric scattering remain unfinished.++## Animation and resources++Pass the entire point-light list in `frame.environment.pointLights` to replace the constructor list. An empty list removes all local lights. Omitted fields continue using constructor defaults.++```js+renderer.render({+ eye: [0, 2, 5], target: [0, 1, 0], fov: 40,+ environment: {+ pointLights: [{ position: [Math.sin(time), 2, 0], intensity: 4 }],+ },+});+```++Absolute-time animation keeps light movement independent of seek order. Each renderer retains one set of light uniform arrays, containing 75 floats. Light updates add no geometry, texture, framebuffer or draw pass. Shading cost grows with active lights and covered pixels. Excessive brightness clips at the finite half-float HDR target limit of 65,504 before bloom and tone mapping.++Validation runs before light arrays or the framebuffer change. Invalid later lights leave the previous lighting state intact. This guarantee applies to ordinary data objects. Caller-defined getters and proxies are not a supported scene format.++## Design and references++Two shapes were considered: mutable light nodes with independent scene ownership, and serializable lights in the existing environment contract. Environment data was chosen because film samples already provide absolute-time frame overrides. Light hierarchy nodes and editor handles require a later authoring contract.++[Three.js PointLight](https://threejs.org/docs/pages/PointLight.html) documents candela intensity, inverse-square attenuation and a smooth finite cutoff. [Blender light objects](https://docs.blender.org/manual/en/dev/render/lights/light_object.html) distinguish source size and emitted power. 67.js radius currently regularizes attenuation. It does not reproduce Blender's spherical emitter or watt-based power.++Run `node --test tests/lighting.test.js` for retained-state checks and `node scripts/smoke-lighting.mjs` with the development server running for linear HDR pixel checks, native GPU timing and before/after laboratory images.diff --git a/package.json b/package.jsonindex a5fcbc8d..a7e1b8a3 100644--- a/package.json+++ b/package.json@@ -29,7 +29,8 @@"docs/scene-graph.md","docs/camera-path.md","docs/skinning.md",- "docs/physics.md"+ "docs/physics.md",+ "docs/lighting.md"],"main": "./build/67.module.js","module": "./build/67.module.js",diff --git a/scripts/smoke-lighting.mjs b/scripts/smoke-lighting.mjsnew file mode 100644index 00000000..c2e7e2bf--- /dev/null+++ b/scripts/smoke-lighting.mjs@@ -0,0 +1,135 @@+import assert from 'node:assert/strict';+import { readFile, writeFile } from 'node:fs/promises';+import { execFileSync } from 'node:child_process';+import { constants, setPriority } from 'node:os';+import { chromium } from 'playwright';++setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+const browser = await chromium.launch({+ executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe',+ headless: true,+ args: ['--enable-webgl', '--ignore-gpu-blocklist'],+});+const reports = {};+try {+ const page = await browser.newPage({ viewport: { width: 960, height: 540 } });+ await page.route('**/lighting-smoke.html', route => route.fulfill({ contentType: 'text/html', body: '<canvas style="width:960px;height:540px;display:block"></canvas>' }));+ await page.goto('http://127.0.0.1:5173/lighting-smoke.html');+ reports.contract = await page.evaluate(async () => {+ const { Renderer67, box } = await import('/build/67.module.js');+ const canvas = document.querySelector('canvas');+ const part = { geometry: box(), matrix: new Float32Array([4, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0.2, 0, 0, 0, 0, 1]), material: { color: [1, 1, 1], metallic: 0, roughness: 1 } };+ const renderer = new Renderer67(canvas, [part], { ground: false, hdr: true, pixelRatio: 1, samples: 1 });+ const context = renderer.context;+ if (!renderer.hdr) throw new Error('Lighting contract requires a linear HDR target');+ const identity = renderer.lighting.positions;+ const frame = { eye: [0, 0, 5], target: [0, 0, 0], fov: 40, exposure: 1, effects: { grain: 0 }, environment: { keyIntensity: 0, fillIntensity: 0, ambientIntensity: 0 } };+ function sample(light) {+ frame.environment.pointLights = Array.isArray(light) ? light : light ? [light] : [];+ renderer.render(frame);+ context.bindFramebuffer(context.FRAMEBUFFER, renderer.resolveFramebuffer);+ const pixel = new Float32Array(4);+ context.readPixels(canvas.width / 2, canvas.height / 2, 1, 1, context.RGBA, context.FLOAT, pixel);+ context.bindFramebuffer(context.FRAMEBUFFER, null);+ return Array.from(pixel);+ }+ const darkness = sample();+ const near = sample({ position: [0, 0, 1.1], radius: 0.01 });+ const far = sample({ position: [0, 0, 2.1], radius: 0.01 });+ const red = sample({ position: [0, 0, 1.1], color: [1, 0, 0], radius: 0.01 });+ const finalSlot = sample(Array.from({ length: 8 }, (_, index) => ({ position: [0, 0, 1.1], color: [1, 0, 0], radius: 0.01, intensity: index === 7 ? 1 : 0 })));+ const outsideRange = sample({ position: [0, 0, 1.1], range: 0.5 });+ const faded = sample({ position: [0, 0, 1.1], range: 2, radius: 0.01 });+ const repeated = sample({ position: [0, 0, 1.1], radius: 0.01 });+ const behind = sample({ position: [0, 0, -1] });+ const proceduralDarkness = {};+ for (const tag of ['water', 'foliage', 'grass', 'terrain']) {+ part.material.tag = tag;+ renderer.updateParts([part]);+ proceduralDarkness[tag] = sample();+ }+ part.material.tag = 'standard';+ renderer.updateParts([part]);+ const peak = sample({ position: [0, 0, 0.101], intensity: 100000, radius: 0.001 });+ const uniformsBeforeError = Array.from(renderer.lighting.positions);+ let rejected = false;+ try {+ renderer.render({ ...frame, environment: { ...frame.environment, pointLights: [{ position: [0, NaN, 0] }] } });+ } catch {+ rejected = true;+ }+ const report = { darkness, near, far, red, finalSlot, outsideRange, faded, repeated, behind, proceduralDarkness, peak, rejected, uniformsPreserved: uniformsBeforeError.every((value, index) => value === renderer.lighting.positions[index]), retained: identity === renderer.lighting.positions, glError: context.getError(), drawBatches: renderer.batches.length, estimatedBytes: renderer.memoryPlan.estimatedBytes };+ renderer.dispose();+ return report;+ });+ await page.close();+ assert.equal(reports.contract.glError, 0);+ assert.ok(reports.contract.darkness.slice(0, 3).every(value => value === 0));+ assert.ok(Math.abs(reports.contract.near[0] / reports.contract.far[0] - 4) < 0.02, 'Inverse-square falloff must match independently read linear pixels');+ assert.ok(reports.contract.red[0] > 0 && reports.contract.red[1] === 0 && reports.contract.red[2] === 0);+ assert.deepEqual(reports.contract.finalSlot, reports.contract.red, 'The final slot must light surfaces through all eight packed GPU uniform entries');+ assert.ok(reports.contract.outsideRange.slice(0, 3).every(value => value === 0));+ assert.ok(Math.abs(reports.contract.faded[0] / reports.contract.near[0] - (1 - 1 / 16) ** 2) < 0.002);+ assert.ok(reports.contract.behind.slice(0, 3).every(value => value === 0));+ for (const pixel of Object.values(reports.contract.proceduralDarkness)) assert.ok(pixel.slice(0, 3).every(value => value === 0));+ assert.deepEqual(reports.contract.near, reports.contract.repeated);+ assert.ok(reports.contract.peak.every(Number.isFinite), 'Strong lights must not overflow half-float render targets');+ assert.equal(reports.contract.retained, true);+ assert.equal(reports.contract.rejected, true);+ assert.equal(reports.contract.uniformsPreserved, true);++ const variants = {+ before: execFileSync('git', ['show', `${process.argv[2] ?? 'fe6a22b'}:src/shaders.js`], { encoding: 'utf8', windowsHide: true }),+ after: await readFile('src/shaders.js', 'utf8'),+ };+ for (const [name, source] of Object.entries(variants)) {+ const scenePage = await browser.newPage({ viewport: { width: 960, height: 540 } });+ await scenePage.route('**/src/shaders.js*', route => route.fulfill({ contentType: 'application/javascript', body: source }));+ await scenePage.route('**/lighting-smoke.html', route => route.fulfill({ contentType: 'text/html', body: '<canvas style="width:960px;height:540px;display:block"></canvas>' }));+ await scenePage.goto('http://127.0.0.1:5173/lighting-smoke.html');+ reports[name] = await scenePage.evaluate(async () => {+ const { Renderer67 } = await import('/src/renderer.js');+ const { createFilmScenes, sampleFilm } = await import('/src/film.js');+ const scene = createFilmScenes().laboratory;+ scene.animate(36);+ const canvas = document.querySelector('canvas');+ const renderer = new Renderer67(canvas, scene.parts, { ground: false, world: true, environment: scene.environment, shadowBounds: scene.shadowBounds, samples: 4, hdr: true, pixelRatio: 1, memoryBudgetMiB: 384 });+ const frame = { ...sampleFilm(36).camera, effects: { grain: 0 }, time: 36 };+ const context = renderer.context;+ const timer = context.getExtension('EXT_disjoint_timer_query_webgl2');+ if (!timer) throw new Error('GPU timer unavailable');+ const samples = [];+ for (let index = 0; index < 10; index++) renderer.render(frame);+ for (let index = 0; index < 40; index++) {+ const query = context.createQuery();+ context.beginQuery(timer.TIME_ELAPSED_EXT, query);+ renderer.render(frame);+ context.endQuery(timer.TIME_ELAPSED_EXT);+ context.flush();+ const started = performance.now();+ while (!context.getQueryParameter(query, context.QUERY_RESULT_AVAILABLE)) {+ if (performance.now() - started > 2000) throw new Error('GPU query timed out');+ await new Promise(resolve => setTimeout(resolve, 2));+ }+ if (context.getParameter(timer.GPU_DISJOINT_EXT)) throw new Error('Disjoint GPU timer');+ samples.push(context.getQueryParameter(query, context.QUERY_RESULT) / 1e6);+ context.deleteQuery(query);+ }+ const sorted = [...samples].sort((first, second) => first - second);+ renderer.render(frame);+ const report = { medianMilliseconds: (sorted[19] + sorted[20]) / 2, p90Milliseconds: sorted[35], samples, glError: context.getError(), estimatedBytes: renderer.memoryPlan.estimatedBytes, drawBatches: renderer.batches.length, image: canvas.toDataURL('image/png') };+ renderer.dispose();+ return report;+ });+ await writeFile(`artifacts/laboratory-lighting-${name}.png`, Buffer.from(reports[name].image.split(',')[1], 'base64'));+ delete reports[name].image;+ assert.equal(reports[name].glError, 0);+ await scenePage.close();+ }+ assert.equal(reports.before.estimatedBytes, reports.after.estimatedBytes);+ assert.equal(reports.before.drawBatches, reports.after.drawBatches);+ await writeFile('artifacts/lighting-gpu.json', JSON.stringify(reports, null, 2));+ console.log(JSON.stringify(reports, null, 2));+} finally {+ await browser.close();+}diff --git a/scripts/smoke-package.mjs b/scripts/smoke-package.mjsindex 22428972..9fa2b66a 100644--- a/scripts/smoke-package.mjs+++ b/scripts/smoke-package.mjs@@ -40,6 +40,7 @@ import { parseGltf } from '67js/addons/gltf';import { createPhysicsScene, planPhysicsScene } from '67js/addons/physics';assert.equal(VERSION, '${metadata.version}');assert.equal(typeof Renderer67, 'function');+assert.throws(() => new Renderer67({}, [], { environment: { pointLights: Array(9).fill({ position: [0, 1, 0] }) } }), /at most/, 'Packed renderer must validate light limits before requesting a GPU context.');assert.ok(box().positions.length > 0);const parts = createModel();assert.equal(parts.length, 574);diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.mdindex bae605cd..1ea2f629 100644--- a/skills/build-67js-scene/SKILL.md+++ b/skills/build-67js-scene/SKILL.md@@ -17,6 +17,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.- A deterministic film uses `src/film.js` and `src/film-player.js`.- A keyframe scene uses `src/animation.js`, `src/motion.js` and `src/motion-player.js`.- An authored camera uses `src/camera-path.js` and the checkout's `docs/camera-path.md`.+- Local lights use the renderer environment and the checkout's `docs/lighting.md`.- A skeletal asset uses `src/skinning.js`, `src/gltf.js` and the checkout's `docs/skinning.md`.- Recorded contacts or articulated physics use optional `src/physics.js` and the checkout's `docs/physics.md`.- A flat scene or axis view uses `src/canvas2d.js`, `src/camera.js` and `src/view2d.js`.diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.mdindex 0509f3e4..5bce90a8 100644--- a/skills/build-67js-scene/references/scene-contract.md+++ b/skills/build-67js-scene/references/scene-contract.md@@ -52,6 +52,11 @@ Interpolated numeric tags can change by tiny amounts and select the wrong shadinAn outdoor renderer receives `world: true`, `ground: false` and the scene environment.The environment provides `fogColor`, `fogDensity`, `skyTop`, `skyBottom`, `lightDirection` and optional `daylight`.The sky colors are display RGB. Fog colors are linear RGB.+Local `environment.pointLights` support eight world-space sources with inverse-square falloff.+Each light provides `position` and optional `color`, `intensity`, `radius` and `range`.+`keyIntensity`, `fillIntensity` and `ambientIntensity` independently scale existing lighting.+Read the checkout's `docs/lighting.md` for defaults, numeric limits and frame overrides.+Point lights currently cast no local shadows. Radius limits attenuation without creating an area emitter.```jsconst renderer = new Renderer67(canvas, world.parts, {diff --git a/src/film.js b/src/film.jsindex 378ac682..c81b4271 100644--- a/src/film.js+++ b/src/film.js@@ -749,6 +749,12 @@ export function createFilmScenes() {...studio, fogDensity: 0.006, daylight: 0.75,skyTop: [0.12, 0.17, 0.18], skyBottom: [0.22, 0.23, 0.18],lightDirection: [-0.85, 0.5, -0.35],+ keyIntensity: 0.7,+ fillIntensity: 0.35,+ ambientIntensity: 0.45,+ pointLights: [-2.8, 0, 2.8].map(horizontal => ({+ position: [horizontal, 3.34, -1], color: [1, 0.71, 0.43], intensity: 18, range: 9, radius: 0.08,+ })),};const desert = {fogColor: [0.25, 0.20, 0.13], fogDensity: 0.0035,@@ -768,7 +774,7 @@ export function createFilmScenes() {towerParts.push(...towerBuilder.parts);return {apparatus: set(createApparatus(meshes), studio),- office: set(createOffice(meshes), interior, { extent: 7, target: [0, 1.6, -1], eye: [-8, 7, -4], near: 0.1, far: 30 }, 'office'),+ office: set(createOffice(meshes), { ...interior, pointLights: [...interior.pointLights, { position: [-1.45, 1.36, 0.25], color: [1, 0.82, 0.57], intensity: 1.8, range: 3, radius: 0.08 }] }, { extent: 7, target: [0, 1.6, -1], eye: [-8, 7, -4], near: 0.1, far: 30 }, 'office'),laboratory: set(createOffice(meshes, true), interior, { extent: 7, target: [0, 1.6, -1], eye: [-8, 7, -4], near: 0.1, far: 30 }, 'laboratory'),settlement: set(createSettlement(meshes), desert, desertShadows, 'settlement'),portrait: set(createPortrait(meshes), { ...desert, lightDirection: [-0.7, 0.55, 0.8] }, { extent: 6, target: [0, 1, 0], eye: [-8, 5, 6], near: 0.1, far: 35 }, 'portrait'),diff --git a/src/lighting.js b/src/lighting.jsnew file mode 100644index 00000000..6e2814bb--- /dev/null+++ b/src/lighting.js@@ -0,0 +1,66 @@+export const MAX_POINT_LIGHTS = 8;++function numberInRange(value, minimum, maximum, name) {+ if (typeof value !== 'number' || !Number.isFinite(value) || value < minimum || value > maximum) {+ throw new RangeError(`${name} must be between ${minimum} and ${maximum}`);+ }+ return value;+}++function vectorInRange(value, minimum, maximum, name) {+ if (value?.length !== 3) throw new TypeError(`${name} must have three components`);+ for (let axis = 0; axis < 3; axis++) numberInRange(value[axis], minimum, maximum, name);+ return value;+}++export function createLightingState() {+ return {+ positions: new Float32Array(MAX_POINT_LIGHTS * 4),+ colors: new Float32Array(MAX_POINT_LIGHTS * 4),+ radii: new Float32Array(MAX_POINT_LIGHTS),+ keyColor: new Float32Array(3),+ pointCount: 0,+ fillIntensity: 1,+ ambientIntensity: 1,+ };+}++// Preflight before publishing so malformed later lights cannot corrupt retained uniforms.+export function updateLightingState(state, environment, { world = false } = {}) {+ const pointLights = environment.pointLights ?? [];+ if (!Array.isArray(pointLights) || pointLights.length > MAX_POINT_LIGHTS) {+ throw new RangeError(`pointLights must be an array of at most ${MAX_POINT_LIGHTS} lights`);+ }+ const keyIntensity = numberInRange(environment.keyIntensity ?? 1, 0, 100, 'Key intensity');+ const fillIntensity = numberInRange(environment.fillIntensity ?? 1, 0, 100, 'Fill intensity');+ const ambientIntensity = numberInRange(environment.ambientIntensity ?? 1, 0, 100, 'Ambient intensity');+ const daylight = numberInRange(environment.daylight ?? 1, 0, 100, 'Daylight');+ const keyColor = environment.keyColor ?? (world ? [3.7 * daylight, 3.4 * daylight, 2.9 * daylight] : [5.2, 4.7, 4.1]);+ vectorInRange(keyColor, 0, 1000, 'Key color');+ for (const light of pointLights) {+ if (!light || typeof light !== 'object' || Array.isArray(light)) throw new TypeError('Point light must be an object');+ vectorInRange(light.position, -1e6, 1e6, 'Point light position');+ vectorInRange(light.color ?? [1, 1, 1], 0, 1, 'Point light color');+ numberInRange(light.intensity ?? 1, 0, 1e5, 'Point light intensity');+ numberInRange(light.radius ?? 0.05, 0.001, 1e6, 'Point light radius');+ const range = light.range ?? 0;+ numberInRange(range, 0, 1e6, 'Point light range');+ if (range !== 0 && range < 0.001) throw new RangeError('Point light range must be zero or at least 0.001');+ }+ state.positions.fill(0);+ state.colors.fill(0);+ state.radii.fill(0);+ for (let index = 0; index < pointLights.length; index++) {+ const light = pointLights[index];+ state.positions.set(light.position, index * 4);+ state.positions[index * 4 + 3] = light.range ?? 0;+ state.colors.set(light.color ?? [1, 1, 1], index * 4);+ state.colors[index * 4 + 3] = light.intensity ?? 1;+ state.radii[index] = light.radius ?? 0.05;+ }+ for (let axis = 0; axis < 3; axis++) state.keyColor[axis] = keyColor[axis] * keyIntensity;+ state.pointCount = pointLights.length;+ state.fillIntensity = fillIntensity;+ state.ambientIntensity = ambientIntensity;+ return state;+}diff --git a/src/renderer.js b/src/renderer.jsindex 90470ccd..923ae2ee 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -4,6 +4,7 @@ import { fullscreenVertex, postFragment, skyFragment, bloomFragment } from './poimport { planRenderSize, estimateTextureBytes } from './budget.js';import { applyProjection } from './camera.js';import { resolveEffects } from './effects.js';+import { createLightingState, updateLightingState } from './lighting.js';import { validateSkinGeometry, validateSkinPose, skinTextureLayout, packSkinInfluences } from './skinning.js';const MATERIAL_TAGS = { armor: 1, floor: 2, water: 3, foliage: 4, terrain: 5, grass: 7, fire: 8, smoke: 9, unlit: 10 };@@ -170,6 +171,8 @@ export class Renderer67 {this.canvas = canvas;if (!Number.isInteger(samples) || samples < 1) throw new Error('MSAA sample count must be a positive integer.');if (new Set(parts).size !== parts.length) throw new Error('Scene parts must have distinct object identities for animation.');+ this.lighting = createLightingState();+ updateLightingState(this.lighting, environment, { world });this.context = canvas.getContext('webgl2', { antialias: true, alpha: Boolean(transparent), premultipliedAlpha: true, powerPreference: 'high-performance' });if (!this.context) throw new Error('WebGL2 is unavailable. Enable hardware acceleration or use a supported browser.');this.transparent = Boolean(transparent);@@ -239,6 +242,9 @@ export class Renderer67 {this.program = compileProgram(this.context, benchmark ? benchmarkVertexShader : vertexShader, benchmark ? benchmarkFragmentShader : fragmentShader);this.depthProgram = compileProgram(this.context, depthVertexShader, depthFragmentShader);this.uniforms = Object.fromEntries(['viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, 'normalScale', 'occlusionStrength', 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'lightDirection', 'fogColor', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount'].map((name) => [name, this.context.getUniformLocation(this.program, name)]));+ for (const name of ['pointLightCount', 'pointLightPositions[0]', 'pointLightColors[0]', 'pointLightRadii[0]', 'keyColor', 'fillIntensity', 'ambientIntensity']) {+ this.uniforms[name] = this.context.getUniformLocation(this.program, name);+ }this.depthSkinUniforms = Object.fromEntries(SKIN_UNIFORMS.map(name => [name, this.context.getUniformLocation(this.depthProgram, name)]));if (!benchmark) {this.postProgram = compileProgram(this.context, fullscreenVertex, postFragment);@@ -675,6 +681,8 @@ export class Renderer67 {render(frame) {const { eye, target = [0, 1.2, 0], armorColor = [0.53, 0.39, 0.24], armorSurface = [0.88, 0.32], exposure = 1, inspection = false } = frame;const effects = resolveEffects(frame.effects);+ const environment = { lightDirection: [-3, 6, 4], fogColor: [0.35, 0.43, 0.43], fogDensity: 0.006, daylight: 1, explosionCenter: [0, 0, 0], ...this.environment, ...frame.environment };+ updateLightingState(this.lighting, environment, { world: this.world });const start = performance.now();const context = this.context;const assemblyAmount = Math.max(0, Math.min(1, frame.assemblyAmount ?? 0));@@ -706,7 +714,13 @@ export class Renderer67 {context.uniform1f(this.uniforms.exposure, exposure);context.uniform1f(this.uniforms.inspection, inspection ? 1 : 0);context.uniform1f(this.uniforms.hdrEnabled, this.hdr ? 1 : 0);- const environment = { lightDirection: [-3, 6, 4], fogColor: [0.35, 0.43, 0.43], fogDensity: 0.006, daylight: 1, explosionCenter: [0, 0, 0], ...this.environment, ...frame.environment };+ context.uniform1i(this.uniforms.pointLightCount, this.lighting.pointCount);+ context.uniform4fv(this.uniforms['pointLightPositions[0]'], this.lighting.positions);+ context.uniform4fv(this.uniforms['pointLightColors[0]'], this.lighting.colors);+ context.uniform1fv(this.uniforms['pointLightRadii[0]'], this.lighting.radii);+ context.uniform3fv(this.uniforms.keyColor, this.lighting.keyColor);+ context.uniform1f(this.uniforms.fillIntensity, this.lighting.fillIntensity);+ context.uniform1f(this.uniforms.ambientIntensity, this.lighting.ambientIntensity);context.uniform1f(this.uniforms.time, frame.time ?? 0);context.uniform1f(this.uniforms.wind, frame.wind ?? 0.3);context.uniform1f(this.uniforms.worldMode, this.world ? 1 : 0);diff --git a/src/shaders.js b/src/shaders.jsindex e1c6f5a1..cfc4f722 100644--- a/src/shaders.js+++ b/src/shaders.js@@ -133,6 +133,13 @@ uniform float worldMode;uniform float time;uniform float daylight;uniform vec3 lightDirection;+uniform int pointLightCount;+uniform vec4 pointLightPositions[8];+uniform vec4 pointLightColors[8];+uniform float pointLightRadii[8];+uniform vec3 keyColor;+uniform float fillIntensity;+uniform float ambientIntensity;uniform vec3 fogColor;uniform float fogDensity;uniform vec3 waterRipple;@@ -220,8 +227,9 @@ vec3 studio(vec3 direction, float roughness) {}vec3 illuminate(vec3 normal, vec3 viewDirection, vec3 lightDirection, vec3 radiance, vec3 color, float metallic, float roughness) {- vec3 halfway = normalize(viewDirection + lightDirection);float normalLight = max(dot(normal, lightDirection), 0.0);+ if (normalLight == 0.0) return vec3(0);+ vec3 halfway = normalize(viewDirection + lightDirection);float normalView = max(dot(normal, viewDirection), 0.001);float normalHalf = max(dot(normal, halfway), 0.0);float alpha = roughness * roughness;@@ -326,22 +334,41 @@ void main() {roughness = clamp(roughness + (grains.x - 0.5) * 0.06 * grainWeight, 0.075, 1.0);}float visibility = shadowVisibility(normal);- vec3 keyColor = mix(vec3(5.2, 4.7, 4.1), vec3(3.7, 3.4, 2.9) * daylight, worldMode);vec3 radiance = illuminate(normal, viewDirection, normalize(lightDirection), keyColor * visibility, color, metallic, roughness);- radiance += illuminate(normal, viewDirection, normalize(vec3(4.0, 2.0, -3.0)), mix(vec3(0.8, 2.0, 1.8), vec3(0.12, 0.17, 0.20) * daylight, worldMode), color, metallic, roughness);- radiance += illuminate(normal, viewDirection, normalize(vec3(1.0, 2.0, 5.0)), vec3(0.6, 0.7, 0.8) * mix(1.0, 0.25 * daylight, worldMode), color, metallic, roughness);+ radiance += illuminate(normal, viewDirection, normalize(vec3(4.0, 2.0, -3.0)), mix(vec3(0.8, 2.0, 1.8), vec3(0.12, 0.17, 0.20) * daylight, worldMode) * fillIntensity, color, metallic, roughness);+ radiance += illuminate(normal, viewDirection, normalize(vec3(1.0, 2.0, 5.0)), vec3(0.6, 0.7, 0.8) * mix(1.0, 0.25 * daylight, worldMode) * fillIntensity, color, metallic, roughness);+ for (int index = 0; index < 8; index++) {+ if (index >= pointLightCount) break;+ vec3 offset = pointLightPositions[index].xyz - worldPosition;+ float distanceSquared = dot(offset, offset);+ if (distanceSquared < 1e-12 || pointLightColors[index].w == 0.0) continue;+ float range = pointLightPositions[index].w;+ float cutoff = 1.0;+ if (range > 0.0) {+ float squaredRatio = distanceSquared / (range * range);+ float fade = max(1.0 - squaredRatio * squaredRatio, 0.0);+ cutoff = fade * fade;+ }+ if (cutoff == 0.0) continue;+ float radius = pointLightRadii[index];+ float attenuation = cutoff / max(distanceSquared, radius * radius);+ vec3 lightRadiance = pointLightColors[index].rgb * pointLightColors[index].w * attenuation;+ radiance += illuminate(normal, viewDirection, offset * inversesqrt(distanceSquared), lightRadiance, color, metallic, roughness);+ }vec3 reflectance = fresnel(max(dot(normal, viewDirection), 0.0), mix(vec3(0.04), color, metallic));float occlusion = 1.0;if (hasOcclusionMap > 0.5) occlusion = mix(1.0, texture(occlusionMap, textureUV).r, occlusionStrength);- radiance += studio(reflect(-viewDirection, normal), roughness) * reflectance * (1.0 - roughness * 0.55) * mix(1.0, 0.5 * daylight, worldMode) * occlusion;- radiance += color * (1.0 - metallic) * mix(vec3(0.16, 0.20, 0.22), vec3(0.19, 0.25, 0.30) * max(daylight, 0.08), worldMode) * (0.45 + 0.55 * max(normal.y, 0.0)) * occlusion;- if (surface.w == 4.0 || surface.w == 7.0) radiance += color * max(dot(-normal, normalize(lightDirection)), 0.0) * 0.3 * daylight;+ radiance += studio(reflect(-viewDirection, normal), roughness) * reflectance * (1.0 - roughness * 0.55) * mix(1.0, 0.5 * daylight, worldMode) * occlusion * ambientIntensity;+ radiance += color * (1.0 - metallic) * mix(vec3(0.16, 0.20, 0.22), vec3(0.19, 0.25, 0.30) * max(daylight, 0.08), worldMode) * (0.45 + 0.55 * max(normal.y, 0.0)) * occlusion * ambientIntensity;+ vec3 keyResponse = keyColor / mix(vec3(5.2, 4.7, 4.1), vec3(3.7, 3.4, 2.9), worldMode);+ keyResponse *= mix(daylight, 1.0, worldMode);+ if (surface.w == 4.0 || surface.w == 7.0) radiance += color * max(dot(-normal, normalize(lightDirection)), 0.0) * 0.3 * keyResponse;radiance += emission;if (surface.w == 3.0) {float reflectivity = 0.20 + 0.65 * pow(1.0 - max(dot(normal, viewDirection), 0.0), 3.0);vec3 reflection = mix(vec3(0.12, 0.24, 0.28), vec3(0.40, 0.63, 0.78), clamp(reflect(-viewDirection, normal).y, 0.0, 1.0));- radiance = mix(radiance * 0.6, reflection * daylight, reflectivity);- radiance += vec3(1.0, 0.85, 0.55) * pow(max(dot(reflect(-normalize(lightDirection), normal), viewDirection), 0.0), 220.0) * 2.0 * daylight;+ radiance = mix(radiance * 0.6, reflection * daylight * ambientIntensity, reflectivity);+ radiance += vec3(1.0, 0.85, 0.55) * pow(max(dot(reflect(-normalize(lightDirection), normal), viewDirection), 0.0), 220.0) * 2.0 * keyResponse;}if (surface.w == 2.0) {float contact = 1.0 - 0.45 * exp(-dot(worldPosition.xz, worldPosition.xz) * 1.4);@@ -361,7 +388,7 @@ void main() {float fog = 1.0 - exp(-length(worldPosition - eye) * fogDensity);radiance = mix(radiance, fogColor, fog * worldMode);if (inspection > 0.5) radiance = normal * 0.5 + 0.5;- outputColor = vec4(hdrEnabled > 0.5 ? max(radiance * exposure, vec3(0)) : pow(toneMap(radiance * exposure), vec3(1.0 / 2.2)), 1.0);+ outputColor = vec4(hdrEnabled > 0.5 ? clamp(radiance * exposure, vec3(0), vec3(65504.0)) : pow(toneMap(radiance * exposure), vec3(1.0 / 2.2)), 1.0);if (surface.w == 2.0 && inspection < 0.5) {float distanceFade = exp(-length(worldPosition.xz) * 0.08);float contact = 1.0 - 0.1 * exp(-dot(worldPosition.xz, worldPosition.xz) * 1.4);diff --git a/tests/lighting.test.js b/tests/lighting.test.jsnew file mode 100644index 00000000..deb1d8a4--- /dev/null+++ b/tests/lighting.test.js@@ -0,0 +1,58 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { createLightingState, updateLightingState } from '../src/lighting.js';++test('lighting preserves legacy key defaults and independently controls direct fill and ambient light', () => {+ const state = createLightingState();+ updateLightingState(state, {});+ assert.deepEqual(Array.from(state.keyColor), [5.2, 4.7, 4.1].map(Math.fround));+ updateLightingState(state, { daylight: 0.5 }, { world: true });+ assert.deepEqual(Array.from(state.keyColor), [1.85, 1.7, 1.45].map(Math.fround));+ updateLightingState(state, { keyColor: [1, 0.5, 0.1], keyIntensity: 2, fillIntensity: 0, ambientIntensity: 0 });+ assert.deepEqual(Array.from(state.keyColor), [2, 1, 0.2].map(Math.fround));+ assert.equal(state.fillIntensity, 0);+ assert.equal(state.ambientIntensity, 0);+});++test('animated lights retain uniform buffers and removal clears stale lights without mutating source', () => {+ const state = createLightingState();+ const identities = [state.positions, state.colors, state.radii, state.keyColor];+ const light = { position: [1, 2, 3], color: [1, 0.5, 0], intensity: 12, range: 7, radius: 0.2 };+ const original = structuredClone(light);+ updateLightingState(state, { pointLights: [light] });+ assert.deepEqual(Array.from(state.positions.slice(0, 4)), [1, 2, 3, 7]);+ assert.deepEqual(Array.from(state.colors.slice(0, 4)), [1, 0.5, 0, 12]);+ assert.equal(state.pointCount, 1);+ for (let frame = 0; frame < 100; frame++) updateLightingState(state, { pointLights: [{ ...light, position: [frame, 2, 3] }] });+ updateLightingState(state, { pointLights: [] });+ assert.equal(state.pointCount, 0);+ assert.ok(state.positions.every(value => value === 0));+ assert.ok(state.colors.every(value => value === 0));+ assert.ok(state.radii.every(value => value === 0));+ assert.deepEqual([state.positions, state.colors, state.radii, state.keyColor], identities);+ assert.deepEqual(light, original);+});++test('malformed later lights reject atomically before replacing any retained lighting values', () => {+ const state = createLightingState();+ const light = { position: [0, 2, 1] };+ updateLightingState(state, { pointLights: [light], fillIntensity: 0.4 });+ const snapshot = structuredClone(state);+ for (const malformed of [+ null,+ { position: [0, 0] },+ { position: [Infinity, 0, 0] },+ { position: ['1', 0, 0] },+ { position: [0, 0, 0], color: [1, -1, 0] },+ { position: [0, 0, 0], intensity: NaN },+ { position: [0, 0, 0], radius: 1e-100 },+ { position: [0, 0, 0], range: 1e-100 },+ ]) {+ assert.throws(() => updateLightingState(state, { pointLights: [light, malformed], fillIntensity: 0 }));+ assert.deepEqual(state, snapshot);+ }+ assert.throws(() => updateLightingState(state, { pointLights: Array(9).fill(light) }), /at most/);+ assert.throws(() => updateLightingState(state, { keyIntensity: -1 }));+ assert.throws(() => updateLightingState(state, { ambientIntensity: Infinity }));+ assert.deepEqual(state, snapshot);+});