BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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