BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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