BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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