BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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