BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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