BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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