BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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