BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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