BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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