BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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