BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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