BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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