BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

worldView.js 194.8 KiB Download Raw
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX, ENTITY_STACK_SPREAD_DIAMETER_PX } from "/shared/protocol/constants.js";
2import { dynamicLightAtTile, dynamicDarknessAtTile, lightIntensity } from "/shared/lighting/raycast.js";
3import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js";
4import { bakeChunkOcclusion, tileLightOcclusionAt } from "/shared/lighting/chunkOcclusion.js";
5import { 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, fluidCoastContinues } 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 continues = (x, y) => fluidCoastContinues(
3762 this.#groundTypeAt(x, y),
3763 (typeId) => isLiquidWaterGround(typeId, season)
3764 );
3765 const n = continues(tileX, tileY - 1);
3766 const e = continues(tileX + 1, tileY);
3767 const s = continues(tileX, tileY + 1);
3768 const w = continues(tileX - 1, tileY);
3769 const ne = continues(tileX + 1, tileY - 1);
3770 const nw = continues(tileX - 1, tileY - 1);
3771 const se = continues(tileX + 1, tileY + 1);
3772 const sw = continues(tileX - 1, tileY + 1);
3773 return {
3774 n: n ? 0 : 1,
3775 e: e ? 0 : 1,
3776 s: s ? 0 : 1,
3777 w: w ? 0 : 1,
3778 // Pure diagonal land pockets (e.g. WWW/WLL) — only when cardinals stay water.
3779 ne: (!ne && n && e) ? 1 : 0,
3780 nw: (!nw && n && w) ? 1 : 0,
3781 se: (!se && s && e) ? 1 : 0,
3782 sw: (!sw && s && w) ? 1 : 0
3783 };
3784 }
3785
3786 /**
3787 * Corner deepness = average of liquid-water tiles meeting that corner.
3788 * Bilinear sampling of these corners is continuous across shared edges/corners.
3789 */
3790 #waterDeepCorners (tileX, tileY, selfDeep)
3791 {
3792 const season = this.worldSeason;
3793 const fallback = selfDeep ? 1 : 0;
3794 const depthAt = (x, y) =>
3795 {
3796 const typeId = this.#groundTypeAt(x, y);
3797 if (!isLiquidWaterGround(typeId, season))
3798 { return null; }
3799 return typeId === GroundType.deepWater ? 1 : 0;
3800 };
3801 const corner = (offsets) =>
3802 {
3803 let sum = 0;
3804 let count = 0;
3805 for (const [dx, dy] of offsets)
3806 {
3807 const d = depthAt(tileX + dx, tileY + dy);
3808 if (d == null)
3809 { continue; }
3810 sum += d;
3811 count += 1;
3812 }
3813 return count ? sum / count : fallback;
3814 };
3815 return {
3816 nw: corner([[0, 0], [-1, 0], [0, -1], [-1, -1]]),
3817 ne: corner([[0, 0], [1, 0], [0, -1], [1, -1]]),
3818 sw: corner([[0, 0], [-1, 0], [0, 1], [-1, 1]]),
3819 se: corner([[0, 0], [1, 0], [0, 1], [1, 1]])
3820 };
3821 }
3822
3823 /**
3824 * Neighbor ground sprite for coast retreat peeks.
3825 * Water prefers wet-shore (sand-wet); lava uses dry land only.
3826 */
3827 #fluidCoastShore (tileX, tileY, edges, { preferWet = true } = {})
3828 {
3829 const season = this.worldSeason;
3830 const candidates = [];
3831 if (edges?.n)
3832 { candidates.push({ edge: "n", tileX, tileY: tileY - 1 }); }
3833 if (edges?.e)
3834 { candidates.push({ edge: "e", tileX: tileX + 1, tileY }); }
3835 if (edges?.s)
3836 { candidates.push({ edge: "s", tileX, tileY: tileY + 1 }); }
3837 if (edges?.w)
3838 { candidates.push({ edge: "w", tileX: tileX - 1, tileY }); }
3839 if (edges?.ne)
3840 { candidates.push({ edge: "ne", tileX: tileX + 1, tileY: tileY - 1 }); }
3841 if (edges?.nw)
3842 { candidates.push({ edge: "nw", tileX: tileX - 1, tileY: tileY - 1 }); }
3843 if (edges?.se)
3844 { candidates.push({ edge: "se", tileX: tileX + 1, tileY: tileY + 1 }); }
3845 if (edges?.sw)
3846 { candidates.push({ edge: "sw", tileX: tileX - 1, tileY: tileY + 1 }); }
3847 let pick = null;
3848 for (const candidate of candidates)
3849 {
3850 const ground = this.#groundAtTile(candidate.tileX, candidate.tileY);
3851 if (ground == null)
3852 { continue; }
3853 const entry = normalizeGround(ground);
3854 const def = GROUND_DEFINITIONS[entry.typeId];
3855 if (!def || def.proceduralWaves || !def.blendable)
3856 { continue; }
3857 let spriteName = null;
3858 if (preferWet && def.wetShore)
3859 {
3860 const wetState = `${def.key}-wet`;
3861 const states = this.catalog?.grounds?.[def.key]?.states ?? [];
3862 if (states.includes(wetState))
3863 { spriteName = spriteImageName("ground", def.key, wetState); }
3864 }
3865 if (!spriteName)
3866 {
3867 const states = this.catalog?.grounds?.[def.key]?.states ?? [];
3868 const state = resolveSeasonalVisualState(states, entry.state, season) ?? def.key;
3869 spriteName = spriteImageName("ground", def.key, state);
3870 }
3871 const sprite = spriteName ? this.game.images[spriteName] : null;
3872 if (!sprite)
3873 { continue; }
3874 const ranked = { ...candidate, sprite, wet: !!(preferWet && def.wetShore) };
3875 if (ranked.wet)
3876 {
3877 pick = ranked;
3878 break;
3879 }
3880 if (!pick)
3881 { pick = ranked; }
3882 }
3883 const shore = {
3884 sprite: pick?.sprite ?? null,
3885 edgeN: 0,
3886 edgeE: 0,
3887 edgeS: 0,
3888 edgeW: 0,
3889 edgeNE: 0,
3890 edgeNW: 0,
3891 edgeSE: 0,
3892 edgeSW: 0
3893 };
3894 if (pick?.edge === "n")
3895 { shore.edgeN = 1; }
3896 else if (pick?.edge === "e")
3897 { shore.edgeE = 1; }
3898 else if (pick?.edge === "s")
3899 { shore.edgeS = 1; }
3900 else if (pick?.edge === "w")
3901 { shore.edgeW = 1; }
3902 else if (pick?.edge === "ne")
3903 { shore.edgeNE = 1; }
3904 else if (pick?.edge === "nw")
3905 { shore.edgeNW = 1; }
3906 else if (pick?.edge === "se")
3907 { shore.edgeSE = 1; }
3908 else if (pick?.edge === "sw")
3909 { shore.edgeSW = 1; }
3910 return shore;
3911 }
3912
3913 #waterCoastShore (tileX, tileY, edges)
3914 {
3915 return this.#fluidCoastShore(tileX, tileY, edges, { preferWet: true });
3916 }
3917
3918 #syncWaterGroundSprite (object, {
3919 corners = null,
3920 ambientDark = 0,
3921 edges = null,
3922 shore = null,
3923 timeSec = 0,
3924 fallbackLit = 1,
3925 tileX = 0,
3926 tileY = 0,
3927 deepCorners = null
3928 } = {})
3929 {
3930 if (!object?.renderer)
3931 { return; }
3932 const lit = corners ?? {
3933 nw: fallbackLit,
3934 ne: fallbackLit,
3935 sw: fallbackLit,
3936 se: fallbackLit
3937 };
3938 const dark = Math.min(1, Math.max(0, ambientDark ?? 0));
3939 const shoreSprite = shore?.sprite ?? null;
3940 const shoreUv = shoreSprite?.getUvRect?.(0)
3941 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
3942 const dNW = deepCorners?.nw ?? 0;
3943 const dNE = deepCorners?.ne ?? 0;
3944 const dSW = deepCorners?.sw ?? 0;
3945 const dSE = deepCorners?.se ?? 0;
3946 object._lit = true;
3947 object.renderer.shader = getWaterGroundShader();
3948 // Shallow + deep share one noise atlas so texAmp seams don't hard-cut at depth edges.
3949 const sharedNoise = this.game.images[spriteImageName("ground", "water", "water")];
3950 if (sharedNoise)
3951 { object.renderer.sprite = sharedNoise; }
3952 object.renderer.secondaryMap = shoreSprite?.g_image ?? null;
3953 object.renderer.shaderUniforms = {
3954 u_ambientDark: dark,
3955 u_litNW: lit.nw,
3956 u_litNE: lit.ne,
3957 u_litSW: lit.sw,
3958 u_litSE: lit.se,
3959 u_time: timeSec,
3960 u_tileX: tileX | 0,
3961 u_tileY: tileY | 0,
3962 u_deepNW: dNW,
3963 u_deepNE: dNE,
3964 u_deepSW: dSW,
3965 u_deepSE: dSE,
3966 u_edgeN: edges?.n ?? 0,
3967 u_edgeE: edges?.e ?? 0,
3968 u_edgeS: edges?.s ?? 0,
3969 u_edgeW: edges?.w ?? 0,
3970 u_edgeNE: edges?.ne ?? 0,
3971 u_edgeNW: edges?.nw ?? 0,
3972 u_edgeSE: edges?.se ?? 0,
3973 u_edgeSW: edges?.sw ?? 0,
3974 u_hasShore: shoreSprite ? 1 : 0,
3975 u_shoreEdgeN: shore?.edgeN ?? 0,
3976 u_shoreEdgeE: shore?.edgeE ?? 0,
3977 u_shoreEdgeS: shore?.edgeS ?? 0,
3978 u_shoreEdgeW: shore?.edgeW ?? 0,
3979 u_shoreEdgeNE: shore?.edgeNE ?? 0,
3980 u_shoreEdgeNW: shore?.edgeNW ?? 0,
3981 u_shoreEdgeSE: shore?.edgeSE ?? 0,
3982 u_shoreEdgeSW: shore?.edgeSW ?? 0,
3983 u_shoreUvRect: [shoreUv.u0, shoreUv.v0, shoreUv.u1, shoreUv.v1],
3984 ...waterDebugUniforms()
3985 };
3986 }
3987
3988 /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. Lava is procedural heat. */
3989 #syncGroundWaterFx (objects, ambientDark, timeSec, baked = null)
3990 {
3991 if (!objects?.ground)
3992 { return; }
3993 if (isLavaGround(objects.groundTypeId))
3994 {
3995 objects.waterEdges = null;
3996 this.#syncLavaGroundFx(objects, ambientDark, timeSec, baked);
3997 return;
3998 }
3999 this.#clearLavaBloom(objects);
4000 if (!isLiquidWaterGround(objects.groundTypeId, this.worldSeason))
4001 {
4002 objects.waterEdges = null;
4003 this.#syncLitSprite(objects.ground, objects.shadeAlpha ?? 0);
4004 return;
4005 }
4006 const fallbackLit = 1 - (objects.shadeAlpha ?? 0);
4007 const chunkX = Math.floor(objects.tileX / CHUNK_SIZE);
4008 const chunkY = Math.floor(objects.tileY / CHUNK_SIZE);
4009 const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`);
4010 const localX = objects.tileX - chunkX * CHUNK_SIZE;
4011 const localY = objects.tileY - chunkY * CHUNK_SIZE;
4012 let litCorners = null;
4013 if (chunkBaked)
4014 {
4015 if (this.lightingMode === "simple")
4016 {
4017 const gridW = CHUNK_SIZE + 2;
4018 const intensity = chunkBaked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? fallbackLit;
4019 litCorners = { nw: intensity, ne: intensity, sw: intensity, se: intensity };
4020 }
4021 else
4022 { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); }
4023 }
4024 objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
4025 const shore = this.#waterCoastShore(objects.tileX, objects.tileY, objects.waterEdges);
4026 const deep = objects.groundTypeId === GroundType.deepWater;
4027 this.#syncWaterGroundSprite(objects.ground, {
4028 corners: litCorners,
4029 ambientDark,
4030 edges: objects.waterEdges,
4031 shore,
4032 timeSec,
4033 fallbackLit,
4034 tileX: objects.tileX,
4035 tileY: objects.tileY,
4036 deepCorners: this.#waterDeepCorners(objects.tileX, objects.tileY, deep)
4037 });
4038 }
4039
4040 #lavaCoastEdges (tileX, tileY)
4041 {
4042 const continues = (x, y) => fluidCoastContinues(
4043 this.#groundTypeAt(x, y),
4044 (typeId) => isLavaGround(typeId)
4045 );
4046 const n = continues(tileX, tileY - 1);
4047 const e = continues(tileX + 1, tileY);
4048 const s = continues(tileX, tileY + 1);
4049 const w = continues(tileX - 1, tileY);
4050 const ne = continues(tileX + 1, tileY - 1);
4051 const nw = continues(tileX - 1, tileY - 1);
4052 const se = continues(tileX + 1, tileY + 1);
4053 const sw = continues(tileX - 1, tileY + 1);
4054 return {
4055 n: n ? 0 : 1,
4056 e: e ? 0 : 1,
4057 s: s ? 0 : 1,
4058 w: w ? 0 : 1,
4059 ne: (!ne && n && e) ? 1 : 0,
4060 nw: (!nw && n && w) ? 1 : 0,
4061 se: (!se && s && e) ? 1 : 0,
4062 sw: (!sw && s && w) ? 1 : 0
4063 };
4064 }
4065
4066 #clearLavaBloom (objects)
4067 {
4068 if (!objects)
4069 { return; }
4070 objects.lavaBloom?.destroy();
4071 objects.lavaBloom = null;
4072 }
4073
4074 #ensureLavaBloom (objects)
4075 {
4076 const sprite = objects.ground?.renderer?.sprite;
4077 if (!sprite)
4078 { return null; }
4079 if (!objects.lavaBloom)
4080 {
4081 const bloom = new GameObject(0, 0, sprite, LAYER_GROUND);
4082 bloom.renderer.layer = RENDER_LAYER_BLOOM;
4083 this.#markUnlit(bloom);
4084 this.scene.addObject(bloom);
4085 objects.lavaBloom = bloom;
4086 }
4087 else if (objects.lavaBloom.renderer)
4088 { objects.lavaBloom.renderer.sprite = sprite; }
4089 const size = this.tileSize();
4090 objects.lavaBloom.transform.position.x = objects.tileX * size + size / 2;
4091 objects.lavaBloom.transform.position.y = objects.tileY * size + size / 2;
4092 objects.lavaBloom.transform.size = new vector(size, size);
4093 this.#setLayer(objects.lavaBloom, LAYER_GROUND);
4094 return objects.lavaBloom;
4095 }
4096
4097 #syncLavaGroundFx (objects, ambientDark, timeSec, baked = null)
4098 {
4099 const fallbackLit = 1 - (objects.shadeAlpha ?? 0);
4100 const chunkX = Math.floor(objects.tileX / CHUNK_SIZE);
4101 const chunkY = Math.floor(objects.tileY / CHUNK_SIZE);
4102 const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`);
4103 const localX = objects.tileX - chunkX * CHUNK_SIZE;
4104 const localY = objects.tileY - chunkY * CHUNK_SIZE;
4105 let litCorners = null;
4106 if (chunkBaked)
4107 {
4108 if (this.lightingMode === "simple")
4109 {
4110 const gridW = CHUNK_SIZE + 2;
4111 const intensity = chunkBaked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? fallbackLit;
4112 litCorners = { nw: intensity, ne: intensity, sw: intensity, se: intensity };
4113 }
4114 else
4115 { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); }
4116 }
4117 const edges = this.#lavaCoastEdges(objects.tileX, objects.tileY);
4118 const shore = this.#fluidCoastShore(objects.tileX, objects.tileY, edges, { preferWet: false });
4119 this.#syncLavaGroundSprite(objects.ground, {
4120 corners: litCorners,
4121 ambientDark,
4122 edges,
4123 shore,
4124 timeSec,
4125 fallbackLit,
4126 tileX: objects.tileX,
4127 tileY: objects.tileY
4128 });
4129 const bloom = this.#ensureLavaBloom(objects);
4130 if (bloom)
4131 {
4132 this.#syncLavaBloomSprite(bloom, {
4133 edges,
4134 timeSec,
4135 tileX: objects.tileX,
4136 tileY: objects.tileY
4137 });
4138 }
4139 }
4140
4141 #syncLavaGroundSprite (object, {
4142 corners = null,
4143 ambientDark = 0,
4144 edges = null,
4145 shore = null,
4146 timeSec = 0,
4147 fallbackLit = 1,
4148 tileX = 0,
4149 tileY = 0
4150 } = {})
4151 {
4152 if (!object?.renderer)
4153 { return; }
4154 const lit = corners ?? {
4155 nw: fallbackLit,
4156 ne: fallbackLit,
4157 sw: fallbackLit,
4158 se: fallbackLit
4159 };
4160 const dark = Math.min(1, Math.max(0, ambientDark ?? 0));
4161 const shoreSprite = shore?.sprite ?? null;
4162 const shoreUv = shoreSprite?.getUvRect?.(0)
4163 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
4164 object._lit = true;
4165 object.renderer.shader = getLavaGroundShader();
4166 object.renderer.secondaryMap = shoreSprite?.g_image ?? null;
4167 object.renderer.shaderUniforms = {
4168 u_ambientDark: dark,
4169 u_litNW: lit.nw,
4170 u_litNE: lit.ne,
4171 u_litSW: lit.sw,
4172 u_litSE: lit.se,
4173 u_time: timeSec,
4174 u_tileX: tileX | 0,
4175 u_tileY: tileY | 0,
4176 u_edgeN: edges?.n ?? 0,
4177 u_edgeE: edges?.e ?? 0,
4178 u_edgeS: edges?.s ?? 0,
4179 u_edgeW: edges?.w ?? 0,
4180 u_edgeNE: edges?.ne ?? 0,
4181 u_edgeNW: edges?.nw ?? 0,
4182 u_edgeSE: edges?.se ?? 0,
4183 u_edgeSW: edges?.sw ?? 0,
4184 u_hasShore: shoreSprite ? 1 : 0,
4185 u_shoreEdgeN: shore?.edgeN ?? 0,
4186 u_shoreEdgeE: shore?.edgeE ?? 0,
4187 u_shoreEdgeS: shore?.edgeS ?? 0,
4188 u_shoreEdgeW: shore?.edgeW ?? 0,
4189 u_shoreEdgeNE: shore?.edgeNE ?? 0,
4190 u_shoreEdgeNW: shore?.edgeNW ?? 0,
4191 u_shoreEdgeSE: shore?.edgeSE ?? 0,
4192 u_shoreEdgeSW: shore?.edgeSW ?? 0,
4193 u_shoreUvRect: [shoreUv.u0, shoreUv.v0, shoreUv.u1, shoreUv.v1],
4194 ...lavaDebugUniforms()
4195 };
4196 }
4197
4198 #syncLavaBloomSprite (object, {
4199 edges = null,
4200 timeSec = 0,
4201 tileX = 0,
4202 tileY = 0
4203 } = {})
4204 {
4205 if (!object?.renderer)
4206 { return; }
4207 object.renderer.shader = getLavaBloomShader();
4208 object.renderer.shaderUniforms = {
4209 u_time: timeSec,
4210 u_tileX: tileX | 0,
4211 u_tileY: tileY | 0,
4212 u_edgeN: edges?.n ?? 0,
4213 u_edgeE: edges?.e ?? 0,
4214 u_edgeS: edges?.s ?? 0,
4215 u_edgeW: edges?.w ?? 0,
4216 u_edgeNE: edges?.ne ?? 0,
4217 u_edgeNW: edges?.nw ?? 0,
4218 u_edgeSE: edges?.se ?? 0,
4219 u_edgeSW: edges?.sw ?? 0,
4220 ...lavaDebugUniforms()
4221 };
4222 }
4223
4224 #ambientDarkness ()
4225 {
4226 const hour = this.nightPreview ?? this.worldHour;
4227 const calendar = nightFactor(hour, this.settings.nightDarkness);
4228 let dark = resolveDimensionDarknessFactor(this.dimensionLightingMode, calendar);
4229 if (dark == null)
4230 { dark = calendar; }
4231 if (this.localBlind)
4232 { dark = Math.min(1, dark + 0.85); }
4233 return dark;
4234 }
4235
4236 setLocalBlind (blind)
4237 {
4238 this.localBlind = !!blind;
4239 }
4240
4241 /** Soft vision bubble while blinded (client-only; stacks with ambient). */
4242 #blindVisionLight ()
4243 {
4244 if (!this.localBlind)
4245 { return null; }
4246 const local = this.entities.get(this.localEntityId);
4247 if (!local)
4248 { return null; }
4249 const tileSize = this.tileSize();
4250 return {
4251 tileX: Math.floor(local.visualX / tileSize),
4252 tileY: Math.floor(local.visualY / tileSize),
4253 range: 2.25,
4254 intensity: 1
4255 };
4256 }
4257
4258 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY, dualTint = null)
4259 {
4260 const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;
4261 const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0;
4262 const dark = (fromAlpha + toAlpha) / 2;
4263 if (dualTint)
4264 {
4265 this.#syncDualTintLitSprite(object, dark, dualTint);
4266 return;
4267 }
4268 this.#syncLitSprite(object, dark);
4269 }
4270
4271 #dualTintFromPayload (payload)
4272 {
4273 if (!payload?.shaftTint || !payload?.tipTint)
4274 { return null; }
4275 return {
4276 shaft: payload.shaftTint,
4277 tip: payload.tipTint,
4278 ...(payload.coatTint ? { coat: payload.coatTint } : {})
4279 };
4280 }
4281
4282 #syncHpBar (entity)
4283 {
4284 const current = entity.health;
4285 const max = entity.maxHealth;
4286 const show = current != null
4287 && max != null
4288 && max > 0
4289 && current < max;
4290 if (!show)
4291 {
4292 entity.hpBar?.destroy();
4293 entity.hpBar = null;
4294 entity.hpBarCanvas = null;
4295 return;
4296 }
4297 if (!entity.hpBarCanvas)
4298 {
4299 entity.hpBarCanvas = document.createElement("canvas");
4300 entity.hpBarCanvas.width = HP_BAR_W;
4301 entity.hpBarCanvas.height = HP_BAR_H;
4302 const image = frameworkImageFromCanvas(entity.hpBarCanvas);
4303 entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR);
4304 this.#markUnlit(entity.hpBar);
4305 this.scene.addObject(entity.hpBar);
4306 }
4307 drawHpBar(entity.hpBarCanvas, current, max);
4308 invalidateCanvasTexture(this.scene, entity.hpBarCanvas);
4309 }
4310
4311 #placeHpBar (entity, pivotX, pivotY)
4312 {
4313 if (!entity.hpBar)
4314 { return; }
4315 const sprite = entity.object?.renderer?.sprite;
4316 if (!sprite)
4317 { return; }
4318 const zoom = this.zoom;
4319 const drawH = sprite.height * zoom;
4320 const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom);
4321 const spriteTop = centerY - drawH / 2;
4322 const barW = HP_BAR_W * zoom;
4323 const barH = HP_BAR_H * zoom;
4324 entity.hpBar.transform.position.x = pivotX;
4325 entity.hpBar.transform.position.y = spriteTop - barH / 2;
4326 entity.hpBar.transform.size = new vector(barW, barH);
4327 this.#setLayer(entity.hpBar, this.#depthLayer(pivotY, SORT_HP_BAR));
4328 }
4329
4330 #syncSkullMarker (entity)
4331 {
4332 if (!entity?.characterId)
4333 {
4334 entity.skullMarker?.destroy();
4335 entity.skullMarker = null;
4336 return;
4337 }
4338 const tint = skullTintColor(entity.skullValue | 0, this.settings);
4339 if (!tint)
4340 {
4341 entity.skullMarker?.destroy();
4342 entity.skullMarker = null;
4343 return;
4344 }
4345 const image = this.game.images[SKULL_SPRITE]
4346 ?? this.game.images["item:skull:skull"];
4347 if (!image)
4348 { return; }
4349 if (!entity.skullMarker)
4350 {
4351 entity.skullMarker = new GameObject(0, 0, image, SORT_HP_BAR);
4352 this.scene.addObject(entity.skullMarker);
4353 }
4354 entity.skullTint = tint;
4355 entity.skullMarker.renderer.sprite = image;
4356 }
4357
4358 /**
4359 * Bottom edge of the skull sprite sits exactly on the character sprite's top edge.
4360 */
4361 #placeSkullMarker (entity, pivotX, pivotY, darkness)
4362 {
4363 this.#syncSkullMarker(entity);
4364 if (!entity.skullMarker)
4365 { return; }
4366 const body = entity.object?.renderer?.sprite;
4367 const skull = entity.skullMarker.renderer?.sprite;
4368 if (!body || !skull)
4369 { return; }
4370 const zoom = this.zoom;
4371 const scale = entity.visualScale ?? 1;
4372 const bodyH = body.height * zoom * scale;
4373 const skullH = skull.height * zoom;
4374 const skullW = skull.width * zoom;
4375 const bodyCenterY = pivotY - (bodyH / 2 - PIVOT_FROM_BOTTOM_PX * zoom * scale);
4376 const bodyTop = bodyCenterY - bodyH / 2;
4377 // GameObject position is sprite center; bottom of skull at bodyTop ⇒ center at bodyTop - skullH/2
4378 entity.skullMarker.transform.position.x = pivotX;
4379 entity.skullMarker.transform.position.y = bodyTop - skullH / 2;
4380 entity.skullMarker.transform.size = new vector(skullW, skullH);
4381 this.#setLayer(entity.skullMarker, this.#depthLayer(pivotY, SORT_HP_BAR));
4382 this.#syncLitSprite(entity.skullMarker, darkness, 0, false, entity.skullTint);
4383 }
4384
4385 #rebuildChunk (snapshot, { refreshSoftNeighbors = true } = {})
4386 {
4387 this.#bakeAndPlaceChunk(snapshot);
4388 this.#relayoutChunkTiles(snapshot);
4389 // Soft terrain and wet-sand shorelines both sample cross-chunk neighbors.
4390 if (refreshSoftNeighbors && this.#needsSoftTerrainNeighborRefresh())
4391 { this.#rebuildSoftTerrainNeighborChunks(snapshot); }
4392 }
4393
4394 /** Soft blend / wet-sand atlas borders need a rebake when an adjacent chunk arrives. */
4395 #needsSoftTerrainNeighborRefresh ()
4396 {
4397 if (this.softTerrain)
4398 { return true; }
4399 return Math.max(0, Number(this.settings?.wetSandBand) || 0) > 0;
4400 }
4401
4402 #relayoutChunk (snapshot)
4403 {
4404 this.#layoutBakedChunk(snapshot);
4405 this.#relayoutChunkTiles(snapshot);
4406 }
4407
4408 #relayoutChunkTiles (snapshot)
4409 {
4410 for (let localY = 0; localY < CHUNK_SIZE; localY++)
4411 {
4412 for (let localX = 0; localX < CHUNK_SIZE; localX++)
4413 {
4414 const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
4415 const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
4416 this.#drawTile(tileX, tileY);
4417 }
4418 }
4419 }
4420
4421 #scheduleChunkRebuild (snapshot)
4422 {
4423 if (!snapshot)
4424 { return; }
4425 this.#chunkRebuildKeys.add(`${snapshot.chunkX},${snapshot.chunkY}`);
4426 this.#cancelIdlePrefetch();
4427 this.#ensureChunkFlushScheduled();
4428 }
4429
4430 #scheduleEdgeRebuild ()
4431 {
4432 this.#edgesDirty = true;
4433 this.#cancelIdlePrefetch();
4434 this.#ensureChunkFlushScheduled();
4435 }
4436
4437 #ensureChunkFlushScheduled ()
4438 {
4439 if (this.#chunkRebuildRaf)
4440 { return; }
4441 this.#cancelIdlePrefetch();
4442 this.#chunkRebuildRaf = requestAnimationFrame(() => this.#flushChunkWork());
4443 }
4444
4445 #notePlayerTile (tileX, tileY)
4446 {
4447 const chunkX = Math.floor(tileX / CHUNK_SIZE);
4448 const chunkY = Math.floor(tileY / CHUNK_SIZE);
4449 const prevX = this.#playerChunkX;
4450 const prevY = this.#playerChunkY;
4451 if (prevX != null
4452 && (chunkX !== prevX || chunkY !== prevY))
4453 {
4454 const dx = chunkX - prevX;
4455 const dy = chunkY - prevY;
4456 if (dx !== 0)
4457 { this.#playerMoveChunkDx = Math.sign(dx); }
4458 if (dy !== 0)
4459 { this.#playerMoveChunkDy = Math.sign(dy); }
4460 this.#onActiveLightingCenterChanged(prevX, prevY, chunkX, chunkY);
4461 }
4462 this.#playerChunkX = chunkX;
4463 this.#playerChunkY = chunkY;
4464 }
4465
4466 /** When the 3×3 lighting center moves: refresh door sprites (resting vs live) and lightmaps. */
4467 #onActiveLightingCenterChanged (prevChunkX, prevChunkY, chunkX, chunkY)
4468 {
4469 this.#invalidateNeighborLightmapCaches(prevChunkX, prevChunkY);
4470 this.#invalidateNeighborLightmapCaches(chunkX, chunkY);
4471 const doorChunks = new Set();
4472 for (const [cx, cy] of [[prevChunkX, prevChunkY], [chunkX, chunkY]])
4473 {
4474 for (let dy = -1; dy <= 1; dy++)
4475 {
4476 for (let dx = -1; dx <= 1; dx++)
4477 { doorChunks.add(`${cx + dx},${cy + dy}`); }
4478 }
4479 }
4480 for (const key of doorChunks)
4481 {
4482 const [cx, cy] = key.split(",").map(Number);
4483 this.#redrawDoorTilesInChunk(cx, cy);
4484 }
4485 }
4486
4487 #redrawDoorTilesInChunk (chunkX, chunkY)
4488 {
4489 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
4490 if (!snapshot?.blocks)
4491 { return; }
4492 for (let localY = 0; localY < CHUNK_SIZE; localY++)
4493 {
4494 for (let localX = 0; localX < CHUNK_SIZE; localX++)
4495 {
4496 const block = snapshot.blocks[localY * CHUNK_SIZE + localX];
4497 if (!blockDefinition(block?.typeId)?.door)
4498 { continue; }
4499 this.#drawTile(chunkX * CHUNK_SIZE + localX, chunkY * CHUNK_SIZE + localY);
4500 }
4501 }
4502 }
4503
4504 #playerChunkCoords ()
4505 {
4506 const local = this.entities.get(this.localEntityId);
4507 if (local)
4508 {
4509 return {
4510 chunkX: Math.floor(local.tileX / CHUNK_SIZE),
4511 chunkY: Math.floor(local.tileY / CHUNK_SIZE)
4512 };
4513 }
4514 if (this.#playerChunkX != null && this.#playerChunkY != null)
4515 {
4516 return { chunkX: this.#playerChunkX, chunkY: this.#playerChunkY };
4517 }
4518 return null;
4519 }
4520
4521 /** Lower score = bake sooner in urgent mode; idle mode inverts distance. */
4522 #chunkRebuildScore (key, mode = "urgent")
4523 {
4524 const [chunkX, chunkY] = key.split(",").map(Number);
4525 const player = this.#playerChunkCoords();
4526 if (!player)
4527 { return 0; }
4528 const dx = chunkX - player.chunkX;
4529 const dy = chunkY - player.chunkY;
4530 const dist = Math.abs(dx) + Math.abs(dy);
4531 let ahead = 0;
4532 if (this.#playerMoveChunkDx !== 0 || this.#playerMoveChunkDy !== 0)
4533 { ahead = dx * this.#playerMoveChunkDx + dy * this.#playerMoveChunkDy; }
4534 if (mode === "idle")
4535 {
4536 return -dist * 10 + (ahead > 0 ? -ahead * 2 : Math.max(ahead, 0));
4537 }
4538 return dist * 10 - Math.max(0, ahead) * 3;
4539 }
4540
4541 #sortedChunkRebuildKeys (mode = "urgent")
4542 {
4543 return [...this.#chunkRebuildKeys].sort((a, b) =>
4544 this.#chunkRebuildScore(a, mode) - this.#chunkRebuildScore(b, mode));
4545 }
4546
4547 #discoverUnbakedChunks ()
4548 {
4549 for (const key of this.chunks.keys())
4550 {
4551 if (!this.bakedChunks.has(key))
4552 { this.#chunkRebuildKeys.add(key); }
4553 }
4554 }
4555
4556 #hasUnbakedChunks ()
4557 {
4558 for (const key of this.chunks.keys())
4559 {
4560 if (!this.bakedChunks.has(key))
4561 { return true; }
4562 }
4563 return false;
4564 }
4565
4566 #pickIdlePrefetchSnapshot ()
4567 {
4568 let best = null;
4569 let bestScore = Infinity;
4570 for (const snapshot of this.chunks.values())
4571 {
4572 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
4573 if (this.bakedChunks.has(key) || this.#chunkRebuildKeys.has(key))
4574 { continue; }
4575 const score = this.#chunkRebuildScore(key, "idle");
4576 if (score < bestScore)
4577 {
4578 bestScore = score;
4579 best = snapshot;
4580 }
4581 }
4582 return best;
4583 }
4584
4585 #cancelIdlePrefetch ()
4586 {
4587 if (this.#idlePrefetchId && typeof cancelIdleCallback === "function")
4588 { cancelIdleCallback(this.#idlePrefetchId); }
4589 this.#idlePrefetchId = 0;
4590 }
4591
4592 #scheduleIdleChunkPrefetch ()
4593 {
4594 if (this.#idlePrefetchId || this.#chunkRebuildRaf || this.#chunkRebuildKeys.size)
4595 { return; }
4596 if (typeof requestIdleCallback !== "function")
4597 { return; }
4598 if (!this.#hasUnbakedChunks())
4599 { return; }
4600 this.#idlePrefetchId = requestIdleCallback(
4601 (deadline) => this.#runIdleChunkPrefetch(deadline),
4602 { timeout: 2500 }
4603 );
4604 }
4605
4606 #runIdleChunkPrefetch (deadline)
4607 {
4608 this.#idlePrefetchId = 0;
4609 if (this.#chunkRebuildRaf || this.#chunkRebuildKeys.size)
4610 { return; }
4611 this.#discoverUnbakedChunks();
4612 if (this.#chunkRebuildKeys.size)
4613 {
4614 this.#ensureChunkFlushScheduled();
4615 return;
4616 }
4617 const snapshot = this.#pickIdlePrefetchSnapshot();
4618 if (!snapshot)
4619 { return; }
4620 if (deadline.timeRemaining() <= 4 && !deadline.didTimeout)
4621 {
4622 this.#scheduleIdleChunkPrefetch();
4623 return;
4624 }
4625 this.#rebuildChunk(snapshot, { refreshSoftNeighbors: true });
4626 if (this.#hasUnbakedChunks())
4627 { this.#scheduleIdleChunkPrefetch(); }
4628 }
4629
4630 #flushChunkWork ()
4631 {
4632 this.#chunkRebuildRaf = 0;
4633 const keys = this.#sortedChunkRebuildKeys("urgent");
4634 const batch = keys.slice(0, this.#CHUNK_REBUILD_BATCH);
4635 const rest = keys.slice(this.#CHUNK_REBUILD_BATCH);
4636 this.#chunkRebuildKeys.clear();
4637 for (const key of rest)
4638 { this.#chunkRebuildKeys.add(key); }
4639 for (const key of batch)
4640 {
4641 const snap = this.chunks.get(key);
4642 if (snap)
4643 { this.#rebuildChunk(snap, { refreshSoftNeighbors: true }); }
4644 }
4645 if (this.#chunkRebuildKeys.size)
4646 {
4647 this.#ensureChunkFlushScheduled();
4648 return;
4649 }
4650 if (this.#edgesDirty)
4651 {
4652 this.#rebuildAllEdges();
4653 this.#edgesDirty = false;
4654 }
4655 this.#scheduleIdleChunkPrefetch();
4656 }
4657
4658 #previewEqual (a, b)
4659 {
4660 if (a === b)
4661 { return true; }
4662 if (!a || !b)
4663 { return false; }
4664 return a.tileX === b.tileX
4665 && a.tileY === b.tileY
4666 && this.#previewPart(a.ground) === this.#previewPart(b.ground)
4667 && this.#previewPart(a.block) === this.#previewPart(b.block);
4668 }
4669
4670 #previewPart (value)
4671 {
4672 return value === undefined ? undefined : JSON.stringify(value);
4673 }
4674
4675 #rebuildSoftTerrainNeighborChunks (snapshot)
4676 {
4677 for (let dy = -1; dy <= 1; dy++)
4678 {
4679 for (let dx = -1; dx <= 1; dx++)
4680 {
4681 if (dx === 0 && dy === 0)
4682 { continue; }
4683 const neighbor = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
4684 if (neighbor)
4685 { this.#rebuildChunk(neighbor, { refreshSoftNeighbors: false }); }
4686 }
4687 }
4688 }
4689
4690 #rebakeAllChunks ()
4691 {
4692 for (const snapshot of this.chunks.values())
4693 { this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false }); }
4694 }
4695
4696 #bakeAndPlaceChunk (snapshot)
4697 {
4698 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
4699 const atlases = bakeChunkAtlases({
4700 snapshot,
4701 catalog: this.catalog,
4702 images: this.game.images,
4703 preview: this.preview,
4704 season: this.worldSeason,
4705 softTerrain: this.softTerrain,
4706 wetSandBandFraction: Math.max(0, Math.min(1, Number(this.settings?.wetSandBand) || 0)),
4707 resolveGround: (tileX, tileY) => this.#groundAtTile(tileX, tileY),
4708 cache: this.#atlasCache
4709 });
4710 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
4711 let baked = this.bakedChunks.get(key);
4712 this.#releaseBakedAtlasRefs(baked);
4713
4714 const groundImage = this.#atlasCache.getImage(atlases.cacheRefs?.ground);
4715 const blockImages = atlases.cacheRefs?.blockRows.map((entry) => this.#atlasCache.getImage(entry))
4716 ?? atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas));
4717 const bloomImage = this.#atlasCache.getImage(atlases.cacheRefs?.bloom)
4718 ?? frameworkImageFromCanvas(atlases.bloom);
4719
4720 if (!baked)
4721 {
4722 const lightmapCanvas = makeLightmapCanvas(atlasPx);
4723 const natureCanvas = makeNatureNoiseCanvas();
4724 baked = {
4725 groundCanvas: atlases.ground,
4726 blockCanvases: atlases.blockRows,
4727 bloomCanvas: atlases.bloom,
4728 lightmapCanvas,
4729 natureCanvas,
4730 groundImage,
4731 blockImages,
4732 bloomImage,
4733 lightmapImage: frameworkImageFromCanvas(lightmapCanvas),
4734 natureImage: frameworkImageFromCanvas(natureCanvas),
4735 groundObject: null,
4736 blockObjects: [],
4737 bloomObject: null,
4738 tallBlocks: atlases.tallBlocks,
4739 animatedGrounds: atlases.animatedGrounds,
4740 lightmapPixels: null,
4741 atlasCacheRefs: atlases.cacheRefs,
4742 chunkX: snapshot.chunkX,
4743 chunkY: snapshot.chunkY
4744 };
4745 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
4746 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1, baked.natureImage);
4747 this.scene.addObject(baked.groundObject);
4748 for (let row = 0; row < CHUNK_SIZE; row++)
4749 {
4750 const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
4751 this.#applyAtlasLighting(object, baked.lightmapImage, row, null);
4752 this.scene.addObject(object);
4753 baked.blockObjects.push(object);
4754 }
4755 baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK);
4756 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
4757 this.#markUnlit(baked.bloomObject);
4758 this.scene.addObject(baked.bloomObject);
4759 this.bakedChunks.set(key, baked);
4760 }
4761 else
4762 {
4763 baked.chunkX = snapshot.chunkX;
4764 baked.chunkY = snapshot.chunkY;
4765 if (!baked.natureCanvas)
4766 {
4767 baked.natureCanvas = makeNatureNoiseCanvas();
4768 baked.natureImage = frameworkImageFromCanvas(baked.natureCanvas);
4769 }
4770 if (baked.groundCanvas !== atlases.ground)
4771 {
4772 baked.groundCanvas = atlases.ground;
4773 baked.groundImage = groundImage;
4774 baked.groundObject.renderer.sprite = groundImage;
4775 }
4776 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1, baked.natureImage);
4777 for (let row = 0; row < CHUNK_SIZE; row++)
4778 {
4779 if (baked.blockCanvases[row] !== atlases.blockRows[row])
4780 {
4781 baked.blockCanvases[row] = atlases.blockRows[row];
4782 baked.blockImages[row] = blockImages[row];
4783 baked.blockObjects[row].renderer.sprite = blockImages[row];
4784 }
4785 this.#applyAtlasLighting(
4786 baked.blockObjects[row],
4787 baked.lightmapImage,
4788 row,
4789 null
4790 );
4791 }
4792 if (baked.bloomCanvas !== atlases.bloom)
4793 {
4794 baked.bloomCanvas = atlases.bloom;
4795 baked.bloomImage = bloomImage;
4796 baked.bloomObject.renderer.sprite = bloomImage;
4797 }
4798 baked.tallBlocks = atlases.tallBlocks;
4799 baked.animatedGrounds = atlases.animatedGrounds;
4800 baked.atlasCacheRefs = atlases.cacheRefs;
4801 }
4802 baked.chunkX = snapshot.chunkX;
4803 baked.chunkY = snapshot.chunkY;
4804 this.#refreshNatureNoiseAround(snapshot.chunkX, snapshot.chunkY);
4805 baked.lightmapCacheKey = null;
4806 this.#invalidateNeighborLightmapCaches(snapshot.chunkX, snapshot.chunkY);
4807 this.#layoutBakedChunk(snapshot);
4808 this.#queueBakedChunkTextures(baked, snapshot.chunkX, snapshot.chunkY);
4809 }
4810
4811 #releaseBakedAtlasRefs (baked)
4812 {
4813 if (!baked?.atlasCacheRefs)
4814 { return; }
4815 this.#atlasCache.release(baked.atlasCacheRefs.ground);
4816 for (const entry of baked.atlasCacheRefs.blockRows ?? [])
4817 { this.#atlasCache.release(entry); }
4818 this.#atlasCache.release(baked.atlasCacheRefs.bloom);
4819 baked.atlasCacheRefs = null;
4820 }
4821
4822 #chunkTextureWarmPriority (chunkX, chunkY)
4823 {
4824 const local = this.entities.get(this.localEntityId);
4825 if (!local)
4826 { return 999; }
4827 const playerChunkX = Math.floor(local.tileX / CHUNK_SIZE);
4828 const playerChunkY = Math.floor(local.tileY / CHUNK_SIZE);
4829 return Math.abs(chunkX - playerChunkX) + Math.abs(chunkY - playerChunkY);
4830 }
4831
4832 #queueCanvasTextureWarm (canvas, chunkX, chunkY)
4833 {
4834 if (!canvas || this.#pendingTextureCanvasSet.has(canvas))
4835 { return; }
4836 this.#pendingTextureCanvasSet.add(canvas);
4837 this.#pendingTextureCanvases.push({
4838 canvas,
4839 priority: this.#chunkTextureWarmPriority(chunkX, chunkY)
4840 });
4841 this.#scheduleTextureWarm();
4842 }
4843
4844 #queueBakedChunkTextures (baked, chunkX, chunkY)
4845 {
4846 if (!baked)
4847 { return; }
4848 const refs = baked.atlasCacheRefs;
4849 const maybeWarm = (canvas, entry) =>
4850 {
4851 if (!canvas)
4852 { return; }
4853 if (entry && this.#atlasCache.isWarmed(canvas))
4854 { return; }
4855 this.#queueCanvasTextureWarm(canvas, chunkX, chunkY);
4856 };
4857 maybeWarm(baked.groundCanvas, refs?.ground);
4858 for (let row = 0; row < (baked.blockCanvases ?? []).length; row++)
4859 { maybeWarm(baked.blockCanvases[row], refs?.blockRows?.[row]); }
4860 maybeWarm(baked.bloomCanvas, refs?.bloom);
4861 this.#queueCanvasTextureWarm(baked.lightmapCanvas, chunkX, chunkY);
4862 this.#queueCanvasTextureWarm(baked.natureCanvas, chunkX, chunkY);
4863 }
4864
4865 #scheduleTextureWarm ()
4866 {
4867 if (this.#textureWarmRaf)
4868 { return; }
4869 this.#textureWarmRaf = requestAnimationFrame(() => this.#flushTextureWarm());
4870 }
4871
4872 #flushTextureWarm ()
4873 {
4874 this.#textureWarmRaf = 0;
4875 if (!this.#pendingTextureCanvases.length)
4876 { return; }
4877 this.#pendingTextureCanvases.sort((a, b) => a.priority - b.priority);
4878 const batch = this.#pendingTextureCanvases.splice(0, this.#TEXTURE_WARM_BATCH);
4879 for (const entry of batch)
4880 {
4881 this.#pendingTextureCanvasSet.delete(entry.canvas);
4882 setNearestFilter(this.scene, entry.canvas);
4883 this.#atlasCache.markWarmed(entry.canvas);
4884 }
4885 if (this.#pendingTextureCanvases.length)
4886 { this.#scheduleTextureWarm(); }
4887 }
4888
4889 #applyAtlasLighting (object, lightmapImage, lightRow, natureImage = null)
4890 {
4891 if (!object?.renderer)
4892 { return; }
4893 object._lit = true;
4894 object.renderer.shader = getAtlasLightingShader();
4895 const useNature = natureImage != null && lightRow < 0;
4896 object.renderer.bumpMap = useNature ? natureImage : null;
4897 object.renderer.secondaryMap = lightmapImage;
4898 object.renderer.shaderUniforms = {
4899 u_ambientDark: 0,
4900 u_lightRow: lightRow,
4901 u_useNature: useNature ? 1 : 0,
4902 u_natureTint: 0,
4903 u_natureDark: 0,
4904 u_natureContrast: 1,
4905 ...(useNature ? natureTintUniforms() : {})
4906 };
4907 }
4908
4909 /** Rebuild nature noise for a chunk and neighbors (halo needs adjacent grounds). */
4910 #refreshNatureNoiseAround (chunkX, chunkY)
4911 {
4912 for (let dy = -1; dy <= 1; dy++)
4913 {
4914 for (let dx = -1; dx <= 1; dx++)
4915 {
4916 const cx = chunkX + dx;
4917 const cy = chunkY + dy;
4918 const baked = this.bakedChunks.get(`${cx},${cy}`);
4919 const snapshot = this.chunks.get(`${cx},${cy}`);
4920 if (!baked?.natureCanvas || !snapshot)
4921 { continue; }
4922 this.#fillNatureNoise(baked, snapshot);
4923 if (baked.groundObject)
4924 { this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1, baked.natureImage); }
4925 }
4926 }
4927 }
4928
4929 #fillNatureNoise (baked, snapshot)
4930 {
4931 if (!baked?.natureCanvas || !snapshot)
4932 { return; }
4933 const canvas = baked.natureCanvas;
4934 if (canvas.width !== NATURE_NOISE_SIZE || canvas.height !== NATURE_NOISE_SIZE)
4935 {
4936 canvas.width = NATURE_NOISE_SIZE;
4937 canvas.height = NATURE_NOISE_SIZE;
4938 }
4939 const scale = NATURE_TINT.scale;
4940 const ctx = canvas.getContext("2d");
4941 const image = ctx.createImageData(NATURE_NOISE_SIZE, NATURE_NOISE_SIZE);
4942 const baseX = snapshot.chunkX * CHUNK_SIZE;
4943 const baseY = snapshot.chunkY * CHUNK_SIZE;
4944 const pad = NATURE_NOISE_PAD;
4945 for (let py = 0; py < NATURE_NOISE_SIZE; py++)
4946 {
4947 for (let px = 0; px < NATURE_NOISE_SIZE; px++)
4948 {
4949 const lx = px - pad;
4950 const ly = py - pad;
4951 const worldX = baseX + lx;
4952 const worldY = baseY + ly;
4953 const ground = this.#groundAtTile(worldX, worldY);
4954 const typeId = ground == null ? null : normalizeGround(ground).typeId;
4955 const blendable = typeId != null && !!GROUND_DEFINITIONS[typeId]?.blendable;
4956 const n = natureNoise01(worldX, worldY, scale);
4957 const i = (py * NATURE_NOISE_SIZE + px) * 4;
4958 const v = Math.round(n * 255);
4959 image.data[i] = v;
4960 image.data[i + 1] = v;
4961 image.data[i + 2] = v;
4962 image.data[i + 3] = blendable ? 255 : 0;
4963 }
4964 }
4965 ctx.putImageData(image, 0, 0);
4966 invalidateCanvasTexture(this.scene, baked.natureCanvas);
4967 this.#queueCanvasTextureWarm(baked.natureCanvas, snapshot.chunkX, snapshot.chunkY);
4968 if (!baked.natureImage)
4969 { baked.natureImage = frameworkImageFromCanvas(baked.natureCanvas); }
4970 }
4971
4972 #syncCliffGroundTopSprite (object, darkness, groundImage, localX, localY)
4973 {
4974 if (!object?.renderer)
4975 { return; }
4976 object._lit = true;
4977 const dark = Math.min(1, Math.max(0, darkness ?? 0));
4978 object.renderer.shader = getCliffGroundTopShader();
4979 object.renderer.bumpMap = groundImage ?? null;
4980 object.renderer.secondaryMap = null;
4981 object.renderer.shaderUniforms = {
4982 u_darkness: dark,
4983 u_tileLocal: [localX, localY]
4984 };
4985 }
4986
4987 #layoutBakedChunk (snapshot)
4988 {
4989 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
4990 const baked = this.bakedChunks.get(key);
4991 if (!baked)
4992 { return; }
4993 const size = this.tileSize();
4994 const left = snapshot.chunkX * CHUNK_SIZE * size;
4995 const top = snapshot.chunkY * CHUNK_SIZE * size;
4996 const chunkPx = CHUNK_SIZE * size;
4997 baked.groundObject.transform.position.x = left + chunkPx / 2;
4998 baked.groundObject.transform.position.y = top + chunkPx / 2;
4999 baked.groundObject.transform.size = new vector(chunkPx, chunkPx);
5000 this.#setLayer(baked.groundObject, LAYER_GROUND);
5001
5002 for (let row = 0; row < CHUNK_SIZE; row++)
5003 {
5004 const object = baked.blockObjects[row];
5005 const rowY = top + row * size + size / 2;
5006 object.transform.position.x = left + chunkPx / 2;
5007 object.transform.position.y = rowY;
5008 object.transform.size = new vector(chunkPx, size);
5009 this.#setLayer(object, this.#depthLayer(rowY, SORT_BLOCK));
5010 }
5011
5012 baked.bloomObject.transform.position.x = left + chunkPx / 2;
5013 baked.bloomObject.transform.position.y = top + chunkPx / 2;
5014 baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);
5015 this.#setLayer(baked.bloomObject, this.#depthLayer(top + chunkPx, SORT_BLOCK));
5016 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
5017 }
5018
5019 #destroyBakedChunk (key)
5020 {
5021 const baked = this.bakedChunks.get(key);
5022 if (!baked)
5023 { return; }
5024 this.#releaseBakedAtlasRefs(baked);
5025 baked.groundObject?.destroy();
5026 for (const object of baked.blockObjects ?? [])
5027 { object.destroy(); }
5028 baked.bloomObject?.destroy();
5029 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
5030 invalidateCanvasTexture(this.scene, baked.natureCanvas);
5031 this.bakedChunks.delete(key);
5032 }
5033
5034 #redrawPreview ()
5035 {
5036 if (!this.preview)
5037 { return; }
5038 const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`);
5039 if (snapshot)
5040 { this.#rebuildChunk(snapshot); }
5041 }
5042
5043 #refreshWaterCoastsNear (chunkX, chunkY)
5044 {
5045 const timeSec = performance.now() / 1000;
5046 for (const objects of this.tiles.values())
5047 {
5048 if (!objects.ground)
5049 { continue; }
5050 const fluid = isWaterGround(objects.groundTypeId) || isLavaGround(objects.groundTypeId);
5051 if (!fluid)
5052 { continue; }
5053 if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1)
5054 { continue; }
5055 // Light intensity grid is visible light (1 − shade); fluid shaders use ambient=1.
5056 this.#syncGroundWaterFx(objects, 1, timeSec);
5057 }
5058 }
5059
5060 #drawTile (tileX, tileY)
5061 {
5062 const chunkX = Math.floor(tileX / CHUNK_SIZE);
5063 const chunkY = Math.floor(tileY / CHUNK_SIZE);
5064 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
5065 if (!snapshot)
5066 { return; }
5067 const localX = tileX - chunkX * CHUNK_SIZE;
5068 const localY = tileY - chunkY * CHUNK_SIZE;
5069 const index = localY * CHUNK_SIZE + localX;
5070 const key = `${tileX},${tileY}`;
5071 let objects = this.tiles.get(key);
5072 if (!objects)
5073 {
5074 objects = { chunkX, chunkY, tileX, tileY };
5075 this.tiles.set(key, objects);
5076 }
5077 objects.tileX = tileX;
5078 objects.tileY = tileY;
5079 objects.chunkX = chunkX;
5080 objects.chunkY = chunkY;
5081 objects.light = snapshot.light[index] ?? 0;
5082
5083 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
5084 const animatedGround = (baked?.animatedGrounds ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
5085 if (animatedGround)
5086 {
5087 objects.ground = this.#ensureSprite(objects.ground, animatedGround.sprite, LAYER_GROUND);
5088 if (objects.ground)
5089 {
5090 const size = this.tileSize();
5091 objects.ground.transform.position.x = tileX * size + size / 2;
5092 objects.ground.transform.position.y = tileY * size + size / 2;
5093 objects.ground.transform.size = new vector(size, size);
5094 this.#setLayer(objects.ground, LAYER_GROUND);
5095 objects.groundTypeId = animatedGround.typeId;
5096 this.#syncGroundWaterFx(objects, 1, performance.now() / 1000);
5097 }
5098 if (animatedGround.bloom)
5099 { objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, animatedGround.bloom, tilePivot(tileX, tileY, this.tileSize()), LAYER_GROUND); }
5100 else if (!isLavaGround(animatedGround.typeId))
5101 {
5102 objects.groundBloom?.destroy();
5103 objects.groundBloom = null;
5104 }
5105 }
5106 else
5107 {
5108 objects.ground?.destroy();
5109 objects.ground = null;
5110 objects.groundBloom?.destroy();
5111 objects.groundBloom = null;
5112 this.#clearLavaBloom(objects);
5113 objects.groundTypeId = null;
5114 objects.waterEdges = null;
5115 }
5116
5117 let blockSource = snapshot.blocks[index];
5118 if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY && this.preview.block !== undefined)
5119 { blockSource = this.preview.block; }
5120 // Outer map ring: always show doors at resting (matches baked light; no entities there).
5121 if (
5122 blockSource
5123 && blockDefinition(blockSource.typeId)?.door
5124 && !this.#isActiveLightingChunk(chunkX, chunkY)
5125 )
5126 {
5127 const resting = doorRestingState(blockSource);
5128 if (resting && resting !== blockSource.state)
5129 { blockSource = { ...blockSource, state: resting }; }
5130 }
5131 const tileBlock = tileBlockSpriteEntry(
5132 this.catalog,
5133 this.game.images,
5134 blockSource,
5135 this.worldSeason
5136 );
5137 if (tileBlock)
5138 {
5139 const pivot = tilePivot(tileX, tileY, this.tileSize());
5140 const blockEntry = normalizeBlock(blockSource);
5141 const blockDef = blockDefinition(blockEntry?.typeId);
5142 const blockSort = blockDef?.door
5143 ? doorSortSubOrder(blockEntry?.state, SORT_ENTITY)
5144 : SORT_ENTITY;
5145 objects.block = this.#ensureSprite(objects.block, tileBlock.sprite, blockSort);
5146 objects.blockSort = blockSort;
5147 objects.cliffGroundTop = !!blockDef?.cliffGroundTop;
5148 if (objects.block)
5149 {
5150 this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, blockSort);
5151 if (objects.cliffGroundTop)
5152 {
5153 const localX = ((tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE;
5154 const localY = ((tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE;
5155 this.#syncCliffGroundTopSprite(
5156 objects.block,
5157 objects.shadeAlpha ?? 0,
5158 baked?.groundImage ?? null,
5159 localX,
5160 localY
5161 );
5162 }
5163 else
5164 { this.#syncLitSprite(objects.block, objects.shadeAlpha ?? 0); }
5165 }
5166 objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tileBlock.bloom, pivot, SORT_ENTITY);
5167 }
5168 else
5169 {
5170 objects.block?.destroy();
5171 objects.block = null;
5172 objects.blockSort = null;
5173 objects.blockBloom?.destroy();
5174 objects.blockBloom = null;
5175 objects.cliffGroundTop = false;
5176 }
5177 }
5178
5179 #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK)
5180 {
5181 if (!name)
5182 {
5183 existing?.destroy();
5184 return null;
5185 }
5186 const object = this.#ensureSprite(existing, name, sortOrder);
5187 if (!object)
5188 { return null; }
5189 object.renderer.layer = RENDER_LAYER_BLOOM;
5190 this.#markUnlit(object);
5191 this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder);
5192 return object;
5193 }
5194
5195 #placePivoted (object, pivotX, pivotY, sortY, subOrder, scale = 1, flight = false)
5196 {
5197 const sprite = object?.renderer?.sprite;
5198 if (!sprite)
5199 { return; }
5200 const zoom = this.zoom;
5201 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
5202 const factor = Math.max(0.1, Number(scale) || 1);
5203 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height * factor, zoom);
5204 object.transform.position.x = center.x;
5205 object.transform.position.y = center.y;
5206 object.transform.size = new vector(draw.w * factor, draw.h * factor);
5207 this.#setLayer(object, this.#depthLayer(sortY, subOrder, flight));
5208 }
5209
5210 #ensureSprite (existing, name, layer)
5211 {
5212 const sprite = this.game.images[name];
5213 if (!sprite)
5214 {
5215 existing?.destroy();
5216 return null;
5217 }
5218 if (!existing || existing.renderer.sprite !== sprite)
5219 {
5220 existing?.destroy();
5221 existing = new GameObject(0, 0, sprite, layer);
5222 this.#syncLitSprite(existing, 0);
5223 this.scene.addObject(existing);
5224 this.#startIdleAnimation(existing);
5225 }
5226 return existing;
5227 }
5228
5229 #startIdleAnimation (object)
5230 {
5231 const sprite = object?.renderer?.sprite;
5232 if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0)
5233 { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); }
5234 }
5235
5236 #neighborClosed (snapshot, dir, dx, dy)
5237 {
5238 const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
5239 if (other)
5240 { return !other.open; }
5241 return !!snapshot.closedEdges?.[dir];
5242 }
5243
5244 #rebuildAllEdges ()
5245 {
5246 const seen = new Set();
5247 for (const snapshot of this.chunks.values())
5248 {
5249 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
5250 seen.add(key);
5251 this.#rebuildChunkEdges(snapshot);
5252 }
5253 for (const key of [...this.edges.keys()])
5254 {
5255 if (!seen.has(key))
5256 { this.#destroyEdges(key); }
5257 }
5258 }
5259
5260 #rebuildChunkEdges (snapshot)
5261 {
5262 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
5263 let bars = this.edges.get(key);
5264 if (!bars)
5265 {
5266 bars = {};
5267 this.edges.set(key, bars);
5268 }
5269
5270 const size = this.tileSize();
5271 const chunkPx = CHUNK_SIZE * size;
5272 const left = snapshot.chunkX * CHUNK_SIZE * size;
5273 const top = snapshot.chunkY * CHUNK_SIZE * size;
5274 const centerX = left + chunkPx / 2;
5275 const centerY = top + chunkPx / 2;
5276 const thickness = Math.max(2, Math.round(2 * this.zoom));
5277 const draw = snapshot.open === true;
5278
5279 bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1),
5280 centerX, top, chunkPx, thickness, true);
5281 bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1),
5282 centerX, top + chunkPx, chunkPx, thickness, true);
5283 bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0),
5284 left, centerY, chunkPx, thickness, false);
5285 bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0),
5286 left + chunkPx, centerY, chunkPx, thickness, false);
5287 }
5288
5289 #edgeBar (existing, visible, x, y, length, thickness, horizontal)
5290 {
5291 if (!visible)
5292 {
5293 if (existing)
5294 { existing.renderer.visible = false; }
5295 return existing;
5296 }
5297
5298 existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE);
5299 this.#markUnlit(existing);
5300 existing.renderer.visible = true;
5301 existing.transform.position.x = x;
5302 existing.transform.position.y = y;
5303 existing.transform.size = horizontal
5304 ? new vector(length, thickness)
5305 : new vector(thickness, length);
5306 this.#setLayer(existing, LAYER_EDGE);
5307 return existing;
5308 }
5309
5310 #destroyEdges (key)
5311 {
5312 const bars = this.edges.get(key);
5313 if (!bars)
5314 { return; }
5315 bars.north?.destroy();
5316 bars.east?.destroy();
5317 bars.south?.destroy();
5318 bars.west?.destroy();
5319 this.edges.delete(key);
5320 }
5321
5322 #entityShadeAlpha (entity, now)
5323 {
5324 const toAlpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;
5325 if (entity.lerpStarted == null || entity.shadeFromTileX == null || entity.shadeFromTileY == null)
5326 { return toAlpha; }
5327 const fromAlpha = this.tiles.get(`${entity.shadeFromTileX},${entity.shadeFromTileY}`)?.shadeAlpha ?? 0;
5328 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs ?? 1));
5329 return fromAlpha + (toAlpha - fromAlpha) * t;
5330 }
5331
5332 /** A layer write costs the scene a full re-sort, so only write real changes. */
5333 #setLayer (object, layer)
5334 {
5335 if (!object || object.layer === layer)
5336 { return; }
5337 object.layer = layer;
5338 this.#markSortDirty();
5339 }
5340
5341 #markSortDirty ()
5342 {
5343 this.scene._sortDirty = true;
5344 }
5345
5346 /** Player chunk for dynamic lighting; null in editor / before spawn → no 3×3 limit. */
5347 #activeLightingCenterChunk ()
5348 {
5349 const local = this.entities.get(this.localEntityId);
5350 if (!local)
5351 { return null; }
5352 return {
5353 chunkX: Math.floor(local.tileX / CHUNK_SIZE),
5354 chunkY: Math.floor(local.tileY / CHUNK_SIZE)
5355 };
5356 }
5357
5358 #isActiveLightingChunk (chunkX, chunkY)
5359 {
5360 const center = this.#activeLightingCenterChunk();
5361 if (!center)
5362 { return true; }
5363 return Math.abs(chunkX - center.chunkX) <= 1 && Math.abs(chunkY - center.chunkY) <= 1;
5364 }
5365
5366 #isActiveLightingTile (tileX, tileY)
5367 {
5368 return this.#isActiveLightingChunk(
5369 Math.floor(tileX / CHUNK_SIZE),
5370 Math.floor(tileY / CHUNK_SIZE)
5371 );
5372 }
5373
5374 /** Dynamic light sources that originate inside the player 3×3 (never from the outer ring). */
5375 #innerDynamicLights (activeLights)
5376 {
5377 return activeLights.filter((light) => this.#isActiveLightingTile(light.tileX, light.tileY));
5378 }
5379
5380 /**
5381 * Lights to simulate for one chunk.
5382 * Inner 3×3: mobile lights from the inner region + authored block lights that reach the chunk.
5383 * Outer ring: baked base + spill from any dynamic source that originates inside the 3×3
5384 * (lanterns, spells, and torches) so the boundary stays seamless.
5385 */
5386 #dynamicLightsForChunk (chunkX, chunkY, mobileLights, blockLights = [])
5387 {
5388 const center = this.#activeLightingCenterChunk();
5389 if (!center)
5390 { return [...mobileLights, ...blockLights]; }
5391 if (this.#isActiveLightingChunk(chunkX, chunkY))
5392 {
5393 const inner = this.#innerDynamicLights(mobileLights);
5394 const blocks = blockLights.filter((light) => this.#lightAffectsChunkBounds(light, chunkX, chunkY));
5395 return [...inner, ...blocks];
5396 }
5397 const spill = this.#innerDynamicLights([...mobileLights, ...blockLights]);
5398 return spill.filter((light) => this.#lightAffectsChunkBounds(light, chunkX, chunkY));
5399 }
5400
5401 #dynamicLightsForTile (tileX, tileY, mobileLights, blockLights = [])
5402 {
5403 return this.#dynamicLightsForChunk(
5404 Math.floor(tileX / CHUNK_SIZE),
5405 Math.floor(tileY / CHUNK_SIZE),
5406 mobileLights,
5407 blockLights
5408 );
5409 }
5410
5411 /** Authored torches/furnaces/lava in chunks that can light the active 3×3 (or all chunks in editor). */
5412 #collectBlockLightsForShading ()
5413 {
5414 const center = this.#activeLightingCenterChunk();
5415 const maxRange = maxBlockLightRangeTiles();
5416 const halo = Math.ceil(maxRange / CHUNK_SIZE) + 1;
5417 const sources = [];
5418 const pushChunk = (snapshot) =>
5419 {
5420 if (!snapshot)
5421 { return; }
5422 if (snapshot.blocks)
5423 { sources.push(...collectBlockLightSources(snapshot.chunkX, snapshot.chunkY, snapshot.blocks)); }
5424 if (snapshot.grounds)
5425 { sources.push(...collectGroundLightSources(snapshot.chunkX, snapshot.chunkY, snapshot.grounds)); }
5426 };
5427 if (!center)
5428 {
5429 for (const snapshot of this.chunks.values())
5430 { pushChunk(snapshot); }
5431 return sources;
5432 }
5433 for (let dy = -1 - halo; dy <= 1 + halo; dy++)
5434 {
5435 for (let dx = -1 - halo; dx <= 1 + halo; dx++)
5436 {
5437 pushChunk(this.chunks.get(`${center.chunkX + dx},${center.chunkY + dy}`));
5438 }
5439 }
5440 return sources;
5441 }
5442
5443 #updateShade ()
5444 {
5445 const ambientDark = this.#ambientDarkness();
5446 const now = performance.now();
5447 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
5448
5449 const mobileLights = [...this.dynamicLights];
5450 for (const light of this.spellLights.values())
5451 {
5452 if (light.until <= now)
5453 { continue; }
5454 mobileLights.push({
5455 tileX: light.tileX,
5456 tileY: light.tileY,
5457 range: light.range,
5458 intensity: light.intensity
5459 });
5460 }
5461 for (const key of [...this.spellLights.keys()])
5462 {
5463 if (this.spellLights.get(key).until <= now)
5464 {
5465 const expired = this.spellLights.get(key);
5466 this.spellLights.delete(key);
5467 this.#invalidateNeighborLightmapCaches(
5468 Math.floor(expired.tileX / CHUNK_SIZE),
5469 Math.floor(expired.tileY / CHUNK_SIZE)
5470 );
5471 }
5472 }
5473 const activeDarks = [];
5474 for (const dark of this.spellDarks.values())
5475 {
5476 if (dark.until <= now)
5477 { continue; }
5478 activeDarks.push({
5479 tileX: dark.tileX,
5480 tileY: dark.tileY,
5481 range: dark.range,
5482 intensity: dark.intensity
5483 });
5484 }
5485 for (const key of [...this.spellDarks.keys()])
5486 {
5487 if (this.spellDarks.get(key).until <= now)
5488 {
5489 const expired = this.spellDarks.get(key);
5490 this.spellDarks.delete(key);
5491 this.#invalidateNeighborLightmapCaches(
5492 Math.floor(expired.tileX / CHUNK_SIZE),
5493 Math.floor(expired.tileY / CHUNK_SIZE)
5494 );
5495 }
5496 }
5497 this._activeSpellDarks = activeDarks;
5498 const tileSize = this.tileSize();
5499 const blindLight = this.#blindVisionLight();
5500 if (blindLight)
5501 { mobileLights.push(blindLight); }
5502 for (const entity of this.entities.values())
5503 {
5504 const range = entity.lightRadiusTiles ?? 0;
5505 if (range <= 0)
5506 { continue; }
5507 mobileLights.push({
5508 tileX: Math.floor(entity.visualX / tileSize),
5509 tileY: Math.floor(entity.visualY / tileSize),
5510 range,
5511 intensity: entity.lightIntensity ?? 1
5512 });
5513 }
5514 const blockLights = this.#collectBlockLightsForShading();
5515
5516 const lightOcclusion = makeSnapshotLightOcclusion(this.chunks);
5517
5518 for (const objects of this.tiles.values())
5519 {
5520 if (objects._inViewport === false)
5521 { continue; }
5522 const lights = this.#dynamicLightsForTile(objects.tileX, objects.tileY, mobileLights, blockLights);
5523 objects.shadeAlpha = this.#tileShadeAlpha(objects, lights, lightOcclusion, ambientDark);
5524 }
5525
5526 for (const baked of this.bakedChunks.values())
5527 {
5528 if (baked._inViewport === false)
5529 { continue; }
5530 const lights = this.#dynamicLightsForChunk(baked.chunkX, baked.chunkY, mobileLights, blockLights);
5531 this.#writeChunkLightmap(baked, lights, mobileLights, blockLights, lightOcclusion, ambientDark);
5532 // Lightmap stores visible light (1 − shade); shader applies darkness = 1 − lit.
5533 if (baked.groundObject?.renderer?.shaderUniforms)
5534 {
5535 Object.assign(baked.groundObject.renderer.shaderUniforms, {
5536 u_ambientDark: 1,
5537 ...natureTintUniforms()
5538 });
5539 }
5540 for (const object of baked.blockObjects ?? [])
5541 {
5542 if (object?.renderer?.shaderUniforms)
5543 { object.renderer.shaderUniforms.u_ambientDark = 1; }
5544 }
5545 }
5546
5547 const timeSec = now / 1000;
5548 for (const objects of this.tiles.values())
5549 {
5550 if (objects._inViewport === false)
5551 { continue; }
5552 if (objects.block)
5553 {
5554 if (objects.cliffGroundTop)
5555 {
5556 const baked = this.bakedChunks.get(`${objects.chunkX},${objects.chunkY}`);
5557 const localX = ((objects.tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE;
5558 const localY = ((objects.tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE;
5559 this.#syncCliffGroundTopSprite(
5560 objects.block,
5561 objects.shadeAlpha,
5562 baked?.groundImage ?? null,
5563 localX,
5564 localY
5565 );
5566 }
5567 else
5568 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
5569 }
5570 if (objects.ground && (isWaterGround(objects.groundTypeId) || isLavaGround(objects.groundTypeId)))
5571 {
5572 const baked = this.bakedChunks.get(`${objects.chunkX},${objects.chunkY}`);
5573 // Light intensity grid is visible light (1 − shade); fluid shaders use ambient=1.
5574 this.#syncGroundWaterFx(objects, 1, timeSec, baked);
5575 }
5576 else if (objects.ground)
5577 {
5578 this.#clearLavaBloom(objects);
5579 this.#syncLitSprite(objects.ground, objects.shadeAlpha);
5580 }
5581 }
5582
5583 for (const item of this.groundItems.values())
5584 {
5585 const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;
5586 this.#syncGroundItemSprite(item, alpha);
5587 }
5588 }
5589
5590 #tileLightSources (objects, activeLights, lightOcclusion)
5591 {
5592 // Inner 3×3: ignore baked (stale behind doors); outer ring keeps authored lightmaps.
5593 const useBaked = !this.#isActiveLightingTile(objects.tileX, objects.tileY);
5594 const baked = useBaked ? lightIntensity(objects.light ?? 0) : 0;
5595 const dynamic = dynamicLightAtTile(
5596 objects.tileX,
5597 objects.tileY,
5598 activeLights,
5599 lightOcclusion
5600 );
5601 const dark = dynamicDarknessAtTile(
5602 objects.tileX,
5603 objects.tileY,
5604 this._activeSpellDarks ?? [],
5605 lightOcclusion
5606 );
5607 return { lights: Math.max(baked, dynamic), dark };
5608 }
5609
5610 /** Shade 0–1: night ambient over unlit tiles, plus Dark spell dimming daylight/torches. */
5611 #tileShadeAlpha (objects, activeLights, lightOcclusion, ambientDark)
5612 {
5613 const { lights, dark } = this.#tileLightSources(objects, activeLights, lightOcclusion);
5614 return Math.min(1, Math.max(0, ambientDark) * (1 - lights) + dark);
5615 }
5616
5617 #tileLightIntensity (objects, activeLights, lightOcclusion, ambientDark = this.#ambientDarkness())
5618 {
5619 return 1 - this.#tileShadeAlpha(objects, activeLights, lightOcclusion, ambientDark);
5620 }
5621
5622 /** Baked + dynamic light intensity (0–1) for any world tile, including across chunks. */
5623 #intensityAtTile (tileX, tileY, activeLights, lightOcclusion, ambientDark = this.#ambientDarkness())
5624 {
5625 const tileObjects = this.tiles.get(`${tileX},${tileY}`);
5626 if (tileObjects)
5627 { return this.#tileLightIntensity(tileObjects, activeLights, lightOcclusion, ambientDark); }
5628 const chunkX = Math.floor(tileX / CHUNK_SIZE);
5629 const chunkY = Math.floor(tileY / CHUNK_SIZE);
5630 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
5631 if (!snapshot)
5632 { return 1 - Math.min(1, Math.max(0, ambientDark)); }
5633 const localX = tileX - chunkX * CHUNK_SIZE;
5634 const localY = tileY - chunkY * CHUNK_SIZE;
5635 const index = localY * CHUNK_SIZE + localX;
5636 const useBaked = !this.#isActiveLightingTile(tileX, tileY);
5637 const bakedLit = useBaked ? lightIntensity(snapshot.light[index] ?? 0) : 0;
5638 const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion);
5639 const dark = dynamicDarknessAtTile(tileX, tileY, this._activeSpellDarks ?? [], lightOcclusion);
5640 const lights = Math.max(bakedLit, dynamic);
5641 const shade = Math.min(1, Math.max(0, ambientDark) * (1 - lights) + dark);
5642 return 1 - shade;
5643 }
5644
5645 /** True when ground or block on this tile occludes light rays (same rules as bake). */
5646 #tileOccludesLight (tileX, tileY)
5647 {
5648 const chunkX = Math.floor(tileX / CHUNK_SIZE);
5649 const chunkY = Math.floor(tileY / CHUNK_SIZE);
5650 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
5651 if (!snapshot)
5652 { return false; }
5653 const localX = tileX - chunkX * CHUNK_SIZE;
5654 const localY = tileY - chunkY * CHUNK_SIZE;
5655 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
5656 { return false; }
5657 const index = localY * CHUNK_SIZE + localX;
5658 const ground = normalizeGround(snapshot.grounds?.[index]);
5659 if (groundLightOcclusion(ground.typeId) === LightOcclusion.solid)
5660 { return true; }
5661 return blockLightOcclusionForBlock(snapshot.blocks?.[index]) === LightOcclusion.solid;
5662 }
5663
5664 #fillChunkLightGrids (baked, mobileLights, blockLights, lightOcclusion, ambientDark)
5665 {
5666 const gridW = CHUNK_SIZE + 2;
5667 const gridSize = gridW * gridW;
5668 if (!baked.lightIntensityGrid || baked.lightIntensityGrid.length !== gridSize)
5669 { baked.lightIntensityGrid = new Float32Array(gridSize); }
5670 if (!baked.lightOccludeGrid || baked.lightOccludeGrid.length !== gridSize)
5671 { baked.lightOccludeGrid = new Uint8Array(gridSize); }
5672 const grid = baked.lightIntensityGrid;
5673 const occlude = baked.lightOccludeGrid;
5674 for (let ly = -1; ly <= CHUNK_SIZE; ly++)
5675 {
5676 for (let lx = -1; lx <= CHUNK_SIZE; lx++)
5677 {
5678 const tileX = baked.chunkX * CHUNK_SIZE + lx;
5679 const tileY = baked.chunkY * CHUNK_SIZE + ly;
5680 const gi = (ly + 1) * gridW + (lx + 1);
5681 // Halo tiles may sit in the other lighting region (3×3 vs outer). Resolve
5682 // sources per tile so corner blends match the neighbour chunk's shading.
5683 const lights = this.#dynamicLightsForTile(tileX, tileY, mobileLights, blockLights);
5684 grid[gi] = this.#intensityAtTile(tileX, tileY, lights, lightOcclusion, ambientDark);
5685 occlude[gi] = this.#tileOccludesLight(tileX, tileY) ? 1 : 0;
5686 }
5687 }
5688 return { grid, occlude, gridW };
5689 }
5690
5691 #makeLightCornerSampler (grid, occlude, gridW)
5692 {
5693 const sample = (lx, ly) => grid[(ly + 1) * gridW + (lx + 1)];
5694 const blocks = (lx, ly) => occlude[(ly + 1) * gridW + (lx + 1)] !== 0;
5695 const smoothCorner = (homeLx, homeLy, aLx, aLy, bLx, bLy, dLx, dLy) => smoothLitCorner({
5696 homeLit: sample(homeLx, homeLy),
5697 homeBlocks: blocks(homeLx, homeLy),
5698 aLit: sample(aLx, aLy),
5699 aBlocks: blocks(aLx, aLy),
5700 bLit: sample(bLx, bLy),
5701 bBlocks: blocks(bLx, bLy),
5702 dLit: sample(dLx, dLy),
5703 dBlocks: blocks(dLx, dLy)
5704 });
5705 return { smoothCorner };
5706 }
5707
5708 /** Corner lit intensities (0–1) for one tile — matches baked atlas lightmap corners. */
5709 #tileLitCorners (baked, localX, localY)
5710 {
5711 const grid = baked?.lightIntensityGrid;
5712 const occlude = baked?.lightOccludeGrid;
5713 if (!grid?.length || !occlude?.length)
5714 { return null; }
5715 const gridW = CHUNK_SIZE + 2;
5716 const { smoothCorner } = this.#makeLightCornerSampler(grid, occlude, gridW);
5717 return {
5718 nw: smoothCorner(
5719 localX, localY,
5720 localX - 1, localY,
5721 localX, localY - 1,
5722 localX - 1, localY - 1
5723 ),
5724 ne: smoothCorner(
5725 localX, localY,
5726 localX + 1, localY,
5727 localX, localY - 1,
5728 localX + 1, localY - 1
5729 ),
5730 sw: smoothCorner(
5731 localX, localY,
5732 localX - 1, localY,
5733 localX, localY + 1,
5734 localX - 1, localY + 1
5735 ),
5736 se: smoothCorner(
5737 localX, localY,
5738 localX + 1, localY,
5739 localX, localY + 1,
5740 localX + 1, localY + 1
5741 )
5742 };
5743 }
5744
5745 #hashUint8Array (values)
5746 {
5747 let hash = 2166136261;
5748 for (let i = 0; i < values.length; i++)
5749 {
5750 hash ^= values[i];
5751 hash = Math.imul(hash, 16777619);
5752 }
5753 return hash >>> 0;
5754 }
5755
5756 #lightAffectsChunkBounds (light, chunkX, chunkY)
5757 {
5758 const minX = chunkX * CHUNK_SIZE - 1;
5759 const minY = chunkY * CHUNK_SIZE - 1;
5760 const maxX = chunkX * CHUNK_SIZE + CHUNK_SIZE;
5761 const maxY = chunkY * CHUNK_SIZE + CHUNK_SIZE;
5762 const closestX = Math.max(minX, Math.min(light.tileX, maxX));
5763 const closestY = Math.max(minY, Math.min(light.tileY, maxY));
5764 return Math.hypot(light.tileX - closestX, light.tileY - closestY) <= light.range;
5765 }
5766
5767 #chunkLightmapCacheKey (baked, activeLights, ambientDark = this.#ambientDarkness())
5768 {
5769 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
5770 if (!snapshot?.light)
5771 { return null; }
5772 const bakedHash = this.#hashUint8Array(snapshot.light);
5773 // Caller already scoped lights for this chunk (incl. 3×3 spill onto the outer ring).
5774 const lights = activeLights;
5775 const darks = this._activeSpellDarks ?? [];
5776 const mode = this.lightingMode === "simple" ? "s" : "f";
5777 const ambientKey = Math.round(Math.max(0, ambientDark) * 1000);
5778 let lightsKey = "";
5779 for (const light of lights)
5780 {
5781 if (!this.#lightAffectsChunkBounds(light, baked.chunkX, baked.chunkY))
5782 { continue; }
5783 lightsKey += `l${light.tileX},${light.tileY},${light.range},${light.intensity ?? 1};`;
5784 }
5785 let darksKey = "";
5786 for (const dark of darks)
5787 {
5788 if (!this.#lightAffectsChunkBounds(dark, baked.chunkX, baked.chunkY))
5789 { continue; }
5790 darksKey += `d${dark.tileX},${dark.tileY},${dark.range},${dark.intensity ?? 1};`;
5791 }
5792 return `a:${mode}:${ambientKey}:${bakedHash}:${lightsKey}|${darksKey}`;
5793 }
5794
5795 #invalidateNeighborLightmapCaches (chunkX, chunkY)
5796 {
5797 // Halo grid is ±1 tile; outer map ring is ±2 chunks from the player.
5798 for (let dy = -2; dy <= 2; dy++)
5799 {
5800 for (let dx = -2; dx <= 2; dx++)
5801 {
5802 const baked = this.bakedChunks.get(`${chunkX + dx},${chunkY + dy}`);
5803 if (baked)
5804 { baked.lightmapCacheKey = null; }
5805 }
5806 }
5807 }
5808
5809 /**
5810 * Per-chunk lightmap for atlas ground/blocks. Open tiles blend into open neighbours;
5811 * occluding tiles stay flat and contribute 0 into others so light does not bleed
5812 * through a wall to the far side. Diagonals only when both cardinals are clear.
5813 * @param chunkLights Sources that affect this chunk (cache key + in-chunk samples).
5814 * @param mobileLights / blockLights Full lists so the ±1 halo can sample across the 3×3 boundary.
5815 */
5816 #writeChunkLightmap (
5817 baked,
5818 chunkLights,
5819 mobileLights,
5820 blockLights,
5821 lightOcclusion,
5822 ambientDark = this.#ambientDarkness()
5823 )
5824 {
5825 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
5826 if (!snapshot)
5827 { return; }
5828 const cacheKey = this.#chunkLightmapCacheKey(baked, chunkLights, ambientDark);
5829 if (cacheKey && baked.lightmapCacheKey === cacheKey)
5830 { return; }
5831 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
5832 const pixelCount = atlasPx * atlasPx * 4;
5833 if (!baked.lightmapPixels || baked.lightmapPixels.length !== pixelCount)
5834 { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); }
5835 const pixels = baked.lightmapPixels;
5836
5837 this.#fillChunkLightGrids(baked, mobileLights, blockLights, lightOcclusion, ambientDark);
5838 const simple = this.lightingMode === "simple";
5839
5840 for (let localY = 0; localY < CHUNK_SIZE; localY++)
5841 {
5842 for (let localX = 0; localX < CHUNK_SIZE; localX++)
5843 {
5844 const baseX = localX * SPRITE_SIZE_PX;
5845 const baseY = localY * SPRITE_SIZE_PX;
5846 if (simple)
5847 {
5848 const gridW = CHUNK_SIZE + 2;
5849 const intensity = baked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? 0;
5850 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
5851 for (let py = 0; py < SPRITE_SIZE_PX; py++)
5852 {
5853 for (let px = 0; px < SPRITE_SIZE_PX; px++)
5854 {
5855 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
5856 pixels[offset] = value;
5857 pixels[offset + 1] = value;
5858 pixels[offset + 2] = value;
5859 pixels[offset + 3] = 255;
5860 }
5861 }
5862 continue;
5863 }
5864 const corners = this.#tileLitCorners(baked, localX, localY);
5865 const nw = corners.nw;
5866 const ne = corners.ne;
5867 const sw = corners.sw;
5868 const se = corners.se;
5869 for (let py = 0; py < SPRITE_SIZE_PX; py++)
5870 {
5871 const v = (py + 0.5) / SPRITE_SIZE_PX;
5872 const left = nw + (sw - nw) * v;
5873 const right = ne + (se - ne) * v;
5874 for (let px = 0; px < SPRITE_SIZE_PX; px++)
5875 {
5876 const u = (px + 0.5) / SPRITE_SIZE_PX;
5877 const intensity = left + (right - left) * u;
5878 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
5879 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
5880 pixels[offset] = value;
5881 pixels[offset + 1] = value;
5882 pixels[offset + 2] = value;
5883 pixels[offset + 3] = 255;
5884 }
5885 }
5886 }
5887 }
5888 const ctx = baked.lightmapCanvas.getContext("2d");
5889 ctx.putImageData(new ImageData(pixels, atlasPx, atlasPx), 0, 0);
5890 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
5891 this.#queueCanvasTextureWarm(baked.lightmapCanvas, baked.chunkX, baked.chunkY);
5892 baked.lightmapCacheKey = cacheKey;
5893 }
5894
5895 #updateSwipes (now)
5896 {
5897 this.swipes = this.swipes.filter((swipe) =>
5898 {
5899 if (swipe.lerp && swipe.started != null)
5900 {
5901 const durationMs = swipe.durationMs ?? 400;
5902 const t = Math.min(1, (now - swipe.started) / durationMs);
5903 const fromPivot = this.#projectileLaunchPoint(
5904 swipe.attackerId ?? null,
5905 swipe.fromTileX,
5906 swipe.fromTileY
5907 );
5908 const toPivot = this.#projectileEndPivot(swipe);
5909 const x = fromPivot.x + (toPivot.x - fromPivot.x) * t;
5910 const y = fromPivot.y + (toPivot.y - fromPivot.y) * t;
5911 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
5912 if (swipe.object?.transform)
5913 {
5914 swipe.object.transform.rotation = Math.atan2(
5915 toPivot.y - fromPivot.y,
5916 toPivot.x - fromPivot.x
5917 ) * (180 / Math.PI);
5918 }
5919 if (swipe.spellProjectile && swipe.tint)
5920 { this.#syncUnlitTintSprite(swipe.object, swipe.tint); }
5921 this.#placePivoted(swipe.object, x, y, sortY, SORT_FX);
5922 if (!swipe.spellProjectile)
5923 {
5924 this.#applyPhysicalCombatFxDarkness(
5925 swipe.object,
5926 swipe.fromTileX,
5927 swipe.fromTileY,
5928 swipe.tileX,
5929 swipe.tileY,
5930 swipe.dualTint ?? null
5931 );
5932 }
5933 }
5934 else if (swipe.fromTileX != null && !swipe.spellProjectile)
5935 {
5936 this.#applyPhysicalCombatFxDarkness(
5937 swipe.object,
5938 swipe.fromTileX,
5939 swipe.fromTileY,
5940 swipe.tileX,
5941 swipe.tileY,
5942 swipe.dualTint ?? null
5943 );
5944 }
5945 if (swipe.fadeOpacity && swipe.started != null && swipe.object?.renderer)
5946 {
5947 const durationMs = swipe.durationMs ?? MELEE_SWIPE_MS;
5948 const t = Math.min(1, Math.max(0, (now - swipe.started) / durationMs));
5949 swipe.object.renderer.alpha = 1 - t;
5950 }
5951 if (swipe.until > now)
5952 { return true; }
5953 const onImpact = swipe.onImpact;
5954 swipe.onImpact = null;
5955 swipe.object?.destroy();
5956 if (typeof onImpact === "function")
5957 {
5958 try
5959 { onImpact(); }
5960 catch (_)
5961 { /* presentation only */ }
5962 }
5963 return false;
5964 });
5965 }
5966
5967 #projectileEndPivot (swipe)
5968 {
5969 if (swipe.trackTarget && swipe.targetId != null)
5970 { return this.#projectileAimPoint(swipe.targetId, swipe.tileX, swipe.tileY); }
5971 return this.#projectileAimPoint(null, swipe.tileX, swipe.tileY);
5972 }
5973
5974 /**
5975 * Launch point: 4px below the top of the caster sprite (falls back to tile centre).
5976 */
5977 #projectileLaunchPoint (entityId, tileX, tileY)
5978 {
5979 const entity = entityId != null ? this.entities.get(entityId) : null;
5980 if (entity && Number.isFinite(entity.visualX) && Number.isFinite(entity.visualY))
5981 {
5982 const zoom = this.zoom;
5983 const spriteH = entity.object?.renderer?.sprite?.height ?? SPRITE_SIZE_PX;
5984 const pivotX = entity.visualX + (entity.stackOffsetX ?? 0);
5985 const pivotY = entity.visualY + (entity.stackOffsetY ?? 0);
5986 const topY = pivotY - (spriteH - PIVOT_FROM_BOTTOM_PX) * zoom;
5987 return {
5988 x: pivotX,
5989 y: topY + PROJECTILE_LAUNCH_FROM_TOP_PX * zoom
5990 };
5991 }
5992 return tilePivot(tileX, tileY, this.tileSize());
5993 }
5994
5995 /**
5996 * Aim point: sprite centre for creatures, tile centre for tile targets.
5997 */
5998 #projectileAimPoint (entityId, tileX, tileY)
5999 {
6000 const entity = entityId != null ? this.entities.get(entityId) : null;
6001 if (entity && Number.isFinite(entity.visualX) && Number.isFinite(entity.visualY))
6002 {
6003 const zoom = this.zoom;
6004 const spriteH = entity.object?.renderer?.sprite?.height ?? SPRITE_SIZE_PX;
6005 const pivotX = entity.visualX + (entity.stackOffsetX ?? 0);
6006 const pivotY = entity.visualY + (entity.stackOffsetY ?? 0);
6007 return spriteCenterFromPivot(pivotX, pivotY, spriteH, zoom);
6008 }
6009 return tilePivot(tileX, tileY, this.tileSize());
6010 }
6011
6012 #updateDamageNumbers (now)
6013 {
6014 const layer = this.damageNumbersEl;
6015 if (!layer)
6016 { return; }
6017 this.damageFloats = this.damageFloats.filter((entry) =>
6018 {
6019 const elapsed = now - entry.started;
6020 if (elapsed >= DAMAGE_FLOAT_MS)
6021 {
6022 entry.element?.remove();
6023 return false;
6024 }
6025 const entity = this.entities.get(entry.entityId);
6026 if (!entity)
6027 {
6028 entry.element?.remove();
6029 return false;
6030 }
6031 if (!entry.element)
6032 {
6033 entry.element = document.createElement("span");
6034 entry.element.className = "damage-number";
6035 entry.element.textContent = String(entry.damage);
6036 layer.append(entry.element);
6037 }
6038 const anchor = this.nametagAnchor(entity);
6039 if (!anchor)
6040 { return true; }
6041 const t = elapsed / DAMAGE_FLOAT_MS;
6042 entry.element.style.left = `${anchor.x}px`;
6043 entry.element.style.top = `${anchor.y - 6 - t * 28}px`;
6044 entry.element.style.opacity = String(1 - t);
6045 return true;
6046 });
6047 }
6048
6049 #updateSkillLevelFloats (now)
6050 {
6051 const layer = this.skillLevelFloatsEl;
6052 if (!layer)
6053 { return; }
6054 this.skillLevelFloats = this.skillLevelFloats.filter((entry) =>
6055 {
6056 const elapsed = now - entry.started;
6057 if (elapsed >= SKILL_LEVEL_FLOAT_MS)
6058 {
6059 entry.element?.remove();
6060 return false;
6061 }
6062 const entity = this.entities.get(entry.entityId);
6063 if (!entity)
6064 {
6065 entry.element?.remove();
6066 return false;
6067 }
6068 if (!entry.element)
6069 {
6070 const root = document.createElement("div");
6071 root.className = "skill-level-float";
6072
6073 const levelEl = document.createElement("div");
6074 levelEl.className = "skill-level-float-level";
6075 levelEl.textContent = `↑${entry.level}↑`;
6076
6077 const icon = document.createElement("img");
6078 icon.className = "skill-level-float-icon";
6079 icon.src = entry.icon;
6080 icon.alt = entry.displayName || "";
6081
6082 root.append(levelEl, icon);
6083 entry.element = root;
6084 layer.append(entry.element);
6085 }
6086 const anchor = this.nametagAnchor(entity);
6087 if (!anchor)
6088 { return true; }
6089 const t = elapsed / SKILL_LEVEL_FLOAT_MS;
6090 entry.element.style.left = `${anchor.x}px`;
6091 entry.element.style.top = `${anchor.y - 10 - t * 18}px`;
6092 entry.element.style.opacity = String(Math.max(0, 1 - t * 0.85));
6093 return true;
6094 });
6095 }
6096
6097 #syncBloomLayer ()
6098 {
6099 if (!this.bloomEnabled)
6100 {
6101 this.scene.setLayers([{ name: "default" }]);
6102 return;
6103 }
6104 const settings = this.settings ?? DEFAULT_WORLD_SETTINGS;
6105 this.scene.setLayers([
6106 { name: "default" },
6107 {
6108 name: RENDER_LAYER_BLOOM,
6109 composite: "add",
6110 postShaders: Shader.getBloomPostChain({
6111 threshold: settings.bloomThreshold,
6112 softKnee: settings.bloomSoftKnee,
6113 intensity: settings.bloomIntensity,
6114 blurSize: settings.bloomBlurSize,
6115 saturation: settings.bloomSaturation,
6116 colorPreserve: settings.bloomColorPreserve,
6117 dilate: settings.bloomDilate,
6118 scales: Math.max(1, Math.round(settings.bloomScales ?? 1)),
6119 halfRes: (settings.bloomHalfRes ?? 1) >= 0.5
6120 })
6121 }
6122 ]);
6123 }
6124}
6125
6126export function nightFactor (hour, nightDarkness = 0.72)
6127{
6128 const peak = Math.min(1, Math.max(0, nightDarkness));
6129 if (hour >= 8 && hour <= 16)
6130 { return 0; }
6131 if (hour >= 22 || hour <= 5)
6132 { return peak; }
6133 if (hour < 8)
6134 { return lerp(peak, 0, (hour - 5) / 3); }
6135 return lerp(0, peak, (hour - 16) / 6);
6136}
6137
6138function bodySpriteName (sex)
6139{
6140 const key = sex === "female" ? "player-body-female" : "player-body-male";
6141 return spriteImageName("character", key, key);
6142}
6143
6144function lerp (a, b, t)
6145{
6146 return a + (b - a) * Math.min(1, Math.max(0, t));
6147}
6148
6149function makeLightmapCanvas (size)
6150{
6151 const canvas = document.createElement("canvas");
6152 canvas.width = size;
6153 canvas.height = size;
6154 return canvas;
6155}
6156
6157function makeNatureNoiseCanvas ()
6158{
6159 const canvas = document.createElement("canvas");
6160 canvas.width = NATURE_NOISE_SIZE;
6161 canvas.height = NATURE_NOISE_SIZE;
6162 return canvas;
6163}
6164
6165function copyCanvas (source, dest)
6166{
6167 const ctx = dest.getContext("2d");
6168 ctx.imageSmoothingEnabled = false;
6169 ctx.clearRect(0, 0, dest.width, dest.height);
6170 ctx.drawImage(source, 0, 0);
6171}
6172
6173function drawHpBar (canvas, current, max)
6174{
6175 const ctx = canvas.getContext("2d");
6176 ctx.clearRect(0, 0, HP_BAR_W, HP_BAR_H);
6177 ctx.fillStyle = "#000000";
6178 ctx.fillRect(0, 0, HP_BAR_W, HP_BAR_H);
6179 const ratio = max > 0 ? Math.max(0, Math.min(1, current / max)) : 0;
6180 const fillW = Math.round(12 * ratio);
6181 if (fillW > 0)
6182 {
6183 ctx.fillStyle = "#ff0000";
6184 ctx.fillRect(1, 1, fillW, 2);
6185 }
6186}