BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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