BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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