BlueGit

timfa questward

Merge branch 'feature/framework-sort-client-hook'

Draw-order fixes, Framework v0.48 bump, and lighting/render hot-path optimizations.

timfa Tim Falken · pushed by timfa

Authored 2026-09-06 · 2 months ago

Hash
1af0a6fdab59c6d74100afa3e668e0662740dd7c
7 files changed +491 −209
client/frameworkv3 +1 −1
@@ -1 +1 @@
1 Subproject commit 417815da13d52ae7e06b3ce82a15152b5f101cd0
1 Subproject commit b122579368b274094f2dd1b8f03763d6dae47fd9
@@ -1 +1 @@
1Subproject commit 417815da13d52ae7e06b3ce82a15152b5f101cd0
1Subproject commit b122579368b274094f2dd1b8f03763d6dae47fd9
client/src/play/waterDebug.js +15 −13
@@ -107,23 +107,25 @@ function uniformBagFrom (p, extras = {})
107 107 }
108 108
109 109 /** Uniform bag for the water ground fragment shader. */
110 const WATER_DEBUG_UNIFORMS = Object.freeze(uniformBagFrom(DEFAULT_WATER_DEBUG, {
111 u_foamStrength: DEFAULT_WATER_DEBUG.foamStrength,
112 u_shoreClip: DEFAULT_WATER_DEBUG.shoreClip,
113 u_deepDark: DEFAULT_WATER_DEBUG.deepDark,
114 u_deepAbrupt: DEFAULT_WATER_DEBUG.deepAbrupt
115 }));
116
117 /** Uniform bag for lava ground / bloom shaders. */
118 const LAVA_DEBUG_UNIFORMS = Object.freeze(uniformBagFrom(DEFAULT_LAVA_DEBUG, {
119 u_bloomStrength: DEFAULT_LAVA_DEBUG.bloomStrength,
120 u_shoreClip: DEFAULT_LAVA_DEBUG.shoreClip
121 }));
122
110 123 export function waterDebugUniforms ()
111 124 {
112 const p = DEFAULT_WATER_DEBUG;
113 return uniformBagFrom(p, {
114 u_foamStrength: p.foamStrength,
115 u_shoreClip: p.shoreClip,
116 u_deepDark: p.deepDark,
117 u_deepAbrupt: p.deepAbrupt
118 });
125 return WATER_DEBUG_UNIFORMS;
119 126 }
120 127
121 /** Uniform bag for lava ground / bloom shaders. */
122 128 export function lavaDebugUniforms ()
123 129 {
124 const p = DEFAULT_LAVA_DEBUG;
125 return uniformBagFrom(p, {
126 u_bloomStrength: p.bloomStrength,
127 u_shoreClip: p.shoreClip
128 });
130 return LAVA_DEBUG_UNIFORMS;
129 131 }
@@ -107,23 +107,25 @@ function uniformBagFrom (p, extras = {})
107}
107}
108
108
109/** Uniform bag for the water ground fragment shader. */
109/** Uniform bag for the water ground fragment shader. */
110const WATER_DEBUG_UNIFORMS = Object.freeze(uniformBagFrom(DEFAULT_WATER_DEBUG, {
111 u_foamStrength: DEFAULT_WATER_DEBUG.foamStrength,
112 u_shoreClip: DEFAULT_WATER_DEBUG.shoreClip,
113 u_deepDark: DEFAULT_WATER_DEBUG.deepDark,
114 u_deepAbrupt: DEFAULT_WATER_DEBUG.deepAbrupt
115}));
116
117/** Uniform bag for lava ground / bloom shaders. */
118const LAVA_DEBUG_UNIFORMS = Object.freeze(uniformBagFrom(DEFAULT_LAVA_DEBUG, {
119 u_bloomStrength: DEFAULT_LAVA_DEBUG.bloomStrength,
120 u_shoreClip: DEFAULT_LAVA_DEBUG.shoreClip
121}));
122
110export function waterDebugUniforms ()
123export function waterDebugUniforms ()
111{
124{
112 const p = DEFAULT_WATER_DEBUG;
125 return WATER_DEBUG_UNIFORMS;
113 return uniformBagFrom(p, {
114 u_foamStrength: p.foamStrength,
115 u_shoreClip: p.shoreClip,
116 u_deepDark: p.deepDark,
117 u_deepAbrupt: p.deepAbrupt
118 });
119}
126}
120
127
121/** Uniform bag for lava ground / bloom shaders. */
122export function lavaDebugUniforms ()
128export function lavaDebugUniforms ()
123{
129{
124 const p = DEFAULT_LAVA_DEBUG;
130 return LAVA_DEBUG_UNIFORMS;
125 return uniformBagFrom(p, {
126 u_bloomStrength: p.bloomStrength,
127 u_shoreClip: p.shoreClip
128 });
129}
131}
client/src/render/canvasSprite.js +53 −0
@@ -19,3 +19,56 @@ export function invalidateCanvasTexture (scene, canvas)
19 19 glContext.gl.deleteTexture(texture);
20 20 glContext.textures.delete(canvas);
21 21 }
22
23 /**
24 * Upload/replace RGBA pixels for a canvas-keyed GL texture.
25 * Reuses the existing texture via texSubImage2D when possible (no delete/recreate).
26 * @returns {boolean} true when a new texture was created
27 */
28 export function uploadCanvasTextureRgba (scene, canvas, pixels, width, height, filter = null)
29 {
30 const glContext = scene?.glContext;
31 const gl = glContext?.gl;
32 if (!gl || !glContext?.textures || !canvas || !pixels)
33 { return false; }
34
35 let texture = glContext.textures.get(canvas);
36 if (texture)
37 {
38 gl.bindTexture(gl.TEXTURE_2D, texture);
39 gl.texSubImage2D(
40 gl.TEXTURE_2D,
41 0,
42 0,
43 0,
44 width,
45 height,
46 gl.RGBA,
47 gl.UNSIGNED_BYTE,
48 pixels
49 );
50 return false;
51 }
52
53 texture = gl.createTexture();
54 gl.bindTexture(gl.TEXTURE_2D, texture);
55 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
56 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
57 const minFilter = filter ?? glContext.textureMinFilter ?? gl.LINEAR;
58 const magFilter = filter ?? glContext.textureMagFilter ?? gl.LINEAR;
59 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
60 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
61 gl.texImage2D(
62 gl.TEXTURE_2D,
63 0,
64 gl.RGBA,
65 width,
66 height,
67 0,
68 gl.RGBA,
69 gl.UNSIGNED_BYTE,
70 pixels
71 );
72 glContext.textures.set(canvas, texture);
73 return true;
74 }
@@ -19,3 +19,56 @@ export function invalidateCanvasTexture (scene, canvas)
19 glContext.gl.deleteTexture(texture);
19 glContext.gl.deleteTexture(texture);
20 glContext.textures.delete(canvas);
20 glContext.textures.delete(canvas);
21}
21}
22
23/**
24 * Upload/replace RGBA pixels for a canvas-keyed GL texture.
25 * Reuses the existing texture via texSubImage2D when possible (no delete/recreate).
26 * @returns {boolean} true when a new texture was created
27 */
28export function uploadCanvasTextureRgba (scene, canvas, pixels, width, height, filter = null)
29{
30 const glContext = scene?.glContext;
31 const gl = glContext?.gl;
32 if (!gl || !glContext?.textures || !canvas || !pixels)
33 { return false; }
34
35 let texture = glContext.textures.get(canvas);
36 if (texture)
37 {
38 gl.bindTexture(gl.TEXTURE_2D, texture);
39 gl.texSubImage2D(
40 gl.TEXTURE_2D,
41 0,
42 0,
43 0,
44 width,
45 height,
46 gl.RGBA,
47 gl.UNSIGNED_BYTE,
48 pixels
49 );
50 return false;
51 }
52
53 texture = gl.createTexture();
54 gl.bindTexture(gl.TEXTURE_2D, texture);
55 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
56 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
57 const minFilter = filter ?? glContext.textureMinFilter ?? gl.LINEAR;
58 const magFilter = filter ?? glContext.textureMagFilter ?? gl.LINEAR;
59 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
60 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
61 gl.texImage2D(
62 gl.TEXTURE_2D,
63 0,
64 gl.RGBA,
65 width,
66 height,
67 0,
68 gl.RGBA,
69 gl.UNSIGNED_BYTE,
70 pixels
71 );
72 glContext.textures.set(canvas, texture);
73 return true;
74}
client/src/render/sprites.js +16 −3
@@ -152,18 +152,30 @@ function setGlNearest (gl, texture)
152 152 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
153 153 }
154 154
155 /** Framework defaults to LINEAR; patch uploads so pixel art stays crisp when scaled. */
155 /** Framework defaults to LINEAR; set NEAREST once at upload for pixel-art games. */
156 156 export function patchNearestNeighbourTextures (scene)
157 157 {
158 158 const glContext = scene?.glContext;
159 159 if (!glContext || glContext._nearestPatched)
160 160 { return; }
161 const gl = glContext.gl;
162 if (typeof glContext.setDefaultTextureFilter === "function")
163 {
164 glContext.setDefaultTextureFilter(gl.NEAREST, gl.NEAREST);
165 glContext._nearestPatched = true;
166 return;
167 }
168 // Legacy Framework: apply NEAREST once per texture object, not every getTexture hit.
161 169 const original = glContext.getTexture.bind(glContext);
170 const nearestOnce = new WeakSet();
162 171 glContext.getTexture = (htmlImage) =>
163 172 {
164 173 const texture = original(htmlImage);
165 if (texture)
166 { setGlNearest(glContext.gl, texture); }
174 if (texture && !nearestOnce.has(texture))
175 {
176 setGlNearest(gl, texture);
177 nearestOnce.add(texture);
178 }
167 179 return texture;
168 180 };
169 181 glContext._nearestPatched = true;
@@ -180,6 +192,7 @@ export function setNearestFilter (scene, source)
180 192 { return; }
181 193 const htmlImage = source.g_image ?? source;
182 194 const texture = glContext.getTexture(htmlImage);
195 // Text-assert for textures uploaded before NEAREST was the default.
183 196 if (texture)
184 197 { setGlNearest(glContext.gl, texture); }
185 198 }
@@ -152,18 +152,30 @@ function setGlNearest (gl, texture)
152 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
152 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
153}
153}
154
154
155/** Framework defaults to LINEAR; patch uploads so pixel art stays crisp when scaled. */
155/** Framework defaults to LINEAR; set NEAREST once at upload for pixel-art games. */
156export function patchNearestNeighbourTextures (scene)
156export function patchNearestNeighbourTextures (scene)
157{
157{
158 const glContext = scene?.glContext;
158 const glContext = scene?.glContext;
159 if (!glContext || glContext._nearestPatched)
159 if (!glContext || glContext._nearestPatched)
160 { return; }
160 { return; }
161 const gl = glContext.gl;
162 if (typeof glContext.setDefaultTextureFilter === "function")
163 {
164 glContext.setDefaultTextureFilter(gl.NEAREST, gl.NEAREST);
165 glContext._nearestPatched = true;
166 return;
167 }
168 // Legacy Framework: apply NEAREST once per texture object, not every getTexture hit.
161 const original = glContext.getTexture.bind(glContext);
169 const original = glContext.getTexture.bind(glContext);
170 const nearestOnce = new WeakSet();
162 glContext.getTexture = (htmlImage) =>
171 glContext.getTexture = (htmlImage) =>
163 {
172 {
164 const texture = original(htmlImage);
173 const texture = original(htmlImage);
165 if (texture)
174 if (texture && !nearestOnce.has(texture))
166 { setGlNearest(glContext.gl, texture); }
175 {
176 setGlNearest(gl, texture);
177 nearestOnce.add(texture);
178 }
167 return texture;
179 return texture;
168 };
180 };
169 glContext._nearestPatched = true;
181 glContext._nearestPatched = true;
@@ -180,6 +192,7 @@ export function setNearestFilter (scene, source)
180 { return; }
192 { return; }
181 const htmlImage = source.g_image ?? source;
193 const htmlImage = source.g_image ?? source;
182 const texture = glContext.getTexture(htmlImage);
194 const texture = glContext.getTexture(htmlImage);
195 // Text-assert for textures uploaded before NEAREST was the default.
183 if (texture)
196 if (texture)
184 { setGlNearest(glContext.gl, texture); }
197 { setGlNearest(glContext.gl, texture); }
185}
198}
client/src/render/worldView.js +343 −187
@@ -24,7 +24,8 @@ import { createChunkAtlasCache } from "./chunkAtlasCache.js";
24 24 import
25 25 {
26 26 frameworkImageFromCanvas,
27 invalidateCanvasTexture
27 invalidateCanvasTexture,
28 uploadCanvasTextureRgba
28 29 } from "./canvasSprite.js";
29 30 import { setNearestFilter } from "./sprites.js";
30 31 import { waterDebugUniforms, lavaDebugUniforms } from "../play/waterDebug.js";
@@ -1050,6 +1051,8 @@ export class WorldView
1050 1051 #playerChunkY = null;
1051 1052 #playerMoveChunkDx = 0;
1052 1053 #playerMoveChunkDy = 0;
1054 /** Reused by {@link #placePivoted} to avoid per-call `new vector()`. */
1055 #placeSizeScratch = new vector(0, 0);
1053 1056
1054 1057 constructor(game, scene, catalog = { grounds: {}, blocks: {} })
1055 1058 {
@@ -3184,11 +3187,7 @@ export class WorldView
3184 3187 this.#setRendererVisible(objects.groundBloom, visible && this.bloomEnabled);
3185 3188 this.#setRendererVisible(objects.block, visible);
3186 3189 this.#setRendererVisible(objects.blockBloom, visible && this.bloomEnabled);
3187 if (objects.waterEdges)
3188 {
3189 for (const edge of Object.values(objects.waterEdges))
3190 { this.#setRendererVisible(edge, visible); }
3191 }
3190 this.#setRendererVisible(objects.lavaBloom, visible && this.bloomEnabled);
3192 3191 }
3193 3192 }
3194 3193
@@ -3566,9 +3565,69 @@ export class WorldView
3566 3565 object._lit = false;
3567 3566 object.renderer.shader = null;
3568 3567 object.renderer.shaderUniforms = null;
3568 object.renderer._shaderUniformKind = null;
3569 3569 object.renderer.secondaryMap = null;
3570 3570 }
3571 3571
3572 #ensureUniformBag (renderer, shader, kind)
3573 {
3574 renderer.shader = shader;
3575 if (!renderer.shaderUniforms || renderer._shaderUniformKind !== kind)
3576 {
3577 renderer.shaderUniforms = {};
3578 renderer._shaderUniformKind = kind;
3579 }
3580 return renderer.shaderUniforms;
3581 }
3582
3583 #writeUniformVec3 (uniforms, key, src)
3584 {
3585 let arr = uniforms[key];
3586 if (!Array.isArray(arr) || arr.length !== 3)
3587 {
3588 arr = [0, 0, 0];
3589 uniforms[key] = arr;
3590 }
3591 if (Array.isArray(src))
3592 {
3593 arr[0] = src[0];
3594 arr[1] = src[1];
3595 arr[2] = src[2];
3596 }
3597 else
3598 {
3599 arr[0] = src.r;
3600 arr[1] = src.g;
3601 arr[2] = src.b;
3602 }
3603 }
3604
3605 #writeUniformVec2 (uniforms, key, a, b)
3606 {
3607 let arr = uniforms[key];
3608 if (!Array.isArray(arr) || arr.length !== 2)
3609 {
3610 arr = [0, 0];
3611 uniforms[key] = arr;
3612 }
3613 arr[0] = a;
3614 arr[1] = b;
3615 }
3616
3617 #writeUniformVec4 (uniforms, key, a, b, c, d)
3618 {
3619 let arr = uniforms[key];
3620 if (!Array.isArray(arr) || arr.length !== 4)
3621 {
3622 arr = [0, 0, 0, 0];
3623 uniforms[key] = arr;
3624 }
3625 arr[0] = a;
3626 arr[1] = b;
3627 arr[2] = c;
3628 arr[3] = d;
3629 }
3630
3572 3631 /** Bloom / unlit overlays that still need magenta channel tint (e.g. elemental sprites). */
3573 3632 #syncUnlitTintSprite (object, tintColor)
3574 3633 {
@@ -3576,16 +3635,14 @@ export class WorldView
3576 3635 { return; }
3577 3636 const tint = normalizeRgb(tintColor);
3578 3637 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
3579 object.renderer.shader = getTintLitSpriteShader();
3580 object.renderer.shaderUniforms = {
3581 u_darkness: 0,
3582 u_strength: 0,
3583 u_flashColor: FLASH_COLOR_DAMAGE,
3584 u_wade: 0,
3585 u_spriteHeight: height,
3586 u_useTint: 1,
3587 u_tintColor: [tint.r, tint.g, tint.b]
3588 };
3638 const uniforms = this.#ensureUniformBag(object.renderer, getTintLitSpriteShader(), "unlitTint");
3639 uniforms.u_darkness = 0;
3640 uniforms.u_strength = 0;
3641 this.#writeUniformVec3(uniforms, "u_flashColor", FLASH_COLOR_DAMAGE);
3642 uniforms.u_wade = 0;
3643 uniforms.u_spriteHeight = height;
3644 uniforms.u_useTint = 1;
3645 this.#writeUniformVec3(uniforms, "u_tintColor", tint);
3589 3646 object.renderer.secondaryMap = null;
3590 3647 }
3591 3648
@@ -3601,27 +3658,23 @@ export class WorldView
3601 3658 const tint = tintColor ? normalizeRgb(tintColor) : null;
3602 3659 if (tint)
3603 3660 {
3604 object.renderer.shader = getTintLitSpriteShader();
3605 object.renderer.shaderUniforms = {
3606 u_darkness: dark,
3607 u_strength: flash,
3608 u_flashColor: flashRgb,
3609 u_wade: wade ? 1 : 0,
3610 u_spriteHeight: height,
3611 u_useTint: 1,
3612 u_tintColor: [tint.r, tint.g, tint.b]
3613 };
3661 const uniforms = this.#ensureUniformBag(object.renderer, getTintLitSpriteShader(), "tintLit");
3662 uniforms.u_darkness = dark;
3663 uniforms.u_strength = flash;
3664 this.#writeUniformVec3(uniforms, "u_flashColor", flashRgb);
3665 uniforms.u_wade = wade ? 1 : 0;
3666 uniforms.u_spriteHeight = height;
3667 uniforms.u_useTint = 1;
3668 this.#writeUniformVec3(uniforms, "u_tintColor", tint);
3614 3669 }
3615 3670 else
3616 3671 {
3617 object.renderer.shader = getSpriteLightingShader();
3618 object.renderer.shaderUniforms = {
3619 u_darkness: dark,
3620 u_strength: flash,
3621 u_flashColor: flashRgb,
3622 u_wade: wade ? 1 : 0,
3623 u_spriteHeight: height
3624 };
3672 const uniforms = this.#ensureUniformBag(object.renderer, getSpriteLightingShader(), "lit");
3673 uniforms.u_darkness = dark;
3674 uniforms.u_strength = flash;
3675 this.#writeUniformVec3(uniforms, "u_flashColor", flashRgb);
3676 uniforms.u_wade = wade ? 1 : 0;
3677 uniforms.u_spriteHeight = height;
3625 3678 }
3626 3679 object.renderer.secondaryMap = null;
3627 3680 }
@@ -3631,7 +3684,7 @@ export class WorldView
3631 3684 return entity?.object?.renderer?.sprite?.g_image ?? null;
3632 3685 }
3633 3686
3634 #tightFitMaskUniforms (overlay, entity)
3687 #tightFitMaskUniforms (overlay, entity, into = null)
3635 3688 {
3636 3689 const bodyRenderer = entity?.object?.renderer;
3637 3690 const clothRenderer = overlay?.renderer;
@@ -3643,13 +3696,13 @@ export class WorldView
3643 3696 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
3644 3697 const bodyUv = bodySprite.getUvRect?.(bodyRenderer.subImage | 0)
3645 3698 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
3646 return {
3647 u_clothSize: [clothSprite.width || SPRITE_SIZE_PX, clothSprite.height || SPRITE_SIZE_PX],
3648 u_bodySize: [bodySprite.width || SPRITE_SIZE_PX, bodySprite.height || SPRITE_SIZE_PX],
3649 u_pivotFromBottom: PIVOT_FROM_BOTTOM_PX,
3650 u_clothUvRect: [clothUv.u0, clothUv.v0, clothUv.u1, clothUv.v1],
3651 u_bodyUvRect: [bodyUv.u0, bodyUv.v0, bodyUv.u1, bodyUv.v1]
3652 };
3699 const uniforms = into ?? {};
3700 this.#writeUniformVec2(uniforms, "u_clothSize", clothSprite.width || SPRITE_SIZE_PX, clothSprite.height || SPRITE_SIZE_PX);
3701 this.#writeUniformVec2(uniforms, "u_bodySize", bodySprite.width || SPRITE_SIZE_PX, bodySprite.height || SPRITE_SIZE_PX);
3702 uniforms.u_pivotFromBottom = PIVOT_FROM_BOTTOM_PX;
3703 this.#writeUniformVec4(uniforms, "u_clothUvRect", clothUv.u0, clothUv.v0, clothUv.u1, clothUv.v1);
3704 this.#writeUniformVec4(uniforms, "u_bodyUvRect", bodyUv.u0, bodyUv.v0, bodyUv.u1, bodyUv.v1);
3705 return uniforms;
3653 3706 }
3654 3707
3655 3708 #syncTightFitLitSprite (overlay, entity, darkness, flashStrength = 0, wade = false, tintColor = null, flashColor = null)
@@ -3657,9 +3710,8 @@ export class WorldView
3657 3710 if (!overlay?.renderer || entity?.object?.renderer == null)
3658 3711 { return; }
3659 3712 const bodyMap = this.#bodySecondaryMap(entity);
3660 const maskUniforms = this.#tightFitMaskUniforms(overlay, entity);
3661 3713 const flashRgb = flashColor ?? FLASH_COLOR_DAMAGE;
3662 if (!bodyMap || !maskUniforms)
3714 if (!bodyMap)
3663 3715 {
3664 3716 this.#syncLitSprite(overlay, darkness, flashStrength, wade, tintColor, flashRgb);
3665 3717 return;
@@ -3670,31 +3722,23 @@ export class WorldView
3670 3722 const height = overlay.renderer.sprite?.height ?? SPRITE_SIZE_PX;
3671 3723 const tint = tintColor ? normalizeRgb(tintColor) : null;
3672 3724 overlay.renderer.secondaryMap = bodyMap;
3673 if (tint)
3725 const kind = tint ? "tightFitTint" : "tightFit";
3726 const shader = tint ? getTightFitTintLitSpriteShader() : getTightFitLitSpriteShader();
3727 const uniforms = this.#ensureUniformBag(overlay.renderer, shader, kind);
3728 if (!this.#tightFitMaskUniforms(overlay, entity, uniforms))
3674 3729 {
3675 overlay.renderer.shader = getTightFitTintLitSpriteShader();
3676 overlay.renderer.shaderUniforms = {
3677 u_darkness: dark,
3678 u_strength: flash,
3679 u_flashColor: flashRgb,
3680 u_wade: wade ? 1 : 0,
3681 u_spriteHeight: height,
3682 u_useTint: 1,
3683 u_tintColor: [tint.r, tint.g, tint.b],
3684 ...maskUniforms
3685 };
3730 this.#syncLitSprite(overlay, darkness, flashStrength, wade, tintColor, flashRgb);
3731 return;
3686 3732 }
3687 else
3733 uniforms.u_darkness = dark;
3734 uniforms.u_strength = flash;
3735 this.#writeUniformVec3(uniforms, "u_flashColor", flashRgb);
3736 uniforms.u_wade = wade ? 1 : 0;
3737 uniforms.u_spriteHeight = height;
3738 if (tint)
3688 3739 {
3689 overlay.renderer.shader = getTightFitLitSpriteShader();
3690 overlay.renderer.shaderUniforms = {
3691 u_darkness: dark,
3692 u_strength: flash,
3693 u_flashColor: flashRgb,
3694 u_wade: wade ? 1 : 0,
3695 u_spriteHeight: height,
3696 ...maskUniforms
3697 };
3740 uniforms.u_useTint = 1;
3741 this.#writeUniformVec3(uniforms, "u_tintColor", tint);
3698 3742 }
3699 3743 }
3700 3744
@@ -3712,18 +3756,16 @@ export class WorldView
3712 3756 { object._lit = true; }
3713 3757 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
3714 3758 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
3715 object.renderer.shader = getDualTintLitSpriteShader();
3716 object.renderer.shaderUniforms = {
3717 u_darkness: dark,
3718 u_strength: flash,
3719 u_flashColor: flashColor ?? FLASH_COLOR_DAMAGE,
3720 u_wade: wade ? 1 : 0,
3721 u_spriteHeight: height,
3722 u_shaftTint: [shaft.r, shaft.g, shaft.b],
3723 u_tipTint: [tip.r, tip.g, tip.b],
3724 u_coatTint: coat ? [coat.r, coat.g, coat.b] : [0, 0, 0],
3725 u_hasCoat: coat ? 1 : 0
3726 };
3759 const uniforms = this.#ensureUniformBag(object.renderer, getDualTintLitSpriteShader(), "dualTint");
3760 uniforms.u_darkness = dark;
3761 uniforms.u_strength = flash;
3762 this.#writeUniformVec3(uniforms, "u_flashColor", flashColor ?? FLASH_COLOR_DAMAGE);
3763 uniforms.u_wade = wade ? 1 : 0;
3764 uniforms.u_spriteHeight = height;
3765 this.#writeUniformVec3(uniforms, "u_shaftTint", shaft);
3766 this.#writeUniformVec3(uniforms, "u_tipTint", tip);
3767 this.#writeUniformVec3(uniforms, "u_coatTint", coat ?? { r: 0, g: 0, b: 0 });
3768 uniforms.u_hasCoat = coat ? 1 : 0;
3727 3769 object.renderer.secondaryMap = null;
3728 3770 }
3729 3771
@@ -3949,45 +3991,43 @@ export class WorldView
3949 3991 const dSW = deepCorners?.sw ?? 0;
3950 3992 const dSE = deepCorners?.se ?? 0;
3951 3993 object._lit = true;
3952 object.renderer.shader = getWaterGroundShader();
3953 3994 // Shallow + deep share one noise atlas so texAmp seams don't hard-cut at depth edges.
3954 3995 const sharedNoise = this.game.images[spriteImageName("ground", "water", "water")];
3955 3996 if (sharedNoise)
3956 3997 { object.renderer.sprite = sharedNoise; }
3957 3998 object.renderer.secondaryMap = shoreSprite?.g_image ?? null;
3958 object.renderer.shaderUniforms = {
3959 u_ambientDark: dark,
3960 u_litNW: lit.nw,
3961 u_litNE: lit.ne,
3962 u_litSW: lit.sw,
3963 u_litSE: lit.se,
3964 u_time: timeSec,
3965 u_tileX: tileX | 0,
3966 u_tileY: tileY | 0,
3967 u_deepNW: dNW,
3968 u_deepNE: dNE,
3969 u_deepSW: dSW,
3970 u_deepSE: dSE,
3971 u_edgeN: edges?.n ?? 0,
3972 u_edgeE: edges?.e ?? 0,
3973 u_edgeS: edges?.s ?? 0,
3974 u_edgeW: edges?.w ?? 0,
3975 u_edgeNE: edges?.ne ?? 0,
3976 u_edgeNW: edges?.nw ?? 0,
3977 u_edgeSE: edges?.se ?? 0,
3978 u_edgeSW: edges?.sw ?? 0,
3979 u_hasShore: shoreSprite ? 1 : 0,
3980 u_shoreEdgeN: shore?.edgeN ?? 0,
3981 u_shoreEdgeE: shore?.edgeE ?? 0,
3982 u_shoreEdgeS: shore?.edgeS ?? 0,
3983 u_shoreEdgeW: shore?.edgeW ?? 0,
3984 u_shoreEdgeNE: shore?.edgeNE ?? 0,
3985 u_shoreEdgeNW: shore?.edgeNW ?? 0,
3986 u_shoreEdgeSE: shore?.edgeSE ?? 0,
3987 u_shoreEdgeSW: shore?.edgeSW ?? 0,
3988 u_shoreUvRect: [shoreUv.u0, shoreUv.v0, shoreUv.u1, shoreUv.v1],
3989 ...waterDebugUniforms()
3990 };
3999 const uniforms = this.#ensureUniformBag(object.renderer, getWaterGroundShader(), "water");
4000 uniforms.u_ambientDark = dark;
4001 uniforms.u_litNW = lit.nw;
4002 uniforms.u_litNE = lit.ne;
4003 uniforms.u_litSW = lit.sw;
4004 uniforms.u_litSE = lit.se;
4005 uniforms.u_time = timeSec;
4006 uniforms.u_tileX = tileX | 0;
4007 uniforms.u_tileY = tileY | 0;
4008 uniforms.u_deepNW = dNW;
4009 uniforms.u_deepNE = dNE;
4010 uniforms.u_deepSW = dSW;
4011 uniforms.u_deepSE = dSE;
4012 uniforms.u_edgeN = edges?.n ?? 0;
4013 uniforms.u_edgeE = edges?.e ?? 0;
4014 uniforms.u_edgeS = edges?.s ?? 0;
4015 uniforms.u_edgeW = edges?.w ?? 0;
4016 uniforms.u_edgeNE = edges?.ne ?? 0;
4017 uniforms.u_edgeNW = edges?.nw ?? 0;
4018 uniforms.u_edgeSE = edges?.se ?? 0;
4019 uniforms.u_edgeSW = edges?.sw ?? 0;
4020 uniforms.u_hasShore = shoreSprite ? 1 : 0;
4021 uniforms.u_shoreEdgeN = shore?.edgeN ?? 0;
4022 uniforms.u_shoreEdgeE = shore?.edgeE ?? 0;
4023 uniforms.u_shoreEdgeS = shore?.edgeS ?? 0;
4024 uniforms.u_shoreEdgeW = shore?.edgeW ?? 0;
4025 uniforms.u_shoreEdgeNE = shore?.edgeNE ?? 0;
4026 uniforms.u_shoreEdgeNW = shore?.edgeNW ?? 0;
4027 uniforms.u_shoreEdgeSE = shore?.edgeSE ?? 0;
4028 uniforms.u_shoreEdgeSW = shore?.edgeSW ?? 0;
4029 this.#writeUniformVec4(uniforms, "u_shoreUvRect", shoreUv.u0, shoreUv.v0, shoreUv.u1, shoreUv.v1);
4030 Object.assign(uniforms, waterDebugUniforms());
3991 4031 }
3992 4032
3993 4033 /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. Lava is procedural heat. */
@@ -4167,37 +4207,35 @@ export class WorldView
4167 4207 const shoreUv = shoreSprite?.getUvRect?.(0)
4168 4208 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
4169 4209 object._lit = true;
4170 object.renderer.shader = getLavaGroundShader();
4171 4210 object.renderer.secondaryMap = shoreSprite?.g_image ?? null;
4172 object.renderer.shaderUniforms = {
4173 u_ambientDark: dark,
4174 u_litNW: lit.nw,
4175 u_litNE: lit.ne,
4176 u_litSW: lit.sw,
4177 u_litSE: lit.se,
4178 u_time: timeSec,
4179 u_tileX: tileX | 0,
4180 u_tileY: tileY | 0,
4181 u_edgeN: edges?.n ?? 0,
4182 u_edgeE: edges?.e ?? 0,
4183 u_edgeS: edges?.s ?? 0,
4184 u_edgeW: edges?.w ?? 0,
4185 u_edgeNE: edges?.ne ?? 0,
4186 u_edgeNW: edges?.nw ?? 0,
4187 u_edgeSE: edges?.se ?? 0,
4188 u_edgeSW: edges?.sw ?? 0,
4189 u_hasShore: shoreSprite ? 1 : 0,
4190 u_shoreEdgeN: shore?.edgeN ?? 0,
4191 u_shoreEdgeE: shore?.edgeE ?? 0,
4192 u_shoreEdgeS: shore?.edgeS ?? 0,
4193 u_shoreEdgeW: shore?.edgeW ?? 0,
4194 u_shoreEdgeNE: shore?.edgeNE ?? 0,
4195 u_shoreEdgeNW: shore?.edgeNW ?? 0,
4196 u_shoreEdgeSE: shore?.edgeSE ?? 0,
4197 u_shoreEdgeSW: shore?.edgeSW ?? 0,
4198 u_shoreUvRect: [shoreUv.u0, shoreUv.v0, shoreUv.u1, shoreUv.v1],
4199 ...lavaDebugUniforms()
4200 };
4211 const uniforms = this.#ensureUniformBag(object.renderer, getLavaGroundShader(), "lava");
4212 uniforms.u_ambientDark = dark;
4213 uniforms.u_litNW = lit.nw;
4214 uniforms.u_litNE = lit.ne;
4215 uniforms.u_litSW = lit.sw;
4216 uniforms.u_litSE = lit.se;
4217 uniforms.u_time = timeSec;
4218 uniforms.u_tileX = tileX | 0;
4219 uniforms.u_tileY = tileY | 0;
4220 uniforms.u_edgeN = edges?.n ?? 0;
4221 uniforms.u_edgeE = edges?.e ?? 0;
4222 uniforms.u_edgeS = edges?.s ?? 0;
4223 uniforms.u_edgeW = edges?.w ?? 0;
4224 uniforms.u_edgeNE = edges?.ne ?? 0;
4225 uniforms.u_edgeNW = edges?.nw ?? 0;
4226 uniforms.u_edgeSE = edges?.se ?? 0;
4227 uniforms.u_edgeSW = edges?.sw ?? 0;
4228 uniforms.u_hasShore = shoreSprite ? 1 : 0;
4229 uniforms.u_shoreEdgeN = shore?.edgeN ?? 0;
4230 uniforms.u_shoreEdgeE = shore?.edgeE ?? 0;
4231 uniforms.u_shoreEdgeS = shore?.edgeS ?? 0;
4232 uniforms.u_shoreEdgeW = shore?.edgeW ?? 0;
4233 uniforms.u_shoreEdgeNE = shore?.edgeNE ?? 0;
4234 uniforms.u_shoreEdgeNW = shore?.edgeNW ?? 0;
4235 uniforms.u_shoreEdgeSE = shore?.edgeSE ?? 0;
4236 uniforms.u_shoreEdgeSW = shore?.edgeSW ?? 0;
4237 this.#writeUniformVec4(uniforms, "u_shoreUvRect", shoreUv.u0, shoreUv.v0, shoreUv.u1, shoreUv.v1);
4238 Object.assign(uniforms, lavaDebugUniforms());
4201 4239 }
4202 4240
4203 4241 #syncLavaBloomSprite (object, {
@@ -4209,21 +4247,19 @@ export class WorldView
4209 4247 {
4210 4248 if (!object?.renderer)
4211 4249 { return; }
4212 object.renderer.shader = getLavaBloomShader();
4213 object.renderer.shaderUniforms = {
4214 u_time: timeSec,
4215 u_tileX: tileX | 0,
4216 u_tileY: tileY | 0,
4217 u_edgeN: edges?.n ?? 0,
4218 u_edgeE: edges?.e ?? 0,
4219 u_edgeS: edges?.s ?? 0,
4220 u_edgeW: edges?.w ?? 0,
4221 u_edgeNE: edges?.ne ?? 0,
4222 u_edgeNW: edges?.nw ?? 0,
4223 u_edgeSE: edges?.se ?? 0,
4224 u_edgeSW: edges?.sw ?? 0,
4225 ...lavaDebugUniforms()
4226 };
4250 const uniforms = this.#ensureUniformBag(object.renderer, getLavaBloomShader(), "lavaBloom");
4251 uniforms.u_time = timeSec;
4252 uniforms.u_tileX = tileX | 0;
4253 uniforms.u_tileY = tileY | 0;
4254 uniforms.u_edgeN = edges?.n ?? 0;
4255 uniforms.u_edgeE = edges?.e ?? 0;
4256 uniforms.u_edgeS = edges?.s ?? 0;
4257 uniforms.u_edgeW = edges?.w ?? 0;
4258 uniforms.u_edgeNE = edges?.ne ?? 0;
4259 uniforms.u_edgeNW = edges?.nw ?? 0;
4260 uniforms.u_edgeSE = edges?.se ?? 0;
4261 uniforms.u_edgeSW = edges?.sw ?? 0;
4262 Object.assign(uniforms, lavaDebugUniforms());
4227 4263 }
4228 4264
4229 4265 #ambientDarkness ()
@@ -5045,13 +5081,11 @@ export class WorldView
5045 5081 { return; }
5046 5082 object._lit = true;
5047 5083 const dark = Math.min(1, Math.max(0, darkness ?? 0));
5048 object.renderer.shader = getCliffGroundTopShader();
5049 5084 object.renderer.bumpMap = groundImage ?? null;
5050 5085 object.renderer.secondaryMap = null;
5051 object.renderer.shaderUniforms = {
5052 u_darkness: dark,
5053 u_tileLocal: [localX, localY]
5054 };
5086 const uniforms = this.#ensureUniformBag(object.renderer, getCliffGroundTopShader(), "cliffTop");
5087 uniforms.u_darkness = dark;
5088 this.#writeUniformVec2(uniforms, "u_tileLocal", localX, localY);
5055 5089 }
5056 5090
5057 5091 #layoutBakedChunk (snapshot)
@@ -5211,7 +5245,7 @@ export class WorldView
5211 5245 const blockDef = blockDefinition(blockEntry?.typeId);
5212 5246 const blockSort = blockDef?.door
5213 5247 ? doorSortSubOrder(blockEntry?.state, SORT_ENTITY)
5214 : SORT_ENTITY;
5248 : SORT_BLOCK;
5215 5249 objects.block = this.#ensureSprite(objects.block, tileBlock.sprite, blockSort);
5216 5250 objects.blockSort = blockSort;
5217 5251 objects.cliffGroundTop = !!blockDef?.cliffGroundTop;
@@ -5270,11 +5304,29 @@ export class WorldView
5270 5304 const zoom = this.zoom;
5271 5305 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
5272 5306 const factor = Math.max(0.1, Number(scale) || 1);
5307 const w = draw.w * factor;
5308 const h = draw.h * factor;
5273 5309 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height * factor, zoom);
5310 const layer = this.#depthLayer(sortY, subOrder, flight);
5311 if (
5312 object._placeX === center.x
5313 && object._placeY === center.y
5314 && object._placeW === w
5315 && object._placeH === h
5316 && object.layer === layer
5317 )
5318 { return; }
5319 object._placeX = center.x;
5320 object._placeY = center.y;
5321 object._placeW = w;
5322 object._placeH = h;
5274 5323 object.transform.position.x = center.x;
5275 5324 object.transform.position.y = center.y;
5276 object.transform.size = new vector(draw.w * factor, draw.h * factor);
5277 this.#setLayer(object, this.#depthLayer(sortY, subOrder, flight));
5325 const size = this.#placeSizeScratch;
5326 size.x = w;
5327 size.y = h;
5328 object.transform.size = size;
5329 this.#setLayer(object, layer);
5278 5330 }
5279 5331
5280 5332 #ensureSprite (existing, name, layer)
@@ -5399,18 +5451,20 @@ export class WorldView
5399 5451 return fromAlpha + (toAlpha - fromAlpha) * t;
5400 5452 }
5401 5453
5402 /** A layer write costs the scene a full re-sort, so only write real changes. */
5454 /** Layer writes notify the scene; avoid redundant full-sort flags. */
5403 5455 #setLayer (object, layer)
5404 5456 {
5405 5457 if (!object || object.layer === layer)
5406 5458 { return; }
5407 5459 object.layer = layer;
5408 this.#markSortDirty();
5409 5460 }
5410 5461
5411 5462 #markSortDirty ()
5412 5463 {
5413 this.scene._sortDirty = true;
5464 if (typeof this.scene?.markSortDirty === "function")
5465 { this.scene.markSortDirty(); }
5466 else
5467 { this.scene._sortDirty = true; }
5414 5468 }
5415 5469
5416 5470 /** Player chunk for dynamic lighting; null in editor / before spawn → no 3×3 limit. */
@@ -5510,6 +5564,45 @@ export class WorldView
5510 5564 return sources;
5511 5565 }
5512 5566
5567 /**
5568 * Lights for one chunk, memoized for a single shade pass.
5569 * Halo tiles in {@link #fillChunkLightGrids} often share the same chunk key.
5570 */
5571 #cachedLightsForChunk (chunkX, chunkY, mobileLights, blockLights, cache)
5572 {
5573 const key = `${chunkX},${chunkY}`;
5574 let lights = cache.get(key);
5575 if (!lights)
5576 {
5577 lights = this.#dynamicLightsForChunk(chunkX, chunkY, mobileLights, blockLights);
5578 cache.set(key, lights);
5579 }
5580 return lights;
5581 }
5582
5583 /**
5584 * Shade 0–1 from the chunk intensity grid (1 − lit). Same quantity
5585 * {@link #intensityAtTile} writes during lightmap fills — avoids a second
5586 * per-tile raycast pass after the grids are current.
5587 * @returns {number|null}
5588 */
5589 #shadeAlphaFromLightGrid (tileX, tileY)
5590 {
5591 const chunkX = Math.floor(tileX / CHUNK_SIZE);
5592 const chunkY = Math.floor(tileY / CHUNK_SIZE);
5593 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
5594 const grid = baked?.lightIntensityGrid;
5595 if (!grid?.length)
5596 { return null; }
5597 const localX = tileX - chunkX * CHUNK_SIZE;
5598 const localY = tileY - chunkY * CHUNK_SIZE;
5599 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
5600 { return null; }
5601 const gridW = CHUNK_SIZE + 2;
5602 const lit = grid[(localY + 1) * gridW + (localX + 1)] ?? 0;
5603 return Math.min(1, Math.max(0, 1 - lit));
5604 }
5605
5513 5606 #updateShade ()
5514 5607 {
5515 5608 const ambientDark = this.#ambientDarkness();
@@ -5582,23 +5675,30 @@ export class WorldView
5582 5675 });
5583 5676 }
5584 5677 const blockLights = this.#collectBlockLightsForShading();
5585
5586 5678 const lightOcclusion = makeSnapshotLightOcclusion(this.chunks);
5679 const lightsByChunk = new Map();
5587 5680
5588 for (const objects of this.tiles.values())
5589 {
5590 if (objects._inViewport === false)
5591 { continue; }
5592 const lights = this.#dynamicLightsForTile(objects.tileX, objects.tileY, mobileLights, blockLights);
5593 objects.shadeAlpha = this.#tileShadeAlpha(objects, lights, lightOcclusion, ambientDark);
5594 }
5595
5681 // Lightmaps first so intensity grids are filled (or kept on cache hit).
5596 5682 for (const baked of this.bakedChunks.values())
5597 5683 {
5598 5684 if (baked._inViewport === false)
5599 5685 { continue; }
5600 const lights = this.#dynamicLightsForChunk(baked.chunkX, baked.chunkY, mobileLights, blockLights);
5601 this.#writeChunkLightmap(baked, lights, mobileLights, blockLights, lightOcclusion, ambientDark);
5686 const lights = this.#cachedLightsForChunk(
5687 baked.chunkX,
5688 baked.chunkY,
5689 mobileLights,
5690 blockLights,
5691 lightsByChunk
5692 );
5693 this.#writeChunkLightmap(
5694 baked,
5695 lights,
5696 mobileLights,
5697 blockLights,
5698 lightOcclusion,
5699 ambientDark,
5700 lightsByChunk
5701 );
5602 5702 // Lightmap stores visible light (1 − shade); shader applies darkness = 1 − lit.
5603 5703 if (baked.groundObject?.renderer?.shaderUniforms)
5604 5704 {
@@ -5615,6 +5715,27 @@ export class WorldView
5615 5715 }
5616 5716 }
5617 5717
5718 // Per-tile shade from the same grids the lightmap used — no second raycast sweep.
5719 for (const objects of this.tiles.values())
5720 {
5721 if (objects._inViewport === false)
5722 { continue; }
5723 const fromGrid = this.#shadeAlphaFromLightGrid(objects.tileX, objects.tileY);
5724 if (fromGrid != null)
5725 { objects.shadeAlpha = fromGrid; }
5726 else
5727 {
5728 const lights = this.#cachedLightsForChunk(
5729 objects.chunkX,
5730 objects.chunkY,
5731 mobileLights,
5732 blockLights,
5733 lightsByChunk
5734 );
5735 objects.shadeAlpha = this.#tileShadeAlpha(objects, lights, lightOcclusion, ambientDark);
5736 }
5737 }
5738
5618 5739 const timeSec = now / 1000;
5619 5740 for (const objects of this.tiles.values())
5620 5741 {
@@ -5732,7 +5853,7 @@ export class WorldView
5732 5853 return blockLightOcclusionForBlock(snapshot.blocks?.[index]) === LightOcclusion.solid;
5733 5854 }
5734 5855
5735 #fillChunkLightGrids (baked, mobileLights, blockLights, lightOcclusion, ambientDark)
5856 #fillChunkLightGrids (baked, mobileLights, blockLights, lightOcclusion, ambientDark, lightsByChunk = null)
5736 5857 {
5737 5858 const gridW = CHUNK_SIZE + 2;
5738 5859 const gridSize = gridW * gridW;
@@ -5742,6 +5863,7 @@ export class WorldView
5742 5863 { baked.lightOccludeGrid = new Uint8Array(gridSize); }
5743 5864 const grid = baked.lightIntensityGrid;
5744 5865 const occlude = baked.lightOccludeGrid;
5866 const cache = lightsByChunk ?? new Map();
5745 5867 for (let ly = -1; ly <= CHUNK_SIZE; ly++)
5746 5868 {
5747 5869 for (let lx = -1; lx <= CHUNK_SIZE; lx++)
@@ -5751,7 +5873,13 @@ export class WorldView
5751 5873 const gi = (ly + 1) * gridW + (lx + 1);
5752 5874 // Halo tiles may sit in the other lighting region (3×3 vs outer). Resolve
5753 5875 // sources per tile so corner blends match the neighbour chunk's shading.
5754 const lights = this.#dynamicLightsForTile(tileX, tileY, mobileLights, blockLights);
5876 const lights = this.#cachedLightsForChunk(
5877 Math.floor(tileX / CHUNK_SIZE),
5878 Math.floor(tileY / CHUNK_SIZE),
5879 mobileLights,
5880 blockLights,
5881 cache
5882 );
5755 5883 grid[gi] = this.#intensityAtTile(tileX, tileY, lights, lightOcclusion, ambientDark);
5756 5884 occlude[gi] = this.#tileOccludesLight(tileX, tileY) ? 1 : 0;
5757 5885 }
@@ -5883,6 +6011,7 @@ export class WorldView
5883 6011 * through a wall to the far side. Diagonals only when both cardinals are clear.
5884 6012 * @param chunkLights Sources that affect this chunk (cache key + in-chunk samples).
5885 6013 * @param mobileLights / blockLights Full lists so the ±1 halo can sample across the 3×3 boundary.
6014 * @param lightsByChunk Optional per-pass memo of chunk → light list.
5886 6015 */
5887 6016 #writeChunkLightmap (
5888 6017 baked,
@@ -5890,7 +6019,8 @@ export class WorldView
5890 6019 mobileLights,
5891 6020 blockLights,
5892 6021 lightOcclusion,
5893 ambientDark = this.#ambientDarkness()
6022 ambientDark = this.#ambientDarkness(),
6023 lightsByChunk = null
5894 6024 )
5895 6025 {
5896 6026 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
@@ -5905,7 +6035,14 @@ export class WorldView
5905 6035 { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); }
5906 6036 const pixels = baked.lightmapPixels;
5907 6037
5908 this.#fillChunkLightGrids(baked, mobileLights, blockLights, lightOcclusion, ambientDark);
6038 this.#fillChunkLightGrids(
6039 baked,
6040 mobileLights,
6041 blockLights,
6042 lightOcclusion,
6043 ambientDark,
6044 lightsByChunk
6045 );
5909 6046 const simple = this.lightingMode === "simple";
5910 6047
5911 6048 for (let localY = 0; localY < CHUNK_SIZE; localY++)
@@ -5956,10 +6093,29 @@ export class WorldView
5956 6093 }
5957 6094 }
5958 6095 }
5959 const ctx = baked.lightmapCanvas.getContext("2d");
5960 ctx.putImageData(new ImageData(pixels, atlasPx, atlasPx), 0, 0);
5961 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
5962 this.#queueCanvasTextureWarm(baked.lightmapCanvas, baked.chunkX, baked.chunkY);
6096 // Keep canvas pixels in sync for Framework getTexture fallbacks, but upload
6097 // to GL via texSubImage2D when the texture already exists (no delete/recreate).
6098 if (!baked.lightmapImageData || baked.lightmapImageData.data !== pixels)
6099 { baked.lightmapImageData = new ImageData(pixels, atlasPx, atlasPx); }
6100 if (baked.lightmapUploadSize !== atlasPx)
6101 {
6102 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
6103 baked.lightmapUploadSize = atlasPx;
6104 }
6105 const gl = this.scene?.glContext?.gl;
6106 const created = uploadCanvasTextureRgba(
6107 this.scene,
6108 baked.lightmapCanvas,
6109 pixels,
6110 atlasPx,
6111 atlasPx,
6112 gl?.NEAREST ?? null
6113 );
6114 if (created)
6115 {
6116 const ctx = baked.lightmapCanvas.getContext("2d");
6117 ctx.putImageData(baked.lightmapImageData, 0, 0);
6118 }
5963 6119 baked.lightmapCacheKey = cacheKey;
5964 6120 }
5965 6121
@@ -24,7 +24,8 @@ import { createChunkAtlasCache } from "./chunkAtlasCache.js";
24import
24import
25{
25{
26 frameworkImageFromCanvas,
26 frameworkImageFromCanvas,
27 invalidateCanvasTexture
27 invalidateCanvasTexture,
28 uploadCanvasTextureRgba
28} from "./canvasSprite.js";
29} from "./canvasSprite.js";
29import { setNearestFilter } from "./sprites.js";
30import { setNearestFilter } from "./sprites.js";
30import { waterDebugUniforms, lavaDebugUniforms } from "../play/waterDebug.js";
31import { waterDebugUniforms, lavaDebugUniforms } from "../play/waterDebug.js";
@@ -1050,6 +1051,8 @@ export class WorldView
1050 #playerChunkY = null;
1051 #playerChunkY = null;
1051 #playerMoveChunkDx = 0;
1052 #playerMoveChunkDx = 0;
1052 #playerMoveChunkDy = 0;
1053 #playerMoveChunkDy = 0;
1054 /** Reused by {@link #placePivoted} to avoid per-call `new vector()`. */
1055 #placeSizeScratch = new vector(0, 0);
1053
1056
1054 constructor(game, scene, catalog = { grounds: {}, blocks: {} })
1057 constructor(game, scene, catalog = { grounds: {}, blocks: {} })
1055 {
1058 {
@@ -3184,11 +3187,7 @@ export class WorldView
3184 this.#setRendererVisible(objects.groundBloom, visible && this.bloomEnabled);
3187 this.#setRendererVisible(objects.groundBloom, visible && this.bloomEnabled);
3185 this.#setRendererVisible(objects.block, visible);
3188 this.#setRendererVisible(objects.block, visible);
3186 this.#setRendererVisible(objects.blockBloom, visible && this.bloomEnabled);
3189 this.#setRendererVisible(objects.blockBloom, visible && this.bloomEnabled);
3187 if (objects.waterEdges)
3190 this.#setRendererVisible(objects.lavaBloom, visible && this.bloomEnabled);
3188 {
3189 for (const edge of Object.values(objects.waterEdges))
3190 { this.#setRendererVisible(edge, visible); }
3191 }
3192 }
3191 }
3193 }
3192 }
3194
3193
@@ -3566,9 +3565,69 @@ export class WorldView
3566 object._lit = false;
3565 object._lit = false;
3567 object.renderer.shader = null;
3566 object.renderer.shader = null;
3568 object.renderer.shaderUniforms = null;
3567 object.renderer.shaderUniforms = null;
3568 object.renderer._shaderUniformKind = null;
3569 object.renderer.secondaryMap = null;
3569 object.renderer.secondaryMap = null;
3570 }
3570 }
3571
3571
3572 #ensureUniformBag (renderer, shader, kind)
3573 {
3574 renderer.shader = shader;
3575 if (!renderer.shaderUniforms || renderer._shaderUniformKind !== kind)
3576 {
3577 renderer.shaderUniforms = {};
3578 renderer._shaderUniformKind = kind;
3579 }
3580 return renderer.shaderUniforms;
3581 }
3582
3583 #writeUniformVec3 (uniforms, key, src)
3584 {
3585 let arr = uniforms[key];
3586 if (!Array.isArray(arr) || arr.length !== 3)
3587 {
3588 arr = [0, 0, 0];
3589 uniforms[key] = arr;
3590 }
3591 if (Array.isArray(src))
3592 {
3593 arr[0] = src[0];
3594 arr[1] = src[1];
3595 arr[2] = src[2];
3596 }
3597 else
3598 {
3599 arr[0] = src.r;
3600 arr[1] = src.g;
3601 arr[2] = src.b;
3602 }
3603 }
3604
3605 #writeUniformVec2 (uniforms, key, a, b)
3606 {
3607 let arr = uniforms[key];
3608 if (!Array.isArray(arr) || arr.length !== 2)
3609 {
3610 arr = [0, 0];
3611 uniforms[key] = arr;
3612 }
3613 arr[0] = a;
3614 arr[1] = b;
3615 }
3616
3617 #writeUniformVec4 (uniforms, key, a, b, c, d)
3618 {
3619 let arr = uniforms[key];
3620 if (!Array.isArray(arr) || arr.length !== 4)
3621 {
3622 arr = [0, 0, 0, 0];
3623 uniforms[key] = arr;
3624 }
3625 arr[0] = a;
3626 arr[1] = b;
3627 arr[2] = c;
3628 arr[3] = d;
3629 }
3630
3572 /** Bloom / unlit overlays that still need magenta channel tint (e.g. elemental sprites). */
3631 /** Bloom / unlit overlays that still need magenta channel tint (e.g. elemental sprites). */
3573 #syncUnlitTintSprite (object, tintColor)
3632 #syncUnlitTintSprite (object, tintColor)
3574 {
3633 {
@@ -3576,16 +3635,14 @@ export class WorldView
3576 { return; }
3635 { return; }
3577 const tint = normalizeRgb(tintColor);
3636 const tint = normalizeRgb(tintColor);
3578 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
3637 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
3579 object.renderer.shader = getTintLitSpriteShader();
3638 const uniforms = this.#ensureUniformBag(object.renderer, getTintLitSpriteShader(), "unlitTint");
3580 object.renderer.shaderUniforms = {
3639 uniforms.u_darkness = 0;
3581 u_darkness: 0,
3640 uniforms.u_strength = 0;
3582 u_strength: 0,
3641 this.#writeUniformVec3(uniforms, "u_flashColor", FLASH_COLOR_DAMAGE);
3583 u_flashColor: FLASH_COLOR_DAMAGE,
3642 uniforms.u_wade = 0;
3584 u_wade: 0,
3643 uniforms.u_spriteHeight = height;
3585 u_spriteHeight: height,
3644 uniforms.u_useTint = 1;
3586 u_useTint: 1,
3645 this.#writeUniformVec3(uniforms, "u_tintColor", tint);
3587 u_tintColor: [tint.r, tint.g, tint.b]
3588 };
3589 object.renderer.secondaryMap = null;
3646 object.renderer.secondaryMap = null;
3590 }
3647 }
3591
3648
@@ -3601,27 +3658,23 @@ export class WorldView
3601 const tint = tintColor ? normalizeRgb(tintColor) : null;
3658 const tint = tintColor ? normalizeRgb(tintColor) : null;
3602 if (tint)
3659 if (tint)
3603 {
3660 {
3604 object.renderer.shader = getTintLitSpriteShader();
3661 const uniforms = this.#ensureUniformBag(object.renderer, getTintLitSpriteShader(), "tintLit");
3605 object.renderer.shaderUniforms = {
3662 uniforms.u_darkness = dark;
3606 u_darkness: dark,
3663 uniforms.u_strength = flash;
3607 u_strength: flash,
3664 this.#writeUniformVec3(uniforms, "u_flashColor", flashRgb);
3608 u_flashColor: flashRgb,
3665 uniforms.u_wade = wade ? 1 : 0;
3609 u_wade: wade ? 1 : 0,
3666 uniforms.u_spriteHeight = height;
3610 u_spriteHeight: height,
3667 uniforms.u_useTint = 1;
3611 u_useTint: 1,
3668 this.#writeUniformVec3(uniforms, "u_tintColor", tint);
3612 u_tintColor: [tint.r, tint.g, tint.b]
3613 };
3614 }
3669 }
3615 else
3670 else
3616 {
3671 {
3617 object.renderer.shader = getSpriteLightingShader();
3672 const uniforms = this.#ensureUniformBag(object.renderer, getSpriteLightingShader(), "lit");
3618 object.renderer.shaderUniforms = {
3673 uniforms.u_darkness = dark;
3619 u_darkness: dark,
3674 uniforms.u_strength = flash;
3620 u_strength: flash,
3675 this.#writeUniformVec3(uniforms, "u_flashColor", flashRgb);
3621 u_flashColor: flashRgb,
3676 uniforms.u_wade = wade ? 1 : 0;
3622 u_wade: wade ? 1 : 0,
3677 uniforms.u_spriteHeight = height;
3623 u_spriteHeight: height
3624 };
3625 }
3678 }
3626 object.renderer.secondaryMap = null;
3679 object.renderer.secondaryMap = null;
3627 }
3680 }
@@ -3631,7 +3684,7 @@ export class WorldView
3631 return entity?.object?.renderer?.sprite?.g_image ?? null;
3684 return entity?.object?.renderer?.sprite?.g_image ?? null;
3632 }
3685 }
3633
3686
3634 #tightFitMaskUniforms (overlay, entity)
3687 #tightFitMaskUniforms (overlay, entity, into = null)
3635 {
3688 {
3636 const bodyRenderer = entity?.object?.renderer;
3689 const bodyRenderer = entity?.object?.renderer;
3637 const clothRenderer = overlay?.renderer;
3690 const clothRenderer = overlay?.renderer;
@@ -3643,13 +3696,13 @@ export class WorldView
3643 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
3696 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
3644 const bodyUv = bodySprite.getUvRect?.(bodyRenderer.subImage | 0)
3697 const bodyUv = bodySprite.getUvRect?.(bodyRenderer.subImage | 0)
3645 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
3698 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
3646 return {
3699 const uniforms = into ?? {};
3647 u_clothSize: [clothSprite.width || SPRITE_SIZE_PX, clothSprite.height || SPRITE_SIZE_PX],
3700 this.#writeUniformVec2(uniforms, "u_clothSize", clothSprite.width || SPRITE_SIZE_PX, clothSprite.height || SPRITE_SIZE_PX);
3648 u_bodySize: [bodySprite.width || SPRITE_SIZE_PX, bodySprite.height || SPRITE_SIZE_PX],
3701 this.#writeUniformVec2(uniforms, "u_bodySize", bodySprite.width || SPRITE_SIZE_PX, bodySprite.height || SPRITE_SIZE_PX);
3649 u_pivotFromBottom: PIVOT_FROM_BOTTOM_PX,
3702 uniforms.u_pivotFromBottom = PIVOT_FROM_BOTTOM_PX;
3650 u_clothUvRect: [clothUv.u0, clothUv.v0, clothUv.u1, clothUv.v1],
3703 this.#writeUniformVec4(uniforms, "u_clothUvRect", clothUv.u0, clothUv.v0, clothUv.u1, clothUv.v1);
3651 u_bodyUvRect: [bodyUv.u0, bodyUv.v0, bodyUv.u1, bodyUv.v1]
3704 this.#writeUniformVec4(uniforms, "u_bodyUvRect", bodyUv.u0, bodyUv.v0, bodyUv.u1, bodyUv.v1);
3652 };
3705 return uniforms;
3653 }
3706 }
3654
3707
3655 #syncTightFitLitSprite (overlay, entity, darkness, flashStrength = 0, wade = false, tintColor = null, flashColor = null)
3708 #syncTightFitLitSprite (overlay, entity, darkness, flashStrength = 0, wade = false, tintColor = null, flashColor = null)
@@ -3657,9 +3710,8 @@ export class WorldView
3657 if (!overlay?.renderer || entity?.object?.renderer == null)
3710 if (!overlay?.renderer || entity?.object?.renderer == null)
3658 { return; }
3711 { return; }
3659 const bodyMap = this.#bodySecondaryMap(entity);
3712 const bodyMap = this.#bodySecondaryMap(entity);
3660 const maskUniforms = this.#tightFitMaskUniforms(overlay, entity);
3661 const flashRgb = flashColor ?? FLASH_COLOR_DAMAGE;
3713 const flashRgb = flashColor ?? FLASH_COLOR_DAMAGE;
3662 if (!bodyMap || !maskUniforms)
3714 if (!bodyMap)
3663 {
3715 {
3664 this.#syncLitSprite(overlay, darkness, flashStrength, wade, tintColor, flashRgb);
3716 this.#syncLitSprite(overlay, darkness, flashStrength, wade, tintColor, flashRgb);
3665 return;
3717 return;
@@ -3670,31 +3722,23 @@ export class WorldView
3670 const height = overlay.renderer.sprite?.height ?? SPRITE_SIZE_PX;
3722 const height = overlay.renderer.sprite?.height ?? SPRITE_SIZE_PX;
3671 const tint = tintColor ? normalizeRgb(tintColor) : null;
3723 const tint = tintColor ? normalizeRgb(tintColor) : null;
3672 overlay.renderer.secondaryMap = bodyMap;
3724 overlay.renderer.secondaryMap = bodyMap;
3673 if (tint)
3725 const kind = tint ? "tightFitTint" : "tightFit";
3726 const shader = tint ? getTightFitTintLitSpriteShader() : getTightFitLitSpriteShader();
3727 const uniforms = this.#ensureUniformBag(overlay.renderer, shader, kind);
3728 if (!this.#tightFitMaskUniforms(overlay, entity, uniforms))
3674 {
3729 {
3675 overlay.renderer.shader = getTightFitTintLitSpriteShader();
3730 this.#syncLitSprite(overlay, darkness, flashStrength, wade, tintColor, flashRgb);
3676 overlay.renderer.shaderUniforms = {
3731 return;
3677 u_darkness: dark,
3678 u_strength: flash,
3679 u_flashColor: flashRgb,
3680 u_wade: wade ? 1 : 0,
3681 u_spriteHeight: height,
3682 u_useTint: 1,
3683 u_tintColor: [tint.r, tint.g, tint.b],
3684 ...maskUniforms
3685 };
3686 }
3732 }
3687 else
3733 uniforms.u_darkness = dark;
3734 uniforms.u_strength = flash;
3735 this.#writeUniformVec3(uniforms, "u_flashColor", flashRgb);
3736 uniforms.u_wade = wade ? 1 : 0;
3737 uniforms.u_spriteHeight = height;
3738 if (tint)
3688 {
3739 {
3689 overlay.renderer.shader = getTightFitLitSpriteShader();
3740 uniforms.u_useTint = 1;
3690 overlay.renderer.shaderUniforms = {
3741 this.#writeUniformVec3(uniforms, "u_tintColor", tint);
3691 u_darkness: dark,
3692 u_strength: flash,
3693 u_flashColor: flashRgb,
3694 u_wade: wade ? 1 : 0,
3695 u_spriteHeight: height,
3696 ...maskUniforms
3697 };
3698 }
3742 }
3699 }
3743 }
3700
3744
@@ -3712,18 +3756,16 @@ export class WorldView
3712 { object._lit = true; }
3756 { object._lit = true; }
3713 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
3757 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
3714 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
3758 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
3715 object.renderer.shader = getDualTintLitSpriteShader();
3759 const uniforms = this.#ensureUniformBag(object.renderer, getDualTintLitSpriteShader(), "dualTint");
3716 object.renderer.shaderUniforms = {
3760 uniforms.u_darkness = dark;
3717 u_darkness: dark,
3761 uniforms.u_strength = flash;
3718 u_strength: flash,
3762 this.#writeUniformVec3(uniforms, "u_flashColor", flashColor ?? FLASH_COLOR_DAMAGE);
3719 u_flashColor: flashColor ?? FLASH_COLOR_DAMAGE,
3763 uniforms.u_wade = wade ? 1 : 0;
3720 u_wade: wade ? 1 : 0,
3764 uniforms.u_spriteHeight = height;
3721 u_spriteHeight: height,
3765 this.#writeUniformVec3(uniforms, "u_shaftTint", shaft);
3722 u_shaftTint: [shaft.r, shaft.g, shaft.b],
3766 this.#writeUniformVec3(uniforms, "u_tipTint", tip);
3723 u_tipTint: [tip.r, tip.g, tip.b],
3767 this.#writeUniformVec3(uniforms, "u_coatTint", coat ?? { r: 0, g: 0, b: 0 });
3724 u_coatTint: coat ? [coat.r, coat.g, coat.b] : [0, 0, 0],
3768 uniforms.u_hasCoat = coat ? 1 : 0;
3725 u_hasCoat: coat ? 1 : 0
3726 };
3727 object.renderer.secondaryMap = null;
3769 object.renderer.secondaryMap = null;
3728 }
3770 }
3729
3771
@@ -3949,45 +3991,43 @@ export class WorldView
3949 const dSW = deepCorners?.sw ?? 0;
3991 const dSW = deepCorners?.sw ?? 0;
3950 const dSE = deepCorners?.se ?? 0;
3992 const dSE = deepCorners?.se ?? 0;
3951 object._lit = true;
3993 object._lit = true;
3952 object.renderer.shader = getWaterGroundShader();
3953 // Shallow + deep share one noise atlas so texAmp seams don't hard-cut at depth edges.
3994 // Shallow + deep share one noise atlas so texAmp seams don't hard-cut at depth edges.
3954 const sharedNoise = this.game.images[spriteImageName("ground", "water", "water")];
3995 const sharedNoise = this.game.images[spriteImageName("ground", "water", "water")];
3955 if (sharedNoise)
3996 if (sharedNoise)
3956 { object.renderer.sprite = sharedNoise; }
3997 { object.renderer.sprite = sharedNoise; }
3957 object.renderer.secondaryMap = shoreSprite?.g_image ?? null;
3998 object.renderer.secondaryMap = shoreSprite?.g_image ?? null;
3958 object.renderer.shaderUniforms = {
3999 const uniforms = this.#ensureUniformBag(object.renderer, getWaterGroundShader(), "water");
3959 u_ambientDark: dark,
4000 uniforms.u_ambientDark = dark;
3960 u_litNW: lit.nw,
4001 uniforms.u_litNW = lit.nw;
3961 u_litNE: lit.ne,
4002 uniforms.u_litNE = lit.ne;
3962 u_litSW: lit.sw,
4003 uniforms.u_litSW = lit.sw;
3963 u_litSE: lit.se,
4004 uniforms.u_litSE = lit.se;
3964 u_time: timeSec,
4005 uniforms.u_time = timeSec;
3965 u_tileX: tileX | 0,
4006 uniforms.u_tileX = tileX | 0;
3966 u_tileY: tileY | 0,
4007 uniforms.u_tileY = tileY | 0;
3967 u_deepNW: dNW,
4008 uniforms.u_deepNW = dNW;
3968 u_deepNE: dNE,
4009 uniforms.u_deepNE = dNE;
3969 u_deepSW: dSW,
4010 uniforms.u_deepSW = dSW;
3970 u_deepSE: dSE,
4011 uniforms.u_deepSE = dSE;
3971 u_edgeN: edges?.n ?? 0,
4012 uniforms.u_edgeN = edges?.n ?? 0;
3972 u_edgeE: edges?.e ?? 0,
4013 uniforms.u_edgeE = edges?.e ?? 0;
3973 u_edgeS: edges?.s ?? 0,
4014 uniforms.u_edgeS = edges?.s ?? 0;
3974 u_edgeW: edges?.w ?? 0,
4015 uniforms.u_edgeW = edges?.w ?? 0;
3975 u_edgeNE: edges?.ne ?? 0,
4016 uniforms.u_edgeNE = edges?.ne ?? 0;
3976 u_edgeNW: edges?.nw ?? 0,
4017 uniforms.u_edgeNW = edges?.nw ?? 0;
3977 u_edgeSE: edges?.se ?? 0,
4018 uniforms.u_edgeSE = edges?.se ?? 0;
3978 u_edgeSW: edges?.sw ?? 0,
4019 uniforms.u_edgeSW = edges?.sw ?? 0;
3979 u_hasShore: shoreSprite ? 1 : 0,
4020 uniforms.u_hasShore = shoreSprite ? 1 : 0;
3980 u_shoreEdgeN: shore?.edgeN ?? 0,
4021 uniforms.u_shoreEdgeN = shore?.edgeN ?? 0;
3981 u_shoreEdgeE: shore?.edgeE ?? 0,
4022 uniforms.u_shoreEdgeE = shore?.edgeE ?? 0;
3982 u_shoreEdgeS: shore?.edgeS ?? 0,
4023 uniforms.u_shoreEdgeS = shore?.edgeS ?? 0;
3983 u_shoreEdgeW: shore?.edgeW ?? 0,
4024 uniforms.u_shoreEdgeW = shore?.edgeW ?? 0;
3984 u_shoreEdgeNE: shore?.edgeNE ?? 0,
4025 uniforms.u_shoreEdgeNE = shore?.edgeNE ?? 0;
3985 u_shoreEdgeNW: shore?.edgeNW ?? 0,
4026 uniforms.u_shoreEdgeNW = shore?.edgeNW ?? 0;
3986 u_shoreEdgeSE: shore?.edgeSE ?? 0,
4027 uniforms.u_shoreEdgeSE = shore?.edgeSE ?? 0;
3987 u_shoreEdgeSW: shore?.edgeSW ?? 0,
4028 uniforms.u_shoreEdgeSW = shore?.edgeSW ?? 0;
3988 u_shoreUvRect: [shoreUv.u0, shoreUv.v0, shoreUv.u1, shoreUv.v1],
4029 this.#writeUniformVec4(uniforms, "u_shoreUvRect", shoreUv.u0, shoreUv.v0, shoreUv.u1, shoreUv.v1);
3989 ...waterDebugUniforms()
4030 Object.assign(uniforms, waterDebugUniforms());
3990 };
3991 }
4031 }
3992
4032
3993 /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. Lava is procedural heat. */
4033 /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. Lava is procedural heat. */
@@ -4167,37 +4207,35 @@ export class WorldView
4167 const shoreUv = shoreSprite?.getUvRect?.(0)
4207 const shoreUv = shoreSprite?.getUvRect?.(0)
4168 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
4208 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
4169 object._lit = true;
4209 object._lit = true;
4170 object.renderer.shader = getLavaGroundShader();
4171 object.renderer.secondaryMap = shoreSprite?.g_image ?? null;
4210 object.renderer.secondaryMap = shoreSprite?.g_image ?? null;
4172 object.renderer.shaderUniforms = {
4211 const uniforms = this.#ensureUniformBag(object.renderer, getLavaGroundShader(), "lava");
4173 u_ambientDark: dark,
4212 uniforms.u_ambientDark = dark;
4174 u_litNW: lit.nw,
4213 uniforms.u_litNW = lit.nw;
4175 u_litNE: lit.ne,
4214 uniforms.u_litNE = lit.ne;
4176 u_litSW: lit.sw,
4215 uniforms.u_litSW = lit.sw;
4177 u_litSE: lit.se,
4216 uniforms.u_litSE = lit.se;
4178 u_time: timeSec,
4217 uniforms.u_time = timeSec;
4179 u_tileX: tileX | 0,
4218 uniforms.u_tileX = tileX | 0;
4180 u_tileY: tileY | 0,
4219 uniforms.u_tileY = tileY | 0;
4181 u_edgeN: edges?.n ?? 0,
4220 uniforms.u_edgeN = edges?.n ?? 0;
4182 u_edgeE: edges?.e ?? 0,
4221 uniforms.u_edgeE = edges?.e ?? 0;
4183 u_edgeS: edges?.s ?? 0,
4222 uniforms.u_edgeS = edges?.s ?? 0;
4184 u_edgeW: edges?.w ?? 0,
4223 uniforms.u_edgeW = edges?.w ?? 0;
4185 u_edgeNE: edges?.ne ?? 0,
4224 uniforms.u_edgeNE = edges?.ne ?? 0;
4186 u_edgeNW: edges?.nw ?? 0,
4225 uniforms.u_edgeNW = edges?.nw ?? 0;
4187 u_edgeSE: edges?.se ?? 0,
4226 uniforms.u_edgeSE = edges?.se ?? 0;
4188 u_edgeSW: edges?.sw ?? 0,
4227 uniforms.u_edgeSW = edges?.sw ?? 0;
4189 u_hasShore: shoreSprite ? 1 : 0,
4228 uniforms.u_hasShore = shoreSprite ? 1 : 0;
4190 u_shoreEdgeN: shore?.edgeN ?? 0,
4229 uniforms.u_shoreEdgeN = shore?.edgeN ?? 0;
4191 u_shoreEdgeE: shore?.edgeE ?? 0,
4230 uniforms.u_shoreEdgeE = shore?.edgeE ?? 0;
4192 u_shoreEdgeS: shore?.edgeS ?? 0,
4231 uniforms.u_shoreEdgeS = shore?.edgeS ?? 0;
4193 u_shoreEdgeW: shore?.edgeW ?? 0,
4232 uniforms.u_shoreEdgeW = shore?.edgeW ?? 0;
4194 u_shoreEdgeNE: shore?.edgeNE ?? 0,
4233 uniforms.u_shoreEdgeNE = shore?.edgeNE ?? 0;
4195 u_shoreEdgeNW: shore?.edgeNW ?? 0,
4234 uniforms.u_shoreEdgeNW = shore?.edgeNW ?? 0;
4196 u_shoreEdgeSE: shore?.edgeSE ?? 0,
4235 uniforms.u_shoreEdgeSE = shore?.edgeSE ?? 0;
4197 u_shoreEdgeSW: shore?.edgeSW ?? 0,
4236 uniforms.u_shoreEdgeSW = shore?.edgeSW ?? 0;
4198 u_shoreUvRect: [shoreUv.u0, shoreUv.v0, shoreUv.u1, shoreUv.v1],
4237 this.#writeUniformVec4(uniforms, "u_shoreUvRect", shoreUv.u0, shoreUv.v0, shoreUv.u1, shoreUv.v1);
4199 ...lavaDebugUniforms()
4238 Object.assign(uniforms, lavaDebugUniforms());
4200 };
4201 }
4239 }
4202
4240
4203 #syncLavaBloomSprite (object, {
4241 #syncLavaBloomSprite (object, {
@@ -4209,21 +4247,19 @@ export class WorldView
4209 {
4247 {
4210 if (!object?.renderer)
4248 if (!object?.renderer)
4211 { return; }
4249 { return; }
4212 object.renderer.shader = getLavaBloomShader();
4250 const uniforms = this.#ensureUniformBag(object.renderer, getLavaBloomShader(), "lavaBloom");
4213 object.renderer.shaderUniforms = {
4251 uniforms.u_time = timeSec;
4214 u_time: timeSec,
4252 uniforms.u_tileX = tileX | 0;
4215 u_tileX: tileX | 0,
4253 uniforms.u_tileY = tileY | 0;
4216 u_tileY: tileY | 0,
4254 uniforms.u_edgeN = edges?.n ?? 0;
4217 u_edgeN: edges?.n ?? 0,
4255 uniforms.u_edgeE = edges?.e ?? 0;
4218 u_edgeE: edges?.e ?? 0,
4256 uniforms.u_edgeS = edges?.s ?? 0;
4219 u_edgeS: edges?.s ?? 0,
4257 uniforms.u_edgeW = edges?.w ?? 0;
4220 u_edgeW: edges?.w ?? 0,
4258 uniforms.u_edgeNE = edges?.ne ?? 0;
4221 u_edgeNE: edges?.ne ?? 0,
4259 uniforms.u_edgeNW = edges?.nw ?? 0;
4222 u_edgeNW: edges?.nw ?? 0,
4260 uniforms.u_edgeSE = edges?.se ?? 0;
4223 u_edgeSE: edges?.se ?? 0,
4261 uniforms.u_edgeSW = edges?.sw ?? 0;
4224 u_edgeSW: edges?.sw ?? 0,
4262 Object.assign(uniforms, lavaDebugUniforms());
4225 ...lavaDebugUniforms()
4226 };
4227 }
4263 }
4228
4264
4229 #ambientDarkness ()
4265 #ambientDarkness ()
@@ -5045,13 +5081,11 @@ export class WorldView
5045 { return; }
5081 { return; }
5046 object._lit = true;
5082 object._lit = true;
5047 const dark = Math.min(1, Math.max(0, darkness ?? 0));
5083 const dark = Math.min(1, Math.max(0, darkness ?? 0));
5048 object.renderer.shader = getCliffGroundTopShader();
5049 object.renderer.bumpMap = groundImage ?? null;
5084 object.renderer.bumpMap = groundImage ?? null;
5050 object.renderer.secondaryMap = null;
5085 object.renderer.secondaryMap = null;
5051 object.renderer.shaderUniforms = {
5086 const uniforms = this.#ensureUniformBag(object.renderer, getCliffGroundTopShader(), "cliffTop");
5052 u_darkness: dark,
5087 uniforms.u_darkness = dark;
5053 u_tileLocal: [localX, localY]
5088 this.#writeUniformVec2(uniforms, "u_tileLocal", localX, localY);
5054 };
5055 }
5089 }
5056
5090
5057 #layoutBakedChunk (snapshot)
5091 #layoutBakedChunk (snapshot)
@@ -5211,7 +5245,7 @@ export class WorldView
5211 const blockDef = blockDefinition(blockEntry?.typeId);
5245 const blockDef = blockDefinition(blockEntry?.typeId);
5212 const blockSort = blockDef?.door
5246 const blockSort = blockDef?.door
5213 ? doorSortSubOrder(blockEntry?.state, SORT_ENTITY)
5247 ? doorSortSubOrder(blockEntry?.state, SORT_ENTITY)
5214 : SORT_ENTITY;
5248 : SORT_BLOCK;
5215 objects.block = this.#ensureSprite(objects.block, tileBlock.sprite, blockSort);
5249 objects.block = this.#ensureSprite(objects.block, tileBlock.sprite, blockSort);
5216 objects.blockSort = blockSort;
5250 objects.blockSort = blockSort;
5217 objects.cliffGroundTop = !!blockDef?.cliffGroundTop;
5251 objects.cliffGroundTop = !!blockDef?.cliffGroundTop;
@@ -5270,11 +5304,29 @@ export class WorldView
5270 const zoom = this.zoom;
5304 const zoom = this.zoom;
5271 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
5305 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
5272 const factor = Math.max(0.1, Number(scale) || 1);
5306 const factor = Math.max(0.1, Number(scale) || 1);
5307 const w = draw.w * factor;
5308 const h = draw.h * factor;
5273 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height * factor, zoom);
5309 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height * factor, zoom);
5310 const layer = this.#depthLayer(sortY, subOrder, flight);
5311 if (
5312 object._placeX === center.x
5313 && object._placeY === center.y
5314 && object._placeW === w
5315 && object._placeH === h
5316 && object.layer === layer
5317 )
5318 { return; }
5319 object._placeX = center.x;
5320 object._placeY = center.y;
5321 object._placeW = w;
5322 object._placeH = h;
5274 object.transform.position.x = center.x;
5323 object.transform.position.x = center.x;
5275 object.transform.position.y = center.y;
5324 object.transform.position.y = center.y;
5276 object.transform.size = new vector(draw.w * factor, draw.h * factor);
5325 const size = this.#placeSizeScratch;
5277 this.#setLayer(object, this.#depthLayer(sortY, subOrder, flight));
5326 size.x = w;
5327 size.y = h;
5328 object.transform.size = size;
5329 this.#setLayer(object, layer);
5278 }
5330 }
5279
5331
5280 #ensureSprite (existing, name, layer)
5332 #ensureSprite (existing, name, layer)
@@ -5399,18 +5451,20 @@ export class WorldView
5399 return fromAlpha + (toAlpha - fromAlpha) * t;
5451 return fromAlpha + (toAlpha - fromAlpha) * t;
5400 }
5452 }
5401
5453
5402 /** A layer write costs the scene a full re-sort, so only write real changes. */
5454 /** Layer writes notify the scene; avoid redundant full-sort flags. */
5403 #setLayer (object, layer)
5455 #setLayer (object, layer)
5404 {
5456 {
5405 if (!object || object.layer === layer)
5457 if (!object || object.layer === layer)
5406 { return; }
5458 { return; }
5407 object.layer = layer;
5459 object.layer = layer;
5408 this.#markSortDirty();
5409 }
5460 }
5410
5461
5411 #markSortDirty ()
5462 #markSortDirty ()
5412 {
5463 {
5413 this.scene._sortDirty = true;
5464 if (typeof this.scene?.markSortDirty === "function")
5465 { this.scene.markSortDirty(); }
5466 else
5467 { this.scene._sortDirty = true; }
5414 }
5468 }
5415
5469
5416 /** Player chunk for dynamic lighting; null in editor / before spawn → no 3×3 limit. */
5470 /** Player chunk for dynamic lighting; null in editor / before spawn → no 3×3 limit. */
@@ -5510,6 +5564,45 @@ export class WorldView
5510 return sources;
5564 return sources;
5511 }
5565 }
5512
5566
5567 /**
5568 * Lights for one chunk, memoized for a single shade pass.
5569 * Halo tiles in {@link #fillChunkLightGrids} often share the same chunk key.
5570 */
5571 #cachedLightsForChunk (chunkX, chunkY, mobileLights, blockLights, cache)
5572 {
5573 const key = `${chunkX},${chunkY}`;
5574 let lights = cache.get(key);
5575 if (!lights)
5576 {
5577 lights = this.#dynamicLightsForChunk(chunkX, chunkY, mobileLights, blockLights);
5578 cache.set(key, lights);
5579 }
5580 return lights;
5581 }
5582
5583 /**
5584 * Shade 0–1 from the chunk intensity grid (1 − lit). Same quantity
5585 * {@link #intensityAtTile} writes during lightmap fills — avoids a second
5586 * per-tile raycast pass after the grids are current.
5587 * @returns {number|null}
5588 */
5589 #shadeAlphaFromLightGrid (tileX, tileY)
5590 {
5591 const chunkX = Math.floor(tileX / CHUNK_SIZE);
5592 const chunkY = Math.floor(tileY / CHUNK_SIZE);
5593 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
5594 const grid = baked?.lightIntensityGrid;
5595 if (!grid?.length)
5596 { return null; }
5597 const localX = tileX - chunkX * CHUNK_SIZE;
5598 const localY = tileY - chunkY * CHUNK_SIZE;
5599 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
5600 { return null; }
5601 const gridW = CHUNK_SIZE + 2;
5602 const lit = grid[(localY + 1) * gridW + (localX + 1)] ?? 0;
5603 return Math.min(1, Math.max(0, 1 - lit));
5604 }
5605
5513 #updateShade ()
5606 #updateShade ()
5514 {
5607 {
5515 const ambientDark = this.#ambientDarkness();
5608 const ambientDark = this.#ambientDarkness();
@@ -5582,23 +5675,30 @@ export class WorldView
5582 });
5675 });
5583 }
5676 }
5584 const blockLights = this.#collectBlockLightsForShading();
5677 const blockLights = this.#collectBlockLightsForShading();
5585
5586 const lightOcclusion = makeSnapshotLightOcclusion(this.chunks);
5678 const lightOcclusion = makeSnapshotLightOcclusion(this.chunks);
5679 const lightsByChunk = new Map();
5587
5680
5588 for (const objects of this.tiles.values())
5681 // Lightmaps first so intensity grids are filled (or kept on cache hit).
5589 {
5590 if (objects._inViewport === false)
5591 { continue; }
5592 const lights = this.#dynamicLightsForTile(objects.tileX, objects.tileY, mobileLights, blockLights);
5593 objects.shadeAlpha = this.#tileShadeAlpha(objects, lights, lightOcclusion, ambientDark);
5594 }
5595
5596 for (const baked of this.bakedChunks.values())
5682 for (const baked of this.bakedChunks.values())
5597 {
5683 {
5598 if (baked._inViewport === false)
5684 if (baked._inViewport === false)
5599 { continue; }
5685 { continue; }
5600 const lights = this.#dynamicLightsForChunk(baked.chunkX, baked.chunkY, mobileLights, blockLights);
5686 const lights = this.#cachedLightsForChunk(
5601 this.#writeChunkLightmap(baked, lights, mobileLights, blockLights, lightOcclusion, ambientDark);
5687 baked.chunkX,
5688 baked.chunkY,
5689 mobileLights,
5690 blockLights,
5691 lightsByChunk
5692 );
5693 this.#writeChunkLightmap(
5694 baked,
5695 lights,
5696 mobileLights,
5697 blockLights,
5698 lightOcclusion,
5699 ambientDark,
5700 lightsByChunk
5701 );
5602 // Lightmap stores visible light (1 − shade); shader applies darkness = 1 − lit.
5702 // Lightmap stores visible light (1 − shade); shader applies darkness = 1 − lit.
5603 if (baked.groundObject?.renderer?.shaderUniforms)
5703 if (baked.groundObject?.renderer?.shaderUniforms)
5604 {
5704 {
@@ -5615,6 +5715,27 @@ export class WorldView
5615 }
5715 }
5616 }
5716 }
5617
5717
5718 // Per-tile shade from the same grids the lightmap used — no second raycast sweep.
5719 for (const objects of this.tiles.values())
5720 {
5721 if (objects._inViewport === false)
5722 { continue; }
5723 const fromGrid = this.#shadeAlphaFromLightGrid(objects.tileX, objects.tileY);
5724 if (fromGrid != null)
5725 { objects.shadeAlpha = fromGrid; }
5726 else
5727 {
5728 const lights = this.#cachedLightsForChunk(
5729 objects.chunkX,
5730 objects.chunkY,
5731 mobileLights,
5732 blockLights,
5733 lightsByChunk
5734 );
5735 objects.shadeAlpha = this.#tileShadeAlpha(objects, lights, lightOcclusion, ambientDark);
5736 }
5737 }
5738
5618 const timeSec = now / 1000;
5739 const timeSec = now / 1000;
5619 for (const objects of this.tiles.values())
5740 for (const objects of this.tiles.values())
5620 {
5741 {
@@ -5732,7 +5853,7 @@ export class WorldView
5732 return blockLightOcclusionForBlock(snapshot.blocks?.[index]) === LightOcclusion.solid;
5853 return blockLightOcclusionForBlock(snapshot.blocks?.[index]) === LightOcclusion.solid;
5733 }
5854 }
5734
5855
5735 #fillChunkLightGrids (baked, mobileLights, blockLights, lightOcclusion, ambientDark)
5856 #fillChunkLightGrids (baked, mobileLights, blockLights, lightOcclusion, ambientDark, lightsByChunk = null)
5736 {
5857 {
5737 const gridW = CHUNK_SIZE + 2;
5858 const gridW = CHUNK_SIZE + 2;
5738 const gridSize = gridW * gridW;
5859 const gridSize = gridW * gridW;
@@ -5742,6 +5863,7 @@ export class WorldView
5742 { baked.lightOccludeGrid = new Uint8Array(gridSize); }
5863 { baked.lightOccludeGrid = new Uint8Array(gridSize); }
5743 const grid = baked.lightIntensityGrid;
5864 const grid = baked.lightIntensityGrid;
5744 const occlude = baked.lightOccludeGrid;
5865 const occlude = baked.lightOccludeGrid;
5866 const cache = lightsByChunk ?? new Map();
5745 for (let ly = -1; ly <= CHUNK_SIZE; ly++)
5867 for (let ly = -1; ly <= CHUNK_SIZE; ly++)
5746 {
5868 {
5747 for (let lx = -1; lx <= CHUNK_SIZE; lx++)
5869 for (let lx = -1; lx <= CHUNK_SIZE; lx++)
@@ -5751,7 +5873,13 @@ export class WorldView
5751 const gi = (ly + 1) * gridW + (lx + 1);
5873 const gi = (ly + 1) * gridW + (lx + 1);
5752 // Halo tiles may sit in the other lighting region (3×3 vs outer). Resolve
5874 // Halo tiles may sit in the other lighting region (3×3 vs outer). Resolve
5753 // sources per tile so corner blends match the neighbour chunk's shading.
5875 // sources per tile so corner blends match the neighbour chunk's shading.
5754 const lights = this.#dynamicLightsForTile(tileX, tileY, mobileLights, blockLights);
5876 const lights = this.#cachedLightsForChunk(
5877 Math.floor(tileX / CHUNK_SIZE),
5878 Math.floor(tileY / CHUNK_SIZE),
5879 mobileLights,
5880 blockLights,
5881 cache
5882 );
5755 grid[gi] = this.#intensityAtTile(tileX, tileY, lights, lightOcclusion, ambientDark);
5883 grid[gi] = this.#intensityAtTile(tileX, tileY, lights, lightOcclusion, ambientDark);
5756 occlude[gi] = this.#tileOccludesLight(tileX, tileY) ? 1 : 0;
5884 occlude[gi] = this.#tileOccludesLight(tileX, tileY) ? 1 : 0;
5757 }
5885 }
@@ -5883,6 +6011,7 @@ export class WorldView
5883 * through a wall to the far side. Diagonals only when both cardinals are clear.
6011 * through a wall to the far side. Diagonals only when both cardinals are clear.
5884 * @param chunkLights Sources that affect this chunk (cache key + in-chunk samples).
6012 * @param chunkLights Sources that affect this chunk (cache key + in-chunk samples).
5885 * @param mobileLights / blockLights Full lists so the ±1 halo can sample across the 3×3 boundary.
6013 * @param mobileLights / blockLights Full lists so the ±1 halo can sample across the 3×3 boundary.
6014 * @param lightsByChunk Optional per-pass memo of chunk → light list.
5886 */
6015 */
5887 #writeChunkLightmap (
6016 #writeChunkLightmap (
5888 baked,
6017 baked,
@@ -5890,7 +6019,8 @@ export class WorldView
5890 mobileLights,
6019 mobileLights,
5891 blockLights,
6020 blockLights,
5892 lightOcclusion,
6021 lightOcclusion,
5893 ambientDark = this.#ambientDarkness()
6022 ambientDark = this.#ambientDarkness(),
6023 lightsByChunk = null
5894 )
6024 )
5895 {
6025 {
5896 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
6026 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
@@ -5905,7 +6035,14 @@ export class WorldView
5905 { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); }
6035 { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); }
5906 const pixels = baked.lightmapPixels;
6036 const pixels = baked.lightmapPixels;
5907
6037
5908 this.#fillChunkLightGrids(baked, mobileLights, blockLights, lightOcclusion, ambientDark);
6038 this.#fillChunkLightGrids(
6039 baked,
6040 mobileLights,
6041 blockLights,
6042 lightOcclusion,
6043 ambientDark,
6044 lightsByChunk
6045 );
5909 const simple = this.lightingMode === "simple";
6046 const simple = this.lightingMode === "simple";
5910
6047
5911 for (let localY = 0; localY < CHUNK_SIZE; localY++)
6048 for (let localY = 0; localY < CHUNK_SIZE; localY++)
@@ -5956,10 +6093,29 @@ export class WorldView
5956 }
6093 }
5957 }
6094 }
5958 }
6095 }
5959 const ctx = baked.lightmapCanvas.getContext("2d");
6096 // Keep canvas pixels in sync for Framework getTexture fallbacks, but upload
5960 ctx.putImageData(new ImageData(pixels, atlasPx, atlasPx), 0, 0);
6097 // to GL via texSubImage2D when the texture already exists (no delete/recreate).
5961 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
6098 if (!baked.lightmapImageData || baked.lightmapImageData.data !== pixels)
5962 this.#queueCanvasTextureWarm(baked.lightmapCanvas, baked.chunkX, baked.chunkY);
6099 { baked.lightmapImageData = new ImageData(pixels, atlasPx, atlasPx); }
6100 if (baked.lightmapUploadSize !== atlasPx)
6101 {
6102 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
6103 baked.lightmapUploadSize = atlasPx;
6104 }
6105 const gl = this.scene?.glContext?.gl;
6106 const created = uploadCanvasTextureRgba(
6107 this.scene,
6108 baked.lightmapCanvas,
6109 pixels,
6110 atlasPx,
6111 atlasPx,
6112 gl?.NEAREST ?? null
6113 );
6114 if (created)
6115 {
6116 const ctx = baked.lightmapCanvas.getContext("2d");
6117 ctx.putImageData(baked.lightmapImageData, 0, 0);
6118 }
5963 baked.lightmapCacheKey = cacheKey;
6119 baked.lightmapCacheKey = cacheKey;
5964 }
6120 }
5965
6121
server/tests/lighting.test.js +29 −0
@@ -62,6 +62,35 @@ test("dynamic lights use the same wall occlusion as baked light", () =>
62 62 assert.ok(dynamicLightAtTile(2, 0, sources, () => true) > 0);
63 63 });
64 64
65 test("dynamic lights skip rays beyond range before occlusion work", () =>
66 {
67 let occlusionCalls = 0;
68 const occlusion = () =>
69 {
70 occlusionCalls += 1;
71 return LightOcclusion.clear;
72 };
73 const sources = [{ tileX: 0, tileY: 0, range: 4, intensity: 1 }];
74 assert.equal(dynamicLightAtTile(10, 0, sources, occlusion), 0);
75 assert.equal(occlusionCalls, 0, "out-of-range tiles must not run LOS");
76 // Two steps away → one intermediate tile, so occlusion is consulted.
77 assert.ok(dynamicLightAtTile(2, 0, sources, occlusion) > 0);
78 assert.ok(occlusionCalls > 0);
79 });
80
81 test("evaluateLightRay matches Bresenham intermediates without allocating the path", () =>
82 {
83 const blocked = new Set(["1,0"]);
84 const occlusion = (x, y) => (blocked.has(`${x},${y}`)
85 ? LightOcclusion.solid
86 : LightOcclusion.clear);
87 assert.equal(evaluateLightRay(0, 0, 2, 0, occlusion).reaches, false);
88 assert.equal(evaluateLightRay(0, 0, 3, 0, () => LightOcclusion.clear).reaches, true);
89 assert.equal(evaluateLightRay(0, 0, 3, 0, () => LightOcclusion.clear).extraDistance, 0);
90 const partial = (x, y) => (x === 1 && y === 0 ? LightOcclusion.partial : LightOcclusion.clear);
91 assert.equal(evaluateLightRay(0, 0, 2, 0, partial).extraDistance, 1);
92 });
93
65 94 test("tables and marketplace counters do not occlude light rays", () =>
66 95 {
67 96 const origin = createEmptyChunkData();
@@ -62,6 +62,35 @@ test("dynamic lights use the same wall occlusion as baked light", () =>
62 assert.ok(dynamicLightAtTile(2, 0, sources, () => true) > 0);
62 assert.ok(dynamicLightAtTile(2, 0, sources, () => true) > 0);
63});
63});
64
64
65test("dynamic lights skip rays beyond range before occlusion work", () =>
66{
67 let occlusionCalls = 0;
68 const occlusion = () =>
69 {
70 occlusionCalls += 1;
71 return LightOcclusion.clear;
72 };
73 const sources = [{ tileX: 0, tileY: 0, range: 4, intensity: 1 }];
74 assert.equal(dynamicLightAtTile(10, 0, sources, occlusion), 0);
75 assert.equal(occlusionCalls, 0, "out-of-range tiles must not run LOS");
76 // Two steps away → one intermediate tile, so occlusion is consulted.
77 assert.ok(dynamicLightAtTile(2, 0, sources, occlusion) > 0);
78 assert.ok(occlusionCalls > 0);
79});
80
81test("evaluateLightRay matches Bresenham intermediates without allocating the path", () =>
82{
83 const blocked = new Set(["1,0"]);
84 const occlusion = (x, y) => (blocked.has(`${x},${y}`)
85 ? LightOcclusion.solid
86 : LightOcclusion.clear);
87 assert.equal(evaluateLightRay(0, 0, 2, 0, occlusion).reaches, false);
88 assert.equal(evaluateLightRay(0, 0, 3, 0, () => LightOcclusion.clear).reaches, true);
89 assert.equal(evaluateLightRay(0, 0, 3, 0, () => LightOcclusion.clear).extraDistance, 0);
90 const partial = (x, y) => (x === 1 && y === 0 ? LightOcclusion.partial : LightOcclusion.clear);
91 assert.equal(evaluateLightRay(0, 0, 2, 0, partial).extraDistance, 1);
92});
93
65test("tables and marketplace counters do not occlude light rays", () =>
94test("tables and marketplace counters do not occlude light rays", () =>
66{
95{
67 const origin = createEmptyChunkData();
96 const origin = createEmptyChunkData();
shared/lighting/raycast.js +34 −5
@@ -47,6 +47,7 @@ export function rayReaches (fromX, fromY, toX, toY, isClear)
47 47
48 48 /**
49 49 * Light transmission along a Bresenham ray.
50 * Walks the line without allocating a tile array (hot path for dynamic lights).
50 51 * @param {(x: number, y: number) => number} occlusionAt
51 52 * {@link LightOcclusion.clear|partial|solid}
52 53 * @returns {{ reaches: boolean, extraDistance: number }}
@@ -63,12 +64,32 @@ export function evaluateLightRay (fromX, fromY, toX, toY, occlusionAt)
63 64 };
64 65 }
65 66
66 const tiles = bresenhamTiles(fromX, fromY, toX, toY);
67 let x = fromX;
68 let y = fromY;
69 const dx = Math.abs(toX - fromX);
70 const dy = Math.abs(toY - fromY);
71 const sx = fromX < toX ? 1 : -1;
72 const sy = fromY < toY ? 1 : -1;
73 let err = dx - dy;
67 74 let extraDistance = 0;
75
68 76 // Only tiles strictly between source and target can occlude / add penalty.
69 for (let i = 1; i < tiles.length - 1; i++)
77 while (x !== toX || y !== toY)
70 78 {
71 const level = occlusionAt(tiles[i].x, tiles[i].y) | 0;
79 const e2 = 2 * err;
80 if (e2 > -dy)
81 {
82 err -= dy;
83 x += sx;
84 }
85 if (e2 < dx)
86 {
87 err += dx;
88 y += sy;
89 }
90 if (x === toX && y === toY)
91 { break; }
92 const level = occlusionAt(x, y) | 0;
72 93 if (level >= LightOcclusion.solid)
73 94 { return { reaches: false, extraDistance: 0 }; }
74 95 if (level === LightOcclusion.partial)
@@ -108,18 +129,26 @@ export function lightIntensity (encoded)
108 129 */
109 130 export function dynamicLightAtTile (tileX, tileY, sources, occlusionAt)
110 131 {
132 if (!sources?.length)
133 { return 0; }
111 134 const occlude = normalizeOcclusionFn(occlusionAt);
112 135 let best = 0;
113 136 for (const source of sources)
114 137 {
138 const range = source.range;
139 if (!(range > 0))
140 { continue; }
115 141 const geo = Math.hypot(tileX - source.tileX, tileY - source.tileY);
142 // Partial occlusion only *increases* distance — never shortens it.
143 if (geo > range)
144 { continue; }
116 145 const ray = evaluateLightRay(source.tileX, source.tileY, tileX, tileY, occlude);
117 146 if (!ray.reaches)
118 147 { continue; }
119 148 const dist = geo + ray.extraDistance;
120 if (dist > source.range)
149 if (dist > range)
121 150 { continue; }
122 best = Math.max(best, falloffAtDistance(dist, source.range) * (source.intensity ?? 1));
151 best = Math.max(best, falloffAtDistance(dist, range) * (source.intensity ?? 1));
123 152 }
124 153 return best;
125 154 }
@@ -47,6 +47,7 @@ export function rayReaches (fromX, fromY, toX, toY, isClear)
47
47
48/**
48/**
49 * Light transmission along a Bresenham ray.
49 * Light transmission along a Bresenham ray.
50 * Walks the line without allocating a tile array (hot path for dynamic lights).
50 * @param {(x: number, y: number) => number} occlusionAt
51 * @param {(x: number, y: number) => number} occlusionAt
51 * {@link LightOcclusion.clear|partial|solid}
52 * {@link LightOcclusion.clear|partial|solid}
52 * @returns {{ reaches: boolean, extraDistance: number }}
53 * @returns {{ reaches: boolean, extraDistance: number }}
@@ -63,12 +64,32 @@ export function evaluateLightRay (fromX, fromY, toX, toY, occlusionAt)
63 };
64 };
64 }
65 }
65
66
66 const tiles = bresenhamTiles(fromX, fromY, toX, toY);
67 let x = fromX;
68 let y = fromY;
69 const dx = Math.abs(toX - fromX);
70 const dy = Math.abs(toY - fromY);
71 const sx = fromX < toX ? 1 : -1;
72 const sy = fromY < toY ? 1 : -1;
73 let err = dx - dy;
67 let extraDistance = 0;
74 let extraDistance = 0;
75
68 // Only tiles strictly between source and target can occlude / add penalty.
76 // Only tiles strictly between source and target can occlude / add penalty.
69 for (let i = 1; i < tiles.length - 1; i++)
77 while (x !== toX || y !== toY)
70 {
78 {
71 const level = occlusionAt(tiles[i].x, tiles[i].y) | 0;
79 const e2 = 2 * err;
80 if (e2 > -dy)
81 {
82 err -= dy;
83 x += sx;
84 }
85 if (e2 < dx)
86 {
87 err += dx;
88 y += sy;
89 }
90 if (x === toX && y === toY)
91 { break; }
92 const level = occlusionAt(x, y) | 0;
72 if (level >= LightOcclusion.solid)
93 if (level >= LightOcclusion.solid)
73 { return { reaches: false, extraDistance: 0 }; }
94 { return { reaches: false, extraDistance: 0 }; }
74 if (level === LightOcclusion.partial)
95 if (level === LightOcclusion.partial)
@@ -108,18 +129,26 @@ export function lightIntensity (encoded)
108 */
129 */
109export function dynamicLightAtTile (tileX, tileY, sources, occlusionAt)
130export function dynamicLightAtTile (tileX, tileY, sources, occlusionAt)
110{
131{
132 if (!sources?.length)
133 { return 0; }
111 const occlude = normalizeOcclusionFn(occlusionAt);
134 const occlude = normalizeOcclusionFn(occlusionAt);
112 let best = 0;
135 let best = 0;
113 for (const source of sources)
136 for (const source of sources)
114 {
137 {
138 const range = source.range;
139 if (!(range > 0))
140 { continue; }
115 const geo = Math.hypot(tileX - source.tileX, tileY - source.tileY);
141 const geo = Math.hypot(tileX - source.tileX, tileY - source.tileY);
142 // Partial occlusion only *increases* distance — never shortens it.
143 if (geo > range)
144 { continue; }
116 const ray = evaluateLightRay(source.tileX, source.tileY, tileX, tileY, occlude);
145 const ray = evaluateLightRay(source.tileX, source.tileY, tileX, tileY, occlude);
117 if (!ray.reaches)
146 if (!ray.reaches)
118 { continue; }
147 { continue; }
119 const dist = geo + ray.extraDistance;
148 const dist = geo + ray.extraDistance;
120 if (dist > source.range)
149 if (dist > range)
121 { continue; }
150 { continue; }
122 best = Math.max(best, falloffAtDistance(dist, source.range) * (source.intensity ?? 1));
151 best = Math.max(best, falloffAtDistance(dist, range) * (source.intensity ?? 1));
123 }
152 }
124 return best;
153 return best;
125}
154}