BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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