BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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