BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

worldView.js 206.3 KiB Download Raw
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX, ENTITY_STACK_SPREAD_DIAMETER_PX } from "/shared/protocol/constants.js";
2import { dynamicLightAtTile, dynamicDarknessAtTile, lightIntensity } from "/shared/lighting/raycast.js";
3import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js";
4import { bakeChunkOcclusion, tileLightOcclusionAt } from "/shared/lighting/chunkOcclusion.js";
5import { collectBlockLightSources, collectGroundLightSources, maxBlockLightRangeTiles } from "/shared/lighting/blockLights.js";
6import { smoothLitCorner } from "/shared/lighting/lightCorners.js";
7import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
8import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemSpriteNameForStack, itemDefinition } from "/shared/definitions/items.js";
9import
10{
11 resolveItemTint,
12 resolveEquipTint,
13 resolveItemDualTint,
14 resolveEquipDualTint,
15 normalizeRgb
16} from "/shared/render/tint.js";
17import { layersFromSpawnerConfig } from "/shared/appearance/layers.js";
18import { normalizeSpawnerConfig } from "/shared/definitions/mobs.js";
19import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js";
20import { normalizeGround, normalizeBlock, isWadeGroundInSeason, isWaterGround, isLavaGround, isLiquidWaterGround, isGroundPassable, groundLightOcclusion, LightOcclusion, blockDefinition, blockLightOcclusionForBlock, GroundType, GROUND_DEFINITIONS, fluidCoastContinues } from "/shared/definitions/tiles.js";
21import { doorSortSubOrder, doorRestingState } from "/shared/world/doors.js";
22import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer, flightSortLayer } from "/shared/render/pivot.js";
23import { bakeChunkAtlases, tileBlockSpriteEntry } from "./chunkBake.js";
24import { createChunkAtlasCache } from "./chunkAtlasCache.js";
25import
26{
27 frameworkImageFromCanvas,
28 invalidateCanvasTexture,
29 uploadCanvasTextureRgba
30} from "./canvasSprite.js";
31import { setNearestFilter } from "./sprites.js";
32import { waterDebugUniforms, lavaDebugUniforms } from "../play/waterDebug.js";
33import { natureNoise01, natureTintUniforms, NATURE_TINT, NATURE_NOISE_SIZE, NATURE_NOISE_PAD } from "/shared/render/natureNoise.js";
34import { SeasonId, seasonIdAt, resolveSeasonalVisualState } from "/shared/world/season.js";
35import
36{
37 OVERWORLD_ID,
38 normalizeDimensionId,
39 normalizeLightingMode,
40 normalizeSeasonMode,
41 resolveDimensionDarknessFactor,
42 resolveDimensionSeasonId
43} from "/shared/world/dimensions.js";
44import { spellDefinition, spellProjectileTint } from "/shared/definitions/spells.js";
45import { skullTintColor } from "/shared/combat/skull.js";
46
47const LAYER_GROUND = 0;
48const LAYER_EDGE = 900000;
49const SORT_BLOCK = 2;
50const SORT_ENTITY = 3;
51/** Equipment overlays use SORT_ENTITY + 1 + index (same sortY band). */
52const SORT_HP_BAR = 14;
53const SORT_FX = 5;
54const RENDER_LAYER_BLOOM = "bloom";
55const SKULL_SPRITE = "fx:skull:skull";
56
57const HP_BAR_W = 14;
58const HP_BAR_H = 4;
59const WALK_TILT_DEG = 6;
60const RUN_TILT_DEG = 8;
61const SHOVE_TILE_FRACTION = 0.25;
62const SHOVE_MS = 280;
63/** Soft reflow when stack circle targets change (join/leave a shared tile). */
64const STACK_SPREAD_LERP_MS = 280;
65/** Melee swipe fade: full opacity → transparent over this duration, then remove. */
66const MELEE_SWIPE_MS = 500;
67/** Extra random yaw (±deg) on top of aim rotation. */
68const MELEE_SWIPE_JITTER_DEG = 10;
69/** Hold gather-tool equip overlay slightly past swing interval so it stays visible between swings. */
70const GATHER_TOOL_HOLD_MS = 1100;
71const DAMAGE_FLASH_MS = 180;
72const FLASH_COLOR_DAMAGE = Object.freeze([1.0, 0.12, 0.12]);
73const FLASH_COLOR_BLOCK = Object.freeze([1.0, 1.0, 1.0]);
74/** Combat death: full red silhouette fades to transparent after the killing blow. */
75const DEATH_FADE_MS = 500;
76/** Interest leave / non-combat despawn: plain alpha fade (still lit / darkened). */
77const DESPAWN_FADE_MS = 500;
78const DAMAGE_FLOAT_MS = 900;
79const SKILL_LEVEL_FLOAT_MS = 2800;
80/** Projectiles spawn this many sprite-pixels below the caster sprite top. */
81const PROJECTILE_LAUNCH_FROM_TOP_PX = 4;
82
83const SPRITE_LIGHTING_FRAG = [
84 "precision mediump float;",
85 "varying vec2 v_texCoord;",
86 "uniform sampler2D u_texture;",
87 "uniform float u_alpha;",
88 "uniform float u_darkness;",
89 "uniform float u_strength;",
90 "uniform vec3 u_flashColor;",
91 "uniform float u_wade;",
92 "uniform float u_spriteHeight;",
93 "void main() {",
94 " vec4 color = texture2D(u_texture, v_texCoord);",
95 " if (color.a <= 0.0) { discard; }",
96 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
97 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
98 " vec3 rgb = color.rgb;",
99 " if (u_wade > 0.5 && fromBottom < 5.0) {",
100 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
101 " }",
102 " rgb = mix(rgb, vec3(0.0), u_darkness);",
103 " rgb = mix(rgb, u_flashColor, u_strength);",
104 " gl_FragColor = vec4(rgb, color.a * u_alpha);",
105 "}"
106].join("\n");
107
108const WATER_GROUND_FRAG = [
109 "precision mediump float;",
110 "varying vec2 v_texCoord;",
111 "uniform sampler2D u_texture;",
112 "uniform sampler2D u_secondary;",
113 "uniform float u_alpha;",
114 "uniform float u_ambientDark;",
115 "uniform float u_litNW;",
116 "uniform float u_litNE;",
117 "uniform float u_litSW;",
118 "uniform float u_litSE;",
119 "uniform float u_time;",
120 "uniform float u_tileX;",
121 "uniform float u_tileY;",
122 "uniform float u_deepNW;",
123 "uniform float u_deepNE;",
124 "uniform float u_deepSW;",
125 "uniform float u_deepSE;",
126 "uniform float u_edgeN;",
127 "uniform float u_edgeE;",
128 "uniform float u_edgeS;",
129 "uniform float u_edgeW;",
130 "uniform float u_edgeNE;",
131 "uniform float u_edgeNW;",
132 "uniform float u_edgeSE;",
133 "uniform float u_edgeSW;",
134 "uniform float u_hasShore;",
135 "uniform float u_shoreEdgeN;",
136 "uniform float u_shoreEdgeE;",
137 "uniform float u_shoreEdgeS;",
138 "uniform float u_shoreEdgeW;",
139 "uniform float u_shoreEdgeNE;",
140 "uniform float u_shoreEdgeNW;",
141 "uniform float u_shoreEdgeSE;",
142 "uniform float u_shoreEdgeSW;",
143 "uniform vec4 u_shoreUvRect;",
144 "uniform float u_flowX;",
145 "uniform float u_flowY;",
146 "uniform float u_flowZ;",
147 "uniform float u_waveScale;",
148 "uniform float u_fbmAmp;",
149 "uniform float u_texAmp;",
150 "uniform float u_distort;",
151 "uniform float u_normalZ;",
152 "uniform float u_waveGain;",
153 "uniform float u_crestLo;",
154 "uniform float u_crestHi;",
155 "uniform float u_crestPow;",
156 "uniform float u_glitterPow;",
157 "uniform float u_crestGlitter;",
158 "uniform float u_glitterCap;",
159 "uniform float u_glitterMix;",
160 "uniform float u_shadeLo;",
161 "uniform float u_shadeHi;",
162 "uniform float u_bodyLo;",
163 "uniform float u_bodyHi;",
164 "uniform float u_litLo;",
165 "uniform float u_litHi;",
166 "uniform float u_litMix;",
167 "uniform float u_edgeDark;",
168 "uniform float u_lightDirX;",
169 "uniform float u_lightDirY;",
170 "uniform float u_lightDirZ;",
171 "uniform float u_normalEps;",
172 "uniform float u_foamStrength;",
173 "uniform float u_shoreClip;",
174 "uniform float u_deepDark;",
175 "uniform float u_deepAbrupt;",
176 // 3D simplex (Ashima / Gustavson style — OpenSimplex-class continuous field).
177 "vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }",
178 "vec4 mod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }",
179 "vec4 permute(vec4 x) { return mod289(((x * 34.0) + 1.0) * x); }",
180 "vec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; }",
181 "float snoise(vec3 v) {",
182 " vec2 C = vec2(1.0 / 6.0, 1.0 / 3.0);",
183 " vec4 D = vec4(0.0, 0.5, 1.0, 2.0);",
184 " vec3 i = floor(v + dot(v, C.yyy));",
185 " vec3 x0 = v - i + dot(i, C.xxx);",
186 " vec3 g = step(x0.yzx, x0.xyz);",
187 " vec3 l = 1.0 - g;",
188 " vec3 i1 = min(g.xyz, l.zxy);",
189 " vec3 i2 = max(g.xyz, l.zxy);",
190 " vec3 x1 = x0 - i1 + C.xxx;",
191 " vec3 x2 = x0 - i2 + C.yyy;",
192 " vec3 x3 = x0 - D.yyy;",
193 " i = mod289(i);",
194 " vec4 p = permute(permute(permute(",
195 " i.z + vec4(0.0, i1.z, i2.z, 1.0))",
196 " + i.y + vec4(0.0, i1.y, i2.y, 1.0))",
197 " + i.x + vec4(0.0, i1.x, i2.x, 1.0));",
198 " float n_ = 0.142857142857;",
199 " vec3 ns = n_ * D.wyz - D.xzx;",
200 " vec4 j = p - 49.0 * floor(p * ns.z * ns.z);",
201 " vec4 x_ = floor(j * ns.z);",
202 " vec4 y_ = floor(j - 7.0 * x_);",
203 " vec4 x = x_ * ns.x + ns.yyyy;",
204 " vec4 y = y_ * ns.x + ns.yyyy;",
205 " vec4 h = 1.0 - abs(x) - abs(y);",
206 " vec4 b0 = vec4(x.xy, y.xy);",
207 " vec4 b1 = vec4(x.zw, y.zw);",
208 " vec4 s0 = floor(b0) * 2.0 + 1.0;",
209 " vec4 s1 = floor(b1) * 2.0 + 1.0;",
210 " vec4 sh = -step(h, vec4(0.0));",
211 " vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;",
212 " vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;",
213 " vec3 p0 = vec3(a0.xy, h.x);",
214 " vec3 p1 = vec3(a0.zw, h.y);",
215 " vec3 p2 = vec3(a1.xy, h.z);",
216 " vec3 p3 = vec3(a1.zw, h.w);",
217 " vec4 norm = taylorInvSqrt(vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3)));",
218 " p0 *= norm.x; p1 *= norm.y; p2 *= norm.z; p3 *= norm.w;",
219 " vec4 m = max(0.6 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0);",
220 " m = m * m;",
221 " return 42.0 * dot(m * m, vec4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3)));",
222 "}",
223 // 4-octave FBM: freq ×2, amp ×0.5 each layer; time in Z for continuous ripple.
224 "float fbm(vec3 p) {",
225 " float sum = 0.0;",
226 " float amp = 0.5;",
227 " sum += amp * snoise(p); p *= 2.0; amp *= 0.5;",
228 " sum += amp * snoise(p); p *= 2.0; amp *= 0.5;",
229 " sum += amp * snoise(p); p *= 2.0; amp *= 0.5;",
230 " sum += amp * snoise(p);",
231 " return sum;",
232 "}",
233 "vec2 wrapUv(vec2 uv) {",
234 " return fract(uv) * 0.998 + 0.001;",
235 "}",
236 "float sampleShore(",
237 " float enabled, float useShore, vec2 shoreNu,",
238 " inout vec3 shoreRgb, inout float shoreW",
239 ") {",
240 " if (enabled < 0.5 || useShore < 0.5 || u_hasShore < 0.5) { return 0.0; }",
241 " vec2 shoreUv = u_shoreUvRect.xy + shoreNu * (u_shoreUvRect.zw - u_shoreUvRect.xy);",
242 " vec4 shore = texture2D(u_secondary, shoreUv);",
243 " if (shore.a <= 0.1) { return 0.0; }",
244 " shoreRgb = shore.rgb;",
245 " shoreW = 1.0;",
246 " return 1.0;",
247 "}",
248 "void main() {",
249 " vec2 px = floor(v_texCoord * 16.0) + 0.5;",
250 " vec2 puv = px / 16.0;",
251 " vec2 world = vec2(u_tileX, u_tileY) + puv;",
252 " float t = u_time;",
253 " vec2 flow = vec2(t * u_flowX, t * u_flowY);",
254 " float eps = max(u_normalEps, 0.001);",
255 " vec3 base = vec3(world * u_waveScale + flow, t * u_flowZ);",
256 " float nC = fbm(base);",
257 " float nL = fbm(base + vec3(-eps, 0.0, 0.0));",
258 " float nR = fbm(base + vec3(eps, 0.0, 0.0));",
259 " float nD = fbm(base + vec3(0.0, -eps, 0.0));",
260 " float nU = fbm(base + vec3(0.0, eps, 0.0));",
261 " vec2 distort = vec2(nL - nR, nD - nU) * u_distort;",
262 " float texN = texture2D(u_texture, wrapUv(world * 0.28 + flow * 0.6 + distort)).r;",
263 " float h = nC * u_fbmAmp + (texN - 0.5) * u_texAmp;",
264 " vec3 normal = normalize(vec3(nL - nR, nD - nU, max(u_normalZ, 0.05)));",
265 " float ndotl = clamp(dot(normal, normalize(vec3(u_lightDirX, u_lightDirY, u_lightDirZ))), 0.0, 1.0);",
266 " float wave = clamp(h * u_waveGain + 0.5, 0.0, 1.0);",
267 " float crest = pow(smoothstep(u_crestLo, max(u_crestHi, u_crestLo + 0.01), wave), max(u_crestPow, 0.01));",
268 " float glitter = pow(max(0.0, ndotl), max(u_glitterPow, 0.01)) * crest;",
269 " glitter = max(glitter, pow(crest, 2.5) * u_crestGlitter);",
270 " float edgeProx = 0.0;",
271 " if (u_edgeN > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.y)); }",
272 " if (u_edgeS > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.y)); }",
273 " if (u_edgeW > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.x)); }",
274 " if (u_edgeE > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.x)); }",
275 " if (u_edgeNE > 0.5) {",
276 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, puv.y))));",
277 " }",
278 " if (u_edgeNW > 0.5) {",
279 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, puv.y))));",
280 " }",
281 " if (u_edgeSE > 0.5) {",
282 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, 1.0 - puv.y))));",
283 " }",
284 " if (u_edgeSW > 0.5) {",
285 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, 1.0 - puv.y))));",
286 " }",
287 " float waveBody = wave * (1.0 - edgeProx * 0.72);",
288 " float deepTop = mix(u_deepNW, u_deepNE, puv.x);",
289 " float deepBot = mix(u_deepSW, u_deepSE, puv.x);",
290 " float deepMix = mix(deepTop, deepBot, puv.y);",
291 " float deepAmt = pow(clamp(deepMix, 0.0, 1.0), max(u_deepAbrupt, 0.05));",
292 " float darkW = clamp(u_deepDark, 0.0, 1.0);",
293 " vec3 deepCol = mix(vec3(0.12, 0.34, 0.54), mix(vec3(0.05, 0.16, 0.34), vec3(0.015, 0.055, 0.14), darkW), deepAmt);",
294 " vec3 midCol = mix(vec3(0.24, 0.52, 0.70), mix(vec3(0.10, 0.30, 0.50), vec3(0.04, 0.14, 0.28), darkW), deepAmt);",
295 " vec3 litCol = mix(vec3(0.52, 0.78, 0.90), mix(vec3(0.26, 0.46, 0.66), vec3(0.12, 0.28, 0.46), darkW), deepAmt);",
296 " vec3 sparkCol = mix(vec3(0.98, 1.0, 1.0), mix(vec3(0.72, 0.88, 0.98), vec3(0.48, 0.68, 0.86), darkW), deepAmt);",
297 " vec3 foamCol = vec3(0.94, 0.99, 1.0);",
298 " float shade = mix(u_shadeLo, u_shadeHi, ndotl);",
299 " vec3 rgb = mix(deepCol, midCol, smoothstep(u_bodyLo, max(u_bodyHi, u_bodyLo + 0.01), waveBody));",
300 " rgb = mix(rgb, litCol, smoothstep(u_litLo, max(u_litHi, u_litLo + 0.01), waveBody) * u_litMix);",
301 " rgb *= shade;",
302 " rgb = mix(rgb, sparkCol, min(glitter, u_glitterCap) * u_glitterMix * (1.0 - edgeProx * 0.7));",
303 " rgb = mix(rgb, deepCol, edgeProx * u_edgeDark);",
304 " float shoreW = 0.0;",
305 " vec3 shoreRgb = rgb;",
306 " if (u_edgeN > 0.5) {",
307 " sampleShore(1.0, u_shoreEdgeN, vec2(puv.x, 1.0 - puv.y), shoreRgb, shoreW);",
308 " }",
309 " if (u_edgeS > 0.5) {",
310 " sampleShore(1.0, u_shoreEdgeS, vec2(puv.x, 1.0 - puv.y), shoreRgb, shoreW);",
311 " }",
312 " if (u_edgeW > 0.5) {",
313 " sampleShore(1.0, u_shoreEdgeW, vec2(1.0 - puv.x, puv.y), shoreRgb, shoreW);",
314 " }",
315 " if (u_edgeE > 0.5) {",
316 " sampleShore(1.0, u_shoreEdgeE, vec2(1.0 - puv.x, puv.y), shoreRgb, shoreW);",
317 " }",
318 " if (u_edgeNE > 0.5) {",
319 " sampleShore(1.0, max(u_shoreEdgeNE, u_hasShore), vec2(1.0 - puv.x, puv.y), shoreRgb, shoreW);",
320 " }",
321 " if (u_edgeNW > 0.5) {",
322 " sampleShore(1.0, max(u_shoreEdgeNW, u_hasShore), vec2(puv.x, puv.y), shoreRgb, shoreW);",
323 " }",
324 " if (u_edgeSE > 0.5) {",
325 " sampleShore(1.0, max(u_shoreEdgeSE, u_hasShore), vec2(1.0 - puv.x, 1.0 - puv.y), shoreRgb, shoreW);",
326 " }",
327 " if (u_edgeSW > 0.5) {",
328 " sampleShore(1.0, max(u_shoreEdgeSW, u_hasShore), vec2(puv.x, 1.0 - puv.y), shoreRgb, shoreW);",
329 " }",
330 " float darkAmt = 1.0 - smoothstep(0.18, 0.52, waveBody);",
331 " float retreat = edgeProx * (0.35 + 0.65 * darkAmt);",
332 " float shoreClip = u_shoreClip;",
333 " float shoreMask = step(shoreClip, retreat) * shoreW;",
334 " float foamAmt = (1.0 - shoreMask) * smoothstep(shoreClip - 0.24, shoreClip - 0.08, retreat)",
335 " * (1.0 - smoothstep(shoreClip - 0.08, shoreClip, retreat));",
336 " rgb = mix(rgb, foamCol, foamAmt * u_foamStrength);",
337 " rgb = mix(rgb, shoreRgb, shoreMask);",
338 " float litTop = mix(u_litNW, u_litNE, v_texCoord.x);",
339 " float litBottom = mix(u_litSW, u_litSE, v_texCoord.x);",
340 " float lit = mix(litTop, litBottom, v_texCoord.y);",
341 " float darkness = u_ambientDark * (1.0 - lit);",
342 " rgb = mix(rgb, vec3(0.0), darkness);",
343 " gl_FragColor = vec4(rgb, u_alpha);",
344 "}"
345].join("\n");
346
347/** Lava heat: dark red → red → orange → yellow; yellow drives bloom companion. */
348const LAVA_FBM_COMMON = [
349 "vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }",
350 "vec4 mod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }",
351 "vec4 permute(vec4 x) { return mod289(((x * 34.0) + 1.0) * x); }",
352 "vec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; }",
353 "float snoise(vec3 v) {",
354 " vec2 C = vec2(1.0 / 6.0, 1.0 / 3.0);",
355 " vec4 D = vec4(0.0, 0.5, 1.0, 2.0);",
356 " vec3 i = floor(v + dot(v, C.yyy));",
357 " vec3 x0 = v - i + dot(i, C.xxx);",
358 " vec3 g = step(x0.yzx, x0.xyz);",
359 " vec3 l = 1.0 - g;",
360 " vec3 i1 = min(g.xyz, l.zxy);",
361 " vec3 i2 = max(g.xyz, l.zxy);",
362 " vec3 x1 = x0 - i1 + C.xxx;",
363 " vec3 x2 = x0 - i2 + C.yyy;",
364 " vec3 x3 = x0 - D.yyy;",
365 " i = mod289(i);",
366 " vec4 p = permute(permute(permute(",
367 " i.z + vec4(0.0, i1.z, i2.z, 1.0))",
368 " + i.y + vec4(0.0, i1.y, i2.y, 1.0))",
369 " + i.x + vec4(0.0, i1.x, i2.x, 1.0));",
370 " float n_ = 0.142857142857;",
371 " vec3 ns = n_ * D.wyz - D.xzx;",
372 " vec4 j = p - 49.0 * floor(p * ns.z * ns.z);",
373 " vec4 x_ = floor(j * ns.z);",
374 " vec4 y_ = floor(j - 7.0 * x_);",
375 " vec4 x = x_ * ns.x + ns.yyyy;",
376 " vec4 y = y_ * ns.x + ns.yyyy;",
377 " vec4 h = 1.0 - abs(x) - abs(y);",
378 " vec4 b0 = vec4(x.xy, y.xy);",
379 " vec4 b1 = vec4(x.zw, y.zw);",
380 " vec4 s0 = floor(b0) * 2.0 + 1.0;",
381 " vec4 s1 = floor(b1) * 2.0 + 1.0;",
382 " vec4 sh = -step(h, vec4(0.0));",
383 " vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;",
384 " vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;",
385 " vec3 p0 = vec3(a0.xy, h.x);",
386 " vec3 p1 = vec3(a0.zw, h.y);",
387 " vec3 p2 = vec3(a1.xy, h.z);",
388 " vec3 p3 = vec3(a1.zw, h.w);",
389 " vec4 norm = taylorInvSqrt(vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3)));",
390 " p0 *= norm.x; p1 *= norm.y; p2 *= norm.z; p3 *= norm.w;",
391 " vec4 m = max(0.6 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0);",
392 " m = m * m;",
393 " return 42.0 * dot(m * m, vec4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3)));",
394 "}",
395 "float fbm(vec3 p) {",
396 " float sum = 0.0;",
397 " float amp = 0.5;",
398 " sum += amp * snoise(p); p *= 2.0; amp *= 0.5;",
399 " sum += amp * snoise(p); p *= 2.0; amp *= 0.5;",
400 " sum += amp * snoise(p); p *= 2.0; amp *= 0.5;",
401 " sum += amp * snoise(p);",
402 " return sum;",
403 "}",
404 "vec2 wrapUv(vec2 uv) {",
405 " return fract(uv) * 0.998 + 0.001;",
406 "}"
407];
408
409const LAVA_GROUND_FRAG = [
410 "precision mediump float;",
411 "varying vec2 v_texCoord;",
412 "uniform sampler2D u_texture;",
413 "uniform float u_alpha;",
414 "uniform float u_ambientDark;",
415 "uniform float u_litNW;",
416 "uniform float u_litNE;",
417 "uniform float u_litSW;",
418 "uniform float u_litSE;",
419 "uniform float u_time;",
420 "uniform float u_tileX;",
421 "uniform float u_tileY;",
422 "uniform float u_edgeN;",
423 "uniform float u_edgeE;",
424 "uniform float u_edgeS;",
425 "uniform float u_edgeW;",
426 "uniform float u_edgeNE;",
427 "uniform float u_edgeNW;",
428 "uniform float u_edgeSE;",
429 "uniform float u_edgeSW;",
430 "uniform float u_flowX;",
431 "uniform float u_flowY;",
432 "uniform float u_flowZ;",
433 "uniform float u_waveScale;",
434 "uniform float u_fbmAmp;",
435 "uniform float u_texAmp;",
436 "uniform float u_distort;",
437 "uniform float u_normalZ;",
438 "uniform float u_waveGain;",
439 "uniform float u_crestLo;",
440 "uniform float u_crestHi;",
441 "uniform float u_crestPow;",
442 "uniform float u_glitterPow;",
443 "uniform float u_crestGlitter;",
444 "uniform float u_glitterCap;",
445 "uniform float u_glitterMix;",
446 "uniform float u_shadeLo;",
447 "uniform float u_shadeHi;",
448 "uniform float u_bodyLo;",
449 "uniform float u_bodyHi;",
450 "uniform float u_litLo;",
451 "uniform float u_litHi;",
452 "uniform float u_litMix;",
453 "uniform float u_edgeDark;",
454 "uniform float u_lightDirX;",
455 "uniform float u_lightDirY;",
456 "uniform float u_lightDirZ;",
457 "uniform float u_normalEps;",
458 "uniform float u_shoreClip;",
459 "uniform float u_hasShore;",
460 "uniform float u_shoreEdgeN;",
461 "uniform float u_shoreEdgeE;",
462 "uniform float u_shoreEdgeS;",
463 "uniform float u_shoreEdgeW;",
464 "uniform float u_shoreEdgeNE;",
465 "uniform float u_shoreEdgeNW;",
466 "uniform float u_shoreEdgeSE;",
467 "uniform float u_shoreEdgeSW;",
468 "uniform vec4 u_shoreUvRect;",
469 "uniform sampler2D u_secondary;",
470 ...LAVA_FBM_COMMON,
471 "float sampleShore(",
472 " float enabled, float useShore, vec2 shoreNu,",
473 " inout vec3 shoreRgb, inout float shoreW",
474 ") {",
475 " if (enabled < 0.5 || useShore < 0.5 || u_hasShore < 0.5) { return 0.0; }",
476 " vec2 shoreUv = u_shoreUvRect.xy + shoreNu * (u_shoreUvRect.zw - u_shoreUvRect.xy);",
477 " vec4 shore = texture2D(u_secondary, shoreUv);",
478 " if (shore.a <= 0.1) { return 0.0; }",
479 " shoreRgb = shore.rgb;",
480 " shoreW = 1.0;",
481 " return 1.0;",
482 "}",
483 "void main() {",
484 " vec2 px = floor(v_texCoord * 16.0) + 0.5;",
485 " vec2 puv = px / 16.0;",
486 " vec2 world = vec2(u_tileX, u_tileY) + puv;",
487 " float t = u_time;",
488 " vec2 flow = vec2(t * u_flowX, t * u_flowY);",
489 " float eps = max(u_normalEps, 0.001);",
490 " vec3 base = vec3(world * u_waveScale + flow, t * u_flowZ);",
491 " float nC = fbm(base);",
492 " float nL = fbm(base + vec3(-eps, 0.0, 0.0));",
493 " float nR = fbm(base + vec3(eps, 0.0, 0.0));",
494 " float nD = fbm(base + vec3(0.0, -eps, 0.0));",
495 " float nU = fbm(base + vec3(0.0, eps, 0.0));",
496 " vec2 distort = vec2(nL - nR, nD - nU) * u_distort;",
497 " float texN = texture2D(u_texture, wrapUv(world * 0.28 + flow * 0.6 + distort)).r;",
498 " float h = nC * u_fbmAmp + (texN - 0.5) * u_texAmp;",
499 " vec3 normal = normalize(vec3(nL - nR, nD - nU, max(u_normalZ, 0.05)));",
500 " float ndotl = clamp(dot(normal, normalize(vec3(u_lightDirX, u_lightDirY, u_lightDirZ))), 0.0, 1.0);",
501 " float wave = clamp(h * u_waveGain + 0.5, 0.0, 1.0);",
502 " float crest = pow(smoothstep(u_crestLo, max(u_crestHi, u_crestLo + 0.01), wave), max(u_crestPow, 0.01));",
503 " float glitter = pow(max(0.0, ndotl), max(u_glitterPow, 0.01)) * crest;",
504 " glitter = max(glitter, pow(crest, 2.5) * u_crestGlitter);",
505 " float edgeProx = 0.0;",
506 " if (u_edgeN > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.y)); }",
507 " if (u_edgeS > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.y)); }",
508 " if (u_edgeW > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.x)); }",
509 " if (u_edgeE > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.x)); }",
510 " if (u_edgeNE > 0.5) {",
511 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, puv.y))));",
512 " }",
513 " if (u_edgeNW > 0.5) {",
514 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, puv.y))));",
515 " }",
516 " if (u_edgeSE > 0.5) {",
517 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, 1.0 - puv.y))));",
518 " }",
519 " if (u_edgeSW > 0.5) {",
520 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, 1.0 - puv.y))));",
521 " }",
522 " float waveBody = wave * (1.0 - edgeProx * 0.72);",
523 " float heat = smoothstep(u_bodyLo, max(u_bodyHi, u_bodyLo + 0.01), waveBody);",
524 " heat = mix(heat, 1.0, smoothstep(u_litLo, max(u_litHi, u_litLo + 0.01), waveBody) * u_litMix * 0.35);",
525 " heat = clamp(heat + min(glitter, u_glitterCap) * u_glitterMix * 0.45, 0.0, 1.0);",
526 " vec3 darkRed = vec3(0.16, 0.015, 0.01);",
527 " vec3 brightRed = vec3(0.78, 0.08, 0.02);",
528 " vec3 orange = vec3(0.98, 0.38, 0.04);",
529 " vec3 yellow = vec3(1.0, 0.9, 0.28);",
530 " vec3 rgb = mix(darkRed, brightRed, smoothstep(0.0, 0.38, heat));",
531 " rgb = mix(rgb, orange, smoothstep(0.28, 0.68, heat));",
532 " float yellowAmt = smoothstep(0.55, 0.98, heat);",
533 " rgb = mix(rgb, yellow, yellowAmt);",
534 " float shade = mix(u_shadeLo, u_shadeHi, ndotl);",
535 " rgb *= shade;",
536 " rgb = mix(rgb, darkRed, edgeProx * u_edgeDark * 0.35);",
537 " float shoreW = 0.0;",
538 " vec3 shoreRgb = rgb;",
539 " if (u_edgeN > 0.5) {",
540 " sampleShore(1.0, u_shoreEdgeN, vec2(puv.x, 1.0 - puv.y), shoreRgb, shoreW);",
541 " }",
542 " if (u_edgeS > 0.5) {",
543 " sampleShore(1.0, u_shoreEdgeS, vec2(puv.x, 1.0 - puv.y), shoreRgb, shoreW);",
544 " }",
545 " if (u_edgeW > 0.5) {",
546 " sampleShore(1.0, u_shoreEdgeW, vec2(1.0 - puv.x, puv.y), shoreRgb, shoreW);",
547 " }",
548 " if (u_edgeE > 0.5) {",
549 " sampleShore(1.0, u_shoreEdgeE, vec2(1.0 - puv.x, puv.y), shoreRgb, shoreW);",
550 " }",
551 " if (u_edgeNE > 0.5) {",
552 " sampleShore(1.0, max(u_shoreEdgeNE, u_hasShore), vec2(1.0 - puv.x, puv.y), shoreRgb, shoreW);",
553 " }",
554 " if (u_edgeNW > 0.5) {",
555 " sampleShore(1.0, max(u_shoreEdgeNW, u_hasShore), vec2(puv.x, puv.y), shoreRgb, shoreW);",
556 " }",
557 " if (u_edgeSE > 0.5) {",
558 " sampleShore(1.0, max(u_shoreEdgeSE, u_hasShore), vec2(1.0 - puv.x, 1.0 - puv.y), shoreRgb, shoreW);",
559 " }",
560 " if (u_edgeSW > 0.5) {",
561 " sampleShore(1.0, max(u_shoreEdgeSW, u_hasShore), vec2(puv.x, 1.0 - puv.y), shoreRgb, shoreW);",
562 " }",
563 " float darkAmt = 1.0 - smoothstep(0.12, 0.48, waveBody);",
564 " float retreat = edgeProx * mix(0.72, 1.0, darkAmt);",
565 " float shoreClip = u_shoreClip;",
566 " float shoreMask = step(shoreClip, retreat) * shoreW;",
567 " float crustAmt = (1.0 - shoreMask) * smoothstep(shoreClip - 0.2, shoreClip - 0.06, retreat)",
568 " * (1.0 - smoothstep(shoreClip - 0.06, shoreClip, retreat));",
569 " rgb = mix(rgb, vec3(0.05, 0.01, 0.0), crustAmt);",
570 " rgb = mix(rgb, shoreRgb, shoreMask);",
571 " float litTop = mix(u_litNW, u_litNE, v_texCoord.x);",
572 " float litBottom = mix(u_litSW, u_litSE, v_texCoord.x);",
573 " float lit = mix(litTop, litBottom, v_texCoord.y);",
574 " float darkness = u_ambientDark * (1.0 - lit);",
575 " rgb = mix(rgb, vec3(0.0), darkness);",
576 " gl_FragColor = vec4(rgb, u_alpha);",
577 "}"
578].join("\n");
579
580/** Unlit bloom overlay — strength tracks yellow heat (exempt from world darkness). */
581const LAVA_BLOOM_FRAG = [
582 "precision mediump float;",
583 "varying vec2 v_texCoord;",
584 "uniform sampler2D u_texture;",
585 "uniform float u_alpha;",
586 "uniform float u_time;",
587 "uniform float u_tileX;",
588 "uniform float u_tileY;",
589 "uniform float u_edgeN;",
590 "uniform float u_edgeE;",
591 "uniform float u_edgeS;",
592 "uniform float u_edgeW;",
593 "uniform float u_edgeNE;",
594 "uniform float u_edgeNW;",
595 "uniform float u_edgeSE;",
596 "uniform float u_edgeSW;",
597 "uniform float u_flowX;",
598 "uniform float u_flowY;",
599 "uniform float u_flowZ;",
600 "uniform float u_waveScale;",
601 "uniform float u_fbmAmp;",
602 "uniform float u_texAmp;",
603 "uniform float u_distort;",
604 "uniform float u_normalZ;",
605 "uniform float u_waveGain;",
606 "uniform float u_crestLo;",
607 "uniform float u_crestHi;",
608 "uniform float u_crestPow;",
609 "uniform float u_glitterPow;",
610 "uniform float u_crestGlitter;",
611 "uniform float u_glitterCap;",
612 "uniform float u_glitterMix;",
613 "uniform float u_bodyLo;",
614 "uniform float u_bodyHi;",
615 "uniform float u_litLo;",
616 "uniform float u_litHi;",
617 "uniform float u_litMix;",
618 "uniform float u_lightDirX;",
619 "uniform float u_lightDirY;",
620 "uniform float u_lightDirZ;",
621 "uniform float u_normalEps;",
622 "uniform float u_bloomStrength;",
623 "uniform float u_shoreClip;",
624 ...LAVA_FBM_COMMON,
625 "void main() {",
626 " vec2 px = floor(v_texCoord * 16.0) + 0.5;",
627 " vec2 puv = px / 16.0;",
628 " vec2 world = vec2(u_tileX, u_tileY) + puv;",
629 " float t = u_time;",
630 " vec2 flow = vec2(t * u_flowX, t * u_flowY);",
631 " float eps = max(u_normalEps, 0.001);",
632 " vec3 base = vec3(world * u_waveScale + flow, t * u_flowZ);",
633 " float nC = fbm(base);",
634 " float nL = fbm(base + vec3(-eps, 0.0, 0.0));",
635 " float nR = fbm(base + vec3(eps, 0.0, 0.0));",
636 " float nD = fbm(base + vec3(0.0, -eps, 0.0));",
637 " float nU = fbm(base + vec3(0.0, eps, 0.0));",
638 " vec2 distort = vec2(nL - nR, nD - nU) * u_distort;",
639 " float texN = texture2D(u_texture, wrapUv(world * 0.28 + flow * 0.6 + distort)).r;",
640 " float h = nC * u_fbmAmp + (texN - 0.5) * u_texAmp;",
641 " vec3 normal = normalize(vec3(nL - nR, nD - nU, max(u_normalZ, 0.05)));",
642 " float ndotl = clamp(dot(normal, normalize(vec3(u_lightDirX, u_lightDirY, u_lightDirZ))), 0.0, 1.0);",
643 " float wave = clamp(h * u_waveGain + 0.5, 0.0, 1.0);",
644 " float crest = pow(smoothstep(u_crestLo, max(u_crestHi, u_crestLo + 0.01), wave), max(u_crestPow, 0.01));",
645 " float glitter = pow(max(0.0, ndotl), max(u_glitterPow, 0.01)) * crest;",
646 " glitter = max(glitter, pow(crest, 2.5) * u_crestGlitter);",
647 " float edgeProx = 0.0;",
648 " if (u_edgeN > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.y)); }",
649 " if (u_edgeS > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.y)); }",
650 " if (u_edgeW > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.x)); }",
651 " if (u_edgeE > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.x)); }",
652 " if (u_edgeNE > 0.5) {",
653 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, puv.y))));",
654 " }",
655 " if (u_edgeNW > 0.5) {",
656 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, puv.y))));",
657 " }",
658 " if (u_edgeSE > 0.5) {",
659 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, 1.0 - puv.y))));",
660 " }",
661 " if (u_edgeSW > 0.5) {",
662 " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, 1.0 - puv.y))));",
663 " }",
664 " float waveBody = wave * (1.0 - edgeProx * 0.72);",
665 " float heat = smoothstep(u_bodyLo, max(u_bodyHi, u_bodyLo + 0.01), waveBody);",
666 " heat = mix(heat, 1.0, smoothstep(u_litLo, max(u_litHi, u_litLo + 0.01), waveBody) * u_litMix * 0.35);",
667 " heat = clamp(heat + min(glitter, u_glitterCap) * u_glitterMix * 0.45, 0.0, 1.0);",
668 " float darkAmt = 1.0 - smoothstep(0.12, 0.48, waveBody);",
669 " float retreat = edgeProx * mix(0.72, 1.0, darkAmt);",
670 " float hasEdge = max(max(u_edgeN, u_edgeE), max(u_edgeS, u_edgeW));",
671 " hasEdge = max(hasEdge, max(max(u_edgeNE, u_edgeNW), max(u_edgeSE, u_edgeSW)));",
672 " float shoreW = step(0.5, hasEdge);",
673 " float shoreMask = step(u_shoreClip, retreat) * shoreW;",
674 " float yellowAmt = smoothstep(0.55, 0.98, heat) * (1.0 - edgeProx * 0.85) * (1.0 - shoreMask);",
675 " float bloom = yellowAmt * max(u_bloomStrength, 0.0);",
676 " vec3 glow = vec3(1.0, 0.82, 0.28) * bloom;",
677 " gl_FragColor = vec4(glow, bloom * u_alpha);",
678 "}"
679].join("\n");
680
681/** Magenta-tint (R==B, G < R) then lit effects; darkness always after tint. */
682const TINT_LIT_SPRITE_FRAG = [
683 "precision mediump float;",
684 "varying vec2 v_texCoord;",
685 "uniform sampler2D u_texture;",
686 "uniform float u_alpha;",
687 "uniform float u_darkness;",
688 "uniform float u_strength;",
689 "uniform vec3 u_flashColor;",
690 "uniform float u_wade;",
691 "uniform float u_spriteHeight;",
692 "uniform float u_useTint;",
693 "uniform vec3 u_tintColor;",
694 "void main() {",
695 " vec4 color = texture2D(u_texture, v_texCoord);",
696 " if (color.a <= 0.0) { discard; }",
697 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
698 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
699 " vec3 rgb = color.rgb;",
700 " if (u_useTint > 0.5) {",
701 " if (abs(color.r - color.b) * 255.0 <= 2.01 && color.g < color.r) {",
702 " float L = color.r;",
703 " float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;",
704 " rgb = mix(u_tintColor, vec3(1.0), gBlend) * L;",
705 " }",
706 " }",
707 " if (u_wade > 0.5 && fromBottom < 5.0) {",
708 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
709 " }",
710 " rgb = mix(rgb, vec3(0.0), u_darkness);",
711 " rgb = mix(rgb, u_flashColor, u_strength);",
712 " gl_FragColor = vec4(rgb, color.a * u_alpha);",
713 "}"
714].join("\n");
715
716/** Dual/triple-channel tint: red = shaft, blue = tip, green = coat; then darkness.
717 * Only when the primary channel is highest and the other two are equal;
718 * equal non-zero secondaries lighten the assigned tint toward white. */
719const DUAL_TINT_LIT_SPRITE_FRAG = [
720 "precision mediump float;",
721 "varying vec2 v_texCoord;",
722 "uniform sampler2D u_texture;",
723 "uniform float u_alpha;",
724 "uniform float u_darkness;",
725 "uniform float u_strength;",
726 "uniform vec3 u_flashColor;",
727 "uniform float u_wade;",
728 "uniform float u_spriteHeight;",
729 "uniform vec3 u_shaftTint;",
730 "uniform vec3 u_tipTint;",
731 "uniform vec3 u_coatTint;",
732 "uniform float u_hasCoat;",
733 "vec3 channelTint(float L, float secondary, vec3 tint) {",
734 " float blend = L > 0.0 ? clamp(secondary / L, 0.0, 1.0) : 0.0;",
735 " return mix(tint, vec3(1.0), blend) * L;",
736 "}",
737 "float channelMask(float primary, float o1, float o2) {",
738 " float equal = step(abs(o1 - o2), 0.04);",
739 " return clamp((primary - max(o1, o2)) * 1.75, 0.0, 1.0) * equal;",
740 "}",
741 "void main() {",
742 " vec4 color = texture2D(u_texture, v_texCoord);",
743 " if (color.a <= 0.0) { discard; }",
744 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
745 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
746 " vec3 rgb = color.rgb;",
747 " if (u_hasCoat > 0.5) {",
748 " float coatMask = channelMask(color.g, color.r, color.b);",
749 " if (coatMask > 0.0) {",
750 " vec3 coatCol = channelTint(color.g, color.r, u_coatTint);",
751 " rgb = mix(rgb, coatCol, coatMask);",
752 " }",
753 " }",
754 " float tipMask = channelMask(color.b, color.r, color.g);",
755 " if (tipMask > 0.0) {",
756 " vec3 tipCol = channelTint(color.b, color.r, u_tipTint);",
757 " rgb = mix(rgb, tipCol, tipMask);",
758 " }",
759 " float shaftMask = channelMask(color.r, color.g, color.b);",
760 " if (shaftMask > 0.0) {",
761 " vec3 shaftCol = channelTint(color.r, color.g, u_shaftTint);",
762 " rgb = mix(rgb, shaftCol, shaftMask);",
763 " }",
764 " if (u_wade > 0.5 && fromBottom < 5.0) {",
765 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
766 " }",
767 " rgb = mix(rgb, vec3(0.0), u_darkness);",
768 " rgb = mix(rgb, u_flashColor, u_strength);",
769 " gl_FragColor = vec4(rgb, color.a * u_alpha);",
770 "}"
771].join("\n");
772
773/** Magenta-tint equip overlay that clips alpha to the worn body silhouette. */
774/**
775 * Tight-fit: clip clothing alpha to the body silhouette in *pivot space*
776 * (sizes may differ: shirt 20×24 vs body 16×24). Sample body UV remapped from
777 * clothing frame coords; 1px dilate fills armpit/crotch gaps in the body art.
778 */
779const TIGHT_FIT_BODY_MASK_GLSL = [
780 "uniform vec2 u_clothSize;",
781 "uniform vec2 u_bodySize;",
782 "uniform float u_pivotFromBottom;",
783 "uniform vec4 u_clothUvRect;",
784 "uniform vec4 u_bodyUvRect;",
785 "float tightFitBodyAlpha() {",
786 " vec2 clothSpan = max(u_clothUvRect.zw - u_clothUvRect.xy, vec2(1e-5));",
787 " vec2 nu = (v_texCoord - u_clothUvRect.xy) / clothSpan;",
788 " float ox = (nu.x - 0.5) * u_clothSize.x;",
789 " float oy = nu.y * u_clothSize.y - (u_clothSize.y - u_pivotFromBottom);",
790 " vec2 bodySize = max(u_bodySize, vec2(1.0));",
791 " vec2 bodyNu = vec2(0.5 + ox / bodySize.x, ((u_bodySize.y - u_pivotFromBottom) + oy) / bodySize.y);",
792 " vec2 bodySpan = max(u_bodyUvRect.zw - u_bodyUvRect.xy, vec2(1e-5));",
793 " vec2 texel = 1.0 / bodySize;",
794 " float bodyA = 0.0;",
795 " for (int dy = -1; dy <= 1; dy++) {",
796 " for (int dx = -1; dx <= 1; dx++) {",
797 " vec2 sampleNu = bodyNu + vec2(float(dx), float(dy)) * texel;",
798 " if (sampleNu.x < 0.0 || sampleNu.x > 1.0 || sampleNu.y < 0.0 || sampleNu.y > 1.0) { continue; }",
799 " vec2 sampleUv = u_bodyUvRect.xy + sampleNu * bodySpan;",
800 " bodyA = max(bodyA, texture2D(u_secondary, sampleUv).a);",
801 " }",
802 " }",
803 " return bodyA;",
804 "}"
805].join("\n");
806
807const TIGHT_FIT_TINT_LIT_SPRITE_FRAG = [
808 "precision mediump float;",
809 "varying vec2 v_texCoord;",
810 "uniform sampler2D u_texture;",
811 "uniform sampler2D u_secondary;",
812 "uniform float u_alpha;",
813 "uniform float u_darkness;",
814 "uniform float u_strength;",
815 "uniform vec3 u_flashColor;",
816 "uniform float u_wade;",
817 "uniform float u_spriteHeight;",
818 "uniform float u_useTint;",
819 "uniform vec3 u_tintColor;",
820 TIGHT_FIT_BODY_MASK_GLSL,
821 "void main() {",
822 " vec4 color = texture2D(u_texture, v_texCoord);",
823 " if (color.a <= 0.0) { discard; }",
824 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
825 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
826 " vec3 rgb = color.rgb;",
827 " if (u_useTint > 0.5) {",
828 " if (abs(color.r - color.b) * 255.0 <= 2.01 && color.g < color.r) {",
829 " float L = color.r;",
830 " float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;",
831 " rgb = mix(u_tintColor, vec3(1.0), gBlend) * L;",
832 " }",
833 " }",
834 " if (u_wade > 0.5 && fromBottom < 5.0) {",
835 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
836 " }",
837 " rgb = mix(rgb, vec3(0.0), u_darkness);",
838 " rgb = mix(rgb, u_flashColor, u_strength);",
839 " float alpha = min(tightFitBodyAlpha(), color.a) * u_alpha;",
840 " if (alpha <= 0.0) { discard; }",
841 " gl_FragColor = vec4(rgb, alpha);",
842 "}"
843].join("\n");
844
845/** Body-clipped equip overlay without dye recolour. */
846const TIGHT_FIT_LIT_SPRITE_FRAG = [
847 "precision mediump float;",
848 "varying vec2 v_texCoord;",
849 "uniform sampler2D u_texture;",
850 "uniform sampler2D u_secondary;",
851 "uniform float u_alpha;",
852 "uniform float u_darkness;",
853 "uniform float u_strength;",
854 "uniform vec3 u_flashColor;",
855 "uniform float u_wade;",
856 "uniform float u_spriteHeight;",
857 TIGHT_FIT_BODY_MASK_GLSL,
858 "void main() {",
859 " vec4 color = texture2D(u_texture, v_texCoord);",
860 " if (color.a <= 0.0) { discard; }",
861 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
862 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
863 " vec3 rgb = color.rgb;",
864 " if (u_wade > 0.5 && fromBottom < 5.0) {",
865 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
866 " }",
867 " rgb = mix(rgb, vec3(0.0), u_darkness);",
868 " rgb = mix(rgb, u_flashColor, u_strength);",
869 " float alpha = min(tightFitBodyAlpha(), color.a) * u_alpha;",
870 " if (alpha <= 0.0) { discard; }",
871 " gl_FragColor = vec4(rgb, alpha);",
872 "}"
873].join("\n");
874
875const ATLAS_LIGHTING_FRAG = [
876 "precision mediump float;",
877 "varying vec2 v_texCoord;",
878 "uniform sampler2D u_texture;",
879 "uniform sampler2D u_secondary;",
880 "uniform sampler2D u_bump;",
881 "uniform float u_alpha;",
882 "uniform float u_ambientDark;",
883 "uniform float u_lightRow;",
884 "uniform float u_useNature;",
885 "uniform float u_natureTint;",
886 "uniform float u_natureDark;",
887 "uniform float u_natureContrast;",
888 "void main() {",
889 " vec4 color = texture2D(u_texture, v_texCoord);",
890 " if (color.a <= 0.0) { discard; }",
891 " vec3 rgb = color.rgb;",
892 " if (u_useNature > 0.5) {",
893 // Soft bilinear over 18×18 noise (1-tile halo) so blend crosses chunk edges.
894 " vec2 texel = v_texCoord * 16.0 - 0.5;",
895 " vec2 i0 = floor(texel);",
896 " vec2 f = fract(texel);",
897 " vec2 i1 = i0 + 1.0;",
898 " vec2 c00 = (i0 + 1.5) / 18.0;",
899 " vec2 c10 = (vec2(i1.x, i0.y) + 1.5) / 18.0;",
900 " vec2 c01 = (vec2(i0.x, i1.y) + 1.5) / 18.0;",
901 " vec2 c11 = (i1 + 1.5) / 18.0;",
902 " vec4 s00 = texture2D(u_bump, c00);",
903 " vec4 s10 = texture2D(u_bump, c10);",
904 " vec4 s01 = texture2D(u_bump, c01);",
905 " vec4 s11 = texture2D(u_bump, c11);",
906 " float nRaw = mix(mix(s00.r, s10.r, f.x), mix(s01.r, s11.r, f.x), f.y);",
907 " float a = mix(mix(s00.a, s10.a, f.x), mix(s01.a, s11.a, f.x), f.y);",
908 " if (a > 0.01) {",
909 " float n = clamp((nRaw - 0.5) * max(u_natureContrast, 0.01) + 0.5, 0.0, 1.0);",
910 " float c = (n - 0.5) * 2.0;",
911 " vec3 tinted = rgb * (1.0 - c * u_natureDark);",
912 " vec3 cool = vec3(0.72, 1.14, 1.08);",
913 " vec3 warm = vec3(1.28, 1.06, 0.68);",
914 " vec3 tint = mix(cool, warm, n);",
915 " tinted *= mix(vec3(1.0), tint, clamp(u_natureTint, 0.0, 1.0));",
916 " rgb = mix(rgb, tinted, clamp(a, 0.0, 1.0));",
917 " }",
918 " }",
919 " vec2 lightUV = v_texCoord;",
920 " if (u_lightRow >= 0.0) {",
921 " lightUV.y = (u_lightRow + v_texCoord.y) / 16.0;",
922 " }",
923 " float lit = texture2D(u_secondary, lightUV).r;",
924 " float darkness = u_ambientDark * (1.0 - lit);",
925 " rgb = mix(rgb, vec3(0.0), darkness);",
926 " gl_FragColor = vec4(rgb, color.a * u_alpha);",
927 "}"
928].join("\n");
929
930/**
931 * Per-tile cliff sprite: high-chroma / authored magenta top → sample this chunk's
932 * ground atlas (u_bump) at the cliff's tile-local UV. Only assigned to
933 * `cliffGroundTop` blocks — never to chunk block-row atlases (those keep normal
934 * lighting so magenta wood tints are not mistaken for cliff tops).
935 */
936const SPRITE_CLIFF_GROUND_TOP_FRAG = [
937 "precision mediump float;",
938 "varying vec2 v_texCoord;",
939 "uniform sampler2D u_texture;",
940 "uniform sampler2D u_bump;",
941 "uniform float u_alpha;",
942 "uniform float u_darkness;",
943 "uniform vec2 u_tileLocal;",
944 "void main() {",
945 " vec4 color = texture2D(u_texture, v_texCoord);",
946 " if (color.a <= 0.0) { discard; }",
947 " vec3 rgb = color.rgb;",
948 " float rbDiff = abs(rgb.r - rgb.b);",
949 " if (rbDiff < 0.02 && rgb.g < rgb.r) {",
950 " vec2 groundUV = (u_tileLocal + v_texCoord) / 16.0;",
951 " rgb = texture2D(u_bump, groundUV).rgb;",
952 " }",
953 " rgb = mix(rgb, vec3(0.0), u_darkness);",
954 " gl_FragColor = vec4(rgb, color.a * u_alpha);",
955 "}"
956].join("\n");
957
958let spriteLightingShader = null;
959let atlasLightingShader = null;
960let cliffGroundTopShader = null;
961let waterGroundShader = null;
962let lavaGroundShader = null;
963let lavaBloomShader = null;
964let tintLitSpriteShader = null;
965let dualTintLitSpriteShader = null;
966let tightFitTintLitSpriteShader = null;
967let tightFitLitSpriteShader = null;
968
969function getSpriteLightingShader ()
970{
971 if (!spriteLightingShader)
972 { spriteLightingShader = Shader.fragment(SPRITE_LIGHTING_FRAG); }
973 return spriteLightingShader;
974}
975
976function getAtlasLightingShader ()
977{
978 if (!atlasLightingShader)
979 { atlasLightingShader = Shader.fragment(ATLAS_LIGHTING_FRAG); }
980 return atlasLightingShader;
981}
982
983function getCliffGroundTopShader ()
984{
985 if (!cliffGroundTopShader)
986 { cliffGroundTopShader = Shader.fragment(SPRITE_CLIFF_GROUND_TOP_FRAG); }
987 return cliffGroundTopShader;
988}
989
990function getWaterGroundShader ()
991{
992 if (!waterGroundShader)
993 { waterGroundShader = Shader.fragment(WATER_GROUND_FRAG); }
994 return waterGroundShader;
995}
996
997function getLavaGroundShader ()
998{
999 if (!lavaGroundShader)
1000 { lavaGroundShader = Shader.fragment(LAVA_GROUND_FRAG); }
1001 return lavaGroundShader;
1002}
1003
1004function getLavaBloomShader ()
1005{
1006 if (!lavaBloomShader)
1007 { lavaBloomShader = Shader.fragment(LAVA_BLOOM_FRAG); }
1008 return lavaBloomShader;
1009}
1010
1011function getTintLitSpriteShader ()
1012{
1013 if (!tintLitSpriteShader)
1014 { tintLitSpriteShader = Shader.fragment(TINT_LIT_SPRITE_FRAG); }
1015 return tintLitSpriteShader;
1016}
1017
1018function getDualTintLitSpriteShader ()
1019{
1020 if (!dualTintLitSpriteShader)
1021 { dualTintLitSpriteShader = Shader.fragment(DUAL_TINT_LIT_SPRITE_FRAG); }
1022 return dualTintLitSpriteShader;
1023}
1024
1025function getTightFitTintLitSpriteShader ()
1026{
1027 if (!tightFitTintLitSpriteShader)
1028 { tightFitTintLitSpriteShader = Shader.fragment(TIGHT_FIT_TINT_LIT_SPRITE_FRAG); }
1029 return tightFitTintLitSpriteShader;
1030}
1031
1032function getTightFitLitSpriteShader ()
1033{
1034 if (!tightFitLitSpriteShader)
1035 { tightFitLitSpriteShader = Shader.fragment(TIGHT_FIT_LIT_SPRITE_FRAG); }
1036 return tightFitLitSpriteShader;
1037}
1038
1039export class WorldView
1040{
1041 #chunkRebuildKeys = new Set();
1042 /** Soft-blend / wet-sand neighbor rebakes — deferred so they do not nest inside a primary bake. */
1043 #chunkSoftNeighborKeys = new Set();
1044 #chunkRebuildRaf = 0;
1045 #edgesDirty = false;
1046 #CHUNK_REBUILD_BATCH = 2;
1047 #pendingTextureCanvases = [];
1048 #pendingTextureCanvasSet = new Set();
1049 #textureWarmRaf = 0;
1050 #TEXTURE_WARM_BATCH = 3;
1051 #atlasCache = createChunkAtlasCache();
1052 #idlePrefetchId = 0;
1053 #playerChunkX = null;
1054 #playerChunkY = null;
1055 #playerMoveChunkDx = 0;
1056 #playerMoveChunkDy = 0;
1057 /** Reused by {@link #placePivoted} to avoid per-call `new vector()`. */
1058 #placeSizeScratch = new vector(0, 0);
1059
1060 constructor(game, scene, catalog = { grounds: {}, blocks: {} })
1061 {
1062 this.game = game;
1063 this.scene = scene;
1064 this.catalog = catalog;
1065 this.preview = null;
1066 this.zoom = 2;
1067 /** Chunk-quantised world-Y origin for the depth sort (see {@link #depthLayer}). */
1068 this.ySortOrigin = null;
1069 this.chunks = new Map();
1070 this.bakedChunks = new Map();
1071 this.tiles = new Map();
1072 this.entities = new Map();
1073 this.groundItems = new Map();
1074 this.edges = new Map();
1075 this.localEntityId = null;
1076 this.localBlind = false;
1077 /** @type {string} */
1078 this.dimensionId = OVERWORLD_ID;
1079 /** @type {string} */
1080 this.dimensionLightingMode = "dayNight";
1081 /** @type {string} */
1082 this.dimensionSeasonMode = "auto";
1083 /** Calendar season from worldStatus when dimension season is auto. */
1084 this.calendarSeason = seasonIdAt();
1085 /** @type {"soft"|"simple"} */
1086 this.lightingMode = "soft";
1087 /** @type {boolean} */
1088 this.bloomEnabled = true;
1089 /** Soft edge blend for blendable grounds (grass, dirt, …). */
1090 this.softTerrain = false;
1091 /**
1092 * Per-chunk nature Perlin tint. Off in the world editor while painting
1093 * (rebakes are frequent); editor enables a one-shot bake on chunk save.
1094 */
1095 this.natureTintEnabled = true;
1096 this.settings = { ...DEFAULT_WORLD_SETTINGS };
1097 this.worldHour = 12;
1098 /** Calendar season for seasonal ground/block visuals (`spring` / `summer` / `fall` / `winter`). */
1099 this.worldSeason = seasonIdAt();
1100 this.nightPreview = null;
1101 this.followPlayer = true;
1102 this.dynamicLights = [];
1103 /** Persistent Light-spell tile lights (server-driven). */
1104 this.spellLights = new Map();
1105 /** Persistent Dark-spell tile darkness (server-driven). */
1106 this.spellDarks = new Map();
1107 this.swipes = [];
1108 this.damageFloats = [];
1109 this.damageNumbersEl = document.getElementById("damage-numbers");
1110 this.skillLevelFloats = [];
1111 this.skillLevelFloatsEl = document.getElementById("skill-level-floats");
1112 /** @type {Map<string, { object: object, tileX: number, tileY: number, spriteName: string }>} */
1113 this.editorSpawners = new Map();
1114 this.spawnRangeHighlight = null;
1115 this.wanderRangeHighlight = null;
1116 this.spellTargetHighlight = null;
1117 this.#syncBloomLayer();
1118 }
1119
1120 setSettings (settings)
1121 {
1122 const previous = this.settings;
1123 this.settings = { ...DEFAULT_WORLD_SETTINGS, ...settings };
1124 this.#syncBloomLayer();
1125 const prevBand = Number(previous?.wetSandBand);
1126 const nextBand = Number(this.settings.wetSandBand);
1127 if (Number.isFinite(nextBand) && prevBand !== nextBand)
1128 { this.#rebakeAllChunks(); }
1129 }
1130
1131 /**
1132 * Client graphics prefs (lighting Soft/Simple, bloom On/Off, soft terrain).
1133 * @param {{ lighting?: string, bloom?: string, softTerrain?: string }} prefs
1134 */
1135 setGraphicsPrefs (prefs)
1136 {
1137 if (prefs?.lighting === "simple" || prefs?.lighting === "soft")
1138 { this.lightingMode = prefs.lighting; }
1139 if (prefs?.bloom === "off" || prefs?.bloom === "on")
1140 {
1141 const enabled = prefs.bloom !== "off";
1142 if (enabled !== this.bloomEnabled)
1143 {
1144 this.bloomEnabled = enabled;
1145 this.#syncBloomLayer();
1146 }
1147 else
1148 { this.bloomEnabled = enabled; }
1149 }
1150 if (prefs?.softTerrain === "on" || prefs?.softTerrain === "off")
1151 {
1152 const enabled = prefs.softTerrain === "on";
1153 if (enabled !== this.softTerrain)
1154 {
1155 this.softTerrain = enabled;
1156 this.#rebakeAllChunks();
1157 }
1158 }
1159 }
1160
1161 /** Apply server (or local) calendar season; rebakes chunks when it changes. */
1162 setWorldSeason (season)
1163 {
1164 const calendar = season === SeasonId.spring
1165 || season === SeasonId.fall
1166 || season === SeasonId.winter
1167 || season === SeasonId.summer
1168 ? season
1169 : seasonIdAt();
1170 this.calendarSeason = calendar;
1171 const forced = resolveDimensionSeasonId(this.dimensionSeasonMode);
1172 const next = forced ?? calendar;
1173 if (next === this.worldSeason)
1174 { return; }
1175 this.worldSeason = next;
1176 this.#rebakeAllChunks();
1177 }
1178
1179 setDimensionId (dimensionId)
1180 {
1181 this.dimensionId = normalizeDimensionId(dimensionId);
1182 }
1183
1184 setDimensionModes (lightingMode, seasonMode)
1185 {
1186 this.dimensionLightingMode = normalizeLightingMode(lightingMode);
1187 this.dimensionSeasonMode = normalizeSeasonMode(seasonMode);
1188 const forced = resolveDimensionSeasonId(this.dimensionSeasonMode);
1189 const next = forced ?? this.calendarSeason ?? seasonIdAt();
1190 if (next !== this.worldSeason)
1191 {
1192 this.worldSeason = next;
1193 this.#rebakeAllChunks();
1194 }
1195 }
1196
1197 clearAllChunks ()
1198 {
1199 for (const key of [...this.chunks.keys()])
1200 {
1201 const [chunkX, chunkY] = key.split(",").map(Number);
1202 this.removeChunk(chunkX, chunkY);
1203 }
1204 for (const [id] of [...this.entities.entries()])
1205 {
1206 if (id === this.localEntityId)
1207 { continue; }
1208 this.despawnEntity(id, { immediate: true });
1209 }
1210 for (const [id] of [...this.groundItems.entries()])
1211 { this.despawnGroundItem(id); }
1212 }
1213
1214 /** Full client wipe when leaving the world (menu / disconnect). Includes the local player. */
1215 clearPlaySession ()
1216 {
1217 this.#cancelIdlePrefetch();
1218 this.#chunkRebuildKeys.clear();
1219 this.#chunkSoftNeighborKeys.clear();
1220 this.#playerChunkX = null;
1221 this.#playerChunkY = null;
1222 this.#playerMoveChunkDx = 0;
1223 this.#playerMoveChunkDy = 0;
1224 this.localEntityId = null;
1225 for (const key of [...this.chunks.keys()])
1226 {
1227 const [chunkX, chunkY] = key.split(",").map(Number);
1228 this.removeChunk(chunkX, chunkY);
1229 }
1230 for (const [id] of [...this.entities.entries()])
1231 { this.despawnEntity(id, { immediate: true }); }
1232 for (const [id] of [...this.groundItems.entries()])
1233 { this.despawnGroundItem(id); }
1234 }
1235
1236 applySnapshot (snapshot)
1237 {
1238 const snapDim = normalizeDimensionId(snapshot.dimensionId ?? OVERWORLD_ID);
1239 if (normalizeDimensionId(this.dimensionId) !== snapDim)
1240 { return; }
1241 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
1242 snapshot.occlusion = bakeChunkOcclusion(snapshot);
1243 this.chunks.set(key, snapshot);
1244 this.#scheduleChunkRebuild(snapshot);
1245 this.#redrawPreview();
1246 this.#refreshWaterCoastsNear(snapshot.chunkX, snapshot.chunkY);
1247 if (snapshot.staticOnly)
1248 {
1249 this.#stripChunkDynamic(snapshot.chunkX, snapshot.chunkY);
1250 this.#scheduleEdgeRebuild();
1251 return;
1252 }
1253 for (const entity of snapshot.entities ?? [])
1254 { this.#upsertEntity(entity); }
1255 for (const [id, item] of [...this.groundItems.entries()])
1256 {
1257 if (Math.floor(item.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(item.tileY / CHUNK_SIZE) === snapshot.chunkY)
1258 { this.despawnGroundItem(id); }
1259 }
1260 for (const item of snapshot.groundItems ?? [])
1261 { this.upsertGroundItem(item); }
1262 this.#scheduleEdgeRebuild();
1263 }
1264
1265 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null, skullValue = 0)
1266 {
1267 this.localEntityId = entityId;
1268 this.#upsertEntity({
1269 entityId,
1270 characterId,
1271 tileX,
1272 tileY,
1273 gait,
1274 sex,
1275 firstName,
1276 lastName,
1277 layers: layers ?? undefined,
1278 skullValue: skullValue | 0,
1279 ...(health != null ? { health } : {}),
1280 ...(maxHealth != null ? { maxHealth } : {})
1281 });
1282 this.#notePlayerTile(tileX, tileY);
1283 }
1284
1285 #stripChunkDynamic (chunkX, chunkY)
1286 {
1287 for (const [id, item] of [...this.groundItems.entries()])
1288 {
1289 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
1290 { this.despawnGroundItem(id); }
1291 }
1292 for (const [id, entity] of [...this.entities.entries()])
1293 {
1294 if (id === this.localEntityId)
1295 { continue; }
1296 if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX
1297 && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY)
1298 { this.despawnEntity(id, { immediate: true }); }
1299 }
1300 }
1301
1302 removeChunk (chunkX, chunkY)
1303 {
1304 const key = `${chunkX},${chunkY}`;
1305 this.chunks.delete(key);
1306 this.#destroyBakedChunk(key);
1307 this.#destroyEdges(key);
1308 const prefix = `${chunkX},${chunkY}:`;
1309 for (const [spawnerKey, entry] of [...this.editorSpawners.entries()])
1310 {
1311 if (!spawnerKey.startsWith(prefix))
1312 { continue; }
1313 this.#destroyEditorSpawnerEntry(entry);
1314 this.editorSpawners.delete(spawnerKey);
1315 }
1316 for (const [tileKey, objects] of [...this.tiles.entries()])
1317 {
1318 if (objects.chunkX === chunkX && objects.chunkY === chunkY)
1319 {
1320 objects.ground?.destroy();
1321 objects.groundBloom?.destroy();
1322 objects.lavaBloom?.destroy();
1323 objects.block?.destroy();
1324 objects.blockBloom?.destroy();
1325 this.tiles.delete(tileKey);
1326 }
1327 }
1328 for (const [id, item] of [...this.groundItems.entries()])
1329 {
1330 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
1331 { this.despawnGroundItem(id); }
1332 }
1333 // Server sends unsubscribeChunk when a chunk leaves the static 5×5 ring.
1334 // Entity replication is limited to the inner 3×3; static-only chunks strip dynamics via staticOnly snapshots.
1335 for (const [id, entity] of [...this.entities.entries()])
1336 {
1337 if (id === this.localEntityId)
1338 { continue; }
1339 if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX
1340 && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY)
1341 { this.despawnEntity(id, { immediate: true }); }
1342 }
1343 this.#rebuildAllEdges();
1344 }
1345
1346 setChunkOpen (chunkX, chunkY, open)
1347 {
1348 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
1349 if (!snapshot)
1350 { return; }
1351 snapshot.open = !!open;
1352 this.#rebuildAllEdges();
1353 }
1354
1355 spawnEntity (payload)
1356 {
1357 // Fresh spawn is authoritative; do not let an older deferred hit overwrite HP.
1358 this.cancelDeferredCombatHits(payload?.entityId);
1359 this.#upsertEntity(payload);
1360 }
1361
1362 moveEntity (payload)
1363 {
1364 const existing = this.entities.get(payload.entityId);
1365 // Move payloads lack appearance/mobTypeId — never invent a stub entity
1366 // (that looked like a nameless humanoid "target"). Wait for entity-spawn.
1367 if (!existing)
1368 { return; }
1369 // Fading corpses stay put; respawn restores via reviveAfterDeath / spawn.
1370 if (existing.dying)
1371 { return; }
1372 const size = this.tileSize();
1373 existing.fromX = existing.visualX;
1374 existing.fromY = existing.visualY;
1375 existing.shadeFromTileX = existing.tileX;
1376 existing.shadeFromTileY = existing.tileY;
1377 if (existing.tileX !== payload.tileX || existing.tileY !== payload.tileY)
1378 {
1379 existing.previousTileX = existing.tileX;
1380 existing.previousTileY = existing.tileY;
1381 }
1382 existing.tileX = payload.tileX;
1383 existing.tileY = payload.tileY;
1384 existing.gait = payload.gait;
1385 existing.freeFlight = !!payload.freeFlight || existing.freeFlight;
1386 if (payload.worldX != null && payload.worldY != null)
1387 {
1388 existing.worldX = payload.worldX;
1389 existing.worldY = payload.worldY;
1390 existing.targetX = payload.worldX * size;
1391 existing.targetY = payload.worldY * size;
1392 }
1393 else
1394 {
1395 const pivot = tilePivot(payload.tileX, payload.tileY, size);
1396 existing.targetX = pivot.x;
1397 existing.targetY = pivot.y;
1398 }
1399 existing.lerpStarted = performance.now();
1400 existing.lerpMs = payload.lerpMs ?? this.#lerpMs(payload.gait);
1401 if (payload.entityId === this.localEntityId)
1402 { this.#notePlayerTile(payload.tileX, payload.tileY); }
1403 }
1404
1405 despawnEntity (entityId, { immediate = false, combatDeath = false } = {})
1406 {
1407 const existing = this.entities.get(entityId);
1408 if (!existing)
1409 { return; }
1410 if (existing.dying)
1411 {
1412 if (immediate)
1413 { this.#finishEntityFade(entityId); }
1414 else if (combatDeath)
1415 { this.#upgradeToDeathDissolve(existing); }
1416 return;
1417 }
1418 // Chunk unload / session wipe: drop instantly.
1419 if (immediate)
1420 {
1421 this.cancelDeferredCombatHits(entityId);
1422 this.#destroyEntityVisuals(existing);
1423 this.entities.delete(entityId);
1424 return;
1425 }
1426 // Combat death → red silhouette. Leaving 3×3 / summons / etc. → plain fade.
1427 if (combatDeath)
1428 { this.#beginDeathDissolve(existing); }
1429 else
1430 { this.#beginDespawnFade(existing); }
1431 }
1432
1433 /**
1434 * Start the red silhouette fade without requiring a despawn message
1435 * (e.g. local playerDied arrives before entityDespawn).
1436 */
1437 beginDeathDissolve (entityId)
1438 {
1439 const existing = this.entities.get(entityId);
1440 if (!existing)
1441 { return; }
1442 if (existing.dying)
1443 {
1444 this.#upgradeToDeathDissolve(existing);
1445 return;
1446 }
1447 this.#beginDeathDissolve(existing);
1448 }
1449
1450 /**
1451 * Abort an in-progress (or finished) death fade and snap the sprite back.
1452 * Local players are never entity-despawned, so respawn must restore — not
1453 * destroy — the visual. Remotes get a fresh entity-spawn instead.
1454 */
1455 reviveAfterDeath (entityId, { tileX, tileY, health, maxHealth, skullValue } = {})
1456 {
1457 const entity = this.entities.get(entityId);
1458 if (!entity)
1459 { return false; }
1460 this.#abortEntityFade(entity);
1461 if (tileX != null && tileY != null)
1462 { this.#snapEntityToTile(entity, tileX, tileY); }
1463 if (health != null)
1464 { entity.health = health; }
1465 if (maxHealth != null)
1466 { entity.maxHealth = maxHealth; }
1467 if (skullValue != null)
1468 { entity.skullValue = Math.max(0, skullValue | 0); }
1469 this.#syncHpBar(entity);
1470 this.#syncSkullMarker(entity);
1471 this.#placeEntity(entity, performance.now());
1472 return true;
1473 }
1474
1475 #destroyEntityVisuals (existing)
1476 {
1477 existing.object?.destroy();
1478 existing.hpBar?.destroy();
1479 existing.skullMarker?.destroy();
1480 for (const overlay of existing.overlays ?? [])
1481 { overlay.destroy(); }
1482 for (const overlay of existing.bloomOverlays ?? [])
1483 { overlay.destroy(); }
1484 }
1485
1486 #stripEntityChrome (entity)
1487 {
1488 entity.hpBar?.destroy();
1489 entity.hpBar = null;
1490 entity.skullMarker?.destroy();
1491 entity.skullMarker = null;
1492 }
1493
1494 #beginDespawnFade (entity)
1495 {
1496 const now = performance.now();
1497 entity.dying = true;
1498 entity.deathDissolve = false;
1499 entity.untargetable = true;
1500 entity.deathFadeStarted = now;
1501 entity.deathFadeMs = DESPAWN_FADE_MS;
1502 this.#stripEntityChrome(entity);
1503 }
1504
1505 #beginDeathDissolve (entity)
1506 {
1507 const now = performance.now();
1508 entity.dying = true;
1509 entity.deathDissolve = true;
1510 entity.untargetable = true;
1511 entity.deathFadeStarted = now;
1512 entity.deathFadeMs = DEATH_FADE_MS;
1513 // Keep a full red silhouette for the whole fade (hit flash may already be running).
1514 entity.damageFlashUntil = now + DEATH_FADE_MS;
1515 entity.damageFlashColor = FLASH_COLOR_DAMAGE;
1516 this.#stripEntityChrome(entity);
1517 // Leave deferred projectile impacts queued so knockback / float still play on arrival.
1518 }
1519
1520 /** Promote an in-progress plain despawn fade to the red combat dissolve. */
1521 #upgradeToDeathDissolve (entity)
1522 {
1523 if (entity.deathDissolve)
1524 { return; }
1525 const now = performance.now();
1526 const elapsed = Math.max(0, now - (entity.deathFadeStarted ?? now));
1527 const remaining = Math.max(1, (entity.deathFadeMs ?? DESPAWN_FADE_MS) - elapsed);
1528 entity.deathDissolve = true;
1529 entity.deathFadeStarted = now;
1530 entity.deathFadeMs = Math.min(DEATH_FADE_MS, remaining);
1531 entity.damageFlashUntil = now + entity.deathFadeMs;
1532 entity.damageFlashColor = FLASH_COLOR_DAMAGE;
1533 }
1534
1535 #abortEntityFade (entity)
1536 {
1537 entity.dying = false;
1538 entity.deathDissolve = false;
1539 entity.untargetable = false;
1540 entity.deathFadeStarted = null;
1541 entity.deathFadeMs = null;
1542 entity.damageFlashUntil = 0;
1543 entity.damageFlashColor = null;
1544 if (entity.object?.renderer)
1545 { entity.object.renderer.alpha = 1; }
1546 for (const overlay of entity.overlays ?? [])
1547 {
1548 if (overlay.renderer)
1549 { overlay.renderer.alpha = 1; }
1550 }
1551 for (const overlay of entity.bloomOverlays ?? [])
1552 {
1553 if (overlay.renderer)
1554 { overlay.renderer.alpha = 1; }
1555 }
1556 }
1557
1558 #snapEntityToTile (entity, tileX, tileY)
1559 {
1560 const size = this.tileSize();
1561 const pivot = tilePivot(tileX, tileY, size);
1562 entity.tileX = tileX;
1563 entity.tileY = tileY;
1564 entity.visualX = pivot.x;
1565 entity.visualY = pivot.y;
1566 entity.targetX = pivot.x;
1567 entity.targetY = pivot.y;
1568 entity.fromX = pivot.x;
1569 entity.fromY = pivot.y;
1570 entity.lerpStarted = null;
1571 entity.previousTileX = null;
1572 entity.previousTileY = null;
1573 entity.shadeFromTileX = null;
1574 entity.shadeFromTileY = null;
1575 entity.shoveOffsetX = 0;
1576 entity.shoveOffsetY = 0;
1577 if (entity.entityId === this.localEntityId)
1578 { this.#notePlayerTile(tileX, tileY); }
1579 }
1580
1581 #finishEntityFade (entityId)
1582 {
1583 this.cancelDeferredCombatHits(entityId);
1584 const existing = this.entities.get(entityId);
1585 if (!existing)
1586 { return; }
1587 this.#destroyEntityVisuals(existing);
1588 this.entities.delete(entityId);
1589 }
1590
1591 /**
1592 * Drop queued combat-hit/block presentation for a target.
1593 * Killing blows often defer health=0 until a projectile lands; if the
1594 * target already finished dissolving or respawned, that stale apply must not run.
1595 */
1596 cancelDeferredCombatHits (targetId)
1597 {
1598 if (targetId == null)
1599 { return; }
1600 for (const swipe of this.swipes)
1601 {
1602 if (swipe.targetId !== targetId)
1603 { continue; }
1604 swipe.onImpact = null;
1605 swipe.trackTarget = false;
1606 }
1607 }
1608
1609 updateEntitySkull (entityId, skullValue)
1610 {
1611 const entity = this.entities.get(entityId);
1612 if (!entity)
1613 { return; }
1614 entity.skullValue = Math.max(0, skullValue | 0);
1615 const pivotX = (entity.visualX ?? 0) + (entity.shoveOffsetX ?? 0) + (entity.stackOffsetX ?? 0);
1616 const pivotY = (entity.visualY ?? 0) + (entity.shoveOffsetY ?? 0) + (entity.stackOffsetY ?? 0);
1617 const tileShade = this.#entityShadeAlpha?.(entity, performance.now())
1618 ?? this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha
1619 ?? 0;
1620 this.#placeSkullMarker(entity, pivotX, pivotY, tileShade);
1621 }
1622
1623 updateEntityHealth (entityId, health, maxHealth)
1624 {
1625 const entity = this.entities.get(entityId);
1626 if (!entity || entity.dying)
1627 { return; }
1628 entity.health = health;
1629 entity.maxHealth = maxHealth;
1630 this.#syncHpBar(entity);
1631 }
1632
1633 flashDamage (entityId)
1634 {
1635 this.#flashEntity(entityId, FLASH_COLOR_DAMAGE);
1636 }
1637
1638 flashBlock (entityId)
1639 {
1640 this.#flashEntity(entityId, FLASH_COLOR_BLOCK);
1641 }
1642
1643 #flashEntity (entityId, color)
1644 {
1645 const entity = this.entities.get(entityId);
1646 if (!entity)
1647 { return; }
1648 entity.damageFlashUntil = performance.now() + DAMAGE_FLASH_MS;
1649 entity.damageFlashColor = color ?? FLASH_COLOR_DAMAGE;
1650 }
1651
1652 /** Target knocks back away from attacker (hit). */
1653 spawnCombatKnockback (payload)
1654 {
1655 const attacker = this.entities.get(payload?.attackerId);
1656 const target = this.entities.get(payload?.targetId);
1657 if (!attacker || !target)
1658 { return; }
1659 const ax = attacker.visualX + (attacker.stackOffsetX ?? 0);
1660 const ay = attacker.visualY + (attacker.stackOffsetY ?? 0);
1661 const tx = target.visualX + (target.stackOffsetX ?? 0);
1662 const ty = target.visualY + (target.stackOffsetY ?? 0);
1663 this.#applyShoveInDirection(target, tx - ax, ty - ay);
1664 }
1665
1666 /** Target sidesteps perpendicular to the attack (dodge / miss). */
1667 spawnCombatDodge (payload)
1668 {
1669 const attacker = this.entities.get(payload?.attackerId);
1670 const target = this.entities.get(payload?.targetId);
1671 if (!attacker || !target)
1672 { return; }
1673 const ax = attacker.visualX + (attacker.stackOffsetX ?? 0);
1674 const ay = attacker.visualY + (attacker.stackOffsetY ?? 0);
1675 const tx = target.visualX + (target.stackOffsetX ?? 0);
1676 const ty = target.visualY + (target.stackOffsetY ?? 0);
1677 const dx = tx - ax;
1678 const dy = ty - ay;
1679 const side = Math.random() < 0.5 ? 1 : -1;
1680 this.#applyShoveInDirection(target, -dy * side, dx * side);
1681 }
1682
1683 spawnDamageNumber (entityId, damage)
1684 {
1685 const amount = damage | 0;
1686 if (amount <= 0)
1687 { return; }
1688 this.damageFloats.push({
1689 entityId,
1690 damage: amount,
1691 started: performance.now()
1692 });
1693 }
1694
1695 /**
1696 * Queue combat-hit presentation until a matching in-flight projectile lands.
1697 * Returns true when deferred; caller should apply immediately when false.
1698 */
1699 deferCombatHit (message, apply)
1700 {
1701 if (typeof apply !== "function" || message?.targetId == null)
1702 { return false; }
1703 const attackerId = message.attackerId ?? null;
1704 const targetId = message.targetId;
1705 const swipe = this.swipes.find((entry) =>
1706 entry.lerp
1707 && entry.onImpact == null
1708 && entry.targetId === targetId
1709 && (attackerId == null || entry.attackerId === attackerId)
1710 && (entry.until ?? 0) > performance.now());
1711 if (!swipe)
1712 { return false; }
1713 swipe.onImpact = apply;
1714 swipe.trackTarget = true;
1715 return true;
1716 }
1717
1718 /** Stop tracking a living target (misses fly to a fixed tile). */
1719 markProjectileMiss (message)
1720 {
1721 const attackerId = message?.attackerId ?? null;
1722 const targetId = message?.targetId ?? null;
1723 for (const swipe of this.swipes)
1724 {
1725 if (!swipe.lerp || swipe.onImpact != null)
1726 { continue; }
1727 if (targetId != null && swipe.targetId !== targetId)
1728 { continue; }
1729 if (attackerId != null && swipe.attackerId !== attackerId)
1730 { continue; }
1731 swipe.trackTarget = false;
1732 if (message.tileX != null)
1733 { swipe.tileX = message.tileX; }
1734 if (message.tileY != null)
1735 { swipe.tileY = message.tileY; }
1736 }
1737 }
1738
1739 spawnSkillLevelUp (entityId, payload)
1740 {
1741 const level = payload?.level | 0;
1742 if (level <= 0 || !payload?.icon)
1743 { return; }
1744 this.skillLevelFloats.push({
1745 entityId,
1746 level,
1747 icon: payload.icon,
1748 displayName: payload.displayName ?? payload.skillId ?? "",
1749 started: performance.now()
1750 });
1751 }
1752
1753 setAppearance (payload)
1754 {
1755 const existing = this.entities.get(payload.entityId);
1756 if (!existing)
1757 { return; }
1758 existing.lightRadiusTiles = payload.lightRadiusTiles ?? 0;
1759 if (payload.lightIntensity != null)
1760 { existing.lightIntensity = Number(payload.lightIntensity) || 1; }
1761 if (payload.visualScale != null)
1762 { existing.visualScale = Number(payload.visualScale) || 1; }
1763 this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]);
1764 this.#placeEntity(existing);
1765 }
1766
1767 /**
1768 * Render the live entity (body + overlays, same tint/tight-fit shaders as the
1769 * world, unlit) into an offscreen FBO, crop the top square, and return a
1770 * pixel-scaled canvas for UI (e.g. dialogue speaker icons).
1771 * @param {number} entityId
1772 * @param {{ size?: number }} [options]
1773 * @returns {HTMLCanvasElement | null}
1774 */
1775 captureEntityPortrait (entityId, { size = 64 } = {})
1776 {
1777 const entity = this.entities.get(entityId);
1778 const body = entity?.object?.renderer?.sprite;
1779 const glCtx = this.scene?.glContext;
1780 const gl = glCtx?.gl;
1781 if (!entity || !body || !gl)
1782 { return null; }
1783
1784 const frameW = Math.max(1, body.width | 0 || SPRITE_SIZE_PX);
1785 const frameH = Math.max(1, body.height | 0 || SPRITE_SIZE_PX);
1786 if (!this.#ensurePortraitTarget(gl, frameW, frameH))
1787 { return null; }
1788
1789 const prevFb = gl.getParameter(gl.FRAMEBUFFER_BINDING);
1790 const prevViewport = gl.getParameter(gl.VIEWPORT);
1791 const prevW = glCtx._lastWidth;
1792 const prevH = glCtx._lastHeight;
1793 const prevBlend = gl.isEnabled(gl.BLEND);
1794
1795 try
1796 {
1797 // drawSprite projects with _lastWidth/_lastHeight — match the FBO.
1798 glCtx._lastWidth = frameW;
1799 glCtx._lastHeight = frameH;
1800 gl.bindFramebuffer(gl.FRAMEBUFFER, this._portrait.fb);
1801 gl.viewport(0, 0, frameW, frameH);
1802 gl.enable(gl.BLEND);
1803 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
1804 gl.clearColor(0, 0, 0, 0);
1805 gl.clear(gl.COLOR_BUFFER_BIT);
1806
1807 const pivotX = frameW * 0.5;
1808 const pivotY = frameH - PIVOT_FROM_BOTTOM_PX;
1809 this._portraitBodyMap = body.g_image ?? null;
1810 this._portraitTightFitEntity = entity;
1811 this.#drawPortraitLayer(glCtx, entity.object, pivotX, pivotY, null, false);
1812
1813 const overlays = entity.overlays ?? [];
1814 const tints = entity.overlayTints ?? [];
1815 const dualTints = entity.overlayDualTints ?? [];
1816 const tight = entity.overlayTightFit ?? [];
1817 for (let index = 0; index < overlays.length; index++)
1818 {
1819 this.#drawPortraitLayer(
1820 glCtx,
1821 overlays[index],
1822 pivotX,
1823 pivotY,
1824 tints[index] ?? null,
1825 !!tight[index],
1826 dualTints[index] ?? null
1827 );
1828 }
1829 this._portraitBodyMap = null;
1830 this._portraitTightFitEntity = null;
1831
1832 const pixels = this._portrait.pixels;
1833 gl.readPixels(0, 0, frameW, frameH, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
1834 }
1835 finally
1836 {
1837 glCtx._lastWidth = prevW;
1838 glCtx._lastHeight = prevH;
1839 gl.bindFramebuffer(gl.FRAMEBUFFER, prevFb);
1840 gl.viewport(prevViewport[0], prevViewport[1], prevViewport[2], prevViewport[3]);
1841 if (!prevBlend)
1842 { gl.disable(gl.BLEND); }
1843 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
1844 }
1845
1846 return this.#portraitPixelsToCanvas(frameW, frameH, size);
1847 }
1848
1849 #ensurePortraitTarget (gl, width, height)
1850 {
1851 const prev = this._portrait;
1852 if (prev && prev.w === width && prev.h === height && prev.fb && prev.tex)
1853 { return true; }
1854 if (prev?.fb)
1855 { gl.deleteFramebuffer(prev.fb); }
1856 if (prev?.tex)
1857 { gl.deleteTexture(prev.tex); }
1858
1859 const tex = gl.createTexture();
1860 gl.bindTexture(gl.TEXTURE_2D, tex);
1861 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
1862 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
1863 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
1864 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
1865 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
1866
1867 const fb = gl.createFramebuffer();
1868 gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
1869 gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
1870 const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
1871 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
1872 if (status !== gl.FRAMEBUFFER_COMPLETE)
1873 {
1874 gl.deleteFramebuffer(fb);
1875 gl.deleteTexture(tex);
1876 this._portrait = null;
1877 return false;
1878 }
1879 this._portrait = {
1880 fb,
1881 tex,
1882 w: width,
1883 h: height,
1884 pixels: new Uint8Array(width * height * 4),
1885 scratch: document.createElement("canvas")
1886 };
1887 return true;
1888 }
1889
1890 #drawPortraitLayer (glCtx, object, pivotX, pivotY, tintColor, tightFit, dualTint = null)
1891 {
1892 const sprite = object?.renderer?.sprite;
1893 if (!sprite?.g_image)
1894 { return; }
1895 const subImage = object.renderer.subImage | 0;
1896 const height = sprite.height || SPRITE_SIZE_PX;
1897 const draw = spriteDrawSize(sprite.width, sprite.height, 1);
1898 const center = spriteCenterFromPivot(pivotX, pivotY, height, 1);
1899 const tint = tintColor ? normalizeRgb(tintColor) : null;
1900 let shader = glCtx.defaultShader;
1901 let uniforms = null;
1902 let secondaryHtml = null;
1903
1904 const bodyHtml = this._portraitBodyMap;
1905 const portraitEntity = this._portraitTightFitEntity;
1906 const maskUniforms = tightFit && portraitEntity
1907 ? this.#tightFitMaskUniforms(object, portraitEntity)
1908 : null;
1909 if (dualTint)
1910 {
1911 const shaft = normalizeRgb(dualTint.shaft);
1912 const tip = normalizeRgb(dualTint.tip);
1913 const coat = dualTint.coat ? normalizeRgb(dualTint.coat) : null;
1914 shader = getDualTintLitSpriteShader();
1915 uniforms = {
1916 u_darkness: 0,
1917 u_strength: 0,
1918 u_flashColor: FLASH_COLOR_DAMAGE,
1919 u_wade: 0,
1920 u_spriteHeight: height,
1921 u_shaftTint: [shaft.r, shaft.g, shaft.b],
1922 u_tipTint: [tip.r, tip.g, tip.b],
1923 u_coatTint: coat ? [coat.r, coat.g, coat.b] : [0, 0, 0],
1924 u_hasCoat: coat ? 1 : 0
1925 };
1926 }
1927 else if (tightFit && bodyHtml && maskUniforms)
1928 {
1929 secondaryHtml = bodyHtml;
1930 if (tint)
1931 {
1932 shader = getTightFitTintLitSpriteShader();
1933 uniforms = {
1934 u_darkness: 0,
1935 u_strength: 0,
1936 u_flashColor: FLASH_COLOR_DAMAGE,
1937 u_wade: 0,
1938 u_spriteHeight: height,
1939 u_useTint: 1,
1940 u_tintColor: [tint.r, tint.g, tint.b],
1941 ...maskUniforms
1942 };
1943 }
1944 else
1945 {
1946 shader = getTightFitLitSpriteShader();
1947 uniforms = {
1948 u_darkness: 0,
1949 u_strength: 0,
1950 u_flashColor: FLASH_COLOR_DAMAGE,
1951 u_wade: 0,
1952 u_spriteHeight: height,
1953 ...maskUniforms
1954 };
1955 }
1956 }
1957 else if (tint)
1958 {
1959 shader = getTintLitSpriteShader();
1960 uniforms = {
1961 u_darkness: 0,
1962 u_strength: 0,
1963 u_flashColor: FLASH_COLOR_DAMAGE,
1964 u_wade: 0,
1965 u_spriteHeight: height,
1966 u_useTint: 1,
1967 u_tintColor: [tint.r, tint.g, tint.b]
1968 };
1969 }
1970 else
1971 {
1972 shader = getSpriteLightingShader();
1973 uniforms = {
1974 u_darkness: 0,
1975 u_strength: 0,
1976 u_flashColor: FLASH_COLOR_DAMAGE,
1977 u_wade: 0,
1978 u_spriteHeight: height
1979 };
1980 }
1981
1982 glCtx.drawSprite({
1983 texture: glCtx.getTexture(sprite.g_image),
1984 x: center.x,
1985 y: center.y,
1986 w: draw.w,
1987 h: draw.h,
1988 rotationDeg: 0,
1989 mirrorX: false,
1990 mirrorY: false,
1991 alpha: 1,
1992 uvRect: sprite.getUvRect(subImage),
1993 shader,
1994 uniforms,
1995 textures: secondaryHtml ? { u_secondary: glCtx.getTexture(secondaryHtml) } : null,
1996 lights: null
1997 });
1998 }
1999
2000 #portraitPixelsToCanvas (frameW, frameH, size)
2001 {
2002 const pixels = this._portrait?.pixels;
2003 if (!pixels)
2004 { return null; }
2005 const scratch = this._portrait.scratch;
2006 scratch.width = frameW;
2007 scratch.height = frameH;
2008 const sctx = scratch.getContext("2d");
2009 const imageData = sctx.createImageData(frameW, frameH);
2010 // WebGL y=0 is bottom — flip to top-down image order.
2011 for (let y = 0; y < frameH; y++)
2012 {
2013 const src = (frameH - 1 - y) * frameW * 4;
2014 const dst = y * frameW * 4;
2015 imageData.data.set(pixels.subarray(src, src + frameW * 4), dst);
2016 }
2017 sctx.putImageData(imageData, 0, 0);
2018
2019 const crop = Math.min(frameW, frameH);
2020 const out = document.createElement("canvas");
2021 out.width = size;
2022 out.height = size;
2023 const octx = out.getContext("2d");
2024 octx.imageSmoothingEnabled = false;
2025 octx.clearRect(0, 0, size, size);
2026 octx.drawImage(scratch, 0, 0, crop, crop, 0, 0, size, size);
2027 return out;
2028 }
2029
2030 upsertGroundItem (payload)
2031 {
2032 const size = this.tileSize();
2033 const pivot = tilePivot(payload.tileX, payload.tileY, size);
2034 const potion = payload.instance?.kind === "potion" ? payload.instance : null;
2035 const spriteName = potion
2036 ? spriteImageName("item", "potion", `potion-${Math.max(1, Math.min(5, potion.fillLevel | 0 || 4))}`)
2037 : (payload.sprite ?? itemSpriteNameForStack({
2038 itemId: payload.itemId,
2039 instance: payload.instance,
2040 quantity: payload.quantity
2041 }));
2042 let item = this.groundItems.get(payload.groundItemId);
2043 if (!item)
2044 {
2045 const object = new GameObject(0, 0, this.game.images[spriteName] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK);
2046 this.scene.addObject(object);
2047 item = { object };
2048 this.groundItems.set(payload.groundItemId, item);
2049 }
2050 else if (item.object?.renderer && this.game.images[spriteName])
2051 { item.object.renderer.sprite = this.game.images[spriteName]; }
2052 item.groundItemId = payload.groundItemId;
2053 item.tileX = payload.tileX;
2054 item.tileY = payload.tileY;
2055 item.itemId = payload.itemId;
2056 item.quantity = payload.quantity;
2057 item.displayName = payload.displayName;
2058 item.sprite = spriteName;
2059 item.instance = payload.instance ?? null;
2060 const stack = { itemId: payload.itemId, instance: payload.instance ?? null };
2061 const def = itemDefinition(payload.itemId);
2062 item.dualTint = def?.iconTintFromTier ? null : resolveItemDualTint(stack, def);
2063 item.tintColor = item.dualTint ? null : resolveItemTint(stack, def);
2064 if (item.object?.renderer && itemMaxCharges(def) != null)
2065 { item.object.renderer.setSubImage?.(chargeSpriteFrameIndex(stack)); }
2066 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
2067 this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);
2068 }
2069
2070 despawnGroundItem (groundItemId)
2071 {
2072 const item = this.groundItems.get(groundItemId);
2073 if (!item)
2074 { return; }
2075 item.object?.destroy();
2076 this.groundItems.delete(groundItemId);
2077 }
2078
2079 groundItemAtTile (tileX, tileY)
2080 {
2081 return this.groundItemsAtTile(tileX, tileY)[0] ?? null;
2082 }
2083
2084 groundItemsAtTile (tileX, tileY)
2085 {
2086 const items = [];
2087 for (const item of this.groundItems.values())
2088 {
2089 if (item.tileX === tileX && item.tileY === tileY)
2090 { items.push(item); }
2091 }
2092 return items;
2093 }
2094
2095 entitiesAtTile (tileX, tileY, options = {})
2096 {
2097 const includePrevious = !!options.includePrevious;
2098 const matches = [];
2099 for (const entity of this.entities.values())
2100 {
2101 if (entity.tileX === tileX && entity.tileY === tileY)
2102 {
2103 matches.push(entity);
2104 continue;
2105 }
2106 if (
2107 includePrevious
2108 && entity.lerpStarted != null
2109 && entity.previousTileX === tileX
2110 && entity.previousTileY === tileY
2111 )
2112 { matches.push(entity); }
2113 }
2114 matches.sort((a, b) => (b.object?.layer ?? 0) - (a.object?.layer ?? 0));
2115 return matches;
2116 }
2117
2118 setZoom (zoom, limits = { min: 2, max: 4 })
2119 {
2120 const min = limits.min ?? 1;
2121 const max = limits.max ?? 4;
2122 this.zoom = Math.min(max, Math.max(min, zoom));
2123 for (const snapshot of this.chunks.values())
2124 { this.#relayoutChunk(snapshot); }
2125 const size = this.tileSize();
2126 for (const entity of this.entities.values())
2127 {
2128 entity.visualX = tilePivot(entity.tileX, entity.tileY, size).x;
2129 entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y;
2130 entity.fromX = entity.visualX;
2131 entity.fromY = entity.visualY;
2132 entity.targetX = entity.visualX;
2133 entity.targetY = entity.visualY;
2134 entity.lerpStarted = null;
2135 this.#placeEntity(entity);
2136 }
2137 for (const item of this.groundItems.values())
2138 {
2139 const pivot = tilePivot(item.tileX, item.tileY, size);
2140 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
2141 }
2142 this.#rebuildAllEdges();
2143 this.#relayoutEditorSpawners();
2144 this.#relayoutSpawnRangeHighlight();
2145 this.#relayoutSpellTargetHighlight();
2146 // Play: recenter + refresh cull flags with the new tile size immediately.
2147 // Editor sets the camera via frameNeighborhood after setZoom — call refreshViewport there.
2148 if (this.followPlayer)
2149 { this.refreshViewport(); }
2150 }
2151
2152 /** Recenter (when following) and refresh off-screen cull flags after zoom/layout. */
2153 refreshViewport ()
2154 {
2155 this.#centerCamera();
2156 this.#syncYSortOrigin();
2157 this.#refreshDepthLayers();
2158 this.#cullOffscreenDrawables();
2159 }
2160
2161 tileSize ()
2162 {
2163 return SPRITE_SIZE_PX * this.zoom;
2164 }
2165
2166 screenToTile (mouseX, mouseY)
2167 {
2168 const size = this.tileSize();
2169 const worldX = mouseX - this.scene.cameraPosition.x;
2170 const worldY = mouseY - this.scene.cameraPosition.y;
2171 return {
2172 tileX: Math.floor(worldX / size),
2173 tileY: Math.floor(worldY / size)
2174 };
2175 }
2176
2177 entityAtScreen (mouseX, mouseY)
2178 {
2179 let best = null;
2180 let bestLayer = -Infinity;
2181 for (const entity of this.entities.values())
2182 {
2183 const box = this.#entityScreenBox(entity);
2184 if (!box)
2185 { continue; }
2186 if (mouseX >= box.left && mouseX < box.right && mouseY >= box.top && mouseY < box.bottom)
2187 {
2188 const layer = entity.object?.layer ?? 0;
2189 if (layer >= bestLayer)
2190 {
2191 best = entity;
2192 bestLayer = layer;
2193 }
2194 }
2195 }
2196 return best;
2197 }
2198
2199 nametagAnchor (entity)
2200 {
2201 const box = this.#entityScreenBox(entity);
2202 if (!box)
2203 { return null; }
2204 return { x: (box.left + box.right) / 2, y: box.top };
2205 }
2206
2207 #entityScreenBox (entity)
2208 {
2209 const object = entity?.object;
2210 if (!object)
2211 { return null; }
2212 const size = object.transform.size;
2213 const x = object.transform.position.x + this.scene.cameraPosition.x;
2214 const y = object.transform.position.y + this.scene.cameraPosition.y;
2215 return {
2216 left: x - size.x / 2,
2217 right: x + size.x / 2,
2218 top: y - size.y / 2,
2219 bottom: y + size.y / 2
2220 };
2221 }
2222
2223 update (deltaTime)
2224 {
2225 const now = performance.now();
2226 const size = this.tileSize();
2227 this.#refreshStackTargets();
2228 for (const entity of this.entities.values())
2229 {
2230 const target = entity.targetX != null && entity.targetY != null
2231 ? { x: entity.targetX, y: entity.targetY }
2232 : tilePivot(entity.tileX, entity.tileY, size);
2233 if (entity.lerpStarted != null)
2234 {
2235 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs));
2236 entity.visualX = entity.fromX + (target.x - entity.fromX) * t;
2237 entity.visualY = entity.fromY + (target.y - entity.fromY) * t;
2238 if (t >= 1)
2239 {
2240 entity.lerpStarted = null;
2241 entity.previousTileX = null;
2242 entity.previousTileY = null;
2243 }
2244 }
2245 else
2246 {
2247 entity.visualX = target.x;
2248 entity.visualY = target.y;
2249 }
2250 this.#updateStackOffset(entity, now);
2251 this.#updateShove(entity, now, size);
2252 this.#expireGatherToolOverlay(entity, now);
2253 }
2254
2255 // The y-sort origin must settle before any layer is computed this frame,
2256 // otherwise entities and blocks end up sorted against different origins.
2257 // It only moves when the view crosses a chunk row; the static world then
2258 // needs one re-layer pass, and nothing at all on every other frame.
2259 this.#centerCamera();
2260 if (this.#syncYSortOrigin())
2261 { this.#refreshDepthLayers(); }
2262
2263 for (const entity of this.entities.values())
2264 { this.#placeEntity(entity, now); }
2265
2266 this.#updateSwipes(now);
2267 this.#updateDamageNumbers(now);
2268 this.#updateSkillLevelFloats(now);
2269 this.#relayoutSpellTargetHighlight();
2270 this.#cullOffscreenDrawables();
2271 this.#updateShade(deltaTime);
2272 }
2273
2274 /**
2275 * Desired circle offsets for stacked entities (applied via {@link #updateStackOffset}).
2276 * Stable assignment by entityId; free-flight entities stay unshifted.
2277 */
2278 #refreshStackTargets ()
2279 {
2280 const byTile = new Map();
2281 for (const entity of this.entities.values())
2282 {
2283 if (entity.freeFlight || entity.dying)
2284 {
2285 entity.stackTargetX = 0;
2286 entity.stackTargetY = 0;
2287 continue;
2288 }
2289 const key = `${entity.tileX},${entity.tileY}`;
2290 let list = byTile.get(key);
2291 if (!list)
2292 {
2293 list = [];
2294 byTile.set(key, list);
2295 }
2296 list.push(entity);
2297 }
2298 const radius = (ENTITY_STACK_SPREAD_DIAMETER_PX * this.zoom) / 2;
2299 for (const list of byTile.values())
2300 {
2301 if (list.length <= 1)
2302 {
2303 for (const entity of list)
2304 {
2305 entity.stackTargetX = 0;
2306 entity.stackTargetY = 0;
2307 }
2308 continue;
2309 }
2310 list.sort((a, b) => String(a.entityId).localeCompare(String(b.entityId)));
2311 const n = list.length;
2312 for (let i = 0; i < n; i++)
2313 {
2314 const angle = -Math.PI / 2 + (Math.PI * 2 * i) / n;
2315 list[i].stackTargetX = Math.cos(angle) * radius;
2316 list[i].stackTargetY = Math.sin(angle) * radius;
2317 }
2318 }
2319 }
2320
2321 #updateStackOffset (entity, now)
2322 {
2323 const tx = entity.stackTargetX ?? 0;
2324 const ty = entity.stackTargetY ?? 0;
2325 const cx = entity.stackOffsetX ?? 0;
2326 const cy = entity.stackOffsetY ?? 0;
2327 if (entity.stackLerpToX !== tx || entity.stackLerpToY !== ty)
2328 {
2329 entity.stackFromX = cx;
2330 entity.stackFromY = cy;
2331 entity.stackLerpToX = tx;
2332 entity.stackLerpToY = ty;
2333 entity.stackLerpStarted = now;
2334 }
2335 if (entity.stackLerpStarted == null)
2336 {
2337 entity.stackOffsetX = tx;
2338 entity.stackOffsetY = ty;
2339 return;
2340 }
2341 const t = Math.min(1, (now - entity.stackLerpStarted) / STACK_SPREAD_LERP_MS);
2342 entity.stackOffsetX = entity.stackFromX + (tx - entity.stackFromX) * t;
2343 entity.stackOffsetY = entity.stackFromY + (ty - entity.stackFromY) * t;
2344 if (t >= 1)
2345 {
2346 entity.stackOffsetX = tx;
2347 entity.stackOffsetY = ty;
2348 entity.stackLerpStarted = null;
2349 }
2350 }
2351
2352 #updateShove (entity, now, tileSize)
2353 {
2354 if (!entity.shove)
2355 {
2356 entity.shoveOffsetX = 0;
2357 entity.shoveOffsetY = 0;
2358 return;
2359 }
2360 const elapsed = now - entity.shove.started;
2361 const t = Math.min(1, elapsed / entity.shove.durationMs);
2362 const maxDist = tileSize * SHOVE_TILE_FRACTION;
2363 const dx = entity.shove.targetVisualX - entity.shove.startVisualX;
2364 const dy = entity.shove.targetVisualY - entity.shove.startVisualY;
2365 const dist = Math.hypot(dx, dy) || 1;
2366 const ux = dx / dist;
2367 const uy = dy / dist;
2368 let phase;
2369 if (t < 0.45)
2370 { phase = t / 0.45; }
2371 else
2372 { phase = 1 - (t - 0.45) / 0.55; }
2373 entity.shoveOffsetX = ux * maxDist * phase;
2374 entity.shoveOffsetY = uy * maxDist * phase;
2375 if (t >= 1)
2376 { entity.shove = null; }
2377 }
2378
2379 spawnCombatSwing (payload)
2380 {
2381 const attacker = this.entities.get(payload.attackerId);
2382 const target = this.entities.get(payload.targetId);
2383 if (!attacker || !target)
2384 { return; }
2385 const ax = attacker.visualX + (attacker.stackOffsetX ?? 0);
2386 const ay = attacker.visualY + (attacker.stackOffsetY ?? 0);
2387 const tx = target.visualX + (target.stackOffsetX ?? 0);
2388 const ty = target.visualY + (target.stackOffsetY ?? 0);
2389 this.#applyShove(attacker, tx, ty);
2390 const midX = (ax + tx) / 2;
2391 const midY = (ay + ty) / 2;
2392 const sortY = Math.max(ay, ty) + 0.02;
2393 const angle = Math.atan2(ty - ay, tx - ax) * (180 / Math.PI);
2394 const jitter = (Math.random() * 2 - 1) * MELEE_SWIPE_JITTER_DEG;
2395 const spriteName = "fx:melee-swipe:melee-swipe";
2396 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_FX);
2397 if (object.transform)
2398 { object.transform.rotation = angle + jitter; }
2399 if (object.renderer)
2400 { object.renderer.alpha = 1; }
2401 this.scene.addObject(object);
2402 this.#placePivoted(object, midX, midY, sortY, SORT_FX);
2403 this.#applyPhysicalCombatFxDarkness(object, payload.fromTileX, payload.fromTileY, payload.tileX, payload.tileY);
2404 const started = performance.now();
2405 this.swipes.push({
2406 object,
2407 until: started + MELEE_SWIPE_MS,
2408 started,
2409 durationMs: MELEE_SWIPE_MS,
2410 sortY,
2411 fadeOpacity: true,
2412 fromTileX: payload.fromTileX,
2413 fromTileY: payload.fromTileY,
2414 tileX: payload.tileX,
2415 tileY: payload.tileY
2416 });
2417 }
2418
2419 /** Mining / gathering lunge toward a tile — shove only, no swipe FX. */
2420 spawnGatherSwing (payload)
2421 {
2422 const attacker = this.entities.get(payload.attackerId);
2423 if (!attacker)
2424 { return; }
2425 const pivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());
2426 this.#applyShove(attacker, pivot.x, pivot.y);
2427 if (payload.toolItemId != null)
2428 { this.#setGatherToolOverlay(attacker, payload.toolItemId); }
2429 }
2430
2431 #applyShove (entity, targetVisualX, targetVisualY)
2432 {
2433 entity.shove = {
2434 startVisualX: entity.visualX,
2435 startVisualY: entity.visualY,
2436 targetVisualX,
2437 targetVisualY,
2438 started: performance.now(),
2439 durationMs: SHOVE_MS
2440 };
2441 }
2442
2443 #applyShoveInDirection (entity, dirX, dirY)
2444 {
2445 const len = Math.hypot(dirX, dirY);
2446 if (len < 1e-4)
2447 { return; }
2448 const tileSize = this.tileSize();
2449 const ux = dirX / len;
2450 const uy = dirY / len;
2451 this.#applyShove(
2452 entity,
2453 entity.visualX + ux * tileSize,
2454 entity.visualY + uy * tileSize
2455 );
2456 }
2457
2458 /** Physical combat FX (melee swipes, ranged projectiles). Magic spells stay unshaded. */
2459 spawnPhysicalProjectileFx (payload)
2460 {
2461 const spriteName = payload.sprite ?? "fx:projectile:arrow";
2462 const image = this.game.images[spriteName];
2463 if (!image)
2464 { return; }
2465 const dualTint = this.#dualTintFromPayload(payload);
2466 const fromPivot = this.#projectileLaunchPoint(
2467 payload.attackerId ?? null,
2468 payload.fromTileX,
2469 payload.fromTileY
2470 );
2471 const toPivot = this.#projectileAimPoint(
2472 payload.targetId ?? null,
2473 payload.tileX,
2474 payload.tileY
2475 );
2476 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
2477 const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);
2478 const object = new GameObject(0, 0, image, SORT_FX);
2479 if (object.transform)
2480 { object.transform.rotation = angle; }
2481 this.scene.addObject(object);
2482 this.#placePivoted(object, fromPivot.x, fromPivot.y, sortY, SORT_FX);
2483 this.#applyPhysicalCombatFxDarkness(
2484 object,
2485 payload.fromTileX,
2486 payload.fromTileY,
2487 payload.tileX,
2488 payload.tileY,
2489 dualTint
2490 );
2491 const started = performance.now();
2492 const durationMs = payload.durationMs ?? 400;
2493 const trackTarget = payload.trackTarget !== false && payload.targetId != null;
2494 this.swipes.push({
2495 object,
2496 until: started + durationMs,
2497 started,
2498 durationMs,
2499 lerp: true,
2500 dualTint,
2501 fromTileX: payload.fromTileX,
2502 fromTileY: payload.fromTileY,
2503 tileX: payload.tileX,
2504 tileY: payload.tileY,
2505 attackerId: payload.attackerId ?? null,
2506 targetId: payload.targetId ?? null,
2507 trackTarget,
2508 onImpact: null
2509 });
2510 }
2511
2512 /** Bloom-layer spell projectiles — magenta-tinted, unique art per spell. */
2513 spawnSpellProjectileFx (payload)
2514 {
2515 const spellId = payload.spellId ?? null;
2516 const def = spellId != null ? spellDefinition(spellId) : null;
2517 const spriteName = payload.sprite
2518 ?? def?.projectileSprite
2519 ?? "fx:projectile:spell-none-1-mana-bullet";
2520 const image = this.game.images[spriteName];
2521 if (!image)
2522 { return; }
2523 const tint = spellProjectileTint(def?.element);
2524 const fromPivot = this.#projectileLaunchPoint(
2525 payload.casterId ?? null,
2526 payload.fromTileX,
2527 payload.fromTileY
2528 );
2529 const toPivot = this.#projectileAimPoint(
2530 payload.targetId ?? null,
2531 payload.tileX,
2532 payload.tileY
2533 );
2534 // Spell casts push the caster visually toward the spell's target.
2535 // (Presentation only; server authority remains combat-resolution.)
2536 const caster = payload.casterId != null
2537 ? this.entities.get(payload.casterId)
2538 : null;
2539 if (caster && !caster.dying)
2540 {
2541 const casterPivotX = caster.visualX + (caster.stackOffsetX ?? 0);
2542 const casterPivotY = caster.visualY + (caster.stackOffsetY ?? 0);
2543 this.#applyShoveInDirection(caster, toPivot.x - casterPivotX, toPivot.y - casterPivotY);
2544 }
2545 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
2546 const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);
2547 const object = new GameObject(0, 0, image, SORT_FX);
2548 object.renderer.layer = RENDER_LAYER_BLOOM;
2549 this.#markUnlit(object);
2550 this.#syncUnlitTintSprite(object, tint);
2551 if (object.transform)
2552 { object.transform.rotation = angle; }
2553 this.scene.addObject(object);
2554 this.#placePivoted(object, fromPivot.x, fromPivot.y, sortY, SORT_FX);
2555 const started = performance.now();
2556 const durationMs = payload.durationMs ?? 2000;
2557 this.swipes.push({
2558 object,
2559 until: started + durationMs,
2560 started,
2561 durationMs,
2562 lerp: true,
2563 spellProjectile: true,
2564 tint,
2565 fromTileX: payload.fromTileX,
2566 fromTileY: payload.fromTileY,
2567 tileX: payload.tileX,
2568 tileY: payload.tileY,
2569 attackerId: payload.casterId ?? null,
2570 targetId: payload.targetId ?? null,
2571 trackTarget: payload.targetId != null,
2572 onImpact: null
2573 });
2574 }
2575
2576 spawnSpellFizzleFx (_payload)
2577 {
2578 // Visual-only fizzle; no dynamic light (cast flashes skip lightmap rebakes).
2579 }
2580
2581 /**
2582 * Authoritative Light-spell tile light from the server.
2583 * Kept out of short-lived `dynamicLights` so duration follows `remainingMs` updates.
2584 */
2585 setSpellLight (payload)
2586 {
2587 const key = `${payload.tileX},${payload.tileY}`;
2588 this.spellLights.set(key, {
2589 tileX: payload.tileX,
2590 tileY: payload.tileY,
2591 until: performance.now() + Math.max(0, payload.remainingMs ?? 0),
2592 range: payload.rangeTiles ?? 6,
2593 intensity: payload.intensity ?? 0.88
2594 });
2595 this.#invalidateNeighborLightmapCaches(
2596 Math.floor(payload.tileX / CHUNK_SIZE),
2597 Math.floor(payload.tileY / CHUNK_SIZE)
2598 );
2599 }
2600
2601 removeSpellLight (payload)
2602 {
2603 this.spellLights.delete(`${payload.tileX},${payload.tileY}`);
2604 this.#invalidateNeighborLightmapCaches(
2605 Math.floor(payload.tileX / CHUNK_SIZE),
2606 Math.floor(payload.tileY / CHUNK_SIZE)
2607 );
2608 }
2609
2610 setSpellDark (payload)
2611 {
2612 const key = `${payload.tileX},${payload.tileY}`;
2613 this.spellDarks.set(key, {
2614 tileX: payload.tileX,
2615 tileY: payload.tileY,
2616 until: performance.now() + Math.max(0, payload.remainingMs ?? 0),
2617 range: payload.rangeTiles ?? 6,
2618 intensity: payload.intensity ?? 0.88
2619 });
2620 this.#invalidateNeighborLightmapCaches(
2621 Math.floor(payload.tileX / CHUNK_SIZE),
2622 Math.floor(payload.tileY / CHUNK_SIZE)
2623 );
2624 }
2625
2626 removeSpellDark (payload)
2627 {
2628 this.spellDarks.delete(`${payload.tileX},${payload.tileY}`);
2629 this.#invalidateNeighborLightmapCaches(
2630 Math.floor(payload.tileX / CHUNK_SIZE),
2631 Math.floor(payload.tileY / CHUNK_SIZE)
2632 );
2633 }
2634
2635 addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 1, durationMs = 250 })
2636 {
2637 this.dynamicLights.push({
2638 tileX: Math.floor(worldX),
2639 tileY: Math.floor(worldY),
2640 range: radiusTiles,
2641 intensity,
2642 until: performance.now() + durationMs
2643 });
2644 }
2645
2646 updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {})
2647 {
2648 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
2649 if (!snapshot)
2650 { return; }
2651 const index = localY * CHUNK_SIZE + localX;
2652 if (ground !== undefined)
2653 { snapshot.grounds[index] = ground; }
2654 if (block !== undefined)
2655 { snapshot.blocks[index] = block; }
2656 if (light !== undefined)
2657 { snapshot.light[index] = light; }
2658 if (ground !== undefined || block !== undefined)
2659 {
2660 if (!Array.isArray(snapshot.occlusion) || snapshot.occlusion.length < CHUNK_SIZE * CHUNK_SIZE)
2661 { snapshot.occlusion = bakeChunkOcclusion(snapshot); }
2662 else
2663 { snapshot.occlusion[index] = tileLightOcclusionAt(snapshot.grounds, snapshot.blocks, localX, localY); }
2664 }
2665 const tileX = chunkX * CHUNK_SIZE + localX;
2666 const tileY = chunkY * CHUNK_SIZE + localY;
2667 if (block !== undefined)
2668 {
2669 this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false });
2670 this.#drawTile(tileX, tileY);
2671 return;
2672 }
2673 this.#scheduleChunkRebuild(snapshot);
2674 if (ground !== undefined)
2675 { this.#drawTile(tileX, tileY); }
2676 }
2677
2678 /**
2679 * Editor-only mob markers for authored spawners (invisible during play).
2680 * Humanoid / town guard / CE show body + equipment overlays.
2681 * Previews up to 10 bodies using the same stack circle as play.
2682 * @param {number} chunkX
2683 * @param {number} chunkY
2684 * @param {Array<{ localX: number, localY: number, config?: object }>} spawners
2685 * @param {(mobTypeId: number) => string} resolveSprite
2686 */
2687 setEditorSpawners (chunkX, chunkY, spawners, resolveSprite)
2688 {
2689 const prefix = `${chunkX},${chunkY}:`;
2690 for (const [key, entry] of [...this.editorSpawners.entries()])
2691 {
2692 if (!key.startsWith(prefix))
2693 { continue; }
2694 this.#destroyEditorSpawnerEntry(entry);
2695 this.editorSpawners.delete(key);
2696 }
2697 const size = this.tileSize();
2698 for (const spawner of spawners ?? [])
2699 {
2700 const tileX = chunkX * CHUNK_SIZE + spawner.localX;
2701 const tileY = chunkY * CHUNK_SIZE + spawner.localY;
2702 const config = normalizeSpawnerConfig(spawner.config ?? {});
2703 const layers = layersFromSpawnerConfig(config);
2704 const bodySpriteName = layers?.[0]?.sprite
2705 ?? resolveSprite?.(config.mobTypeId)
2706 ?? null;
2707 if (!bodySpriteName)
2708 { continue; }
2709 const previewCount = Math.min(10, Math.max(1, config.maxAlive | 0));
2710 const instances = [];
2711 for (let n = 0; n < previewCount; n++)
2712 {
2713 const object = this.#ensureSprite(null, bodySpriteName, SORT_ENTITY);
2714 if (!object)
2715 { continue; }
2716 object.renderer.alpha = 0.85;
2717 const bodyTint = layers?.[0]?.tint ? normalizeRgb(layers[0].tint) : null;
2718 if (bodyTint)
2719 { this.#syncUnlitTintSprite(object, bodyTint); }
2720 else
2721 { this.#markUnlit(object); }
2722 const overlays = [];
2723 for (const layer of layers?.slice(1) ?? [])
2724 {
2725 const overlay = this.#ensureSprite(null, layer.sprite, SORT_ENTITY);
2726 if (!overlay)
2727 { continue; }
2728 overlay.renderer.alpha = 0.85;
2729 this.#applyEditorSpawnerOverlayLook(overlay, layer);
2730 overlays.push(overlay);
2731 }
2732 instances.push({ object, overlays });
2733 }
2734 if (!instances.length)
2735 { continue; }
2736 const key = `${prefix}${spawner.localX},${spawner.localY}`;
2737 const entry = {
2738 instances,
2739 tileX,
2740 tileY,
2741 spriteName: bodySpriteName
2742 };
2743 this.#placeEditorSpawnerEntry(entry, size);
2744 this.editorSpawners.set(key, entry);
2745 }
2746 }
2747
2748 #destroyEditorSpawnerEntry (entry)
2749 {
2750 for (const instance of entry?.instances ?? [])
2751 {
2752 instance?.object?.destroy();
2753 for (const overlay of instance?.overlays ?? [])
2754 { overlay?.destroy(); }
2755 }
2756 // Legacy single-body shape (pre multi-preview).
2757 entry?.object?.destroy();
2758 for (const overlay of entry?.overlays ?? [])
2759 { overlay?.destroy(); }
2760 }
2761
2762 #applyEditorSpawnerOverlayLook (overlay, layer)
2763 {
2764 const layerDef = layer.itemId != null ? itemDefinition(layer.itemId) : null;
2765 const dualTint = layerDef?.iconTintFromTier
2766 ? null
2767 : (layer.itemId != null
2768 ? resolveEquipDualTint({ itemId: layer.itemId }, layerDef)
2769 : null);
2770 const tint = layer.tint
2771 ? normalizeRgb(layer.tint)
2772 : (dualTint
2773 ? null
2774 : (layerDef?.iconTintFromTier
2775 ? resolveItemTint({ itemId: layer.itemId }, layerDef)
2776 : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null)));
2777 if (dualTint)
2778 {
2779 overlay._lit = true;
2780 this.#syncDualTintLitSprite(overlay, 0, dualTint, 0, false);
2781 return;
2782 }
2783 if (tint)
2784 {
2785 this.#syncUnlitTintSprite(overlay, tint);
2786 return;
2787 }
2788 this.#markUnlit(overlay);
2789 }
2790
2791 clearEditorSpawners ()
2792 {
2793 for (const entry of this.editorSpawners.values())
2794 { this.#destroyEditorSpawnerEntry(entry); }
2795 this.editorSpawners.clear();
2796 }
2797
2798 #placeEditorSpawnerEntry (entry, size = this.tileSize())
2799 {
2800 const instances = entry?.instances ?? [];
2801 if (!instances.length)
2802 { return; }
2803 const pivot = tilePivot(entry.tileX, entry.tileY, size);
2804 const n = instances.length;
2805 const radius = n <= 1 ? 0 : (ENTITY_STACK_SPREAD_DIAMETER_PX * this.zoom) / 2;
2806 for (let i = 0; i < n; i++)
2807 {
2808 const angle = -Math.PI / 2 + (Math.PI * 2 * i) / n;
2809 const x = pivot.x + Math.cos(angle) * radius;
2810 const y = pivot.y + Math.sin(angle) * radius;
2811 const instance = instances[i];
2812 const depthBase = y + 0.05 + 0.0001 * i;
2813 this.#placePivoted(instance.object, x, y, depthBase, SORT_ENTITY);
2814 const overlays = instance.overlays ?? [];
2815 for (let o = 0; o < overlays.length; o++)
2816 {
2817 this.#placePivoted(
2818 overlays[o],
2819 x,
2820 y,
2821 depthBase + 0.001 * (o + 1),
2822 SORT_ENTITY
2823 );
2824 }
2825 }
2826 }
2827
2828 #relayoutEditorSpawners ()
2829 {
2830 const size = this.tileSize();
2831 for (const entry of this.editorSpawners.values())
2832 { this.#placeEditorSpawnerEntry(entry, size); }
2833 }
2834
2835 /**
2836 * Editor-only range overlays: spawn (inner) and wander (outer, Chebyshev squares).
2837 */
2838 setSpawnRangeHighlight (tileX, tileY, spawnRange, wanderRange = null)
2839 {
2840 const spawnRadius = Math.max(0, spawnRange | 0);
2841 const wanderRadius = Math.max(spawnRadius, wanderRange == null ? spawnRadius : (wanderRange | 0));
2842 if (this.spawnRangeHighlight
2843 && this.wanderRangeHighlight
2844 && this.spawnRangeHighlight.tileX === tileX
2845 && this.spawnRangeHighlight.tileY === tileY
2846 && this.spawnRangeHighlight.range === spawnRadius
2847 && this.wanderRangeHighlight.range === wanderRadius)
2848 {
2849 this.#relayoutSpawnRangeHighlight();
2850 return;
2851 }
2852 this.clearSpawnRangeHighlight();
2853 const wanderObject = this.#ensureSprite(null, "wander-range", LAYER_EDGE);
2854 const spawnObject = this.#ensureSprite(null, "spawn-range", LAYER_EDGE);
2855 if (wanderObject)
2856 {
2857 this.#markUnlit(wanderObject);
2858 wanderObject.renderer.alpha = 1;
2859 this.wanderRangeHighlight = { object: wanderObject, tileX, tileY, range: wanderRadius };
2860 }
2861 if (spawnObject)
2862 {
2863 this.#markUnlit(spawnObject);
2864 spawnObject.renderer.alpha = 1;
2865 this.spawnRangeHighlight = { object: spawnObject, tileX, tileY, range: spawnRadius };
2866 }
2867 this.#relayoutSpawnRangeHighlight();
2868 }
2869
2870 clearSpawnRangeHighlight ()
2871 {
2872 this.spawnRangeHighlight?.object?.destroy();
2873 this.wanderRangeHighlight?.object?.destroy();
2874 this.spawnRangeHighlight = null;
2875 this.wanderRangeHighlight = null;
2876 }
2877
2878 setSpellTargetHighlight (tileX, tileY, inRange = true)
2879 {
2880 if (
2881 this.spellTargetHighlight
2882 && this.spellTargetHighlight.mode === "tile"
2883 && this.spellTargetHighlight.tileX === tileX
2884 && this.spellTargetHighlight.tileY === tileY
2885 && this.spellTargetHighlight.inRange === inRange
2886 )
2887 {
2888 this.#relayoutSpellTargetHighlight();
2889 return;
2890 }
2891 this.clearSpellTargetHighlight();
2892 const spriteName = inRange ? "spell-target-tile" : "spell-target-invalid";
2893 const object = this.#ensureSprite(null, spriteName, LAYER_EDGE - 1);
2894 if (!object)
2895 { return; }
2896 this.#markUnlit(object);
2897 object.renderer.alpha = 1;
2898 this.spellTargetHighlight = {
2899 mode: "tile",
2900 object,
2901 tileX,
2902 tileY,
2903 entityId: null,
2904 inRange,
2905 spriteName
2906 };
2907 this.#relayoutSpellTargetHighlight();
2908 }
2909
2910 /** Outline box around a living entity (mob / player) for entity-target spells. */
2911 setSpellEntityTargetHighlight (entityId, inRange = true)
2912 {
2913 const id = entityId | 0;
2914 if (
2915 this.spellTargetHighlight
2916 && this.spellTargetHighlight.mode === "entity"
2917 && this.spellTargetHighlight.entityId === id
2918 && this.spellTargetHighlight.inRange === inRange
2919 )
2920 {
2921 this.#relayoutSpellTargetHighlight();
2922 return;
2923 }
2924 this.clearSpellTargetHighlight();
2925 if (!this.entities.has(id))
2926 { return; }
2927 const spriteName = inRange ? "spell-target-entity" : "spell-target-entity-invalid";
2928 const object = this.#ensureSprite(null, spriteName, LAYER_EDGE - 1);
2929 if (!object)
2930 { return; }
2931 this.#markUnlit(object);
2932 object.renderer.alpha = 1;
2933 this.spellTargetHighlight = {
2934 mode: "entity",
2935 object,
2936 tileX: 0,
2937 tileY: 0,
2938 entityId: id,
2939 inRange,
2940 spriteName
2941 };
2942 this.#relayoutSpellTargetHighlight();
2943 }
2944
2945 clearSpellTargetHighlight ()
2946 {
2947 this.spellTargetHighlight?.object?.destroy();
2948 this.spellTargetHighlight = null;
2949 }
2950
2951 #relayoutSpellTargetHighlight ()
2952 {
2953 const highlight = this.spellTargetHighlight;
2954 if (!highlight?.object)
2955 { return; }
2956 if (highlight.mode === "entity")
2957 {
2958 const entity = this.entities.get(highlight.entityId);
2959 if (!entity?.object)
2960 {
2961 this.clearSpellTargetHighlight();
2962 return;
2963 }
2964 const pad = this.tileSize() * 0.12;
2965 const src = entity.object.transform;
2966 highlight.object.transform.position.x = src.position.x;
2967 highlight.object.transform.position.y = src.position.y;
2968 highlight.object.transform.size = new vector(src.size.x + pad, src.size.y + pad);
2969 this.#setLayer(highlight.object, LAYER_EDGE - 1);
2970 highlight.tileX = entity.tileX;
2971 highlight.tileY = entity.tileY;
2972 return;
2973 }
2974 const size = this.tileSize();
2975 const left = highlight.tileX * size;
2976 const top = highlight.tileY * size;
2977 highlight.object.transform.position.x = left + size / 2;
2978 highlight.object.transform.position.y = top + size / 2;
2979 highlight.object.transform.size = new vector(size, size);
2980 this.#setLayer(highlight.object, LAYER_EDGE - 1);
2981 }
2982
2983 #relayoutSpawnRangeHighlight ()
2984 {
2985 this.#layoutRangeOverlay(this.wanderRangeHighlight, LAYER_EDGE - 2);
2986 this.#layoutRangeOverlay(this.spawnRangeHighlight, LAYER_EDGE - 1);
2987 }
2988
2989 #layoutRangeOverlay (highlight, layer)
2990 {
2991 if (!highlight?.object)
2992 { return; }
2993 const size = this.tileSize();
2994 const side = (2 * highlight.range + 1) * size;
2995 const left = (highlight.tileX - highlight.range) * size;
2996 const top = (highlight.tileY - highlight.range) * size;
2997 highlight.object.transform.position.x = left + side / 2;
2998 highlight.object.transform.position.y = top + side / 2;
2999 highlight.object.transform.size = new vector(side, side);
3000 this.#setLayer(highlight.object, layer);
3001 }
3002
3003 setTilePreview (tileX, tileY, override)
3004 {
3005 const next = { tileX, tileY, ...override };
3006 if (this.#previewEqual(this.preview, next))
3007 { return; }
3008 const previous = this.preview;
3009 this.preview = next;
3010 const chunkX = Math.floor(tileX / CHUNK_SIZE);
3011 const chunkY = Math.floor(tileY / CHUNK_SIZE);
3012 this.#scheduleChunkRebuild(this.chunks.get(`${chunkX},${chunkY}`));
3013 if (previous && (previous.tileX !== tileX || previous.tileY !== tileY))
3014 {
3015 const prevKey = `${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`;
3016 if (prevKey !== `${chunkX},${chunkY}`)
3017 { this.#scheduleChunkRebuild(this.chunks.get(prevKey)); }
3018 // Per-tile blocks (doors, campfires, …) are not in the atlas — refresh sprites.
3019 this.#drawTile(previous.tileX, previous.tileY);
3020 }
3021 this.#drawTile(tileX, tileY);
3022 }
3023
3024 clearTilePreview ()
3025 {
3026 if (!this.preview)
3027 { return; }
3028 const previous = this.preview;
3029 this.preview = null;
3030 const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
3031 this.#scheduleChunkRebuild(snapshot);
3032 this.#drawTile(previous.tileX, previous.tileY);
3033 }
3034
3035 #lerpMs (gait)
3036 {
3037 const walk = this.settings.walkTilesPerSecond || 2;
3038 const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk;
3039 return seconds * 1000;
3040 }
3041
3042 #centerCamera ()
3043 {
3044 if (!this.followPlayer)
3045 { return; }
3046 const local = this.entities.get(this.localEntityId);
3047 if (!local)
3048 { return; }
3049 const x = local.visualX + (local.stackOffsetX ?? 0);
3050 const y = local.visualY + (local.stackOffsetY ?? 0);
3051 this.scene.cameraPosition.x = this.scene.real_size.x / 2 - x;
3052 this.scene.cameraPosition.y = this.scene.real_size.y / 2 - y;
3053 }
3054
3055 /**
3056 * World Y the depth sort is measured against, so layers stay bounded
3057 * (absolute tileY×zoom otherwise overflows past LAYER_EDGE).
3058 *
3059 * Quantised to the chunk row under the viewport centre: every sprite's layer
3060 * is relative to this, so an origin that moved with the camera would mean
3061 * re-layering the whole world every frame. Chunks only span the static 5×5
3062 * ring, so relative sortY stays far inside LAYER_EDGE.
3063 *
3064 * @returns {boolean} whether the origin moved, i.e. callers must re-layer.
3065 */
3066 #syncYSortOrigin ()
3067 {
3068 const camY = this.scene.cameraPosition.y;
3069 const screenH = this.scene.real_size.y;
3070 const chunkPx = CHUNK_SIZE * this.tileSize();
3071 const origin = Math.floor((-camY + screenH / 2) / chunkPx) * chunkPx;
3072 if (origin === this.ySortOrigin)
3073 { return false; }
3074 this.ySortOrigin = origin;
3075 return true;
3076 }
3077
3078 /** Viewport-relative y-sort layer for world sprites. */
3079 #depthLayer (sortY, subOrder, flight = false)
3080 {
3081 const relative = sortY - (this.ySortOrigin ?? 0);
3082 return flight ? flightSortLayer(relative, subOrder) : ySortLayer(relative, subOrder);
3083 }
3084
3085 /**
3086 * Re-apply depth for every world sprite that is not repositioned each frame.
3087 * Their layer is relative to the y-sort origin, so a layer assigned once at
3088 * draw time goes stale as soon as that origin moves.
3089 *
3090 * Only run when {@link #syncYSortOrigin} reports a move (or after a zoom /
3091 * layout change) — entities carry their own per-frame layer via #placeEntity.
3092 */
3093 #refreshDepthLayers ()
3094 {
3095 const size = this.tileSize();
3096 for (const baked of this.bakedChunks.values())
3097 {
3098 const top = baked.chunkY * CHUNK_SIZE * size;
3099 const chunkPx = CHUNK_SIZE * size;
3100 for (let row = 0; row < CHUNK_SIZE; row++)
3101 {
3102 const rowY = top + row * size + size / 2;
3103 this.#setLayer(baked.blockObjects?.[row], this.#depthLayer(rowY, SORT_BLOCK));
3104 }
3105 this.#setLayer(baked.bloomObject, this.#depthLayer(top + chunkPx, SORT_BLOCK));
3106 }
3107 // Unbaked tile sprites: tall blocks, doors and animated grounds.
3108 for (const objects of this.tiles.values())
3109 {
3110 if (!objects.block && !objects.blockBloom && !objects.groundBloom)
3111 { continue; }
3112 const pivotY = objects.tileY * size + size / 2;
3113 this.#setLayer(objects.block, this.#depthLayer(pivotY, objects.blockSort ?? SORT_ENTITY));
3114 this.#setLayer(objects.blockBloom, this.#depthLayer(pivotY, SORT_ENTITY));
3115 this.#setLayer(objects.groundBloom, this.#depthLayer(pivotY, LAYER_GROUND));
3116 }
3117 for (const item of this.groundItems.values())
3118 {
3119 this.#setLayer(
3120 item.object,
3121 this.#depthLayer(item.tileY * size + size / 2 - 0.01, SORT_BLOCK)
3122 );
3123 }
3124 // Lerping FX are re-placed in #updateSwipes; static ones need the refresh.
3125 for (const swipe of this.swipes)
3126 {
3127 if (swipe.lerp || swipe.sortY == null)
3128 { continue; }
3129 this.#setLayer(swipe.object, this.#depthLayer(swipe.sortY, SORT_FX));
3130 }
3131 for (const entry of this.editorSpawners.values())
3132 {
3133 const pivotY = entry.tileY * size + size / 2;
3134 this.#setLayer(entry.object, this.#depthLayer(pivotY + 0.05, SORT_ENTITY));
3135 const overlays = entry.overlays ?? [];
3136 for (let i = 0; i < overlays.length; i++)
3137 {
3138 this.#setLayer(
3139 overlays[i],
3140 this.#depthLayer(pivotY + 0.05 + 0.001 * (i + 1), SORT_ENTITY)
3141 );
3142 }
3143 }
3144 }
3145
3146 /**
3147 * World-pixel AABB of the screen, expanded for tall block sprites (zoom-aware).
3148 * Tiles fully outside this rect are not drawn.
3149 */
3150 #drawBounds ()
3151 {
3152 const pad = this.tileSize() * 2;
3153 const camX = this.scene.cameraPosition.x;
3154 const camY = this.scene.cameraPosition.y;
3155 const w = this.scene.real_size.x;
3156 const h = this.scene.real_size.y;
3157 return {
3158 left: -camX - pad,
3159 right: -camX + w + pad,
3160 top: -camY - pad,
3161 bottom: -camY + h + pad
3162 };
3163 }
3164
3165 #rectIntersects (left, top, right, bottom, bounds)
3166 {
3167 return right >= bounds.left
3168 && left <= bounds.right
3169 && bottom >= bounds.top
3170 && top <= bounds.bottom;
3171 }
3172
3173 #setRendererVisible (object, visible)
3174 {
3175 if (object?.renderer)
3176 { object.renderer.visible = !!visible; }
3177 }
3178
3179 /** Skip drawing (and lighting work) for tiles/chunks more than ½ tile off-screen. */
3180 #cullOffscreenDrawables ()
3181 {
3182 const bounds = this.#drawBounds();
3183 const size = this.tileSize();
3184
3185 for (const baked of this.bakedChunks.values())
3186 {
3187 const left = baked.chunkX * CHUNK_SIZE * size;
3188 const top = baked.chunkY * CHUNK_SIZE * size;
3189 const chunkPx = CHUNK_SIZE * size;
3190 const chunkVisible = this.#rectIntersects(left, top, left + chunkPx, top + chunkPx, bounds);
3191 this.#setRendererVisible(baked.groundObject, chunkVisible);
3192 this.#setRendererVisible(baked.bloomObject, chunkVisible && this.bloomEnabled);
3193 baked._inViewport = chunkVisible;
3194 for (let row = 0; row < CHUNK_SIZE; row++)
3195 {
3196 const rowTop = top + row * size;
3197 const rowVisible = chunkVisible && this.#rectIntersects(
3198 left, rowTop, left + chunkPx, rowTop + size, bounds
3199 );
3200 this.#setRendererVisible(baked.blockObjects?.[row], rowVisible);
3201 }
3202 }
3203
3204 for (const objects of this.tiles.values())
3205 {
3206 const left = objects.tileX * size;
3207 const top = objects.tileY * size;
3208 const visible = this.#rectIntersects(left, top, left + size, top + size, bounds);
3209 objects._inViewport = visible;
3210 this.#setRendererVisible(objects.ground, visible);
3211 this.#setRendererVisible(objects.groundBloom, visible && this.bloomEnabled);
3212 this.#setRendererVisible(objects.block, visible);
3213 this.#setRendererVisible(objects.blockBloom, visible && this.bloomEnabled);
3214 this.#setRendererVisible(objects.lavaBloom, visible && this.bloomEnabled);
3215 }
3216 }
3217
3218 #upsertEntity (payload)
3219 {
3220 const size = this.tileSize();
3221 const pivot = tilePivot(payload.tileX, payload.tileY, size);
3222 let entity = this.entities.get(payload.entityId);
3223 if (entity?.dying)
3224 {
3225 if (entity.entityId === this.localEntityId)
3226 { this.#abortEntityFade(entity); }
3227 else
3228 {
3229 this.#finishEntityFade(payload.entityId);
3230 entity = null;
3231 }
3232 }
3233 if (!entity)
3234 {
3235 const spriteName = payload.layers?.[0]?.sprite
3236 ?? payload.sprite
3237 ?? bodySpriteName(payload.sex);
3238 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY);
3239 this.scene.addObject(object);
3240 this.#startIdleAnimation(object);
3241 entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y };
3242 this.entities.set(payload.entityId, entity);
3243 }
3244 entity.entityId = payload.entityId;
3245 entity.tileX = payload.tileX;
3246 entity.tileY = payload.tileY;
3247 entity.gait = payload.gait;
3248 entity.sex = payload.sex ?? entity.sex;
3249 entity.characterId = payload.characterId ?? entity.characterId ?? null;
3250 entity.accountId = payload.accountId ?? entity.accountId ?? null;
3251 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
3252 if (payload.level != null)
3253 { entity.level = payload.level | 0; }
3254 entity.hostile = payload.hostile != null ? !!payload.hostile : !!entity.hostile;
3255 entity.aggressive = payload.aggressive != null
3256 ? !!payload.aggressive
3257 : (payload.hostile != null ? !!payload.hostile : !!entity.aggressive);
3258 entity.canFight = payload.canFight != null
3259 ? !!payload.canFight
3260 : !!(entity.canFight || (payload.mobTypeId && !payload.talkable));
3261 entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable;
3262 entity.hasDialogue = payload.hasDialogue != null ? !!payload.hasDialogue : !!entity.hasDialogue;
3263 entity.hasShop = payload.hasShop != null ? !!payload.hasShop : !!entity.hasShop;
3264 entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable;
3265 entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight;
3266 entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0;
3267 if (payload.lightIntensity != null)
3268 { entity.lightIntensity = Number(payload.lightIntensity) || 1; }
3269 else if (entity.lightIntensity == null)
3270 { entity.lightIntensity = 1; }
3271 if (payload.visualScale != null)
3272 { entity.visualScale = Number(payload.visualScale) || 1; }
3273 else if (entity.visualScale == null)
3274 { entity.visualScale = 1; }
3275 if (payload.health != null)
3276 { entity.health = payload.health; }
3277 if (payload.maxHealth != null)
3278 { entity.maxHealth = payload.maxHealth; }
3279 if (payload.skullValue != null)
3280 { entity.skullValue = Math.max(0, payload.skullValue | 0); }
3281 else if (entity.skullValue == null)
3282 { entity.skullValue = 0; }
3283 if (payload.firstName)
3284 { entity.firstName = payload.firstName; }
3285 if (payload.lastName)
3286 { entity.lastName = payload.lastName; }
3287 entity.firstName = entity.firstName ?? "";
3288 entity.lastName = entity.lastName ?? "";
3289 if (payload.worldX != null && payload.worldY != null)
3290 {
3291 entity.worldX = payload.worldX;
3292 entity.worldY = payload.worldY;
3293 entity.visualX = payload.worldX * size;
3294 entity.visualY = payload.worldY * size;
3295 entity.targetX = entity.visualX;
3296 entity.targetY = entity.visualY;
3297 }
3298 else
3299 {
3300 entity.visualX = pivot.x;
3301 entity.visualY = pivot.y;
3302 entity.targetX = pivot.x;
3303 entity.targetY = pivot.y;
3304 }
3305 entity.fromX = entity.visualX;
3306 entity.fromY = entity.visualY;
3307 if (payload.layers)
3308 { this.#applyLayers(entity, payload.layers); }
3309 this.#syncHpBar(entity);
3310 this.#syncSkullMarker(entity);
3311 this.#placeEntity(entity, performance.now());
3312 }
3313
3314 #applyLayers (entity, layers)
3315 {
3316 entity.appearanceLayers = layers ?? [{ sprite: bodySpriteName(entity.sex) }];
3317 this.#rebuildOverlays(entity);
3318 }
3319
3320 #setGatherToolOverlay (entity, toolItemId)
3321 {
3322 entity.gatherToolItemId = toolItemId;
3323 entity.gatherToolUntil = performance.now() + GATHER_TOOL_HOLD_MS;
3324 this.#rebuildOverlays(entity);
3325 this.#placeEntity(entity, performance.now());
3326 }
3327
3328 #expireGatherToolOverlay (entity, now)
3329 {
3330 if (entity.gatherToolItemId == null)
3331 { return; }
3332 if ((entity.gatherToolUntil ?? 0) > now)
3333 { return; }
3334 entity.gatherToolItemId = null;
3335 entity.gatherToolUntil = 0;
3336 this.#rebuildOverlays(entity);
3337 }
3338
3339 /** Prefer the active gather tool's equip sprite over the worn weapon (all gather kinds). */
3340 #layersForDisplay (entity)
3341 {
3342 const layers = (entity.appearanceLayers ?? []).map((layer) => ({ ...layer }));
3343 const toolId = entity.gatherToolItemId;
3344 if (toolId == null || (entity.gatherToolUntil ?? 0) <= performance.now())
3345 { return layers; }
3346 const equip = itemEquipSprite(toolId);
3347 if (!equip || !this.game.images[equip])
3348 { return layers; }
3349 const replacement = {
3350 sprite: equip,
3351 itemId: toolId,
3352 tint: resolveEquipTint(toolId)
3353 };
3354 for (let index = layers.length - 1; index >= 1; index--)
3355 {
3356 const def = itemDefinition(layers[index].itemId);
3357 if (def?.equipment?.slot === EQUIPMENT_SLOT.weapon)
3358 {
3359 layers[index] = replacement;
3360 return layers;
3361 }
3362 }
3363 layers.push(replacement);
3364 return layers;
3365 }
3366
3367 #rebuildOverlays (entity)
3368 {
3369 const layers = this.#layersForDisplay(entity);
3370 const base = layers[0]?.sprite
3371 ?? bodySpriteName(entity.sex);
3372 if (this.game.images[base])
3373 {
3374 entity.object.renderer.sprite = this.game.images[base];
3375 this.#startIdleAnimation(entity.object);
3376 }
3377 entity.bodyTint = layers[0]?.tint ? normalizeRgb(layers[0].tint) : null;
3378 entity.bodyDualTint = layers[0]?.dualTint
3379 ? {
3380 shaft: normalizeRgb(layers[0].dualTint.shaft),
3381 tip: normalizeRgb(layers[0].dualTint.tip),
3382 ...(layers[0].dualTint.coat
3383 ? { coat: normalizeRgb(layers[0].dualTint.coat) }
3384 : {})
3385 }
3386 : null;
3387 entity.bloomBody = !!layers[0]?.bloomBody;
3388 for (const overlay of entity.overlays ?? [])
3389 { overlay.destroy(); }
3390 for (const overlay of entity.bloomOverlays ?? [])
3391 { overlay.destroy(); }
3392 entity.overlays = [];
3393 entity.overlayTints = [];
3394 entity.overlayDualTints = [];
3395 entity.overlayTightFit = [];
3396 entity.bloomOverlays = [];
3397 entity.bloomOverlayTints = [];
3398 entity.bloomOverlayDualTints = [];
3399 if (entity.bloomBody && this.game.images[base])
3400 {
3401 const bloomName = bloomCompanionName(base);
3402 const bloomImage = this.game.images[bloomName] ?? this.game.images[base];
3403 if (bloomImage)
3404 {
3405 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
3406 bloom.renderer.layer = RENDER_LAYER_BLOOM;
3407 this.#markUnlit(bloom);
3408 this.#startIdleAnimation(bloom);
3409 this.scene.addObject(bloom);
3410 entity.bloomOverlays.push(bloom);
3411 entity.bloomOverlayTints.push(entity.bodyTint);
3412 entity.bloomOverlayDualTints.push(entity.bodyDualTint);
3413 }
3414 }
3415 for (const layer of layers.slice(1))
3416 {
3417 const image = this.game.images[layer.sprite];
3418 if (!image)
3419 { continue; }
3420 const object = new GameObject(0, 0, image, SORT_ENTITY);
3421 this.scene.addObject(object);
3422 entity.overlays.push(object);
3423 const layerDef = layer.itemId != null ? itemDefinition(layer.itemId) : null;
3424 entity.overlayTightFit.push(!!layerDef?.tightFit);
3425 const dualTint = layer.dualTint
3426 ? {
3427 shaft: normalizeRgb(layer.dualTint.shaft),
3428 tip: normalizeRgb(layer.dualTint.tip),
3429 ...(layer.dualTint.coat
3430 ? { coat: normalizeRgb(layer.dualTint.coat) }
3431 : {})
3432 }
3433 : (layer.itemId != null
3434 ? resolveEquipDualTint({ itemId: layer.itemId }, layerDef)
3435 : null);
3436 entity.overlayDualTints.push(dualTint);
3437 entity.overlayTints.push(
3438 dualTint
3439 ? null
3440 : (layer.tint
3441 ? normalizeRgb(layer.tint)
3442 : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null))
3443 );
3444 const bloomName = bloomCompanionName(layer.sprite);
3445 const bloomImage = this.game.images[bloomName];
3446 if (!bloomImage)
3447 { continue; }
3448 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
3449 bloom.renderer.layer = RENDER_LAYER_BLOOM;
3450 this.#markUnlit(bloom);
3451 this.scene.addObject(bloom);
3452 entity.bloomOverlays.push(bloom);
3453 entity.bloomOverlayTints.push(
3454 layer.tint ? normalizeRgb(layer.tint) : null
3455 );
3456 }
3457 }
3458
3459 #placeEntity (entity, now = performance.now())
3460 {
3461 const zoom = this.zoom;
3462 const offsetX = entity.shoveOffsetX ?? 0;
3463 const offsetY = entity.shoveOffsetY ?? 0;
3464 const pivotX = entity.visualX + offsetX + (entity.stackOffsetX ?? 0);
3465 const pivotY = entity.visualY + offsetY + (entity.stackOffsetY ?? 0);
3466 let walkTilt = 0;
3467 if (entity.lerpStarted != null)
3468 {
3469 const stepMs = Math.max(1, entity.lerpMs ?? this.#lerpMs(entity.gait));
3470 const cycles = ((now - entity.lerpStarted) / stepMs) * Math.PI * 2;
3471 const tilt = entity.gait === GAIT.run ? RUN_TILT_DEG : WALK_TILT_DEG;
3472 walkTilt = Math.sin(cycles) * tilt;
3473 }
3474 let flashStrength = (entity.damageFlashUntil ?? 0) > now
3475 ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS
3476 : 0;
3477 let deathAlpha = 1;
3478 if (entity.dying)
3479 {
3480 const fadeMs = Math.max(1, entity.deathFadeMs ?? DEATH_FADE_MS);
3481 const fadeT = (now - (entity.deathFadeStarted ?? now)) / fadeMs;
3482 if (fadeT >= 1 && entity.entityId !== this.localEntityId)
3483 {
3484 this.#finishEntityFade(entity.entityId);
3485 return;
3486 }
3487 deathAlpha = Math.max(0, 1 - fadeT);
3488 // Red silhouette only for combat death; plain despawn keeps lit colours + darkness.
3489 if (entity.deathDissolve)
3490 { flashStrength = 1; }
3491 }
3492 const flashColor = entity.damageFlashColor ?? FLASH_COLOR_DAMAGE;
3493 const tileShade = this.#entityShadeAlpha(entity, now);
3494 const wade = isWadeGroundInSeason(this.#groundTypeAt(entity.tileX, entity.tileY), this.worldSeason);
3495
3496 entity.object.transform.rotation = walkTilt;
3497 if (entity.object.renderer)
3498 { entity.object.renderer.alpha = deathAlpha; }
3499 if (entity.bodyDualTint)
3500 {
3501 this.#syncDualTintLitSprite(
3502 entity.object,
3503 tileShade,
3504 entity.bodyDualTint,
3505 flashStrength,
3506 wade,
3507 flashColor
3508 );
3509 }
3510 else
3511 {
3512 this.#syncLitSprite(entity.object, tileShade, flashStrength, wade, entity.bodyTint ?? null, flashColor);
3513 }
3514 const flight = !!entity.freeFlight;
3515 this.#placePivoted(entity.object, pivotX, pivotY, pivotY, SORT_ENTITY, entity.visualScale ?? 1, flight);
3516 for (let index = 0; index < (entity.overlays ?? []).length; index++)
3517 {
3518 const overlay = entity.overlays[index];
3519 const overlaySort = Math.min(SORT_HP_BAR - 2, SORT_ENTITY + 1 + index);
3520 overlay.transform.rotation = walkTilt;
3521 if (overlay.renderer)
3522 { overlay.renderer.alpha = deathAlpha; }
3523 const dualTint = entity.overlayDualTints?.[index] ?? null;
3524 if (dualTint)
3525 {
3526 this.#syncDualTintLitSprite(overlay, tileShade, dualTint, flashStrength, wade, flashColor);
3527 }
3528 else if (entity.overlayTightFit?.[index])
3529 {
3530 this.#syncTightFitLitSprite(
3531 overlay,
3532 entity,
3533 tileShade,
3534 flashStrength,
3535 wade,
3536 entity.overlayTints?.[index] ?? null,
3537 flashColor
3538 );
3539 }
3540 else
3541 {
3542 this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null, flashColor);
3543 }
3544 this.#placePivoted(overlay, pivotX, pivotY, pivotY, overlaySort, entity.visualScale ?? 1, flight);
3545 }
3546 for (let index = 0; index < (entity.bloomOverlays ?? []).length; index++)
3547 {
3548 const overlay = entity.bloomOverlays[index];
3549 this.#setRendererVisible(overlay, this.bloomEnabled && deathAlpha > 0.02);
3550 if (!this.bloomEnabled)
3551 { continue; }
3552 /** Multi-frame body bloom locks to the base sprite; static bodies leave bloom free to animate. */
3553 if (entity.bloomBody && index === 0 && entity.object?.renderer)
3554 {
3555 const bodySprite = entity.object.renderer.sprite;
3556 const bloomSprite = overlay.renderer.sprite;
3557 const bodyFrames = Number(bodySprite?.subImages) || Number(bodySprite?.subImgTotal) || 1;
3558 const bloomFrames = Number(bloomSprite?.subImages) || Number(bloomSprite?.subImgTotal) || 1;
3559 if (bodyFrames > 1 && bloomFrames === bodyFrames)
3560 {
3561 overlay.renderer.cycle = null;
3562 overlay.renderer.subImage = entity.object.renderer.subImage | 0;
3563 }
3564 }
3565 overlay.transform.rotation = walkTilt;
3566 if (overlay.renderer)
3567 { overlay.renderer.alpha = deathAlpha; }
3568 const bloomDual = entity.bloomOverlayDualTints?.[index] ?? null;
3569 const bloomTint = entity.bloomOverlayTints?.[index] ?? entity.bodyTint ?? null;
3570 if (bloomDual)
3571 { this.#syncDualTintLitSprite(overlay, 0, bloomDual); }
3572 else if (bloomTint)
3573 { this.#syncUnlitTintSprite(overlay, bloomTint); }
3574 else
3575 { this.#markUnlit(overlay); }
3576 this.#placePivoted(overlay, pivotX, pivotY, pivotY + 0.002, SORT_ENTITY, entity.visualScale ?? 1, flight);
3577 }
3578 if (!entity.dying)
3579 {
3580 this.#placeHpBar(entity, pivotX, pivotY);
3581 this.#placeSkullMarker(entity, pivotX, pivotY, tileShade);
3582 }
3583 }
3584
3585 #markUnlit (object)
3586 {
3587 if (!object?.renderer)
3588 { return; }
3589 object._lit = false;
3590 object.renderer.shader = null;
3591 object.renderer.shaderUniforms = null;
3592 object.renderer._shaderUniformKind = null;
3593 object.renderer.secondaryMap = null;
3594 }
3595
3596 #ensureUniformBag (renderer, shader, kind)
3597 {
3598 renderer.shader = shader;
3599 if (!renderer.shaderUniforms || renderer._shaderUniformKind !== kind)
3600 {
3601 renderer.shaderUniforms = {};
3602 renderer._shaderUniformKind = kind;
3603 }
3604 return renderer.shaderUniforms;
3605 }
3606
3607 #writeUniformVec3 (uniforms, key, src)
3608 {
3609 let arr = uniforms[key];
3610 if (!Array.isArray(arr) || arr.length !== 3)
3611 {
3612 arr = [0, 0, 0];
3613 uniforms[key] = arr;
3614 }
3615 if (Array.isArray(src))
3616 {
3617 arr[0] = src[0];
3618 arr[1] = src[1];
3619 arr[2] = src[2];
3620 }
3621 else
3622 {
3623 arr[0] = src.r;
3624 arr[1] = src.g;
3625 arr[2] = src.b;
3626 }
3627 }
3628
3629 #writeUniformVec2 (uniforms, key, a, b)
3630 {
3631 let arr = uniforms[key];
3632 if (!Array.isArray(arr) || arr.length !== 2)
3633 {
3634 arr = [0, 0];
3635 uniforms[key] = arr;
3636 }
3637 arr[0] = a;
3638 arr[1] = b;
3639 }
3640
3641 #writeUniformVec4 (uniforms, key, a, b, c, d)
3642 {
3643 let arr = uniforms[key];
3644 if (!Array.isArray(arr) || arr.length !== 4)
3645 {
3646 arr = [0, 0, 0, 0];
3647 uniforms[key] = arr;
3648 }
3649 arr[0] = a;
3650 arr[1] = b;
3651 arr[2] = c;
3652 arr[3] = d;
3653 }
3654
3655 /** Bloom / unlit overlays that still need magenta channel tint (e.g. elemental sprites). */
3656 #syncUnlitTintSprite (object, tintColor)
3657 {
3658 if (!object?.renderer || !tintColor)
3659 { return; }
3660 const tint = normalizeRgb(tintColor);
3661 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
3662 const uniforms = this.#ensureUniformBag(object.renderer, getTintLitSpriteShader(), "unlitTint");
3663 uniforms.u_darkness = 0;
3664 uniforms.u_strength = 0;
3665 this.#writeUniformVec3(uniforms, "u_flashColor", FLASH_COLOR_DAMAGE);
3666 uniforms.u_wade = 0;
3667 uniforms.u_spriteHeight = height;
3668 uniforms.u_useTint = 1;
3669 this.#writeUniformVec3(uniforms, "u_tintColor", tint);
3670 object.renderer.secondaryMap = null;
3671 }
3672
3673 #syncLitSprite (object, darkness, flashStrength = 0, wade = false, tintColor = null, flashColor = null)
3674 {
3675 if (!object?.renderer || object._lit === false)
3676 { return; }
3677 object._lit = true;
3678 const dark = Math.min(1, Math.max(0, darkness ?? 0));
3679 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
3680 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
3681 const flashRgb = flashColor ?? FLASH_COLOR_DAMAGE;
3682 const tint = tintColor ? normalizeRgb(tintColor) : null;
3683 if (tint)
3684 {
3685 const uniforms = this.#ensureUniformBag(object.renderer, getTintLitSpriteShader(), "tintLit");
3686 uniforms.u_darkness = dark;
3687 uniforms.u_strength = flash;
3688 this.#writeUniformVec3(uniforms, "u_flashColor", flashRgb);
3689 uniforms.u_wade = wade ? 1 : 0;
3690 uniforms.u_spriteHeight = height;
3691 uniforms.u_useTint = 1;
3692 this.#writeUniformVec3(uniforms, "u_tintColor", tint);
3693 }
3694 else
3695 {
3696 const uniforms = this.#ensureUniformBag(object.renderer, getSpriteLightingShader(), "lit");
3697 uniforms.u_darkness = dark;
3698 uniforms.u_strength = flash;
3699 this.#writeUniformVec3(uniforms, "u_flashColor", flashRgb);
3700 uniforms.u_wade = wade ? 1 : 0;
3701 uniforms.u_spriteHeight = height;
3702 }
3703 object.renderer.secondaryMap = null;
3704 }
3705
3706 #bodySecondaryMap (entity)
3707 {
3708 return entity?.object?.renderer?.sprite?.g_image ?? null;
3709 }
3710
3711 #tightFitMaskUniforms (overlay, entity, into = null)
3712 {
3713 const bodyRenderer = entity?.object?.renderer;
3714 const clothRenderer = overlay?.renderer;
3715 const bodySprite = bodyRenderer?.sprite;
3716 const clothSprite = clothRenderer?.sprite;
3717 if (!bodySprite || !clothSprite)
3718 { return null; }
3719 const clothUv = clothSprite.getUvRect?.(clothRenderer.subImage | 0)
3720 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
3721 const bodyUv = bodySprite.getUvRect?.(bodyRenderer.subImage | 0)
3722 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
3723 const uniforms = into ?? {};
3724 this.#writeUniformVec2(uniforms, "u_clothSize", clothSprite.width || SPRITE_SIZE_PX, clothSprite.height || SPRITE_SIZE_PX);
3725 this.#writeUniformVec2(uniforms, "u_bodySize", bodySprite.width || SPRITE_SIZE_PX, bodySprite.height || SPRITE_SIZE_PX);
3726 uniforms.u_pivotFromBottom = PIVOT_FROM_BOTTOM_PX;
3727 this.#writeUniformVec4(uniforms, "u_clothUvRect", clothUv.u0, clothUv.v0, clothUv.u1, clothUv.v1);
3728 this.#writeUniformVec4(uniforms, "u_bodyUvRect", bodyUv.u0, bodyUv.v0, bodyUv.u1, bodyUv.v1);
3729 return uniforms;
3730 }
3731
3732 #syncTightFitLitSprite (overlay, entity, darkness, flashStrength = 0, wade = false, tintColor = null, flashColor = null)
3733 {
3734 if (!overlay?.renderer || entity?.object?.renderer == null)
3735 { return; }
3736 const bodyMap = this.#bodySecondaryMap(entity);
3737 const flashRgb = flashColor ?? FLASH_COLOR_DAMAGE;
3738 if (!bodyMap)
3739 {
3740 this.#syncLitSprite(overlay, darkness, flashStrength, wade, tintColor, flashRgb);
3741 return;
3742 }
3743 overlay._lit = true;
3744 const dark = Math.min(1, Math.max(0, darkness ?? 0));
3745 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
3746 const height = overlay.renderer.sprite?.height ?? SPRITE_SIZE_PX;
3747 const tint = tintColor ? normalizeRgb(tintColor) : null;
3748 overlay.renderer.secondaryMap = bodyMap;
3749 const kind = tint ? "tightFitTint" : "tightFit";
3750 const shader = tint ? getTightFitTintLitSpriteShader() : getTightFitLitSpriteShader();
3751 const uniforms = this.#ensureUniformBag(overlay.renderer, shader, kind);
3752 if (!this.#tightFitMaskUniforms(overlay, entity, uniforms))
3753 {
3754 this.#syncLitSprite(overlay, darkness, flashStrength, wade, tintColor, flashRgb);
3755 return;
3756 }
3757 uniforms.u_darkness = dark;
3758 uniforms.u_strength = flash;
3759 this.#writeUniformVec3(uniforms, "u_flashColor", flashRgb);
3760 uniforms.u_wade = wade ? 1 : 0;
3761 uniforms.u_spriteHeight = height;
3762 if (tint)
3763 {
3764 uniforms.u_useTint = 1;
3765 this.#writeUniformVec3(uniforms, "u_tintColor", tint);
3766 }
3767 }
3768
3769 #syncDualTintLitSprite (object, darkness, dualTint, flashStrength = 0, wade = false, flashColor = null)
3770 {
3771 if (!object?.renderer || !dualTint)
3772 { return; }
3773 const shaft = normalizeRgb(dualTint.shaft);
3774 const tip = normalizeRgb(dualTint.tip);
3775 const coat = dualTint.coat ? normalizeRgb(dualTint.coat) : null;
3776 const dark = object._lit === false
3777 ? 0
3778 : Math.min(1, Math.max(0, darkness ?? 0));
3779 if (object._lit !== false)
3780 { object._lit = true; }
3781 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
3782 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
3783 const uniforms = this.#ensureUniformBag(object.renderer, getDualTintLitSpriteShader(), "dualTint");
3784 uniforms.u_darkness = dark;
3785 uniforms.u_strength = flash;
3786 this.#writeUniformVec3(uniforms, "u_flashColor", flashColor ?? FLASH_COLOR_DAMAGE);
3787 uniforms.u_wade = wade ? 1 : 0;
3788 uniforms.u_spriteHeight = height;
3789 this.#writeUniformVec3(uniforms, "u_shaftTint", shaft);
3790 this.#writeUniformVec3(uniforms, "u_tipTint", tip);
3791 this.#writeUniformVec3(uniforms, "u_coatTint", coat ?? { r: 0, g: 0, b: 0 });
3792 uniforms.u_hasCoat = coat ? 1 : 0;
3793 object.renderer.secondaryMap = null;
3794 }
3795
3796 #syncGroundItemSprite (item, darkness)
3797 {
3798 if (item?.dualTint)
3799 {
3800 this.#syncDualTintLitSprite(item.object, darkness, item.dualTint);
3801 return;
3802 }
3803 this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null);
3804 }
3805
3806 #groundTypeAt (tileX, tileY)
3807 {
3808 const ground = this.#groundAtTile(tileX, tileY);
3809 return ground == null ? null : normalizeGround(ground).typeId;
3810 }
3811
3812 /** Ground entry at a world tile, including editor hover preview when present. */
3813 #groundAtTile (tileX, tileY)
3814 {
3815 if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY
3816 && this.preview.ground !== undefined)
3817 { return this.preview.ground; }
3818 const chunkX = Math.floor(tileX / CHUNK_SIZE);
3819 const chunkY = Math.floor(tileY / CHUNK_SIZE);
3820 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
3821 if (!snapshot)
3822 { return null; }
3823 const localX = tileX - chunkX * CHUNK_SIZE;
3824 const localY = tileY - chunkY * CHUNK_SIZE;
3825 const index = localY * CHUNK_SIZE + localX;
3826 return snapshot.grounds?.[index] ?? null;
3827 }
3828
3829 #waterCoastEdges (tileX, tileY)
3830 {
3831 const season = this.worldSeason;
3832 const continues = (x, y) => fluidCoastContinues(
3833 this.#groundTypeAt(x, y),
3834 (typeId) => isLiquidWaterGround(typeId, season)
3835 );
3836 const n = continues(tileX, tileY - 1);
3837 const e = continues(tileX + 1, tileY);
3838 const s = continues(tileX, tileY + 1);
3839 const w = continues(tileX - 1, tileY);
3840 const ne = continues(tileX + 1, tileY - 1);
3841 const nw = continues(tileX - 1, tileY - 1);
3842 const se = continues(tileX + 1, tileY + 1);
3843 const sw = continues(tileX - 1, tileY + 1);
3844 return {
3845 n: n ? 0 : 1,
3846 e: e ? 0 : 1,
3847 s: s ? 0 : 1,
3848 w: w ? 0 : 1,
3849 // Pure diagonal land pockets (e.g. WWW/WLL) — only when cardinals stay water.
3850 ne: (!ne && n && e) ? 1 : 0,
3851 nw: (!nw && n && w) ? 1 : 0,
3852 se: (!se && s && e) ? 1 : 0,
3853 sw: (!sw && s && w) ? 1 : 0
3854 };
3855 }
3856
3857 /**
3858 * Corner deepness = average of liquid-water tiles meeting that corner.
3859 * Bilinear sampling of these corners is continuous across shared edges/corners.
3860 */
3861 #waterDeepCorners (tileX, tileY, selfDeep)
3862 {
3863 const season = this.worldSeason;
3864 const fallback = selfDeep ? 1 : 0;
3865 const depthAt = (x, y) =>
3866 {
3867 const typeId = this.#groundTypeAt(x, y);
3868 if (!isLiquidWaterGround(typeId, season))
3869 { return null; }
3870 return typeId === GroundType.deepWater ? 1 : 0;
3871 };
3872 const corner = (offsets) =>
3873 {
3874 let sum = 0;
3875 let count = 0;
3876 for (const [dx, dy] of offsets)
3877 {
3878 const d = depthAt(tileX + dx, tileY + dy);
3879 if (d == null)
3880 { continue; }
3881 sum += d;
3882 count += 1;
3883 }
3884 return count ? sum / count : fallback;
3885 };
3886 return {
3887 nw: corner([[0, 0], [-1, 0], [0, -1], [-1, -1]]),
3888 ne: corner([[0, 0], [1, 0], [0, -1], [1, -1]]),
3889 sw: corner([[0, 0], [-1, 0], [0, 1], [-1, 1]]),
3890 se: corner([[0, 0], [1, 0], [0, 1], [1, 1]])
3891 };
3892 }
3893
3894 /**
3895 * Neighbor ground sprite for coast retreat peeks.
3896 * Water prefers wet-shore (sand-wet); lava uses dry land only.
3897 */
3898 #fluidCoastShore (tileX, tileY, edges, { preferWet = true } = {})
3899 {
3900 const season = this.worldSeason;
3901 const candidates = [];
3902 if (edges?.n)
3903 { candidates.push({ edge: "n", tileX, tileY: tileY - 1 }); }
3904 if (edges?.e)
3905 { candidates.push({ edge: "e", tileX: tileX + 1, tileY }); }
3906 if (edges?.s)
3907 { candidates.push({ edge: "s", tileX, tileY: tileY + 1 }); }
3908 if (edges?.w)
3909 { candidates.push({ edge: "w", tileX: tileX - 1, tileY }); }
3910 if (edges?.ne)
3911 { candidates.push({ edge: "ne", tileX: tileX + 1, tileY: tileY - 1 }); }
3912 if (edges?.nw)
3913 { candidates.push({ edge: "nw", tileX: tileX - 1, tileY: tileY - 1 }); }
3914 if (edges?.se)
3915 { candidates.push({ edge: "se", tileX: tileX + 1, tileY: tileY + 1 }); }
3916 if (edges?.sw)
3917 { candidates.push({ edge: "sw", tileX: tileX - 1, tileY: tileY + 1 }); }
3918 let pick = null;
3919 for (const candidate of candidates)
3920 {
3921 const ground = this.#groundAtTile(candidate.tileX, candidate.tileY);
3922 if (ground == null)
3923 { continue; }
3924 const entry = normalizeGround(ground);
3925 const def = GROUND_DEFINITIONS[entry.typeId];
3926 if (!def || def.proceduralWaves || !def.blendable)
3927 { continue; }
3928 let spriteName = null;
3929 if (preferWet && def.wetShore)
3930 {
3931 const wetState = `${def.key}-wet`;
3932 const states = this.catalog?.grounds?.[def.key]?.states ?? [];
3933 if (states.includes(wetState))
3934 { spriteName = spriteImageName("ground", def.key, wetState); }
3935 }
3936 if (!spriteName)
3937 {
3938 const states = this.catalog?.grounds?.[def.key]?.states ?? [];
3939 const state = resolveSeasonalVisualState(states, entry.state, season) ?? def.key;
3940 spriteName = spriteImageName("ground", def.key, state);
3941 }
3942 const sprite = spriteName ? this.game.images[spriteName] : null;
3943 if (!sprite)
3944 { continue; }
3945 const ranked = { ...candidate, sprite, wet: !!(preferWet && def.wetShore) };
3946 if (ranked.wet)
3947 {
3948 pick = ranked;
3949 break;
3950 }
3951 if (!pick)
3952 { pick = ranked; }
3953 }
3954 const shore = {
3955 sprite: pick?.sprite ?? null,
3956 edgeN: 0,
3957 edgeE: 0,
3958 edgeS: 0,
3959 edgeW: 0,
3960 edgeNE: 0,
3961 edgeNW: 0,
3962 edgeSE: 0,
3963 edgeSW: 0
3964 };
3965 if (pick?.edge === "n")
3966 { shore.edgeN = 1; }
3967 else if (pick?.edge === "e")
3968 { shore.edgeE = 1; }
3969 else if (pick?.edge === "s")
3970 { shore.edgeS = 1; }
3971 else if (pick?.edge === "w")
3972 { shore.edgeW = 1; }
3973 else if (pick?.edge === "ne")
3974 { shore.edgeNE = 1; }
3975 else if (pick?.edge === "nw")
3976 { shore.edgeNW = 1; }
3977 else if (pick?.edge === "se")
3978 { shore.edgeSE = 1; }
3979 else if (pick?.edge === "sw")
3980 { shore.edgeSW = 1; }
3981 return shore;
3982 }
3983
3984 #waterCoastShore (tileX, tileY, edges)
3985 {
3986 return this.#fluidCoastShore(tileX, tileY, edges, { preferWet: true });
3987 }
3988
3989 #syncWaterGroundSprite (object, {
3990 corners = null,
3991 ambientDark = 0,
3992 edges = null,
3993 shore = null,
3994 timeSec = 0,
3995 fallbackLit = 1,
3996 tileX = 0,
3997 tileY = 0,
3998 deepCorners = null
3999 } = {})
4000 {
4001 if (!object?.renderer)
4002 { return; }
4003 const lit = corners ?? {
4004 nw: fallbackLit,
4005 ne: fallbackLit,
4006 sw: fallbackLit,
4007 se: fallbackLit
4008 };
4009 const dark = Math.min(1, Math.max(0, ambientDark ?? 0));
4010 const shoreSprite = shore?.sprite ?? null;
4011 const shoreUv = shoreSprite?.getUvRect?.(0)
4012 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
4013 const dNW = deepCorners?.nw ?? 0;
4014 const dNE = deepCorners?.ne ?? 0;
4015 const dSW = deepCorners?.sw ?? 0;
4016 const dSE = deepCorners?.se ?? 0;
4017 object._lit = true;
4018 // Shallow + deep share one noise atlas so texAmp seams don't hard-cut at depth edges.
4019 const sharedNoise = this.game.images[spriteImageName("ground", "water", "water")];
4020 if (sharedNoise)
4021 { object.renderer.sprite = sharedNoise; }
4022 object.renderer.secondaryMap = shoreSprite?.g_image ?? null;
4023 const uniforms = this.#ensureUniformBag(object.renderer, getWaterGroundShader(), "water");
4024 uniforms.u_ambientDark = dark;
4025 uniforms.u_litNW = lit.nw;
4026 uniforms.u_litNE = lit.ne;
4027 uniforms.u_litSW = lit.sw;
4028 uniforms.u_litSE = lit.se;
4029 uniforms.u_time = timeSec;
4030 uniforms.u_tileX = tileX | 0;
4031 uniforms.u_tileY = tileY | 0;
4032 uniforms.u_deepNW = dNW;
4033 uniforms.u_deepNE = dNE;
4034 uniforms.u_deepSW = dSW;
4035 uniforms.u_deepSE = dSE;
4036 uniforms.u_edgeN = edges?.n ?? 0;
4037 uniforms.u_edgeE = edges?.e ?? 0;
4038 uniforms.u_edgeS = edges?.s ?? 0;
4039 uniforms.u_edgeW = edges?.w ?? 0;
4040 uniforms.u_edgeNE = edges?.ne ?? 0;
4041 uniforms.u_edgeNW = edges?.nw ?? 0;
4042 uniforms.u_edgeSE = edges?.se ?? 0;
4043 uniforms.u_edgeSW = edges?.sw ?? 0;
4044 uniforms.u_hasShore = shoreSprite ? 1 : 0;
4045 uniforms.u_shoreEdgeN = shore?.edgeN ?? 0;
4046 uniforms.u_shoreEdgeE = shore?.edgeE ?? 0;
4047 uniforms.u_shoreEdgeS = shore?.edgeS ?? 0;
4048 uniforms.u_shoreEdgeW = shore?.edgeW ?? 0;
4049 uniforms.u_shoreEdgeNE = shore?.edgeNE ?? 0;
4050 uniforms.u_shoreEdgeNW = shore?.edgeNW ?? 0;
4051 uniforms.u_shoreEdgeSE = shore?.edgeSE ?? 0;
4052 uniforms.u_shoreEdgeSW = shore?.edgeSW ?? 0;
4053 this.#writeUniformVec4(uniforms, "u_shoreUvRect", shoreUv.u0, shoreUv.v0, shoreUv.u1, shoreUv.v1);
4054 Object.assign(uniforms, waterDebugUniforms());
4055 }
4056
4057 /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. Lava is procedural heat. */
4058 #syncGroundWaterFx (objects, ambientDark, timeSec, baked = null)
4059 {
4060 if (!objects?.ground)
4061 { return; }
4062 if (isLavaGround(objects.groundTypeId))
4063 {
4064 objects.waterEdges = null;
4065 this.#syncLavaGroundFx(objects, ambientDark, timeSec, baked);
4066 return;
4067 }
4068 this.#clearLavaBloom(objects);
4069 if (!isLiquidWaterGround(objects.groundTypeId, this.worldSeason))
4070 {
4071 objects.waterEdges = null;
4072 this.#syncLitSprite(objects.ground, objects.shadeAlpha ?? 0);
4073 return;
4074 }
4075 const fallbackLit = 1 - (objects.shadeAlpha ?? 0);
4076 const chunkX = Math.floor(objects.tileX / CHUNK_SIZE);
4077 const chunkY = Math.floor(objects.tileY / CHUNK_SIZE);
4078 const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`);
4079 const localX = objects.tileX - chunkX * CHUNK_SIZE;
4080 const localY = objects.tileY - chunkY * CHUNK_SIZE;
4081 let litCorners = null;
4082 if (chunkBaked)
4083 {
4084 if (this.lightingMode === "simple")
4085 {
4086 const gridW = CHUNK_SIZE + 2;
4087 const intensity = chunkBaked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? fallbackLit;
4088 litCorners = { nw: intensity, ne: intensity, sw: intensity, se: intensity };
4089 }
4090 else
4091 { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); }
4092 }
4093 objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
4094 const shore = this.#waterCoastShore(objects.tileX, objects.tileY, objects.waterEdges);
4095 const deep = objects.groundTypeId === GroundType.deepWater;
4096 this.#syncWaterGroundSprite(objects.ground, {
4097 corners: litCorners,
4098 ambientDark,
4099 edges: objects.waterEdges,
4100 shore,
4101 timeSec,
4102 fallbackLit,
4103 tileX: objects.tileX,
4104 tileY: objects.tileY,
4105 deepCorners: this.#waterDeepCorners(objects.tileX, objects.tileY, deep)
4106 });
4107 }
4108
4109 #lavaCoastEdges (tileX, tileY)
4110 {
4111 const continues = (x, y) => fluidCoastContinues(
4112 this.#groundTypeAt(x, y),
4113 (typeId) => isLavaGround(typeId)
4114 );
4115 const n = continues(tileX, tileY - 1);
4116 const e = continues(tileX + 1, tileY);
4117 const s = continues(tileX, tileY + 1);
4118 const w = continues(tileX - 1, tileY);
4119 const ne = continues(tileX + 1, tileY - 1);
4120 const nw = continues(tileX - 1, tileY - 1);
4121 const se = continues(tileX + 1, tileY + 1);
4122 const sw = continues(tileX - 1, tileY + 1);
4123 return {
4124 n: n ? 0 : 1,
4125 e: e ? 0 : 1,
4126 s: s ? 0 : 1,
4127 w: w ? 0 : 1,
4128 ne: (!ne && n && e) ? 1 : 0,
4129 nw: (!nw && n && w) ? 1 : 0,
4130 se: (!se && s && e) ? 1 : 0,
4131 sw: (!sw && s && w) ? 1 : 0
4132 };
4133 }
4134
4135 #clearLavaBloom (objects)
4136 {
4137 if (!objects)
4138 { return; }
4139 objects.lavaBloom?.destroy();
4140 objects.lavaBloom = null;
4141 }
4142
4143 #ensureLavaBloom (objects)
4144 {
4145 const sprite = objects.ground?.renderer?.sprite;
4146 if (!sprite)
4147 { return null; }
4148 if (!objects.lavaBloom)
4149 {
4150 const bloom = new GameObject(0, 0, sprite, LAYER_GROUND);
4151 bloom.renderer.layer = RENDER_LAYER_BLOOM;
4152 this.#markUnlit(bloom);
4153 this.scene.addObject(bloom);
4154 objects.lavaBloom = bloom;
4155 }
4156 else if (objects.lavaBloom.renderer)
4157 { objects.lavaBloom.renderer.sprite = sprite; }
4158 const size = this.tileSize();
4159 objects.lavaBloom.transform.position.x = objects.tileX * size + size / 2;
4160 objects.lavaBloom.transform.position.y = objects.tileY * size + size / 2;
4161 objects.lavaBloom.transform.size = new vector(size, size);
4162 this.#setLayer(objects.lavaBloom, LAYER_GROUND);
4163 return objects.lavaBloom;
4164 }
4165
4166 #syncLavaGroundFx (objects, ambientDark, timeSec, baked = null)
4167 {
4168 const fallbackLit = 1 - (objects.shadeAlpha ?? 0);
4169 const chunkX = Math.floor(objects.tileX / CHUNK_SIZE);
4170 const chunkY = Math.floor(objects.tileY / CHUNK_SIZE);
4171 const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`);
4172 const localX = objects.tileX - chunkX * CHUNK_SIZE;
4173 const localY = objects.tileY - chunkY * CHUNK_SIZE;
4174 let litCorners = null;
4175 if (chunkBaked)
4176 {
4177 if (this.lightingMode === "simple")
4178 {
4179 const gridW = CHUNK_SIZE + 2;
4180 const intensity = chunkBaked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? fallbackLit;
4181 litCorners = { nw: intensity, ne: intensity, sw: intensity, se: intensity };
4182 }
4183 else
4184 { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); }
4185 }
4186 const edges = this.#lavaCoastEdges(objects.tileX, objects.tileY);
4187 const shore = this.#fluidCoastShore(objects.tileX, objects.tileY, edges, { preferWet: false });
4188 this.#syncLavaGroundSprite(objects.ground, {
4189 corners: litCorners,
4190 ambientDark,
4191 edges,
4192 shore,
4193 timeSec,
4194 fallbackLit,
4195 tileX: objects.tileX,
4196 tileY: objects.tileY
4197 });
4198 const bloom = this.#ensureLavaBloom(objects);
4199 if (bloom)
4200 {
4201 this.#syncLavaBloomSprite(bloom, {
4202 edges,
4203 timeSec,
4204 tileX: objects.tileX,
4205 tileY: objects.tileY
4206 });
4207 }
4208 }
4209
4210 #syncLavaGroundSprite (object, {
4211 corners = null,
4212 ambientDark = 0,
4213 edges = null,
4214 shore = null,
4215 timeSec = 0,
4216 fallbackLit = 1,
4217 tileX = 0,
4218 tileY = 0
4219 } = {})
4220 {
4221 if (!object?.renderer)
4222 { return; }
4223 const lit = corners ?? {
4224 nw: fallbackLit,
4225 ne: fallbackLit,
4226 sw: fallbackLit,
4227 se: fallbackLit
4228 };
4229 const dark = Math.min(1, Math.max(0, ambientDark ?? 0));
4230 const shoreSprite = shore?.sprite ?? null;
4231 const shoreUv = shoreSprite?.getUvRect?.(0)
4232 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
4233 object._lit = true;
4234 object.renderer.secondaryMap = shoreSprite?.g_image ?? null;
4235 const uniforms = this.#ensureUniformBag(object.renderer, getLavaGroundShader(), "lava");
4236 uniforms.u_ambientDark = dark;
4237 uniforms.u_litNW = lit.nw;
4238 uniforms.u_litNE = lit.ne;
4239 uniforms.u_litSW = lit.sw;
4240 uniforms.u_litSE = lit.se;
4241 uniforms.u_time = timeSec;
4242 uniforms.u_tileX = tileX | 0;
4243 uniforms.u_tileY = tileY | 0;
4244 uniforms.u_edgeN = edges?.n ?? 0;
4245 uniforms.u_edgeE = edges?.e ?? 0;
4246 uniforms.u_edgeS = edges?.s ?? 0;
4247 uniforms.u_edgeW = edges?.w ?? 0;
4248 uniforms.u_edgeNE = edges?.ne ?? 0;
4249 uniforms.u_edgeNW = edges?.nw ?? 0;
4250 uniforms.u_edgeSE = edges?.se ?? 0;
4251 uniforms.u_edgeSW = edges?.sw ?? 0;
4252 uniforms.u_hasShore = shoreSprite ? 1 : 0;
4253 uniforms.u_shoreEdgeN = shore?.edgeN ?? 0;
4254 uniforms.u_shoreEdgeE = shore?.edgeE ?? 0;
4255 uniforms.u_shoreEdgeS = shore?.edgeS ?? 0;
4256 uniforms.u_shoreEdgeW = shore?.edgeW ?? 0;
4257 uniforms.u_shoreEdgeNE = shore?.edgeNE ?? 0;
4258 uniforms.u_shoreEdgeNW = shore?.edgeNW ?? 0;
4259 uniforms.u_shoreEdgeSE = shore?.edgeSE ?? 0;
4260 uniforms.u_shoreEdgeSW = shore?.edgeSW ?? 0;
4261 this.#writeUniformVec4(uniforms, "u_shoreUvRect", shoreUv.u0, shoreUv.v0, shoreUv.u1, shoreUv.v1);
4262 Object.assign(uniforms, lavaDebugUniforms());
4263 }
4264
4265 #syncLavaBloomSprite (object, {
4266 edges = null,
4267 timeSec = 0,
4268 tileX = 0,
4269 tileY = 0
4270 } = {})
4271 {
4272 if (!object?.renderer)
4273 { return; }
4274 const uniforms = this.#ensureUniformBag(object.renderer, getLavaBloomShader(), "lavaBloom");
4275 uniforms.u_time = timeSec;
4276 uniforms.u_tileX = tileX | 0;
4277 uniforms.u_tileY = tileY | 0;
4278 uniforms.u_edgeN = edges?.n ?? 0;
4279 uniforms.u_edgeE = edges?.e ?? 0;
4280 uniforms.u_edgeS = edges?.s ?? 0;
4281 uniforms.u_edgeW = edges?.w ?? 0;
4282 uniforms.u_edgeNE = edges?.ne ?? 0;
4283 uniforms.u_edgeNW = edges?.nw ?? 0;
4284 uniforms.u_edgeSE = edges?.se ?? 0;
4285 uniforms.u_edgeSW = edges?.sw ?? 0;
4286 Object.assign(uniforms, lavaDebugUniforms());
4287 }
4288
4289 #ambientDarkness ()
4290 {
4291 const hour = this.nightPreview ?? this.worldHour;
4292 const calendar = nightFactor(hour, this.settings.nightDarkness);
4293 let dark = resolveDimensionDarknessFactor(this.dimensionLightingMode, calendar);
4294 if (dark == null)
4295 { dark = calendar; }
4296 if (this.localBlind)
4297 { dark = Math.min(1, dark + 0.85); }
4298 return dark;
4299 }
4300
4301 setLocalBlind (blind)
4302 {
4303 this.localBlind = !!blind;
4304 }
4305
4306 /** Soft vision bubble while blinded (client-only; stacks with ambient). */
4307 #blindVisionLight ()
4308 {
4309 if (!this.localBlind)
4310 { return null; }
4311 const local = this.entities.get(this.localEntityId);
4312 if (!local)
4313 { return null; }
4314 const tileSize = this.tileSize();
4315 return {
4316 tileX: Math.floor(local.visualX / tileSize),
4317 tileY: Math.floor(local.visualY / tileSize),
4318 range: 2.25,
4319 intensity: 1
4320 };
4321 }
4322
4323 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY, dualTint = null)
4324 {
4325 const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;
4326 const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0;
4327 const dark = (fromAlpha + toAlpha) / 2;
4328 if (dualTint)
4329 {
4330 this.#syncDualTintLitSprite(object, dark, dualTint);
4331 return;
4332 }
4333 this.#syncLitSprite(object, dark);
4334 }
4335
4336 #dualTintFromPayload (payload)
4337 {
4338 if (!payload?.shaftTint || !payload?.tipTint)
4339 { return null; }
4340 return {
4341 shaft: payload.shaftTint,
4342 tip: payload.tipTint,
4343 ...(payload.coatTint ? { coat: payload.coatTint } : {})
4344 };
4345 }
4346
4347 #syncHpBar (entity)
4348 {
4349 const current = entity.health;
4350 const max = entity.maxHealth;
4351 const show = current != null
4352 && max != null
4353 && max > 0
4354 && current < max;
4355 if (!show)
4356 {
4357 entity.hpBar?.destroy();
4358 entity.hpBar = null;
4359 entity.hpBarCanvas = null;
4360 return;
4361 }
4362 if (!entity.hpBarCanvas)
4363 {
4364 entity.hpBarCanvas = document.createElement("canvas");
4365 entity.hpBarCanvas.width = HP_BAR_W;
4366 entity.hpBarCanvas.height = HP_BAR_H;
4367 const image = frameworkImageFromCanvas(entity.hpBarCanvas);
4368 entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR);
4369 this.#markUnlit(entity.hpBar);
4370 this.scene.addObject(entity.hpBar);
4371 }
4372 drawHpBar(entity.hpBarCanvas, current, max);
4373 invalidateCanvasTexture(this.scene, entity.hpBarCanvas);
4374 }
4375
4376 #placeHpBar (entity, pivotX, pivotY)
4377 {
4378 if (!entity.hpBar)
4379 { return; }
4380 const sprite = entity.object?.renderer?.sprite;
4381 if (!sprite)
4382 { return; }
4383 const zoom = this.zoom;
4384 const drawH = sprite.height * zoom;
4385 const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom);
4386 const spriteTop = centerY - drawH / 2;
4387 const barW = HP_BAR_W * zoom;
4388 const barH = HP_BAR_H * zoom;
4389 entity.hpBar.transform.position.x = pivotX;
4390 entity.hpBar.transform.position.y = spriteTop - barH / 2;
4391 entity.hpBar.transform.size = new vector(barW, barH);
4392 this.#setLayer(entity.hpBar, this.#depthLayer(pivotY, SORT_HP_BAR));
4393 }
4394
4395 #syncSkullMarker (entity)
4396 {
4397 if (!entity?.characterId)
4398 {
4399 entity.skullMarker?.destroy();
4400 entity.skullMarker = null;
4401 return;
4402 }
4403 const tint = skullTintColor(entity.skullValue | 0, this.settings);
4404 if (!tint)
4405 {
4406 entity.skullMarker?.destroy();
4407 entity.skullMarker = null;
4408 return;
4409 }
4410 const image = this.game.images[SKULL_SPRITE]
4411 ?? this.game.images["item:skull:skull"];
4412 if (!image)
4413 { return; }
4414 if (!entity.skullMarker)
4415 {
4416 entity.skullMarker = new GameObject(0, 0, image, SORT_HP_BAR);
4417 this.scene.addObject(entity.skullMarker);
4418 }
4419 entity.skullTint = tint;
4420 entity.skullMarker.renderer.sprite = image;
4421 }
4422
4423 /**
4424 * Bottom edge of the skull sprite sits exactly on the character sprite's top edge.
4425 */
4426 #placeSkullMarker (entity, pivotX, pivotY, darkness)
4427 {
4428 this.#syncSkullMarker(entity);
4429 if (!entity.skullMarker)
4430 { return; }
4431 const body = entity.object?.renderer?.sprite;
4432 const skull = entity.skullMarker.renderer?.sprite;
4433 if (!body || !skull)
4434 { return; }
4435 const zoom = this.zoom;
4436 const scale = entity.visualScale ?? 1;
4437 const bodyH = body.height * zoom * scale;
4438 const skullH = skull.height * zoom;
4439 const skullW = skull.width * zoom;
4440 const bodyCenterY = pivotY - (bodyH / 2 - PIVOT_FROM_BOTTOM_PX * zoom * scale);
4441 const bodyTop = bodyCenterY - bodyH / 2;
4442 // GameObject position is sprite center; bottom of skull at bodyTop ⇒ center at bodyTop - skullH/2
4443 entity.skullMarker.transform.position.x = pivotX;
4444 entity.skullMarker.transform.position.y = bodyTop - skullH / 2;
4445 entity.skullMarker.transform.size = new vector(skullW, skullH);
4446 this.#setLayer(entity.skullMarker, this.#depthLayer(pivotY, SORT_HP_BAR));
4447 this.#syncLitSprite(entity.skullMarker, darkness, 0, false, entity.skullTint);
4448 }
4449
4450 #rebuildChunk (snapshot, { refreshSoftNeighbors = true } = {})
4451 {
4452 this.#bakeAndPlaceChunk(snapshot);
4453 this.#relayoutChunkTiles(snapshot);
4454 // Soft terrain and wet-sand shorelines both sample cross-chunk neighbors.
4455 if (refreshSoftNeighbors && this.#needsSoftTerrainNeighborRefresh())
4456 { this.#rebuildSoftTerrainNeighborChunks(snapshot); }
4457 }
4458
4459 /** Soft blend / wet-sand atlas borders need a rebake when an adjacent chunk arrives. */
4460 #needsSoftTerrainNeighborRefresh ()
4461 {
4462 if (this.softTerrain)
4463 { return true; }
4464 return Math.max(0, Number(this.settings?.wetSandBand) || 0) > 0;
4465 }
4466
4467 #relayoutChunk (snapshot)
4468 {
4469 this.#layoutBakedChunk(snapshot);
4470 this.#relayoutChunkTiles(snapshot);
4471 }
4472
4473 #relayoutChunkTiles (snapshot)
4474 {
4475 for (let localY = 0; localY < CHUNK_SIZE; localY++)
4476 {
4477 for (let localX = 0; localX < CHUNK_SIZE; localX++)
4478 {
4479 const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
4480 const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
4481 this.#drawTile(tileX, tileY);
4482 }
4483 }
4484 }
4485
4486 #scheduleChunkRebuild (snapshot)
4487 {
4488 if (!snapshot)
4489 { return; }
4490 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
4491 this.#chunkRebuildKeys.add(key);
4492 this.#chunkSoftNeighborKeys.delete(key);
4493 this.#cancelIdlePrefetch();
4494 this.#ensureChunkFlushScheduled();
4495 }
4496
4497 /** Queue a neighbor atlas rebake without cascading further soft-neighbor work. */
4498 #scheduleSoftNeighborChunkRebuild (snapshot)
4499 {
4500 if (!snapshot)
4501 { return; }
4502 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
4503 if (this.#chunkRebuildKeys.has(key))
4504 { return; }
4505 this.#chunkSoftNeighborKeys.add(key);
4506 this.#cancelIdlePrefetch();
4507 this.#ensureChunkFlushScheduled();
4508 }
4509
4510 #scheduleEdgeRebuild ()
4511 {
4512 this.#edgesDirty = true;
4513 this.#cancelIdlePrefetch();
4514 this.#ensureChunkFlushScheduled();
4515 }
4516
4517 #pendingChunkRebuildCount ()
4518 {
4519 return this.#chunkRebuildKeys.size + this.#chunkSoftNeighborKeys.size;
4520 }
4521
4522 #ensureChunkFlushScheduled ()
4523 {
4524 if (this.#chunkRebuildRaf)
4525 { return; }
4526 this.#cancelIdlePrefetch();
4527 this.#chunkRebuildRaf = requestAnimationFrame(() => this.#flushChunkWork());
4528 }
4529
4530 #notePlayerTile (tileX, tileY)
4531 {
4532 const chunkX = Math.floor(tileX / CHUNK_SIZE);
4533 const chunkY = Math.floor(tileY / CHUNK_SIZE);
4534 const prevX = this.#playerChunkX;
4535 const prevY = this.#playerChunkY;
4536 if (prevX != null
4537 && (chunkX !== prevX || chunkY !== prevY))
4538 {
4539 const dx = chunkX - prevX;
4540 const dy = chunkY - prevY;
4541 if (dx !== 0)
4542 { this.#playerMoveChunkDx = Math.sign(dx); }
4543 if (dy !== 0)
4544 { this.#playerMoveChunkDy = Math.sign(dy); }
4545 this.#onActiveLightingCenterChanged(prevX, prevY, chunkX, chunkY);
4546 }
4547 this.#playerChunkX = chunkX;
4548 this.#playerChunkY = chunkY;
4549 }
4550
4551 /** When the 3×3 lighting center moves: refresh door sprites (resting vs live) and lightmaps. */
4552 #onActiveLightingCenterChanged (prevChunkX, prevChunkY, chunkX, chunkY)
4553 {
4554 this.#invalidateActiveLightingMoveCaches(prevChunkX, prevChunkY, chunkX, chunkY);
4555 const doorChunks = new Set();
4556 for (const [cx, cy] of [[prevChunkX, prevChunkY], [chunkX, chunkY]])
4557 {
4558 for (let dy = -1; dy <= 1; dy++)
4559 {
4560 for (let dx = -1; dx <= 1; dx++)
4561 { doorChunks.add(`${cx + dx},${cy + dy}`); }
4562 }
4563 }
4564 for (const key of doorChunks)
4565 {
4566 const [cx, cy] = key.split(",").map(Number);
4567 this.#redrawDoorTilesInChunk(cx, cy);
4568 }
4569 }
4570
4571 /**
4572 * Only bust lightmaps for chunks whose active-3×3 membership (or ±1 halo) changed.
4573 * Cache keys already track light positions; a full ±2 wipe around both centers was redundant.
4574 */
4575 #invalidateActiveLightingMoveCaches (prevChunkX, prevChunkY, nextChunkX, nextChunkY)
4576 {
4577 const prev = new Set();
4578 const next = new Set();
4579 for (let dy = -1; dy <= 1; dy++)
4580 {
4581 for (let dx = -1; dx <= 1; dx++)
4582 {
4583 prev.add(`${prevChunkX + dx},${prevChunkY + dy}`);
4584 next.add(`${nextChunkX + dx},${nextChunkY + dy}`);
4585 }
4586 }
4587 const changed = [];
4588 for (const key of prev)
4589 {
4590 if (!next.has(key))
4591 { changed.push(key); }
4592 }
4593 for (const key of next)
4594 {
4595 if (!prev.has(key))
4596 { changed.push(key); }
4597 }
4598 const bust = new Set();
4599 for (const key of changed)
4600 {
4601 const [cx, cy] = key.split(",").map(Number);
4602 for (let dy = -1; dy <= 1; dy++)
4603 {
4604 for (let dx = -1; dx <= 1; dx++)
4605 { bust.add(`${cx + dx},${cy + dy}`); }
4606 }
4607 }
4608 for (const key of bust)
4609 {
4610 const baked = this.bakedChunks.get(key);
4611 if (baked)
4612 { baked.lightmapCacheKey = null; }
4613 }
4614 }
4615
4616 #redrawDoorTilesInChunk (chunkX, chunkY)
4617 {
4618 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
4619 if (!snapshot?.blocks)
4620 { return; }
4621 for (let localY = 0; localY < CHUNK_SIZE; localY++)
4622 {
4623 for (let localX = 0; localX < CHUNK_SIZE; localX++)
4624 {
4625 const block = snapshot.blocks[localY * CHUNK_SIZE + localX];
4626 if (!blockDefinition(block?.typeId)?.door)
4627 { continue; }
4628 this.#drawTile(chunkX * CHUNK_SIZE + localX, chunkY * CHUNK_SIZE + localY);
4629 }
4630 }
4631 }
4632
4633 #playerChunkCoords ()
4634 {
4635 const local = this.entities.get(this.localEntityId);
4636 if (local)
4637 {
4638 return {
4639 chunkX: Math.floor(local.tileX / CHUNK_SIZE),
4640 chunkY: Math.floor(local.tileY / CHUNK_SIZE)
4641 };
4642 }
4643 if (this.#playerChunkX != null && this.#playerChunkY != null)
4644 {
4645 return { chunkX: this.#playerChunkX, chunkY: this.#playerChunkY };
4646 }
4647 return null;
4648 }
4649
4650 /** Lower score = bake sooner in urgent mode; idle mode inverts distance. */
4651 #chunkRebuildScore (key, mode = "urgent")
4652 {
4653 const [chunkX, chunkY] = key.split(",").map(Number);
4654 const player = this.#playerChunkCoords();
4655 if (!player)
4656 { return 0; }
4657 const dx = chunkX - player.chunkX;
4658 const dy = chunkY - player.chunkY;
4659 const dist = Math.abs(dx) + Math.abs(dy);
4660 let ahead = 0;
4661 if (this.#playerMoveChunkDx !== 0 || this.#playerMoveChunkDy !== 0)
4662 { ahead = dx * this.#playerMoveChunkDx + dy * this.#playerMoveChunkDy; }
4663 if (mode === "idle")
4664 {
4665 return -dist * 10 + (ahead > 0 ? -ahead * 2 : Math.max(ahead, 0));
4666 }
4667 return dist * 10 - Math.max(0, ahead) * 3;
4668 }
4669
4670 #sortedChunkRebuildKeys (keySet, mode = "urgent")
4671 {
4672 return [...keySet].sort((a, b) =>
4673 this.#chunkRebuildScore(a, mode) - this.#chunkRebuildScore(b, mode));
4674 }
4675
4676 #discoverUnbakedChunks ()
4677 {
4678 for (const key of this.chunks.keys())
4679 {
4680 if (!this.bakedChunks.has(key))
4681 { this.#chunkRebuildKeys.add(key); }
4682 }
4683 }
4684
4685 #hasUnbakedChunks ()
4686 {
4687 for (const key of this.chunks.keys())
4688 {
4689 if (!this.bakedChunks.has(key))
4690 { return true; }
4691 }
4692 return false;
4693 }
4694
4695 #pickIdlePrefetchSnapshot ()
4696 {
4697 let best = null;
4698 let bestScore = Infinity;
4699 for (const snapshot of this.chunks.values())
4700 {
4701 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
4702 if (this.bakedChunks.has(key)
4703 || this.#chunkRebuildKeys.has(key)
4704 || this.#chunkSoftNeighborKeys.has(key))
4705 { continue; }
4706 const score = this.#chunkRebuildScore(key, "idle");
4707 if (score < bestScore)
4708 {
4709 bestScore = score;
4710 best = snapshot;
4711 }
4712 }
4713 return best;
4714 }
4715
4716 #cancelIdlePrefetch ()
4717 {
4718 if (this.#idlePrefetchId && typeof cancelIdleCallback === "function")
4719 { cancelIdleCallback(this.#idlePrefetchId); }
4720 this.#idlePrefetchId = 0;
4721 }
4722
4723 #scheduleIdleChunkPrefetch ()
4724 {
4725 if (this.#idlePrefetchId || this.#chunkRebuildRaf || this.#pendingChunkRebuildCount())
4726 { return; }
4727 if (typeof requestIdleCallback !== "function")
4728 { return; }
4729 if (!this.#hasUnbakedChunks())
4730 { return; }
4731 this.#idlePrefetchId = requestIdleCallback(
4732 (deadline) => this.#runIdleChunkPrefetch(deadline),
4733 { timeout: 2500 }
4734 );
4735 }
4736
4737 #runIdleChunkPrefetch (deadline)
4738 {
4739 this.#idlePrefetchId = 0;
4740 if (this.#chunkRebuildRaf || this.#pendingChunkRebuildCount())
4741 { return; }
4742 this.#discoverUnbakedChunks();
4743 if (this.#pendingChunkRebuildCount())
4744 {
4745 this.#ensureChunkFlushScheduled();
4746 return;
4747 }
4748 const snapshot = this.#pickIdlePrefetchSnapshot();
4749 if (!snapshot)
4750 { return; }
4751 if (deadline.timeRemaining() <= 4 && !deadline.didTimeout)
4752 {
4753 this.#scheduleIdleChunkPrefetch();
4754 return;
4755 }
4756 this.#rebuildChunk(snapshot, { refreshSoftNeighbors: true });
4757 if (this.#hasUnbakedChunks())
4758 { this.#scheduleIdleChunkPrefetch(); }
4759 }
4760
4761 #flushChunkWork ()
4762 {
4763 this.#chunkRebuildRaf = 0;
4764 const primary = this.#sortedChunkRebuildKeys(this.#chunkRebuildKeys, "urgent");
4765 const soft = this.#sortedChunkRebuildKeys(this.#chunkSoftNeighborKeys, "urgent");
4766 let budget = this.#CHUNK_REBUILD_BATCH;
4767 const primaryBatch = primary.slice(0, budget);
4768 budget -= primaryBatch.length;
4769 const softBatch = soft.slice(0, Math.max(0, budget));
4770
4771 for (const key of primaryBatch)
4772 { this.#chunkRebuildKeys.delete(key); }
4773 for (const key of softBatch)
4774 { this.#chunkSoftNeighborKeys.delete(key); }
4775
4776 for (const key of primaryBatch)
4777 {
4778 const snap = this.chunks.get(key);
4779 if (snap)
4780 { this.#rebuildChunk(snap, { refreshSoftNeighbors: true }); }
4781 }
4782 for (const key of softBatch)
4783 {
4784 const snap = this.chunks.get(key);
4785 if (snap)
4786 { this.#rebuildChunk(snap, { refreshSoftNeighbors: false }); }
4787 }
4788
4789 if (this.#pendingChunkRebuildCount())
4790 {
4791 this.#ensureChunkFlushScheduled();
4792 return;
4793 }
4794 if (this.#edgesDirty)
4795 {
4796 this.#rebuildAllEdges();
4797 this.#edgesDirty = false;
4798 }
4799 this.#scheduleIdleChunkPrefetch();
4800 }
4801
4802 #previewEqual (a, b)
4803 {
4804 if (a === b)
4805 { return true; }
4806 if (!a || !b)
4807 { return false; }
4808 return a.tileX === b.tileX
4809 && a.tileY === b.tileY
4810 && this.#previewPart(a.ground) === this.#previewPart(b.ground)
4811 && this.#previewPart(a.block) === this.#previewPart(b.block);
4812 }
4813
4814 #previewPart (value)
4815 {
4816 return value === undefined ? undefined : JSON.stringify(value);
4817 }
4818
4819 #rebuildSoftTerrainNeighborChunks (snapshot)
4820 {
4821 for (let dy = -1; dy <= 1; dy++)
4822 {
4823 for (let dx = -1; dx <= 1; dx++)
4824 {
4825 if (dx === 0 && dy === 0)
4826 { continue; }
4827 const neighbor = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
4828 if (neighbor)
4829 { this.#scheduleSoftNeighborChunkRebuild(neighbor); }
4830 }
4831 }
4832 }
4833
4834 #rebakeAllChunks ()
4835 {
4836 for (const snapshot of this.chunks.values())
4837 { this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false }); }
4838 }
4839
4840 #bakeAndPlaceChunk (snapshot)
4841 {
4842 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
4843 const atlases = bakeChunkAtlases({
4844 snapshot,
4845 catalog: this.catalog,
4846 images: this.game.images,
4847 preview: this.preview,
4848 season: this.worldSeason,
4849 softTerrain: this.softTerrain,
4850 wetSandBandFraction: Math.max(0, Math.min(1, Number(this.settings?.wetSandBand) || 0)),
4851 resolveGround: (tileX, tileY) => this.#groundAtTile(tileX, tileY),
4852 cache: this.#atlasCache
4853 });
4854 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
4855 let baked = this.bakedChunks.get(key);
4856 this.#releaseBakedAtlasRefs(baked);
4857
4858 const groundImage = this.#atlasCache.getImage(atlases.cacheRefs?.ground);
4859 const blockImages = atlases.cacheRefs?.blockRows.map((entry) => this.#atlasCache.getImage(entry))
4860 ?? atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas));
4861 const bloomImage = this.#atlasCache.getImage(atlases.cacheRefs?.bloom)
4862 ?? frameworkImageFromCanvas(atlases.bloom);
4863
4864 if (!baked)
4865 {
4866 const lightmapCanvas = makeLightmapCanvas(atlasPx);
4867 const natureCanvas = makeNatureNoiseCanvas();
4868 baked = {
4869 groundCanvas: atlases.ground,
4870 blockCanvases: atlases.blockRows,
4871 bloomCanvas: atlases.bloom,
4872 lightmapCanvas,
4873 natureCanvas,
4874 groundImage,
4875 blockImages,
4876 bloomImage,
4877 lightmapImage: frameworkImageFromCanvas(lightmapCanvas),
4878 natureImage: frameworkImageFromCanvas(natureCanvas),
4879 groundObject: null,
4880 blockObjects: [],
4881 bloomObject: null,
4882 tallBlocks: atlases.tallBlocks,
4883 animatedGrounds: atlases.animatedGrounds,
4884 lightmapPixels: null,
4885 atlasCacheRefs: atlases.cacheRefs,
4886 chunkX: snapshot.chunkX,
4887 chunkY: snapshot.chunkY
4888 };
4889 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
4890 this.#applyAtlasLighting(
4891 baked.groundObject,
4892 baked.lightmapImage,
4893 -1,
4894 this.#groundNatureImage(baked)
4895 );
4896 this.scene.addObject(baked.groundObject);
4897 for (let row = 0; row < CHUNK_SIZE; row++)
4898 {
4899 const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
4900 this.#applyAtlasLighting(object, baked.lightmapImage, row, null);
4901 this.scene.addObject(object);
4902 baked.blockObjects.push(object);
4903 }
4904 baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK);
4905 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
4906 this.#markUnlit(baked.bloomObject);
4907 this.scene.addObject(baked.bloomObject);
4908 this.bakedChunks.set(key, baked);
4909 }
4910 else
4911 {
4912 baked.chunkX = snapshot.chunkX;
4913 baked.chunkY = snapshot.chunkY;
4914 if (!baked.natureCanvas)
4915 {
4916 baked.natureCanvas = makeNatureNoiseCanvas();
4917 baked.natureImage = frameworkImageFromCanvas(baked.natureCanvas);
4918 }
4919 if (baked.groundCanvas !== atlases.ground)
4920 {
4921 baked.groundCanvas = atlases.ground;
4922 baked.groundImage = groundImage;
4923 baked.groundObject.renderer.sprite = groundImage;
4924 }
4925 this.#applyAtlasLighting(
4926 baked.groundObject,
4927 baked.lightmapImage,
4928 -1,
4929 this.#groundNatureImage(baked)
4930 );
4931 for (let row = 0; row < CHUNK_SIZE; row++)
4932 {
4933 if (baked.blockCanvases[row] !== atlases.blockRows[row])
4934 {
4935 baked.blockCanvases[row] = atlases.blockRows[row];
4936 baked.blockImages[row] = blockImages[row];
4937 baked.blockObjects[row].renderer.sprite = blockImages[row];
4938 }
4939 this.#applyAtlasLighting(
4940 baked.blockObjects[row],
4941 baked.lightmapImage,
4942 row,
4943 null
4944 );
4945 }
4946 if (baked.bloomCanvas !== atlases.bloom)
4947 {
4948 baked.bloomCanvas = atlases.bloom;
4949 baked.bloomImage = bloomImage;
4950 baked.bloomObject.renderer.sprite = bloomImage;
4951 }
4952 baked.tallBlocks = atlases.tallBlocks;
4953 baked.animatedGrounds = atlases.animatedGrounds;
4954 baked.atlasCacheRefs = atlases.cacheRefs;
4955 }
4956 baked.chunkX = snapshot.chunkX;
4957 baked.chunkY = snapshot.chunkY;
4958 if (this.natureTintEnabled)
4959 { this.#refreshNatureNoiseAround(snapshot.chunkX, snapshot.chunkY); }
4960 baked.lightmapCacheKey = null;
4961 this.#invalidateNeighborLightmapCaches(snapshot.chunkX, snapshot.chunkY);
4962 this.#layoutBakedChunk(snapshot);
4963 this.#queueBakedChunkTextures(baked, snapshot.chunkX, snapshot.chunkY);
4964 }
4965
4966 #groundNatureImage (baked)
4967 {
4968 if (!baked?.natureImage)
4969 { return null; }
4970 if (this.natureTintEnabled || baked.natureTintReady)
4971 { return baked.natureImage; }
4972 return null;
4973 }
4974
4975 #releaseBakedAtlasRefs (baked)
4976 {
4977 if (!baked?.atlasCacheRefs)
4978 { return; }
4979 this.#atlasCache.release(baked.atlasCacheRefs.ground);
4980 for (const entry of baked.atlasCacheRefs.blockRows ?? [])
4981 { this.#atlasCache.release(entry); }
4982 this.#atlasCache.release(baked.atlasCacheRefs.bloom);
4983 baked.atlasCacheRefs = null;
4984 }
4985
4986 #chunkTextureWarmPriority (chunkX, chunkY)
4987 {
4988 const local = this.entities.get(this.localEntityId);
4989 if (!local)
4990 { return 999; }
4991 const playerChunkX = Math.floor(local.tileX / CHUNK_SIZE);
4992 const playerChunkY = Math.floor(local.tileY / CHUNK_SIZE);
4993 return Math.abs(chunkX - playerChunkX) + Math.abs(chunkY - playerChunkY);
4994 }
4995
4996 #queueCanvasTextureWarm (canvas, chunkX, chunkY)
4997 {
4998 if (!canvas || this.#pendingTextureCanvasSet.has(canvas))
4999 { return; }
5000 this.#pendingTextureCanvasSet.add(canvas);
5001 this.#pendingTextureCanvases.push({
5002 canvas,
5003 priority: this.#chunkTextureWarmPriority(chunkX, chunkY)
5004 });
5005 this.#scheduleTextureWarm();
5006 }
5007
5008 #queueBakedChunkTextures (baked, chunkX, chunkY)
5009 {
5010 if (!baked)
5011 { return; }
5012 const refs = baked.atlasCacheRefs;
5013 const maybeWarm = (canvas, entry) =>
5014 {
5015 if (!canvas)
5016 { return; }
5017 if (entry && this.#atlasCache.isWarmed(canvas))
5018 { return; }
5019 this.#queueCanvasTextureWarm(canvas, chunkX, chunkY);
5020 };
5021 maybeWarm(baked.groundCanvas, refs?.ground);
5022 for (let row = 0; row < (baked.blockCanvases ?? []).length; row++)
5023 { maybeWarm(baked.blockCanvases[row], refs?.blockRows?.[row]); }
5024 maybeWarm(baked.bloomCanvas, refs?.bloom);
5025 this.#queueCanvasTextureWarm(baked.lightmapCanvas, chunkX, chunkY);
5026 this.#queueCanvasTextureWarm(baked.natureCanvas, chunkX, chunkY);
5027 }
5028
5029 #scheduleTextureWarm ()
5030 {
5031 if (this.#textureWarmRaf)
5032 { return; }
5033 this.#textureWarmRaf = requestAnimationFrame(() => this.#flushTextureWarm());
5034 }
5035
5036 #flushTextureWarm ()
5037 {
5038 this.#textureWarmRaf = 0;
5039 if (!this.#pendingTextureCanvases.length)
5040 { return; }
5041 this.#pendingTextureCanvases.sort((a, b) => a.priority - b.priority);
5042 const batch = this.#pendingTextureCanvases.splice(0, this.#TEXTURE_WARM_BATCH);
5043 for (const entry of batch)
5044 {
5045 this.#pendingTextureCanvasSet.delete(entry.canvas);
5046 setNearestFilter(this.scene, entry.canvas);
5047 this.#atlasCache.markWarmed(entry.canvas);
5048 }
5049 if (this.#pendingTextureCanvases.length)
5050 { this.#scheduleTextureWarm(); }
5051 }
5052
5053 #applyAtlasLighting (object, lightmapImage, lightRow, natureImage = null)
5054 {
5055 if (!object?.renderer)
5056 { return; }
5057 object._lit = true;
5058 object.renderer.shader = getAtlasLightingShader();
5059 const useNature = natureImage != null && lightRow < 0;
5060 object.renderer.bumpMap = useNature ? natureImage : null;
5061 object.renderer.secondaryMap = lightmapImage;
5062 object.renderer.shaderUniforms = {
5063 u_ambientDark: 0,
5064 u_lightRow: lightRow,
5065 u_useNature: useNature ? 1 : 0,
5066 u_natureTint: 0,
5067 u_natureDark: 0,
5068 u_natureContrast: 1,
5069 ...(useNature ? natureTintUniforms() : {})
5070 };
5071 }
5072
5073 /**
5074 * One-shot nature tint bake (editor chunk-save). Fills noise for each chunk
5075 * and its halo neighbors, and enables tint on the ground atlas.
5076 * @param {Iterable<{ chunkX: number, chunkY: number }>} chunks
5077 */
5078 bakeNatureTintForChunks (chunks)
5079 {
5080 const seen = new Set();
5081 for (const entry of chunks ?? [])
5082 {
5083 const chunkX = entry?.chunkX;
5084 const chunkY = entry?.chunkY;
5085 if (!Number.isFinite(chunkX) || !Number.isFinite(chunkY))
5086 { continue; }
5087 for (let dy = -1; dy <= 1; dy++)
5088 {
5089 for (let dx = -1; dx <= 1; dx++)
5090 {
5091 const key = `${chunkX + dx},${chunkY + dy}`;
5092 if (seen.has(key))
5093 { continue; }
5094 seen.add(key);
5095 const baked = this.bakedChunks.get(key);
5096 const snapshot = this.chunks.get(key);
5097 if (!baked?.natureCanvas || !snapshot)
5098 { continue; }
5099 if (this.#fillNatureNoise(baked, snapshot) || baked.natureTintReady)
5100 {
5101 if (baked.groundObject)
5102 {
5103 this.#applyAtlasLighting(
5104 baked.groundObject,
5105 baked.lightmapImage,
5106 -1,
5107 baked.natureImage
5108 );
5109 }
5110 }
5111 }
5112 }
5113 }
5114 }
5115
5116 /** Rebuild nature noise for a chunk and neighbors (halo needs adjacent grounds). */
5117 #refreshNatureNoiseAround (chunkX, chunkY)
5118 {
5119 if (!this.natureTintEnabled)
5120 { return; }
5121 for (let dy = -1; dy <= 1; dy++)
5122 {
5123 for (let dx = -1; dx <= 1; dx++)
5124 {
5125 const cx = chunkX + dx;
5126 const cy = chunkY + dy;
5127 const baked = this.bakedChunks.get(`${cx},${cy}`);
5128 const snapshot = this.chunks.get(`${cx},${cy}`);
5129 if (!baked?.natureCanvas || !snapshot)
5130 { continue; }
5131 if (this.#fillNatureNoise(baked, snapshot) && baked.groundObject)
5132 { this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1, baked.natureImage); }
5133 }
5134 }
5135 }
5136
5137 /**
5138 * Hash of grounds sampled by the nature canvas (chunk + pad halo).
5139 * Used to skip Perlin refill when nothing under the noise map changed.
5140 */
5141 #natureSourceHash (snapshot)
5142 {
5143 let hash = 2166136261;
5144 const baseX = snapshot.chunkX * CHUNK_SIZE;
5145 const baseY = snapshot.chunkY * CHUNK_SIZE;
5146 const pad = NATURE_NOISE_PAD;
5147 for (let ly = -pad; ly < CHUNK_SIZE + pad; ly++)
5148 {
5149 for (let lx = -pad; lx < CHUNK_SIZE + pad; lx++)
5150 {
5151 const ground = this.#groundAtTile(baseX + lx, baseY + ly);
5152 const typeId = ground == null ? -1 : (normalizeGround(ground).typeId ?? -1);
5153 hash ^= (typeId + 1) >>> 0;
5154 hash = Math.imul(hash, 16777619);
5155 }
5156 }
5157 return hash >>> 0;
5158 }
5159
5160 /**
5161 * @returns {boolean} true when the nature canvas was rewritten
5162 */
5163 #fillNatureNoise (baked, snapshot)
5164 {
5165 if (!baked?.natureCanvas || !snapshot)
5166 { return false; }
5167 const sourceHash = this.#natureSourceHash(snapshot);
5168 if (baked.natureSourceHash === sourceHash && baked.natureTintReady && baked.natureImage)
5169 { return false; }
5170
5171 const canvas = baked.natureCanvas;
5172 if (canvas.width !== NATURE_NOISE_SIZE || canvas.height !== NATURE_NOISE_SIZE)
5173 {
5174 canvas.width = NATURE_NOISE_SIZE;
5175 canvas.height = NATURE_NOISE_SIZE;
5176 }
5177 const scale = NATURE_TINT.scale;
5178 const ctx = canvas.getContext("2d");
5179 const pixelCount = NATURE_NOISE_SIZE * NATURE_NOISE_SIZE * 4;
5180 if (!baked.naturePixels || baked.naturePixels.length !== pixelCount)
5181 { baked.naturePixels = new Uint8ClampedArray(pixelCount); }
5182 const pixels = baked.naturePixels;
5183 if (!baked.natureImageData || baked.natureImageData.data !== pixels)
5184 { baked.natureImageData = new ImageData(pixels, NATURE_NOISE_SIZE, NATURE_NOISE_SIZE); }
5185 const baseX = snapshot.chunkX * CHUNK_SIZE;
5186 const baseY = snapshot.chunkY * CHUNK_SIZE;
5187 const pad = NATURE_NOISE_PAD;
5188 for (let py = 0; py < NATURE_NOISE_SIZE; py++)
5189 {
5190 for (let px = 0; px < NATURE_NOISE_SIZE; px++)
5191 {
5192 const lx = px - pad;
5193 const ly = py - pad;
5194 const worldX = baseX + lx;
5195 const worldY = baseY + ly;
5196 const ground = this.#groundAtTile(worldX, worldY);
5197 const typeId = ground == null ? null : normalizeGround(ground).typeId;
5198 const blendable = typeId != null && !!GROUND_DEFINITIONS[typeId]?.blendable;
5199 const n = natureNoise01(worldX, worldY, scale);
5200 const i = (py * NATURE_NOISE_SIZE + px) * 4;
5201 const v = Math.round(n * 255);
5202 pixels[i] = v;
5203 pixels[i + 1] = v;
5204 pixels[i + 2] = v;
5205 pixels[i + 3] = blendable ? 255 : 0;
5206 }
5207 }
5208 ctx.putImageData(baked.natureImageData, 0, 0);
5209 invalidateCanvasTexture(this.scene, baked.natureCanvas);
5210 this.#queueCanvasTextureWarm(baked.natureCanvas, snapshot.chunkX, snapshot.chunkY);
5211 if (!baked.natureImage)
5212 { baked.natureImage = frameworkImageFromCanvas(baked.natureCanvas); }
5213 baked.natureSourceHash = sourceHash;
5214 baked.natureTintReady = true;
5215 return true;
5216 }
5217
5218 #syncCliffGroundTopSprite (object, darkness, groundImage, localX, localY)
5219 {
5220 if (!object?.renderer)
5221 { return; }
5222 object._lit = true;
5223 const dark = Math.min(1, Math.max(0, darkness ?? 0));
5224 object.renderer.bumpMap = groundImage ?? null;
5225 object.renderer.secondaryMap = null;
5226 const uniforms = this.#ensureUniformBag(object.renderer, getCliffGroundTopShader(), "cliffTop");
5227 uniforms.u_darkness = dark;
5228 this.#writeUniformVec2(uniforms, "u_tileLocal", localX, localY);
5229 }
5230
5231 #layoutBakedChunk (snapshot)
5232 {
5233 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
5234 const baked = this.bakedChunks.get(key);
5235 if (!baked)
5236 { return; }
5237 const size = this.tileSize();
5238 const left = snapshot.chunkX * CHUNK_SIZE * size;
5239 const top = snapshot.chunkY * CHUNK_SIZE * size;
5240 const chunkPx = CHUNK_SIZE * size;
5241 baked.groundObject.transform.position.x = left + chunkPx / 2;
5242 baked.groundObject.transform.position.y = top + chunkPx / 2;
5243 baked.groundObject.transform.size = new vector(chunkPx, chunkPx);
5244 this.#setLayer(baked.groundObject, LAYER_GROUND);
5245
5246 for (let row = 0; row < CHUNK_SIZE; row++)
5247 {
5248 const object = baked.blockObjects[row];
5249 const rowY = top + row * size + size / 2;
5250 object.transform.position.x = left + chunkPx / 2;
5251 object.transform.position.y = rowY;
5252 object.transform.size = new vector(chunkPx, size);
5253 this.#setLayer(object, this.#depthLayer(rowY, SORT_BLOCK));
5254 }
5255
5256 baked.bloomObject.transform.position.x = left + chunkPx / 2;
5257 baked.bloomObject.transform.position.y = top + chunkPx / 2;
5258 baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);
5259 this.#setLayer(baked.bloomObject, this.#depthLayer(top + chunkPx, SORT_BLOCK));
5260 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
5261 }
5262
5263 #destroyBakedChunk (key)
5264 {
5265 const baked = this.bakedChunks.get(key);
5266 if (!baked)
5267 { return; }
5268 this.#releaseBakedAtlasRefs(baked);
5269 baked.groundObject?.destroy();
5270 for (const object of baked.blockObjects ?? [])
5271 { object.destroy(); }
5272 baked.bloomObject?.destroy();
5273 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
5274 invalidateCanvasTexture(this.scene, baked.natureCanvas);
5275 this.bakedChunks.delete(key);
5276 }
5277
5278 #redrawPreview ()
5279 {
5280 if (!this.preview)
5281 { return; }
5282 const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`);
5283 if (snapshot)
5284 { this.#rebuildChunk(snapshot); }
5285 }
5286
5287 #refreshWaterCoastsNear (chunkX, chunkY)
5288 {
5289 const timeSec = performance.now() / 1000;
5290 for (const objects of this.tiles.values())
5291 {
5292 if (!objects.ground)
5293 { continue; }
5294 const fluid = isWaterGround(objects.groundTypeId) || isLavaGround(objects.groundTypeId);
5295 if (!fluid)
5296 { continue; }
5297 if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1)
5298 { continue; }
5299 // Light intensity grid is visible light (1 − shade); fluid shaders use ambient=1.
5300 this.#syncGroundWaterFx(objects, 1, timeSec);
5301 }
5302 }
5303
5304 #drawTile (tileX, tileY)
5305 {
5306 const chunkX = Math.floor(tileX / CHUNK_SIZE);
5307 const chunkY = Math.floor(tileY / CHUNK_SIZE);
5308 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
5309 if (!snapshot)
5310 { return; }
5311 const localX = tileX - chunkX * CHUNK_SIZE;
5312 const localY = tileY - chunkY * CHUNK_SIZE;
5313 const index = localY * CHUNK_SIZE + localX;
5314 const key = `${tileX},${tileY}`;
5315 let objects = this.tiles.get(key);
5316 if (!objects)
5317 {
5318 objects = { chunkX, chunkY, tileX, tileY };
5319 this.tiles.set(key, objects);
5320 }
5321 objects.tileX = tileX;
5322 objects.tileY = tileY;
5323 objects.chunkX = chunkX;
5324 objects.chunkY = chunkY;
5325 objects.light = snapshot.light[index] ?? 0;
5326
5327 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
5328 const animatedGround = (baked?.animatedGrounds ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
5329 if (animatedGround)
5330 {
5331 objects.ground = this.#ensureSprite(objects.ground, animatedGround.sprite, LAYER_GROUND);
5332 if (objects.ground)
5333 {
5334 const size = this.tileSize();
5335 objects.ground.transform.position.x = tileX * size + size / 2;
5336 objects.ground.transform.position.y = tileY * size + size / 2;
5337 objects.ground.transform.size = new vector(size, size);
5338 this.#setLayer(objects.ground, LAYER_GROUND);
5339 objects.groundTypeId = animatedGround.typeId;
5340 this.#syncGroundWaterFx(objects, 1, performance.now() / 1000);
5341 }
5342 if (animatedGround.bloom)
5343 { objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, animatedGround.bloom, tilePivot(tileX, tileY, this.tileSize()), LAYER_GROUND); }
5344 else if (!isLavaGround(animatedGround.typeId))
5345 {
5346 objects.groundBloom?.destroy();
5347 objects.groundBloom = null;
5348 }
5349 }
5350 else
5351 {
5352 objects.ground?.destroy();
5353 objects.ground = null;
5354 objects.groundBloom?.destroy();
5355 objects.groundBloom = null;
5356 this.#clearLavaBloom(objects);
5357 objects.groundTypeId = null;
5358 objects.waterEdges = null;
5359 }
5360
5361 let blockSource = snapshot.blocks[index];
5362 if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY && this.preview.block !== undefined)
5363 { blockSource = this.preview.block; }
5364 // Outer map ring: always show doors at resting (matches baked light; no entities there).
5365 if (
5366 blockSource
5367 && blockDefinition(blockSource.typeId)?.door
5368 && !this.#isActiveLightingChunk(chunkX, chunkY)
5369 )
5370 {
5371 const resting = doorRestingState(blockSource);
5372 if (resting && resting !== blockSource.state)
5373 { blockSource = { ...blockSource, state: resting }; }
5374 }
5375 const tileBlock = tileBlockSpriteEntry(
5376 this.catalog,
5377 this.game.images,
5378 blockSource,
5379 this.worldSeason
5380 );
5381 if (tileBlock)
5382 {
5383 const pivot = tilePivot(tileX, tileY, this.tileSize());
5384 const blockEntry = normalizeBlock(blockSource);
5385 const blockDef = blockDefinition(blockEntry?.typeId);
5386 const blockSort = blockDef?.door
5387 ? doorSortSubOrder(blockEntry?.state, SORT_ENTITY)
5388 : SORT_BLOCK;
5389 objects.block = this.#ensureSprite(objects.block, tileBlock.sprite, blockSort);
5390 objects.blockSort = blockSort;
5391 objects.cliffGroundTop = !!blockDef?.cliffGroundTop;
5392 if (objects.block)
5393 {
5394 this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, blockSort);
5395 if (objects.cliffGroundTop)
5396 {
5397 const localX = ((tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE;
5398 const localY = ((tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE;
5399 this.#syncCliffGroundTopSprite(
5400 objects.block,
5401 objects.shadeAlpha ?? 0,
5402 baked?.groundImage ?? null,
5403 localX,
5404 localY
5405 );
5406 }
5407 else
5408 { this.#syncLitSprite(objects.block, objects.shadeAlpha ?? 0); }
5409 }
5410 objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tileBlock.bloom, pivot, SORT_ENTITY);
5411 }
5412 else
5413 {
5414 objects.block?.destroy();
5415 objects.block = null;
5416 objects.blockSort = null;
5417 objects.blockBloom?.destroy();
5418 objects.blockBloom = null;
5419 objects.cliffGroundTop = false;
5420 }
5421 }
5422
5423 #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK)
5424 {
5425 if (!name)
5426 {
5427 existing?.destroy();
5428 return null;
5429 }
5430 const object = this.#ensureSprite(existing, name, sortOrder);
5431 if (!object)
5432 { return null; }
5433 object.renderer.layer = RENDER_LAYER_BLOOM;
5434 this.#markUnlit(object);
5435 this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder);
5436 return object;
5437 }
5438
5439 #placePivoted (object, pivotX, pivotY, sortY, subOrder, scale = 1, flight = false)
5440 {
5441 const sprite = object?.renderer?.sprite;
5442 if (!sprite)
5443 { return; }
5444 const zoom = this.zoom;
5445 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
5446 const factor = Math.max(0.1, Number(scale) || 1);
5447 const w = draw.w * factor;
5448 const h = draw.h * factor;
5449 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height * factor, zoom);
5450 const layer = this.#depthLayer(sortY, subOrder, flight);
5451 if (
5452 object._placeX === center.x
5453 && object._placeY === center.y
5454 && object._placeW === w
5455 && object._placeH === h
5456 && object.layer === layer
5457 )
5458 { return; }
5459 object._placeX = center.x;
5460 object._placeY = center.y;
5461 object._placeW = w;
5462 object._placeH = h;
5463 object.transform.position.x = center.x;
5464 object.transform.position.y = center.y;
5465 const size = this.#placeSizeScratch;
5466 size.x = w;
5467 size.y = h;
5468 object.transform.size = size;
5469 this.#setLayer(object, layer);
5470 }
5471
5472 #ensureSprite (existing, name, layer)
5473 {
5474 const sprite = this.game.images[name];
5475 if (!sprite)
5476 {
5477 existing?.destroy();
5478 return null;
5479 }
5480 if (!existing || existing.renderer.sprite !== sprite)
5481 {
5482 existing?.destroy();
5483 existing = new GameObject(0, 0, sprite, layer);
5484 this.#syncLitSprite(existing, 0);
5485 this.scene.addObject(existing);
5486 this.#startIdleAnimation(existing);
5487 }
5488 return existing;
5489 }
5490
5491 #startIdleAnimation (object)
5492 {
5493 const sprite = object?.renderer?.sprite;
5494 if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0)
5495 { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); }
5496 }
5497
5498 #neighborClosed (snapshot, dir, dx, dy)
5499 {
5500 const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
5501 if (other)
5502 { return !other.open; }
5503 return !!snapshot.closedEdges?.[dir];
5504 }
5505
5506 #rebuildAllEdges ()
5507 {
5508 const seen = new Set();
5509 for (const snapshot of this.chunks.values())
5510 {
5511 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
5512 seen.add(key);
5513 this.#rebuildChunkEdges(snapshot);
5514 }
5515 for (const key of [...this.edges.keys()])
5516 {
5517 if (!seen.has(key))
5518 { this.#destroyEdges(key); }
5519 }
5520 }
5521
5522 #rebuildChunkEdges (snapshot)
5523 {
5524 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
5525 let bars = this.edges.get(key);
5526 if (!bars)
5527 {
5528 bars = {};
5529 this.edges.set(key, bars);
5530 }
5531
5532 const size = this.tileSize();
5533 const chunkPx = CHUNK_SIZE * size;
5534 const left = snapshot.chunkX * CHUNK_SIZE * size;
5535 const top = snapshot.chunkY * CHUNK_SIZE * size;
5536 const centerX = left + chunkPx / 2;
5537 const centerY = top + chunkPx / 2;
5538 const thickness = Math.max(2, Math.round(2 * this.zoom));
5539 const draw = snapshot.open === true;
5540
5541 bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1),
5542 centerX, top, chunkPx, thickness, true);
5543 bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1),
5544 centerX, top + chunkPx, chunkPx, thickness, true);
5545 bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0),
5546 left, centerY, chunkPx, thickness, false);
5547 bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0),
5548 left + chunkPx, centerY, chunkPx, thickness, false);
5549 }
5550
5551 #edgeBar (existing, visible, x, y, length, thickness, horizontal)
5552 {
5553 if (!visible)
5554 {
5555 if (existing)
5556 { existing.renderer.visible = false; }
5557 return existing;
5558 }
5559
5560 existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE);
5561 this.#markUnlit(existing);
5562 existing.renderer.visible = true;
5563 existing.transform.position.x = x;
5564 existing.transform.position.y = y;
5565 existing.transform.size = horizontal
5566 ? new vector(length, thickness)
5567 : new vector(thickness, length);
5568 this.#setLayer(existing, LAYER_EDGE);
5569 return existing;
5570 }
5571
5572 #destroyEdges (key)
5573 {
5574 const bars = this.edges.get(key);
5575 if (!bars)
5576 { return; }
5577 bars.north?.destroy();
5578 bars.east?.destroy();
5579 bars.south?.destroy();
5580 bars.west?.destroy();
5581 this.edges.delete(key);
5582 }
5583
5584 #entityShadeAlpha (entity, now)
5585 {
5586 const toAlpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;
5587 if (entity.lerpStarted == null || entity.shadeFromTileX == null || entity.shadeFromTileY == null)
5588 { return toAlpha; }
5589 const fromAlpha = this.tiles.get(`${entity.shadeFromTileX},${entity.shadeFromTileY}`)?.shadeAlpha ?? 0;
5590 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs ?? 1));
5591 return fromAlpha + (toAlpha - fromAlpha) * t;
5592 }
5593
5594 /** Layer writes notify the scene; avoid redundant full-sort flags. */
5595 #setLayer (object, layer)
5596 {
5597 if (!object || object.layer === layer)
5598 { return; }
5599 object.layer = layer;
5600 }
5601
5602 #markSortDirty ()
5603 {
5604 if (typeof this.scene?.markSortDirty === "function")
5605 { this.scene.markSortDirty(); }
5606 else
5607 { this.scene._sortDirty = true; }
5608 }
5609
5610 /** Player chunk for dynamic lighting; null in editor / before spawn → no 3×3 limit. */
5611 #activeLightingCenterChunk ()
5612 {
5613 const local = this.entities.get(this.localEntityId);
5614 if (!local)
5615 { return null; }
5616 return {
5617 chunkX: Math.floor(local.tileX / CHUNK_SIZE),
5618 chunkY: Math.floor(local.tileY / CHUNK_SIZE)
5619 };
5620 }
5621
5622 #isActiveLightingChunk (chunkX, chunkY)
5623 {
5624 const center = this.#activeLightingCenterChunk();
5625 if (!center)
5626 { return true; }
5627 return Math.abs(chunkX - center.chunkX) <= 1 && Math.abs(chunkY - center.chunkY) <= 1;
5628 }
5629
5630 #isActiveLightingTile (tileX, tileY)
5631 {
5632 return this.#isActiveLightingChunk(
5633 Math.floor(tileX / CHUNK_SIZE),
5634 Math.floor(tileY / CHUNK_SIZE)
5635 );
5636 }
5637
5638 /** Dynamic light sources that originate inside the player 3×3 (never from the outer ring). */
5639 #innerDynamicLights (activeLights)
5640 {
5641 return activeLights.filter((light) => this.#isActiveLightingTile(light.tileX, light.tileY));
5642 }
5643
5644 /**
5645 * Lights to simulate for one chunk.
5646 * Inner 3×3: mobile lights from the inner region + authored block lights that reach the chunk.
5647 * Outer ring: baked base + spill from any dynamic source that originates inside the 3×3
5648 * (lanterns, spells, and torches) so the boundary stays seamless.
5649 */
5650 #dynamicLightsForChunk (chunkX, chunkY, mobileLights, blockLights = [])
5651 {
5652 const center = this.#activeLightingCenterChunk();
5653 if (!center)
5654 { return [...mobileLights, ...blockLights]; }
5655 if (this.#isActiveLightingChunk(chunkX, chunkY))
5656 {
5657 const inner = this.#innerDynamicLights(mobileLights);
5658 const blocks = blockLights.filter((light) => this.#lightAffectsChunkBounds(light, chunkX, chunkY));
5659 return [...inner, ...blocks];
5660 }
5661 const spill = this.#innerDynamicLights([...mobileLights, ...blockLights]);
5662 return spill.filter((light) => this.#lightAffectsChunkBounds(light, chunkX, chunkY));
5663 }
5664
5665 #dynamicLightsForTile (tileX, tileY, mobileLights, blockLights = [])
5666 {
5667 return this.#dynamicLightsForChunk(
5668 Math.floor(tileX / CHUNK_SIZE),
5669 Math.floor(tileY / CHUNK_SIZE),
5670 mobileLights,
5671 blockLights
5672 );
5673 }
5674
5675 /** Authored torches/furnaces/lava in chunks that can light the active 3×3 (or all chunks in editor). */
5676 #collectBlockLightsForShading ()
5677 {
5678 const center = this.#activeLightingCenterChunk();
5679 const maxRange = maxBlockLightRangeTiles();
5680 const halo = Math.ceil(maxRange / CHUNK_SIZE) + 1;
5681 const sources = [];
5682 const pushChunk = (snapshot) =>
5683 {
5684 if (!snapshot)
5685 { return; }
5686 if (snapshot.blocks)
5687 { sources.push(...collectBlockLightSources(snapshot.chunkX, snapshot.chunkY, snapshot.blocks)); }
5688 if (snapshot.grounds)
5689 { sources.push(...collectGroundLightSources(snapshot.chunkX, snapshot.chunkY, snapshot.grounds)); }
5690 };
5691 if (!center)
5692 {
5693 for (const snapshot of this.chunks.values())
5694 { pushChunk(snapshot); }
5695 return sources;
5696 }
5697 for (let dy = -1 - halo; dy <= 1 + halo; dy++)
5698 {
5699 for (let dx = -1 - halo; dx <= 1 + halo; dx++)
5700 {
5701 pushChunk(this.chunks.get(`${center.chunkX + dx},${center.chunkY + dy}`));
5702 }
5703 }
5704 return sources;
5705 }
5706
5707 /**
5708 * Lights for one chunk, memoized for a single shade pass.
5709 * Halo tiles in {@link #fillChunkLightGrids} often share the same chunk key.
5710 */
5711 #cachedLightsForChunk (chunkX, chunkY, mobileLights, blockLights, cache)
5712 {
5713 const key = `${chunkX},${chunkY}`;
5714 let lights = cache.get(key);
5715 if (!lights)
5716 {
5717 lights = this.#dynamicLightsForChunk(chunkX, chunkY, mobileLights, blockLights);
5718 cache.set(key, lights);
5719 }
5720 return lights;
5721 }
5722
5723 /**
5724 * Shade 0–1 from the chunk intensity grid (1 − lit). Same quantity
5725 * {@link #intensityAtTile} writes during lightmap fills — avoids a second
5726 * per-tile raycast pass after the grids are current.
5727 * @returns {number|null}
5728 */
5729 #shadeAlphaFromLightGrid (tileX, tileY)
5730 {
5731 const chunkX = Math.floor(tileX / CHUNK_SIZE);
5732 const chunkY = Math.floor(tileY / CHUNK_SIZE);
5733 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
5734 const grid = baked?.lightIntensityGrid;
5735 if (!grid?.length)
5736 { return null; }
5737 const localX = tileX - chunkX * CHUNK_SIZE;
5738 const localY = tileY - chunkY * CHUNK_SIZE;
5739 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
5740 { return null; }
5741 const gridW = CHUNK_SIZE + 2;
5742 const lit = grid[(localY + 1) * gridW + (localX + 1)] ?? 0;
5743 return Math.min(1, Math.max(0, 1 - lit));
5744 }
5745
5746 #updateShade ()
5747 {
5748 const ambientDark = this.#ambientDarkness();
5749 const now = performance.now();
5750 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
5751
5752 const mobileLights = [...this.dynamicLights];
5753 for (const light of this.spellLights.values())
5754 {
5755 if (light.until <= now)
5756 { continue; }
5757 mobileLights.push({
5758 tileX: light.tileX,
5759 tileY: light.tileY,
5760 range: light.range,
5761 intensity: light.intensity
5762 });
5763 }
5764 for (const key of [...this.spellLights.keys()])
5765 {
5766 if (this.spellLights.get(key).until <= now)
5767 {
5768 const expired = this.spellLights.get(key);
5769 this.spellLights.delete(key);
5770 this.#invalidateNeighborLightmapCaches(
5771 Math.floor(expired.tileX / CHUNK_SIZE),
5772 Math.floor(expired.tileY / CHUNK_SIZE)
5773 );
5774 }
5775 }
5776 const activeDarks = [];
5777 for (const dark of this.spellDarks.values())
5778 {
5779 if (dark.until <= now)
5780 { continue; }
5781 activeDarks.push({
5782 tileX: dark.tileX,
5783 tileY: dark.tileY,
5784 range: dark.range,
5785 intensity: dark.intensity
5786 });
5787 }
5788 for (const key of [...this.spellDarks.keys()])
5789 {
5790 if (this.spellDarks.get(key).until <= now)
5791 {
5792 const expired = this.spellDarks.get(key);
5793 this.spellDarks.delete(key);
5794 this.#invalidateNeighborLightmapCaches(
5795 Math.floor(expired.tileX / CHUNK_SIZE),
5796 Math.floor(expired.tileY / CHUNK_SIZE)
5797 );
5798 }
5799 }
5800 this._activeSpellDarks = activeDarks;
5801 const tileSize = this.tileSize();
5802 const blindLight = this.#blindVisionLight();
5803 if (blindLight)
5804 { mobileLights.push(blindLight); }
5805 for (const entity of this.entities.values())
5806 {
5807 const range = entity.lightRadiusTiles ?? 0;
5808 if (range <= 0)
5809 { continue; }
5810 mobileLights.push({
5811 tileX: Math.floor(entity.visualX / tileSize),
5812 tileY: Math.floor(entity.visualY / tileSize),
5813 range,
5814 intensity: entity.lightIntensity ?? 1
5815 });
5816 }
5817 const blockLights = this.#collectBlockLightsForShading();
5818 const lightOcclusion = makeSnapshotLightOcclusion(this.chunks);
5819 const lightsByChunk = new Map();
5820
5821 // Lightmaps first so intensity grids are filled (or kept on cache hit).
5822 for (const baked of this.bakedChunks.values())
5823 {
5824 if (baked._inViewport === false)
5825 { continue; }
5826 const lights = this.#cachedLightsForChunk(
5827 baked.chunkX,
5828 baked.chunkY,
5829 mobileLights,
5830 blockLights,
5831 lightsByChunk
5832 );
5833 this.#writeChunkLightmap(
5834 baked,
5835 lights,
5836 mobileLights,
5837 blockLights,
5838 lightOcclusion,
5839 ambientDark,
5840 lightsByChunk
5841 );
5842 // Lightmap stores visible light (1 − shade); shader applies darkness = 1 − lit.
5843 if (baked.groundObject?.renderer?.shaderUniforms)
5844 {
5845 const natureOn = this.#groundNatureImage(baked) != null;
5846 Object.assign(baked.groundObject.renderer.shaderUniforms, {
5847 u_ambientDark: 1,
5848 ...(natureOn ? natureTintUniforms() : { u_useNature: 0 })
5849 });
5850 }
5851 for (const object of baked.blockObjects ?? [])
5852 {
5853 if (object?.renderer?.shaderUniforms)
5854 { object.renderer.shaderUniforms.u_ambientDark = 1; }
5855 }
5856 }
5857
5858 // Per-tile shade from the same grids the lightmap used — no second raycast sweep.
5859 for (const objects of this.tiles.values())
5860 {
5861 if (objects._inViewport === false)
5862 { continue; }
5863 const fromGrid = this.#shadeAlphaFromLightGrid(objects.tileX, objects.tileY);
5864 if (fromGrid != null)
5865 { objects.shadeAlpha = fromGrid; }
5866 else
5867 {
5868 const lights = this.#cachedLightsForChunk(
5869 objects.chunkX,
5870 objects.chunkY,
5871 mobileLights,
5872 blockLights,
5873 lightsByChunk
5874 );
5875 objects.shadeAlpha = this.#tileShadeAlpha(objects, lights, lightOcclusion, ambientDark);
5876 }
5877 }
5878
5879 const timeSec = now / 1000;
5880 for (const objects of this.tiles.values())
5881 {
5882 if (objects._inViewport === false)
5883 { continue; }
5884 if (objects.block)
5885 {
5886 if (objects.cliffGroundTop)
5887 {
5888 const baked = this.bakedChunks.get(`${objects.chunkX},${objects.chunkY}`);
5889 const localX = ((objects.tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE;
5890 const localY = ((objects.tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE;
5891 this.#syncCliffGroundTopSprite(
5892 objects.block,
5893 objects.shadeAlpha,
5894 baked?.groundImage ?? null,
5895 localX,
5896 localY
5897 );
5898 }
5899 else
5900 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
5901 }
5902 if (objects.ground && (isWaterGround(objects.groundTypeId) || isLavaGround(objects.groundTypeId)))
5903 {
5904 const baked = this.bakedChunks.get(`${objects.chunkX},${objects.chunkY}`);
5905 // Light intensity grid is visible light (1 − shade); fluid shaders use ambient=1.
5906 this.#syncGroundWaterFx(objects, 1, timeSec, baked);
5907 }
5908 else if (objects.ground)
5909 {
5910 this.#clearLavaBloom(objects);
5911 this.#syncLitSprite(objects.ground, objects.shadeAlpha);
5912 }
5913 }
5914
5915 for (const item of this.groundItems.values())
5916 {
5917 const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;
5918 this.#syncGroundItemSprite(item, alpha);
5919 }
5920 }
5921
5922 #tileLightSources (objects, activeLights, lightOcclusion)
5923 {
5924 // Inner 3×3: ignore baked (stale behind doors); outer ring keeps authored lightmaps.
5925 const useBaked = !this.#isActiveLightingTile(objects.tileX, objects.tileY);
5926 const baked = useBaked ? lightIntensity(objects.light ?? 0) : 0;
5927 const dynamic = dynamicLightAtTile(
5928 objects.tileX,
5929 objects.tileY,
5930 activeLights,
5931 lightOcclusion
5932 );
5933 const dark = dynamicDarknessAtTile(
5934 objects.tileX,
5935 objects.tileY,
5936 this._activeSpellDarks ?? [],
5937 lightOcclusion
5938 );
5939 return { lights: Math.max(baked, dynamic), dark };
5940 }
5941
5942 /** Shade 0–1: night ambient over unlit tiles, plus Dark spell dimming daylight/torches. */
5943 #tileShadeAlpha (objects, activeLights, lightOcclusion, ambientDark)
5944 {
5945 const { lights, dark } = this.#tileLightSources(objects, activeLights, lightOcclusion);
5946 return Math.min(1, Math.max(0, ambientDark) * (1 - lights) + dark);
5947 }
5948
5949 #tileLightIntensity (objects, activeLights, lightOcclusion, ambientDark = this.#ambientDarkness())
5950 {
5951 return 1 - this.#tileShadeAlpha(objects, activeLights, lightOcclusion, ambientDark);
5952 }
5953
5954 /** Baked + dynamic light intensity (0–1) for any world tile, including across chunks. */
5955 #intensityAtTile (tileX, tileY, activeLights, lightOcclusion, ambientDark = this.#ambientDarkness())
5956 {
5957 const tileObjects = this.tiles.get(`${tileX},${tileY}`);
5958 if (tileObjects)
5959 { return this.#tileLightIntensity(tileObjects, activeLights, lightOcclusion, ambientDark); }
5960 const chunkX = Math.floor(tileX / CHUNK_SIZE);
5961 const chunkY = Math.floor(tileY / CHUNK_SIZE);
5962 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
5963 if (!snapshot)
5964 { return 1 - Math.min(1, Math.max(0, ambientDark)); }
5965 const localX = tileX - chunkX * CHUNK_SIZE;
5966 const localY = tileY - chunkY * CHUNK_SIZE;
5967 const index = localY * CHUNK_SIZE + localX;
5968 const useBaked = !this.#isActiveLightingTile(tileX, tileY);
5969 const bakedLit = useBaked ? lightIntensity(snapshot.light[index] ?? 0) : 0;
5970 const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion);
5971 const dark = dynamicDarknessAtTile(tileX, tileY, this._activeSpellDarks ?? [], lightOcclusion);
5972 const lights = Math.max(bakedLit, dynamic);
5973 const shade = Math.min(1, Math.max(0, ambientDark) * (1 - lights) + dark);
5974 return 1 - shade;
5975 }
5976
5977 /** True when ground or block on this tile occludes light rays (same rules as bake). */
5978 #tileOccludesLight (tileX, tileY)
5979 {
5980 const chunkX = Math.floor(tileX / CHUNK_SIZE);
5981 const chunkY = Math.floor(tileY / CHUNK_SIZE);
5982 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
5983 if (!snapshot)
5984 { return false; }
5985 const localX = tileX - chunkX * CHUNK_SIZE;
5986 const localY = tileY - chunkY * CHUNK_SIZE;
5987 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
5988 { return false; }
5989 const index = localY * CHUNK_SIZE + localX;
5990 const ground = normalizeGround(snapshot.grounds?.[index]);
5991 if (groundLightOcclusion(ground.typeId) === LightOcclusion.solid)
5992 { return true; }
5993 return blockLightOcclusionForBlock(snapshot.blocks?.[index]) === LightOcclusion.solid;
5994 }
5995
5996 #fillChunkLightGrids (baked, mobileLights, blockLights, lightOcclusion, ambientDark, lightsByChunk = null)
5997 {
5998 const gridW = CHUNK_SIZE + 2;
5999 const gridSize = gridW * gridW;
6000 if (!baked.lightIntensityGrid || baked.lightIntensityGrid.length !== gridSize)
6001 { baked.lightIntensityGrid = new Float32Array(gridSize); }
6002 if (!baked.lightOccludeGrid || baked.lightOccludeGrid.length !== gridSize)
6003 { baked.lightOccludeGrid = new Uint8Array(gridSize); }
6004 const grid = baked.lightIntensityGrid;
6005 const occlude = baked.lightOccludeGrid;
6006 const cache = lightsByChunk ?? new Map();
6007 for (let ly = -1; ly <= CHUNK_SIZE; ly++)
6008 {
6009 for (let lx = -1; lx <= CHUNK_SIZE; lx++)
6010 {
6011 const tileX = baked.chunkX * CHUNK_SIZE + lx;
6012 const tileY = baked.chunkY * CHUNK_SIZE + ly;
6013 const gi = (ly + 1) * gridW + (lx + 1);
6014 // Halo tiles may sit in the other lighting region (3×3 vs outer). Resolve
6015 // sources per tile so corner blends match the neighbour chunk's shading.
6016 const lights = this.#cachedLightsForChunk(
6017 Math.floor(tileX / CHUNK_SIZE),
6018 Math.floor(tileY / CHUNK_SIZE),
6019 mobileLights,
6020 blockLights,
6021 cache
6022 );
6023 grid[gi] = this.#intensityAtTile(tileX, tileY, lights, lightOcclusion, ambientDark);
6024 occlude[gi] = this.#tileOccludesLight(tileX, tileY) ? 1 : 0;
6025 }
6026 }
6027 return { grid, occlude, gridW };
6028 }
6029
6030 #makeLightCornerSampler (grid, occlude, gridW)
6031 {
6032 const sample = (lx, ly) => grid[(ly + 1) * gridW + (lx + 1)];
6033 const blocks = (lx, ly) => occlude[(ly + 1) * gridW + (lx + 1)] !== 0;
6034 const smoothCorner = (homeLx, homeLy, aLx, aLy, bLx, bLy, dLx, dLy) => smoothLitCorner({
6035 homeLit: sample(homeLx, homeLy),
6036 homeBlocks: blocks(homeLx, homeLy),
6037 aLit: sample(aLx, aLy),
6038 aBlocks: blocks(aLx, aLy),
6039 bLit: sample(bLx, bLy),
6040 bBlocks: blocks(bLx, bLy),
6041 dLit: sample(dLx, dLy),
6042 dBlocks: blocks(dLx, dLy)
6043 });
6044 return { smoothCorner };
6045 }
6046
6047 /** Corner lit intensities (0–1) for one tile — matches baked atlas lightmap corners. */
6048 #tileLitCorners (baked, localX, localY)
6049 {
6050 const grid = baked?.lightIntensityGrid;
6051 const occlude = baked?.lightOccludeGrid;
6052 if (!grid?.length || !occlude?.length)
6053 { return null; }
6054 const gridW = CHUNK_SIZE + 2;
6055 const { smoothCorner } = this.#makeLightCornerSampler(grid, occlude, gridW);
6056 return {
6057 nw: smoothCorner(
6058 localX, localY,
6059 localX - 1, localY,
6060 localX, localY - 1,
6061 localX - 1, localY - 1
6062 ),
6063 ne: smoothCorner(
6064 localX, localY,
6065 localX + 1, localY,
6066 localX, localY - 1,
6067 localX + 1, localY - 1
6068 ),
6069 sw: smoothCorner(
6070 localX, localY,
6071 localX - 1, localY,
6072 localX, localY + 1,
6073 localX - 1, localY + 1
6074 ),
6075 se: smoothCorner(
6076 localX, localY,
6077 localX + 1, localY,
6078 localX, localY + 1,
6079 localX + 1, localY + 1
6080 )
6081 };
6082 }
6083
6084 #hashUint8Array (values)
6085 {
6086 let hash = 2166136261;
6087 for (let i = 0; i < values.length; i++)
6088 {
6089 hash ^= values[i];
6090 hash = Math.imul(hash, 16777619);
6091 }
6092 return hash >>> 0;
6093 }
6094
6095 #lightAffectsChunkBounds (light, chunkX, chunkY)
6096 {
6097 const minX = chunkX * CHUNK_SIZE - 1;
6098 const minY = chunkY * CHUNK_SIZE - 1;
6099 const maxX = chunkX * CHUNK_SIZE + CHUNK_SIZE;
6100 const maxY = chunkY * CHUNK_SIZE + CHUNK_SIZE;
6101 const closestX = Math.max(minX, Math.min(light.tileX, maxX));
6102 const closestY = Math.max(minY, Math.min(light.tileY, maxY));
6103 return Math.hypot(light.tileX - closestX, light.tileY - closestY) <= light.range;
6104 }
6105
6106 #chunkLightmapCacheKey (baked, activeLights, ambientDark = this.#ambientDarkness())
6107 {
6108 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
6109 if (!snapshot?.light)
6110 { return null; }
6111 const bakedHash = this.#hashUint8Array(snapshot.light);
6112 // Caller already scoped lights for this chunk (incl. 3×3 spill onto the outer ring).
6113 const lights = activeLights;
6114 const darks = this._activeSpellDarks ?? [];
6115 const mode = this.lightingMode === "simple" ? "s" : "f";
6116 const ambientKey = Math.round(Math.max(0, ambientDark) * 1000);
6117 let lightsKey = "";
6118 for (const light of lights)
6119 {
6120 if (!this.#lightAffectsChunkBounds(light, baked.chunkX, baked.chunkY))
6121 { continue; }
6122 lightsKey += `l${light.tileX},${light.tileY},${light.range},${light.intensity ?? 1};`;
6123 }
6124 let darksKey = "";
6125 for (const dark of darks)
6126 {
6127 if (!this.#lightAffectsChunkBounds(dark, baked.chunkX, baked.chunkY))
6128 { continue; }
6129 darksKey += `d${dark.tileX},${dark.tileY},${dark.range},${dark.intensity ?? 1};`;
6130 }
6131 return `a:${mode}:${ambientKey}:${bakedHash}:${lightsKey}|${darksKey}`;
6132 }
6133
6134 #invalidateNeighborLightmapCaches (chunkX, chunkY)
6135 {
6136 // Halo grid is ±1 tile; outer map ring is ±2 chunks from the player.
6137 for (let dy = -2; dy <= 2; dy++)
6138 {
6139 for (let dx = -2; dx <= 2; dx++)
6140 {
6141 const baked = this.bakedChunks.get(`${chunkX + dx},${chunkY + dy}`);
6142 if (baked)
6143 { baked.lightmapCacheKey = null; }
6144 }
6145 }
6146 }
6147
6148 /**
6149 * Per-chunk lightmap for atlas ground/blocks. Open tiles blend into open neighbours;
6150 * occluding tiles stay flat and contribute 0 into others so light does not bleed
6151 * through a wall to the far side. Diagonals only when both cardinals are clear.
6152 * @param chunkLights Sources that affect this chunk (cache key + in-chunk samples).
6153 * @param mobileLights / blockLights Full lists so the ±1 halo can sample across the 3×3 boundary.
6154 * @param lightsByChunk Optional per-pass memo of chunk → light list.
6155 */
6156 #writeChunkLightmap (
6157 baked,
6158 chunkLights,
6159 mobileLights,
6160 blo
6161… afgekapt