BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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