BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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