BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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