BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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