BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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