BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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