BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

worldView.js 144.4 KiB Download Raw
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX, ENTITY_STACK_SPREAD_DIAMETER_PX } from "/shared/protocol/constants.js";
2import { dynamicLightAtTile, dynamicDarknessAtTile, lightIntensity } from "/shared/lighting/raycast.js";
3import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js";
4import { bakeChunkOcclusion, 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 }
1369
1370 tileSize ()
1371 {
1372 return SPRITE_SIZE_PX * this.zoom;
1373 }
1374
1375 screenToTile (mouseX, mouseY)
1376 {
1377 const size = this.tileSize();
1378 const worldX = mouseX - this.scene.cameraPosition.x;
1379 const worldY = mouseY - this.scene.cameraPosition.y;
1380 return {
1381 tileX: Math.floor(worldX / size),
1382 tileY: Math.floor(worldY / size)
1383 };
1384 }
1385
1386 entityAtScreen (mouseX, mouseY)
1387 {
1388 let best = null;
1389 let bestLayer = -Infinity;
1390 for (const entity of this.entities.values())
1391 {
1392 const box = this.#entityScreenBox(entity);
1393 if (!box)
1394 { continue; }
1395 if (mouseX >= box.left && mouseX < box.right && mouseY >= box.top && mouseY < box.bottom)
1396 {
1397 const layer = entity.object?.layer ?? 0;
1398 if (layer >= bestLayer)
1399 {
1400 best = entity;
1401 bestLayer = layer;
1402 }
1403 }
1404 }
1405 return best;
1406 }
1407
1408 nametagAnchor (entity)
1409 {
1410 const box = this.#entityScreenBox(entity);
1411 if (!box)
1412 { return null; }
1413 return { x: (box.left + box.right) / 2, y: box.top };
1414 }
1415
1416 #entityScreenBox (entity)
1417 {
1418 const object = entity?.object;
1419 if (!object)
1420 { return null; }
1421 const size = object.transform.size;
1422 const x = object.transform.position.x + this.scene.cameraPosition.x;
1423 const y = object.transform.position.y + this.scene.cameraPosition.y;
1424 return {
1425 left: x - size.x / 2,
1426 right: x + size.x / 2,
1427 top: y - size.y / 2,
1428 bottom: y + size.y / 2
1429 };
1430 }
1431
1432 update (deltaTime)
1433 {
1434 const now = performance.now();
1435 const size = this.tileSize();
1436 this.#refreshStackTargets();
1437 for (const entity of this.entities.values())
1438 {
1439 const target = entity.targetX != null && entity.targetY != null
1440 ? { x: entity.targetX, y: entity.targetY }
1441 : tilePivot(entity.tileX, entity.tileY, size);
1442 if (entity.lerpStarted != null)
1443 {
1444 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs));
1445 entity.visualX = entity.fromX + (target.x - entity.fromX) * t;
1446 entity.visualY = entity.fromY + (target.y - entity.fromY) * t;
1447 if (t >= 1)
1448 {
1449 entity.lerpStarted = null;
1450 entity.previousTileX = null;
1451 entity.previousTileY = null;
1452 }
1453 }
1454 else
1455 {
1456 entity.visualX = target.x;
1457 entity.visualY = target.y;
1458 }
1459 this.#updateStackOffset(entity, now);
1460 this.#updateShove(entity, now, size);
1461 this.#expireGatherToolOverlay(entity, now);
1462 this.#placeEntity(entity, now);
1463 }
1464
1465 this.#updateSwipes(now);
1466 this.#updateDamageNumbers(now);
1467 this.#updateSkillLevelFloats(now);
1468 this.#relayoutSpellTargetHighlight();
1469 this.#centerCamera();
1470 this.#cullOffscreenDrawables();
1471 this.#updateShade(deltaTime);
1472 }
1473
1474 /**
1475 * Desired circle offsets for stacked entities (applied via {@link #updateStackOffset}).
1476 * Stable assignment by entityId; free-flight entities stay unshifted.
1477 */
1478 #refreshStackTargets ()
1479 {
1480 const byTile = new Map();
1481 for (const entity of this.entities.values())
1482 {
1483 if (entity.freeFlight)
1484 {
1485 entity.stackTargetX = 0;
1486 entity.stackTargetY = 0;
1487 continue;
1488 }
1489 const key = `${entity.tileX},${entity.tileY}`;
1490 let list = byTile.get(key);
1491 if (!list)
1492 {
1493 list = [];
1494 byTile.set(key, list);
1495 }
1496 list.push(entity);
1497 }
1498 const radius = (ENTITY_STACK_SPREAD_DIAMETER_PX * this.zoom) / 2;
1499 for (const list of byTile.values())
1500 {
1501 if (list.length <= 1)
1502 {
1503 for (const entity of list)
1504 {
1505 entity.stackTargetX = 0;
1506 entity.stackTargetY = 0;
1507 }
1508 continue;
1509 }
1510 list.sort((a, b) => String(a.entityId).localeCompare(String(b.entityId)));
1511 const n = list.length;
1512 for (let i = 0; i < n; i++)
1513 {
1514 const angle = -Math.PI / 2 + (Math.PI * 2 * i) / n;
1515 list[i].stackTargetX = Math.cos(angle) * radius;
1516 list[i].stackTargetY = Math.sin(angle) * radius;
1517 }
1518 }
1519 }
1520
1521 #updateStackOffset (entity, now)
1522 {
1523 const tx = entity.stackTargetX ?? 0;
1524 const ty = entity.stackTargetY ?? 0;
1525 const cx = entity.stackOffsetX ?? 0;
1526 const cy = entity.stackOffsetY ?? 0;
1527 if (entity.stackLerpToX !== tx || entity.stackLerpToY !== ty)
1528 {
1529 entity.stackFromX = cx;
1530 entity.stackFromY = cy;
1531 entity.stackLerpToX = tx;
1532 entity.stackLerpToY = ty;
1533 entity.stackLerpStarted = now;
1534 }
1535 if (entity.stackLerpStarted == null)
1536 {
1537 entity.stackOffsetX = tx;
1538 entity.stackOffsetY = ty;
1539 return;
1540 }
1541 const t = Math.min(1, (now - entity.stackLerpStarted) / STACK_SPREAD_LERP_MS);
1542 entity.stackOffsetX = entity.stackFromX + (tx - entity.stackFromX) * t;
1543 entity.stackOffsetY = entity.stackFromY + (ty - entity.stackFromY) * t;
1544 if (t >= 1)
1545 {
1546 entity.stackOffsetX = tx;
1547 entity.stackOffsetY = ty;
1548 entity.stackLerpStarted = null;
1549 }
1550 }
1551
1552 #updateShove (entity, now, tileSize)
1553 {
1554 if (!entity.shove)
1555 {
1556 entity.shoveOffsetX = 0;
1557 entity.shoveOffsetY = 0;
1558 return;
1559 }
1560 const elapsed = now - entity.shove.started;
1561 const t = Math.min(1, elapsed / entity.shove.durationMs);
1562 const maxDist = tileSize * SHOVE_TILE_FRACTION;
1563 const dx = entity.shove.targetVisualX - entity.shove.startVisualX;
1564 const dy = entity.shove.targetVisualY - entity.shove.startVisualY;
1565 const dist = Math.hypot(dx, dy) || 1;
1566 const ux = dx / dist;
1567 const uy = dy / dist;
1568 let phase;
1569 if (t < 0.45)
1570 { phase = t / 0.45; }
1571 else
1572 { phase = 1 - (t - 0.45) / 0.55; }
1573 entity.shoveOffsetX = ux * maxDist * phase;
1574 entity.shoveOffsetY = uy * maxDist * phase;
1575 if (t >= 1)
1576 { entity.shove = null; }
1577 }
1578
1579 spawnCombatSwing (payload)
1580 {
1581 const attacker = this.entities.get(payload.attackerId);
1582 const target = this.entities.get(payload.targetId);
1583 if (!attacker || !target)
1584 { return; }
1585 const ax = attacker.visualX + (attacker.stackOffsetX ?? 0);
1586 const ay = attacker.visualY + (attacker.stackOffsetY ?? 0);
1587 const tx = target.visualX + (target.stackOffsetX ?? 0);
1588 const ty = target.visualY + (target.stackOffsetY ?? 0);
1589 this.#applyShove(attacker, tx, ty);
1590 const midX = (ax + tx) / 2;
1591 const midY = (ay + ty) / 2;
1592 const sortY = Math.max(ay, ty) + 0.02;
1593 const angle = Math.atan2(ty - ay, tx - ax) * (180 / Math.PI);
1594 const jitter = (Math.random() * 2 - 1) * MELEE_SWIPE_JITTER_DEG;
1595 const spriteName = "fx:melee-swipe:melee-swipe";
1596 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_FX);
1597 if (object.transform)
1598 { object.transform.rotation = angle + jitter; }
1599 if (object.renderer)
1600 { object.renderer.alpha = 1; }
1601 this.scene.addObject(object);
1602 this.#placePivoted(object, midX, midY, sortY, SORT_FX);
1603 this.#applyPhysicalCombatFxDarkness(object, payload.fromTileX, payload.fromTileY, payload.tileX, payload.tileY);
1604 const started = performance.now();
1605 this.swipes.push({
1606 object,
1607 until: started + MELEE_SWIPE_MS,
1608 started,
1609 durationMs: MELEE_SWIPE_MS,
1610 fadeOpacity: true,
1611 fromTileX: payload.fromTileX,
1612 fromTileY: payload.fromTileY,
1613 tileX: payload.tileX,
1614 tileY: payload.tileY
1615 });
1616 }
1617
1618 /** Mining / gathering lunge toward a tile — shove only, no swipe FX. */
1619 spawnGatherSwing (payload)
1620 {
1621 const attacker = this.entities.get(payload.attackerId);
1622 if (!attacker)
1623 { return; }
1624 const pivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());
1625 this.#applyShove(attacker, pivot.x, pivot.y);
1626 if (payload.toolItemId != null)
1627 { this.#setGatherToolOverlay(attacker, payload.toolItemId); }
1628 }
1629
1630 #applyShove (entity, targetVisualX, targetVisualY)
1631 {
1632 entity.shove = {
1633 startVisualX: entity.visualX,
1634 startVisualY: entity.visualY,
1635 targetVisualX,
1636 targetVisualY,
1637 started: performance.now(),
1638 durationMs: SHOVE_MS
1639 };
1640 }
1641
1642 #applyShoveInDirection (entity, dirX, dirY)
1643 {
1644 const len = Math.hypot(dirX, dirY);
1645 if (len < 1e-4)
1646 { return; }
1647 const tileSize = this.tileSize();
1648 const ux = dirX / len;
1649 const uy = dirY / len;
1650 this.#applyShove(
1651 entity,
1652 entity.visualX + ux * tileSize,
1653 entity.visualY + uy * tileSize
1654 );
1655 }
1656
1657 /** Physical combat FX (melee swipes, ranged projectiles). Magic spells stay unshaded. */
1658 spawnPhysicalProjectileFx (payload)
1659 {
1660 const spriteName = payload.sprite ?? "fx:projectile:arrow";
1661 const image = this.game.images[spriteName];
1662 if (!image)
1663 { return; }
1664 const dualTint = this.#dualTintFromPayload(payload);
1665 const fromPivot = this.#projectileLaunchPoint(
1666 payload.attackerId ?? null,
1667 payload.fromTileX,
1668 payload.fromTileY
1669 );
1670 const toPivot = this.#projectileAimPoint(
1671 payload.targetId ?? null,
1672 payload.tileX,
1673 payload.tileY
1674 );
1675 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
1676 const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);
1677 const object = new GameObject(0, 0, image, SORT_FX);
1678 if (object.transform)
1679 { object.transform.rotation = angle; }
1680 this.scene.addObject(object);
1681 this.#placePivoted(object, fromPivot.x, fromPivot.y, sortY, SORT_FX);
1682 this.#applyPhysicalCombatFxDarkness(
1683 object,
1684 payload.fromTileX,
1685 payload.fromTileY,
1686 payload.tileX,
1687 payload.tileY,
1688 dualTint
1689 );
1690 const started = performance.now();
1691 const durationMs = payload.durationMs ?? 400;
1692 const trackTarget = payload.trackTarget !== false && payload.targetId != null;
1693 this.swipes.push({
1694 object,
1695 until: started + durationMs,
1696 started,
1697 durationMs,
1698 lerp: true,
1699 dualTint,
1700 fromTileX: payload.fromTileX,
1701 fromTileY: payload.fromTileY,
1702 tileX: payload.tileX,
1703 tileY: payload.tileY,
1704 attackerId: payload.attackerId ?? null,
1705 targetId: payload.targetId ?? null,
1706 trackTarget,
1707 onImpact: null
1708 });
1709 }
1710
1711 /** Bloom-layer spell projectiles — magenta-tinted, unique art per spell. */
1712 spawnSpellProjectileFx (payload)
1713 {
1714 const spellId = payload.spellId ?? null;
1715 const def = spellId != null ? spellDefinition(spellId) : null;
1716 const spriteName = payload.sprite
1717 ?? def?.projectileSprite
1718 ?? "fx:projectile:spell-none-1-mana-bullet";
1719 const image = this.game.images[spriteName];
1720 if (!image)
1721 { return; }
1722 const tint = spellProjectileTint(def?.element);
1723 const fromPivot = this.#projectileLaunchPoint(
1724 payload.casterId ?? null,
1725 payload.fromTileX,
1726 payload.fromTileY
1727 );
1728 const toPivot = this.#projectileAimPoint(
1729 payload.targetId ?? null,
1730 payload.tileX,
1731 payload.tileY
1732 );
1733 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
1734 const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);
1735 const object = new GameObject(0, 0, image, SORT_FX);
1736 object.renderer.layer = RENDER_LAYER_BLOOM;
1737 this.#markUnlit(object);
1738 this.#syncUnlitTintSprite(object, tint);
1739 if (object.transform)
1740 { object.transform.rotation = angle; }
1741 this.scene.addObject(object);
1742 this.#placePivoted(object, fromPivot.x, fromPivot.y, sortY, SORT_FX);
1743 const started = performance.now();
1744 const durationMs = payload.durationMs ?? 2000;
1745 this.swipes.push({
1746 object,
1747 until: started + durationMs,
1748 started,
1749 durationMs,
1750 lerp: true,
1751 spellProjectile: true,
1752 tint,
1753 fromTileX: payload.fromTileX,
1754 fromTileY: payload.fromTileY,
1755 tileX: payload.tileX,
1756 tileY: payload.tileY,
1757 attackerId: payload.casterId ?? null,
1758 targetId: payload.targetId ?? null,
1759 trackTarget: payload.targetId != null,
1760 onImpact: null
1761 });
1762 }
1763
1764 spawnSpellFizzleFx (_payload)
1765 {
1766 // Visual-only fizzle; no dynamic light (cast flashes skip lightmap rebakes).
1767 }
1768
1769 /**
1770 * Authoritative Light-spell tile light from the server.
1771 * Kept out of short-lived `dynamicLights` so duration follows `remainingMs` updates.
1772 */
1773 setSpellLight (payload)
1774 {
1775 const key = `${payload.tileX},${payload.tileY}`;
1776 this.spellLights.set(key, {
1777 tileX: payload.tileX,
1778 tileY: payload.tileY,
1779 until: performance.now() + Math.max(0, payload.remainingMs ?? 0),
1780 range: payload.rangeTiles ?? 6,
1781 intensity: payload.intensity ?? 0.88
1782 });
1783 this.#invalidateNeighborLightmapCaches(
1784 Math.floor(payload.tileX / CHUNK_SIZE),
1785 Math.floor(payload.tileY / CHUNK_SIZE)
1786 );
1787 }
1788
1789 removeSpellLight (payload)
1790 {
1791 this.spellLights.delete(`${payload.tileX},${payload.tileY}`);
1792 this.#invalidateNeighborLightmapCaches(
1793 Math.floor(payload.tileX / CHUNK_SIZE),
1794 Math.floor(payload.tileY / CHUNK_SIZE)
1795 );
1796 }
1797
1798 setSpellDark (payload)
1799 {
1800 const key = `${payload.tileX},${payload.tileY}`;
1801 this.spellDarks.set(key, {
1802 tileX: payload.tileX,
1803 tileY: payload.tileY,
1804 until: performance.now() + Math.max(0, payload.remainingMs ?? 0),
1805 range: payload.rangeTiles ?? 6,
1806 intensity: payload.intensity ?? 0.88
1807 });
1808 this.#invalidateNeighborLightmapCaches(
1809 Math.floor(payload.tileX / CHUNK_SIZE),
1810 Math.floor(payload.tileY / CHUNK_SIZE)
1811 );
1812 }
1813
1814 removeSpellDark (payload)
1815 {
1816 this.spellDarks.delete(`${payload.tileX},${payload.tileY}`);
1817 this.#invalidateNeighborLightmapCaches(
1818 Math.floor(payload.tileX / CHUNK_SIZE),
1819 Math.floor(payload.tileY / CHUNK_SIZE)
1820 );
1821 }
1822
1823 addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 1, durationMs = 250 })
1824 {
1825 this.dynamicLights.push({
1826 tileX: Math.floor(worldX),
1827 tileY: Math.floor(worldY),
1828 range: radiusTiles,
1829 intensity,
1830 until: performance.now() + durationMs
1831 });
1832 }
1833
1834 updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {})
1835 {
1836 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
1837 if (!snapshot)
1838 { return; }
1839 const index = localY * CHUNK_SIZE + localX;
1840 if (ground !== undefined)
1841 { snapshot.grounds[index] = ground; }
1842 if (block !== undefined)
1843 { snapshot.blocks[index] = block; }
1844 if (light !== undefined)
1845 { snapshot.light[index] = light; }
1846 if (ground !== undefined || block !== undefined)
1847 {
1848 if (!Array.isArray(snapshot.occlusion) || snapshot.occlusion.length < CHUNK_SIZE * CHUNK_SIZE)
1849 { snapshot.occlusion = bakeChunkOcclusion(snapshot); }
1850 else
1851 { snapshot.occlusion[index] = tileLightOcclusionAt(snapshot.grounds, snapshot.blocks, localX, localY); }
1852 }
1853 const tileX = chunkX * CHUNK_SIZE + localX;
1854 const tileY = chunkY * CHUNK_SIZE + localY;
1855 if (block !== undefined)
1856 {
1857 this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false });
1858 this.#drawTile(tileX, tileY);
1859 return;
1860 }
1861 this.#scheduleChunkRebuild(snapshot);
1862 if (ground !== undefined)
1863 { this.#drawTile(tileX, tileY); }
1864 }
1865
1866 /**
1867 * Editor-only mob markers for authored spawners (invisible during play).
1868 * Humanoid / town guard / CE show body + equipment overlays.
1869 * @param {number} chunkX
1870 * @param {number} chunkY
1871 * @param {Array<{ localX: number, localY: number, config?: object }>} spawners
1872 * @param {(mobTypeId: number) => string} resolveSprite
1873 */
1874 setEditorSpawners (chunkX, chunkY, spawners, resolveSprite)
1875 {
1876 const prefix = `${chunkX},${chunkY}:`;
1877 for (const [key, entry] of [...this.editorSpawners.entries()])
1878 {
1879 if (!key.startsWith(prefix))
1880 { continue; }
1881 this.#destroyEditorSpawnerEntry(entry);
1882 this.editorSpawners.delete(key);
1883 }
1884 const size = this.tileSize();
1885 for (const spawner of spawners ?? [])
1886 {
1887 const tileX = chunkX * CHUNK_SIZE + spawner.localX;
1888 const tileY = chunkY * CHUNK_SIZE + spawner.localY;
1889 const layers = layersFromSpawnerConfig(spawner.config);
1890 const bodySpriteName = layers?.[0]?.sprite
1891 ?? resolveSprite?.(spawner.config?.mobTypeId)
1892 ?? null;
1893 if (!bodySpriteName)
1894 { continue; }
1895 const key = `${prefix}${spawner.localX},${spawner.localY}`;
1896 const object = this.#ensureSprite(null, bodySpriteName, SORT_ENTITY);
1897 if (!object)
1898 { continue; }
1899 object.renderer.alpha = 0.85;
1900 const bodyTint = layers?.[0]?.tint ? normalizeRgb(layers[0].tint) : null;
1901 if (bodyTint)
1902 { this.#syncUnlitTintSprite(object, bodyTint); }
1903 else
1904 { this.#markUnlit(object); }
1905 const overlays = [];
1906 for (const layer of layers?.slice(1) ?? [])
1907 {
1908 const overlay = this.#ensureSprite(null, layer.sprite, SORT_ENTITY);
1909 if (!overlay)
1910 { continue; }
1911 overlay.renderer.alpha = 0.85;
1912 this.#applyEditorSpawnerOverlayLook(overlay, layer);
1913 overlays.push(overlay);
1914 }
1915 const pivot = tilePivot(tileX, tileY, size);
1916 this.#placePivoted(object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY);
1917 for (let i = 0; i < overlays.length; i++)
1918 {
1919 this.#placePivoted(
1920 overlays[i],
1921 pivot.x,
1922 pivot.y,
1923 pivot.y + 0.05 + 0.001 * (i + 1),
1924 SORT_ENTITY
1925 );
1926 }
1927 this.editorSpawners.set(key, {
1928 object,
1929 overlays,
1930 tileX,
1931 tileY,
1932 spriteName: bodySpriteName
1933 });
1934 }
1935 }
1936
1937 #destroyEditorSpawnerEntry (entry)
1938 {
1939 entry?.object?.destroy();
1940 for (const overlay of entry?.overlays ?? [])
1941 { overlay?.destroy(); }
1942 }
1943
1944 #applyEditorSpawnerOverlayLook (overlay, layer)
1945 {
1946 const layerDef = layer.itemId != null ? itemDefinition(layer.itemId) : null;
1947 const dualTint = layerDef?.iconTintFromTier
1948 ? null
1949 : (layer.itemId != null
1950 ? resolveEquipDualTint({ itemId: layer.itemId }, layerDef)
1951 : null);
1952 const tint = layer.tint
1953 ? normalizeRgb(layer.tint)
1954 : (dualTint
1955 ? null
1956 : (layerDef?.iconTintFromTier
1957 ? resolveItemTint({ itemId: layer.itemId }, layerDef)
1958 : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null)));
1959 if (dualTint)
1960 {
1961 overlay._lit = true;
1962 this.#syncDualTintLitSprite(overlay, 0, dualTint, 0, false);
1963 return;
1964 }
1965 if (tint)
1966 {
1967 this.#syncUnlitTintSprite(overlay, tint);
1968 return;
1969 }
1970 this.#markUnlit(overlay);
1971 }
1972
1973 clearEditorSpawners ()
1974 {
1975 for (const entry of this.editorSpawners.values())
1976 { this.#destroyEditorSpawnerEntry(entry); }
1977 this.editorSpawners.clear();
1978 }
1979
1980 #relayoutEditorSpawners ()
1981 {
1982 const size = this.tileSize();
1983 for (const entry of this.editorSpawners.values())
1984 {
1985 if (!entry.object)
1986 { continue; }
1987 const pivot = tilePivot(entry.tileX, entry.tileY, size);
1988 this.#placePivoted(entry.object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY);
1989 const overlays = entry.overlays ?? [];
1990 for (let i = 0; i < overlays.length; i++)
1991 {
1992 this.#placePivoted(
1993 overlays[i],
1994 pivot.x,
1995 pivot.y,
1996 pivot.y + 0.05 + 0.001 * (i + 1),
1997 SORT_ENTITY
1998 );
1999 }
2000 }
2001 }
2002
2003 /**
2004 * Editor-only range overlays: spawn (inner) and wander (outer, Chebyshev squares).
2005 */
2006 setSpawnRangeHighlight (tileX, tileY, spawnRange, wanderRange = null)
2007 {
2008 const spawnRadius = Math.max(0, spawnRange | 0);
2009 const wanderRadius = Math.max(spawnRadius, wanderRange == null ? spawnRadius : (wanderRange | 0));
2010 if (this.spawnRangeHighlight
2011 && this.wanderRangeHighlight
2012 && this.spawnRangeHighlight.tileX === tileX
2013 && this.spawnRangeHighlight.tileY === tileY
2014 && this.spawnRangeHighlight.range === spawnRadius
2015 && this.wanderRangeHighlight.range === wanderRadius)
2016 {
2017 this.#relayoutSpawnRangeHighlight();
2018 return;
2019 }
2020 this.clearSpawnRangeHighlight();
2021 const wanderObject = this.#ensureSprite(null, "wander-range", LAYER_EDGE);
2022 const spawnObject = this.#ensureSprite(null, "spawn-range", LAYER_EDGE);
2023 if (wanderObject)
2024 {
2025 this.#markUnlit(wanderObject);
2026 wanderObject.renderer.alpha = 1;
2027 this.wanderRangeHighlight = { object: wanderObject, tileX, tileY, range: wanderRadius };
2028 }
2029 if (spawnObject)
2030 {
2031 this.#markUnlit(spawnObject);
2032 spawnObject.renderer.alpha = 1;
2033 this.spawnRangeHighlight = { object: spawnObject, tileX, tileY, range: spawnRadius };
2034 }
2035 this.#relayoutSpawnRangeHighlight();
2036 }
2037
2038 clearSpawnRangeHighlight ()
2039 {
2040 this.spawnRangeHighlight?.object?.destroy();
2041 this.wanderRangeHighlight?.object?.destroy();
2042 this.spawnRangeHighlight = null;
2043 this.wanderRangeHighlight = null;
2044 }
2045
2046 setSpellTargetHighlight (tileX, tileY, inRange = true)
2047 {
2048 if (
2049 this.spellTargetHighlight
2050 && this.spellTargetHighlight.mode === "tile"
2051 && this.spellTargetHighlight.tileX === tileX
2052 && this.spellTargetHighlight.tileY === tileY
2053 && this.spellTargetHighlight.inRange === inRange
2054 )
2055 {
2056 this.#relayoutSpellTargetHighlight();
2057 return;
2058 }
2059 this.clearSpellTargetHighlight();
2060 const spriteName = inRange ? "spell-target-tile" : "spell-target-invalid";
2061 const object = this.#ensureSprite(null, spriteName, LAYER_EDGE - 1);
2062 if (!object)
2063 { return; }
2064 this.#markUnlit(object);
2065 object.renderer.alpha = 1;
2066 this.spellTargetHighlight = {
2067 mode: "tile",
2068 object,
2069 tileX,
2070 tileY,
2071 entityId: null,
2072 inRange,
2073 spriteName
2074 };
2075 this.#relayoutSpellTargetHighlight();
2076 }
2077
2078 /** Outline box around a living entity (mob / player) for entity-target spells. */
2079 setSpellEntityTargetHighlight (entityId, inRange = true)
2080 {
2081 const id = entityId | 0;
2082 if (
2083 this.spellTargetHighlight
2084 && this.spellTargetHighlight.mode === "entity"
2085 && this.spellTargetHighlight.entityId === id
2086 && this.spellTargetHighlight.inRange === inRange
2087 )
2088 {
2089 this.#relayoutSpellTargetHighlight();
2090 return;
2091 }
2092 this.clearSpellTargetHighlight();
2093 if (!this.entities.has(id))
2094 { return; }
2095 const spriteName = inRange ? "spell-target-entity" : "spell-target-entity-invalid";
2096 const object = this.#ensureSprite(null, spriteName, LAYER_EDGE - 1);
2097 if (!object)
2098 { return; }
2099 this.#markUnlit(object);
2100 object.renderer.alpha = 1;
2101 this.spellTargetHighlight = {
2102 mode: "entity",
2103 object,
2104 tileX: 0,
2105 tileY: 0,
2106 entityId: id,
2107 inRange,
2108 spriteName
2109 };
2110 this.#relayoutSpellTargetHighlight();
2111 }
2112
2113 clearSpellTargetHighlight ()
2114 {
2115 this.spellTargetHighlight?.object?.destroy();
2116 this.spellTargetHighlight = null;
2117 }
2118
2119 #relayoutSpellTargetHighlight ()
2120 {
2121 const highlight = this.spellTargetHighlight;
2122 if (!highlight?.object)
2123 { return; }
2124 if (highlight.mode === "entity")
2125 {
2126 const entity = this.entities.get(highlight.entityId);
2127 if (!entity?.object)
2128 {
2129 this.clearSpellTargetHighlight();
2130 return;
2131 }
2132 const pad = this.tileSize() * 0.12;
2133 const src = entity.object.transform;
2134 highlight.object.transform.position.x = src.position.x;
2135 highlight.object.transform.position.y = src.position.y;
2136 highlight.object.transform.size = new vector(src.size.x + pad, src.size.y + pad);
2137 highlight.object.layer = LAYER_EDGE - 1;
2138 highlight.tileX = entity.tileX;
2139 highlight.tileY = entity.tileY;
2140 this.#markSortDirty();
2141 return;
2142 }
2143 const size = this.tileSize();
2144 const left = highlight.tileX * size;
2145 const top = highlight.tileY * size;
2146 highlight.object.transform.position.x = left + size / 2;
2147 highlight.object.transform.position.y = top + size / 2;
2148 highlight.object.transform.size = new vector(size, size);
2149 highlight.object.layer = LAYER_EDGE - 1;
2150 this.#markSortDirty();
2151 }
2152
2153 #relayoutSpawnRangeHighlight ()
2154 {
2155 this.#layoutRangeOverlay(this.wanderRangeHighlight, LAYER_EDGE - 2);
2156 this.#layoutRangeOverlay(this.spawnRangeHighlight, LAYER_EDGE - 1);
2157 }
2158
2159 #layoutRangeOverlay (highlight, layer)
2160 {
2161 if (!highlight?.object)
2162 { return; }
2163 const size = this.tileSize();
2164 const side = (2 * highlight.range + 1) * size;
2165 const left = (highlight.tileX - highlight.range) * size;
2166 const top = (highlight.tileY - highlight.range) * size;
2167 highlight.object.transform.position.x = left + side / 2;
2168 highlight.object.transform.position.y = top + side / 2;
2169 highlight.object.transform.size = new vector(side, side);
2170 highlight.object.layer = layer;
2171 this.#markSortDirty();
2172 }
2173
2174 setTilePreview (tileX, tileY, override)
2175 {
2176 const next = { tileX, tileY, ...override };
2177 if (this.#previewEqual(this.preview, next))
2178 { return; }
2179 const previous = this.preview;
2180 this.preview = next;
2181 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2182 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2183 this.#scheduleChunkRebuild(this.chunks.get(`${chunkX},${chunkY}`));
2184 if (previous && (previous.tileX !== tileX || previous.tileY !== tileY))
2185 {
2186 const prevKey = `${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`;
2187 if (prevKey !== `${chunkX},${chunkY}`)
2188 { this.#scheduleChunkRebuild(this.chunks.get(prevKey)); }
2189 // Per-tile blocks (doors, campfires, …) are not in the atlas — refresh sprites.
2190 this.#drawTile(previous.tileX, previous.tileY);
2191 }
2192 this.#drawTile(tileX, tileY);
2193 }
2194
2195 clearTilePreview ()
2196 {
2197 if (!this.preview)
2198 { return; }
2199 const previous = this.preview;
2200 this.preview = null;
2201 const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
2202 this.#scheduleChunkRebuild(snapshot);
2203 this.#drawTile(previous.tileX, previous.tileY);
2204 }
2205
2206 #lerpMs (gait)
2207 {
2208 const walk = this.settings.walkTilesPerSecond || 2;
2209 const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk;
2210 return seconds * 1000;
2211 }
2212
2213 #centerCamera ()
2214 {
2215 if (!this.followPlayer)
2216 { return; }
2217 const local = this.entities.get(this.localEntityId);
2218 if (!local)
2219 { return; }
2220 const x = local.visualX + (local.stackOffsetX ?? 0);
2221 const y = local.visualY + (local.stackOffsetY ?? 0);
2222 this.scene.cameraPosition.x = this.scene.real_size.x / 2 - x;
2223 this.scene.cameraPosition.y = this.scene.real_size.y / 2 - y;
2224 }
2225
2226 /**
2227 * World-pixel AABB of the screen, expanded by half a tile (zoom-aware).
2228 * Tiles fully outside this rect are not drawn.
2229 */
2230 #drawBounds ()
2231 {
2232 const pad = this.tileSize() * 0.5;
2233 const camX = this.scene.cameraPosition.x;
2234 const camY = this.scene.cameraPosition.y;
2235 const w = this.scene.real_size.x;
2236 const h = this.scene.real_size.y;
2237 return {
2238 left: -camX - pad,
2239 right: -camX + w + pad,
2240 top: -camY - pad,
2241 bottom: -camY + h + pad
2242 };
2243 }
2244
2245 #rectIntersects (left, top, right, bottom, bounds)
2246 {
2247 return right >= bounds.left
2248 && left <= bounds.right
2249 && bottom >= bounds.top
2250 && top <= bounds.bottom;
2251 }
2252
2253 #setRendererVisible (object, visible)
2254 {
2255 if (object?.renderer)
2256 { object.renderer.visible = !!visible; }
2257 }
2258
2259 /** Skip drawing (and lighting work) for tiles/chunks more than ½ tile off-screen. */
2260 #cullOffscreenDrawables ()
2261 {
2262 const bounds = this.#drawBounds();
2263 const size = this.tileSize();
2264
2265 for (const baked of this.bakedChunks.values())
2266 {
2267 const left = baked.chunkX * CHUNK_SIZE * size;
2268 const top = baked.chunkY * CHUNK_SIZE * size;
2269 const chunkPx = CHUNK_SIZE * size;
2270 const chunkVisible = this.#rectIntersects(left, top, left + chunkPx, top + chunkPx, bounds);
2271 this.#setRendererVisible(baked.groundObject, chunkVisible);
2272 this.#setRendererVisible(baked.bloomObject, chunkVisible && this.bloomEnabled);
2273 baked._inViewport = chunkVisible;
2274 for (let row = 0; row < CHUNK_SIZE; row++)
2275 {
2276 const rowTop = top + row * size;
2277 const rowVisible = chunkVisible && this.#rectIntersects(
2278 left, rowTop, left + chunkPx, rowTop + size, bounds
2279 );
2280 this.#setRendererVisible(baked.blockObjects?.[row], rowVisible);
2281 }
2282 }
2283
2284 for (const objects of this.tiles.values())
2285 {
2286 const left = objects.tileX * size;
2287 const top = objects.tileY * size;
2288 const visible = this.#rectIntersects(left, top, left + size, top + size, bounds);
2289 objects._inViewport = visible;
2290 this.#setRendererVisible(objects.ground, visible);
2291 this.#setRendererVisible(objects.groundBloom, visible && this.bloomEnabled);
2292 this.#setRendererVisible(objects.block, visible);
2293 this.#setRendererVisible(objects.blockBloom, visible && this.bloomEnabled);
2294 if (objects.waterEdges)
2295 {
2296 for (const edge of Object.values(objects.waterEdges))
2297 { this.#setRendererVisible(edge, visible); }
2298 }
2299 }
2300 }
2301
2302 #upsertEntity (payload)
2303 {
2304 const size = this.tileSize();
2305 const pivot = tilePivot(payload.tileX, payload.tileY, size);
2306 let entity = this.entities.get(payload.entityId);
2307 if (!entity)
2308 {
2309 const spriteName = payload.layers?.[0]?.sprite
2310 ?? payload.sprite
2311 ?? bodySpriteName(payload.sex);
2312 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY);
2313 this.scene.addObject(object);
2314 this.#startIdleAnimation(object);
2315 entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y };
2316 this.entities.set(payload.entityId, entity);
2317 }
2318 entity.entityId = payload.entityId;
2319 entity.tileX = payload.tileX;
2320 entity.tileY = payload.tileY;
2321 entity.gait = payload.gait;
2322 entity.sex = payload.sex ?? entity.sex;
2323 entity.characterId = payload.characterId ?? entity.characterId ?? null;
2324 entity.accountId = payload.accountId ?? entity.accountId ?? null;
2325 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
2326 if (payload.level != null)
2327 { entity.level = payload.level | 0; }
2328 entity.hostile = payload.hostile != null ? !!payload.hostile : !!entity.hostile;
2329 entity.aggressive = payload.aggressive != null
2330 ? !!payload.aggressive
2331 : (payload.hostile != null ? !!payload.hostile : !!entity.aggressive);
2332 entity.canFight = payload.canFight != null
2333 ? !!payload.canFight
2334 : !!(entity.canFight || (payload.mobTypeId && !payload.talkable));
2335 entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable;
2336 entity.hasDialogue = payload.hasDialogue != null ? !!payload.hasDialogue : !!entity.hasDialogue;
2337 entity.hasShop = payload.hasShop != null ? !!payload.hasShop : !!entity.hasShop;
2338 entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable;
2339 entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight;
2340 entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0;
2341 if (payload.lightIntensity != null)
2342 { entity.lightIntensity = Number(payload.lightIntensity) || 1; }
2343 else if (entity.lightIntensity == null)
2344 { entity.lightIntensity = 1; }
2345 if (payload.visualScale != null)
2346 { entity.visualScale = Number(payload.visualScale) || 1; }
2347 else if (entity.visualScale == null)
2348 { entity.visualScale = 1; }
2349 if (payload.health != null)
2350 { entity.health = payload.health; }
2351 if (payload.maxHealth != null)
2352 { entity.maxHealth = payload.maxHealth; }
2353 if (payload.skullValue != null)
2354 { entity.skullValue = Math.max(0, payload.skullValue | 0); }
2355 else if (entity.skullValue == null)
2356 { entity.skullValue = 0; }
2357 if (payload.firstName)
2358 { entity.firstName = payload.firstName; }
2359 if (payload.lastName)
2360 { entity.lastName = payload.lastName; }
2361 entity.firstName = entity.firstName ?? "";
2362 entity.lastName = entity.lastName ?? "";
2363 if (payload.worldX != null && payload.worldY != null)
2364 {
2365 entity.worldX = payload.worldX;
2366 entity.worldY = payload.worldY;
2367 entity.visualX = payload.worldX * size;
2368 entity.visualY = payload.worldY * size;
2369 entity.targetX = entity.visualX;
2370 entity.targetY = entity.visualY;
2371 }
2372 else
2373 {
2374 entity.visualX = pivot.x;
2375 entity.visualY = pivot.y;
2376 entity.targetX = pivot.x;
2377 entity.targetY = pivot.y;
2378 }
2379 entity.fromX = entity.visualX;
2380 entity.fromY = entity.visualY;
2381 if (payload.layers)
2382 { this.#applyLayers(entity, payload.layers); }
2383 this.#syncHpBar(entity);
2384 this.#syncSkullMarker(entity);
2385 this.#placeEntity(entity, performance.now());
2386 }
2387
2388 #applyLayers (entity, layers)
2389 {
2390 entity.appearanceLayers = layers ?? [{ sprite: bodySpriteName(entity.sex) }];
2391 this.#rebuildOverlays(entity);
2392 }
2393
2394 #setGatherToolOverlay (entity, toolItemId)
2395 {
2396 entity.gatherToolItemId = toolItemId;
2397 entity.gatherToolUntil = performance.now() + GATHER_TOOL_HOLD_MS;
2398 this.#rebuildOverlays(entity);
2399 this.#placeEntity(entity, performance.now());
2400 }
2401
2402 #expireGatherToolOverlay (entity, now)
2403 {
2404 if (entity.gatherToolItemId == null)
2405 { return; }
2406 if ((entity.gatherToolUntil ?? 0) > now)
2407 { return; }
2408 entity.gatherToolItemId = null;
2409 entity.gatherToolUntil = 0;
2410 this.#rebuildOverlays(entity);
2411 }
2412
2413 /** Prefer the active gather tool's equip sprite over the worn weapon (all gather kinds). */
2414 #layersForDisplay (entity)
2415 {
2416 const layers = (entity.appearanceLayers ?? []).map((layer) => ({ ...layer }));
2417 const toolId = entity.gatherToolItemId;
2418 if (toolId == null || (entity.gatherToolUntil ?? 0) <= performance.now())
2419 { return layers; }
2420 const equip = itemEquipSprite(toolId);
2421 if (!equip || !this.game.images[equip])
2422 { return layers; }
2423 const replacement = {
2424 sprite: equip,
2425 itemId: toolId,
2426 tint: resolveEquipTint(toolId)
2427 };
2428 for (let index = layers.length - 1; index >= 1; index--)
2429 {
2430 const def = itemDefinition(layers[index].itemId);
2431 if (def?.equipment?.slot === EQUIPMENT_SLOT.weapon)
2432 {
2433 layers[index] = replacement;
2434 return layers;
2435 }
2436 }
2437 layers.push(replacement);
2438 return layers;
2439 }
2440
2441 #rebuildOverlays (entity)
2442 {
2443 const layers = this.#layersForDisplay(entity);
2444 const base = layers[0]?.sprite
2445 ?? bodySpriteName(entity.sex);
2446 if (this.game.images[base])
2447 {
2448 entity.object.renderer.sprite = this.game.images[base];
2449 this.#startIdleAnimation(entity.object);
2450 }
2451 entity.bodyTint = layers[0]?.tint ? normalizeRgb(layers[0].tint) : null;
2452 entity.bodyDualTint = layers[0]?.dualTint
2453 ? {
2454 shaft: normalizeRgb(layers[0].dualTint.shaft),
2455 tip: normalizeRgb(layers[0].dualTint.tip),
2456 ...(layers[0].dualTint.coat
2457 ? { coat: normalizeRgb(layers[0].dualTint.coat) }
2458 : {})
2459 }
2460 : null;
2461 entity.bloomBody = !!layers[0]?.bloomBody;
2462 for (const overlay of entity.overlays ?? [])
2463 { overlay.destroy(); }
2464 for (const overlay of entity.bloomOverlays ?? [])
2465 { overlay.destroy(); }
2466 entity.overlays = [];
2467 entity.overlayTints = [];
2468 entity.overlayDualTints = [];
2469 entity.overlayTightFit = [];
2470 entity.bloomOverlays = [];
2471 entity.bloomOverlayTints = [];
2472 entity.bloomOverlayDualTints = [];
2473 if (entity.bloomBody && this.game.images[base])
2474 {
2475 const bloomName = bloomCompanionName(base);
2476 const bloomImage = this.game.images[bloomName] ?? this.game.images[base];
2477 if (bloomImage)
2478 {
2479 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
2480 bloom.renderer.layer = RENDER_LAYER_BLOOM;
2481 this.#markUnlit(bloom);
2482 this.#startIdleAnimation(bloom);
2483 this.scene.addObject(bloom);
2484 entity.bloomOverlays.push(bloom);
2485 entity.bloomOverlayTints.push(entity.bodyTint);
2486 entity.bloomOverlayDualTints.push(entity.bodyDualTint);
2487 }
2488 }
2489 for (const layer of layers.slice(1))
2490 {
2491 const image = this.game.images[layer.sprite];
2492 if (!image)
2493 { continue; }
2494 const object = new GameObject(0, 0, image, SORT_ENTITY);
2495 this.scene.addObject(object);
2496 entity.overlays.push(object);
2497 const layerDef = layer.itemId != null ? itemDefinition(layer.itemId) : null;
2498 entity.overlayTightFit.push(!!layerDef?.tightFit);
2499 const dualTint = layer.dualTint
2500 ? {
2501 shaft: normalizeRgb(layer.dualTint.shaft),
2502 tip: normalizeRgb(layer.dualTint.tip),
2503 ...(layer.dualTint.coat
2504 ? { coat: normalizeRgb(layer.dualTint.coat) }
2505 : {})
2506 }
2507 : (layer.itemId != null
2508 ? resolveEquipDualTint({ itemId: layer.itemId }, layerDef)
2509 : null);
2510 entity.overlayDualTints.push(dualTint);
2511 entity.overlayTints.push(
2512 dualTint
2513 ? null
2514 : (layer.tint
2515 ? normalizeRgb(layer.tint)
2516 : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null))
2517 );
2518 const bloomName = bloomCompanionName(layer.sprite);
2519 const bloomImage = this.game.images[bloomName];
2520 if (!bloomImage)
2521 { continue; }
2522 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
2523 bloom.renderer.layer = RENDER_LAYER_BLOOM;
2524 this.#markUnlit(bloom);
2525 this.scene.addObject(bloom);
2526 entity.bloomOverlays.push(bloom);
2527 entity.bloomOverlayTints.push(
2528 layer.tint ? normalizeRgb(layer.tint) : null
2529 );
2530 }
2531 }
2532
2533 #placeEntity (entity, now = performance.now())
2534 {
2535 const zoom = this.zoom;
2536 const offsetX = entity.shoveOffsetX ?? 0;
2537 const offsetY = entity.shoveOffsetY ?? 0;
2538 const pivotX = entity.visualX + offsetX + (entity.stackOffsetX ?? 0);
2539 const pivotY = entity.visualY + offsetY + (entity.stackOffsetY ?? 0);
2540 let walkTilt = 0;
2541 if (entity.lerpStarted != null)
2542 {
2543 const stepMs = Math.max(1, entity.lerpMs ?? this.#lerpMs(entity.gait));
2544 const cycles = ((now - entity.lerpStarted) / stepMs) * Math.PI * 2;
2545 const tilt = entity.gait === GAIT.run ? RUN_TILT_DEG : WALK_TILT_DEG;
2546 walkTilt = Math.sin(cycles) * tilt;
2547 }
2548 const flashStrength = (entity.damageFlashUntil ?? 0) > now
2549 ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS
2550 : 0;
2551 const flashColor = entity.damageFlashColor ?? FLASH_COLOR_DAMAGE;
2552 const tileShade = this.#entityShadeAlpha(entity, now);
2553 const wade = isWadeGroundInSeason(this.#groundTypeAt(entity.tileX, entity.tileY), this.worldSeason);
2554
2555 entity.object.transform.rotation = walkTilt;
2556 if (entity.bodyDualTint)
2557 {
2558 this.#syncDualTintLitSprite(
2559 entity.object,
2560 tileShade,
2561 entity.bodyDualTint,
2562 flashStrength,
2563 wade,
2564 flashColor
2565 );
2566 }
2567 else
2568 {
2569 this.#syncLitSprite(entity.object, tileShade, flashStrength, wade, entity.bodyTint ?? null, flashColor);
2570 }
2571 const flight = !!entity.freeFlight;
2572 this.#placePivoted(entity.object, pivotX, pivotY, pivotY, SORT_ENTITY, entity.visualScale ?? 1, flight);
2573 for (let index = 0; index < (entity.overlays ?? []).length; index++)
2574 {
2575 const overlay = entity.overlays[index];
2576 const overlaySort = Math.min(SORT_HP_BAR - 2, SORT_ENTITY + 1 + index);
2577 overlay.transform.rotation = walkTilt;
2578 const dualTint = entity.overlayDualTints?.[index] ?? null;
2579 if (dualTint)
2580 {
2581 this.#syncDualTintLitSprite(overlay, tileShade, dualTint, flashStrength, wade, flashColor);
2582 }
2583 else if (entity.overlayTightFit?.[index])
2584 {
2585 this.#syncTightFitLitSprite(
2586 overlay,
2587 entity,
2588 tileShade,
2589 flashStrength,
2590 wade,
2591 entity.overlayTints?.[index] ?? null,
2592 flashColor
2593 );
2594 }
2595 else
2596 {
2597 this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null, flashColor);
2598 }
2599 this.#placePivoted(overlay, pivotX, pivotY, pivotY, overlaySort, entity.visualScale ?? 1, flight);
2600 }
2601 for (let index = 0; index < (entity.bloomOverlays ?? []).length; index++)
2602 {
2603 const overlay = entity.bloomOverlays[index];
2604 this.#setRendererVisible(overlay, this.bloomEnabled);
2605 if (!this.bloomEnabled)
2606 { continue; }
2607 /** Multi-frame body bloom locks to the base sprite; static bodies leave bloom free to animate. */
2608 if (entity.bloomBody && index === 0 && entity.object?.renderer)
2609 {
2610 const bodySprite = entity.object.renderer.sprite;
2611 const bloomSprite = overlay.renderer.sprite;
2612 const bodyFrames = Number(bodySprite?.subImages) || Number(bodySprite?.subImgTotal) || 1;
2613 const bloomFrames = Number(bloomSprite?.subImages) || Number(bloomSprite?.subImgTotal) || 1;
2614 if (bodyFrames > 1 && bloomFrames === bodyFrames)
2615 {
2616 overlay.renderer.cycle = null;
2617 overlay.renderer.subImage = entity.object.renderer.subImage | 0;
2618 }
2619 }
2620 overlay.transform.rotation = walkTilt;
2621 const bloomDual = entity.bloomOverlayDualTints?.[index] ?? null;
2622 const bloomTint = entity.bloomOverlayTints?.[index] ?? entity.bodyTint ?? null;
2623 if (bloomDual)
2624 { this.#syncDualTintLitSprite(overlay, 0, bloomDual); }
2625 else if (bloomTint)
2626 { this.#syncUnlitTintSprite(overlay, bloomTint); }
2627 else
2628 { this.#markUnlit(overlay); }
2629 this.#placePivoted(overlay, pivotX, pivotY, pivotY + 0.002, SORT_ENTITY, entity.visualScale ?? 1, flight);
2630 }
2631 this.#placeHpBar(entity, pivotX, pivotY);
2632 this.#placeSkullMarker(entity, pivotX, pivotY, tileShade);
2633 }
2634
2635 #markUnlit (object)
2636 {
2637 if (!object?.renderer)
2638 { return; }
2639 object._lit = false;
2640 object.renderer.shader = null;
2641 object.renderer.shaderUniforms = null;
2642 object.renderer.secondaryMap = null;
2643 }
2644
2645 /** Bloom / unlit overlays that still need magenta channel tint (e.g. elemental sprites). */
2646 #syncUnlitTintSprite (object, tintColor)
2647 {
2648 if (!object?.renderer || !tintColor)
2649 { return; }
2650 const tint = normalizeRgb(tintColor);
2651 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
2652 object.renderer.shader = getTintLitSpriteShader();
2653 object.renderer.shaderUniforms = {
2654 u_darkness: 0,
2655 u_strength: 0,
2656 u_flashColor: FLASH_COLOR_DAMAGE,
2657 u_wade: 0,
2658 u_spriteHeight: height,
2659 u_useTint: 1,
2660 u_tintColor: [tint.r, tint.g, tint.b]
2661 };
2662 object.renderer.secondaryMap = null;
2663 }
2664
2665 #syncLitSprite (object, darkness, flashStrength = 0, wade = false, tintColor = null, flashColor = null)
2666 {
2667 if (!object?.renderer || object._lit === false)
2668 { return; }
2669 object._lit = true;
2670 const dark = Math.min(1, Math.max(0, darkness ?? 0));
2671 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
2672 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
2673 const flashRgb = flashColor ?? FLASH_COLOR_DAMAGE;
2674 const tint = tintColor ? normalizeRgb(tintColor) : null;
2675 if (tint)
2676 {
2677 object.renderer.shader = getTintLitSpriteShader();
2678 object.renderer.shaderUniforms = {
2679 u_darkness: dark,
2680 u_strength: flash,
2681 u_flashColor: flashRgb,
2682 u_wade: wade ? 1 : 0,
2683 u_spriteHeight: height,
2684 u_useTint: 1,
2685 u_tintColor: [tint.r, tint.g, tint.b]
2686 };
2687 }
2688 else
2689 {
2690 object.renderer.shader = getSpriteLightingShader();
2691 object.renderer.shaderUniforms = {
2692 u_darkness: dark,
2693 u_strength: flash,
2694 u_flashColor: flashRgb,
2695 u_wade: wade ? 1 : 0,
2696 u_spriteHeight: height
2697 };
2698 }
2699 object.renderer.secondaryMap = null;
2700 }
2701
2702 #bodySecondaryMap (entity)
2703 {
2704 return entity?.object?.renderer?.sprite?.g_image ?? null;
2705 }
2706
2707 #tightFitMaskUniforms (overlay, entity)
2708 {
2709 const bodyRenderer = entity?.object?.renderer;
2710 const clothRenderer = overlay?.renderer;
2711 const bodySprite = bodyRenderer?.sprite;
2712 const clothSprite = clothRenderer?.sprite;
2713 if (!bodySprite || !clothSprite)
2714 { return null; }
2715 const clothUv = clothSprite.getUvRect?.(clothRenderer.subImage | 0)
2716 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
2717 const bodyUv = bodySprite.getUvRect?.(bodyRenderer.subImage | 0)
2718 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
2719 return {
2720 u_clothSize: [clothSprite.width || SPRITE_SIZE_PX, clothSprite.height || SPRITE_SIZE_PX],
2721 u_bodySize: [bodySprite.width || SPRITE_SIZE_PX, bodySprite.height || SPRITE_SIZE_PX],
2722 u_pivotFromBottom: PIVOT_FROM_BOTTOM_PX,
2723 u_clothUvRect: [clothUv.u0, clothUv.v0, clothUv.u1, clothUv.v1],
2724 u_bodyUvRect: [bodyUv.u0, bodyUv.v0, bodyUv.u1, bodyUv.v1]
2725 };
2726 }
2727
2728 #syncTightFitLitSprite (overlay, entity, darkness, flashStrength = 0, wade = false, tintColor = null, flashColor = null)
2729 {
2730 if (!overlay?.renderer || entity?.object?.renderer == null)
2731 { return; }
2732 const bodyMap = this.#bodySecondaryMap(entity);
2733 const maskUniforms = this.#tightFitMaskUniforms(overlay, entity);
2734 const flashRgb = flashColor ?? FLASH_COLOR_DAMAGE;
2735 if (!bodyMap || !maskUniforms)
2736 {
2737 this.#syncLitSprite(overlay, darkness, flashStrength, wade, tintColor, flashRgb);
2738 return;
2739 }
2740 overlay._lit = true;
2741 const dark = Math.min(1, Math.max(0, darkness ?? 0));
2742 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
2743 const height = overlay.renderer.sprite?.height ?? SPRITE_SIZE_PX;
2744 const tint = tintColor ? normalizeRgb(tintColor) : null;
2745 overlay.renderer.secondaryMap = bodyMap;
2746 if (tint)
2747 {
2748 overlay.renderer.shader = getTightFitTintLitSpriteShader();
2749 overlay.renderer.shaderUniforms = {
2750 u_darkness: dark,
2751 u_strength: flash,
2752 u_flashColor: flashRgb,
2753 u_wade: wade ? 1 : 0,
2754 u_spriteHeight: height,
2755 u_useTint: 1,
2756 u_tintColor: [tint.r, tint.g, tint.b],
2757 ...maskUniforms
2758 };
2759 }
2760 else
2761 {
2762 overlay.renderer.shader = getTightFitLitSpriteShader();
2763 overlay.renderer.shaderUniforms = {
2764 u_darkness: dark,
2765 u_strength: flash,
2766 u_flashColor: flashRgb,
2767 u_wade: wade ? 1 : 0,
2768 u_spriteHeight: height,
2769 ...maskUniforms
2770 };
2771 }
2772 }
2773
2774 #syncDualTintLitSprite (object, darkness, dualTint, flashStrength = 0, wade = false, flashColor = null)
2775 {
2776 if (!object?.renderer || !dualTint)
2777 { return; }
2778 const shaft = normalizeRgb(dualTint.shaft);
2779 const tip = normalizeRgb(dualTint.tip);
2780 const coat = dualTint.coat ? normalizeRgb(dualTint.coat) : null;
2781 const dark = object._lit === false
2782 ? 0
2783 : Math.min(1, Math.max(0, darkness ?? 0));
2784 if (object._lit !== false)
2785 { object._lit = true; }
2786 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
2787 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
2788 object.renderer.shader = getDualTintLitSpriteShader();
2789 object.renderer.shaderUniforms = {
2790 u_darkness: dark,
2791 u_strength: flash,
2792 u_flashColor: flashColor ?? FLASH_COLOR_DAMAGE,
2793 u_wade: wade ? 1 : 0,
2794 u_spriteHeight: height,
2795 u_shaftTint: [shaft.r, shaft.g, shaft.b],
2796 u_tipTint: [tip.r, tip.g, tip.b],
2797 u_coatTint: coat ? [coat.r, coat.g, coat.b] : [0, 0, 0],
2798 u_hasCoat: coat ? 1 : 0
2799 };
2800 object.renderer.secondaryMap = null;
2801 }
2802
2803 #syncGroundItemSprite (item, darkness)
2804 {
2805 if (item?.dualTint)
2806 {
2807 this.#syncDualTintLitSprite(item.object, darkness, item.dualTint);
2808 return;
2809 }
2810 this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null);
2811 }
2812
2813 #groundTypeAt (tileX, tileY)
2814 {
2815 const ground = this.#groundAtTile(tileX, tileY);
2816 return ground == null ? null : normalizeGround(ground).typeId;
2817 }
2818
2819 /** Ground entry at a world tile, including editor hover preview when present. */
2820 #groundAtTile (tileX, tileY)
2821 {
2822 if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY
2823 && this.preview.ground !== undefined)
2824 { return this.preview.ground; }
2825 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2826 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2827 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
2828 if (!snapshot)
2829 { return null; }
2830 const localX = tileX - chunkX * CHUNK_SIZE;
2831 const localY = tileY - chunkY * CHUNK_SIZE;
2832 const index = localY * CHUNK_SIZE + localX;
2833 return snapshot.grounds?.[index] ?? null;
2834 }
2835
2836 #waterCoastEdges (tileX, tileY)
2837 {
2838 const season = this.worldSeason;
2839 return {
2840 n: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY - 1), season) ? 1 : 0,
2841 e: !isLiquidWaterGround(this.#groundTypeAt(tileX + 1, tileY), season) ? 1 : 0,
2842 s: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY + 1), season) ? 1 : 0,
2843 w: !isLiquidWaterGround(this.#groundTypeAt(tileX - 1, tileY), season) ? 1 : 0
2844 };
2845 }
2846
2847 #syncWaterGroundSprite (object, corners, ambientDark, edges, timeSec, fallbackLit = 1)
2848 {
2849 if (!object?.renderer)
2850 { return; }
2851 const lit = corners ?? {
2852 nw: fallbackLit,
2853 ne: fallbackLit,
2854 sw: fallbackLit,
2855 se: fallbackLit
2856 };
2857 const dark = Math.min(1, Math.max(0, ambientDark ?? 0));
2858 object._lit = true;
2859 object.renderer.shader = getWaterGroundShader();
2860 object.renderer.secondaryMap = null;
2861 object.renderer.shaderUniforms = {
2862 u_ambientDark: dark,
2863 u_litNW: lit.nw,
2864 u_litNE: lit.ne,
2865 u_litSW: lit.sw,
2866 u_litSE: lit.se,
2867 u_time: timeSec,
2868 u_edgeN: edges?.n ?? 0,
2869 u_edgeE: edges?.e ?? 0,
2870 u_edgeS: edges?.s ?? 0,
2871 u_edgeW: edges?.w ?? 0
2872 };
2873 }
2874
2875 /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. */
2876 #syncGroundWaterFx (objects, ambientDark, timeSec, baked = null)
2877 {
2878 if (!objects?.ground)
2879 { return; }
2880 if (!isLiquidWaterGround(objects.groundTypeId, this.worldSeason))
2881 {
2882 objects.waterEdges = null;
2883 this.#syncLitSprite(objects.ground, objects.shadeAlpha ?? 0);
2884 return;
2885 }
2886 const fallbackLit = 1 - (objects.shadeAlpha ?? 0);
2887 const chunkX = Math.floor(objects.tileX / CHUNK_SIZE);
2888 const chunkY = Math.floor(objects.tileY / CHUNK_SIZE);
2889 const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`);
2890 const localX = objects.tileX - chunkX * CHUNK_SIZE;
2891 const localY = objects.tileY - chunkY * CHUNK_SIZE;
2892 let litCorners = null;
2893 if (chunkBaked)
2894 {
2895 if (this.lightingMode === "simple")
2896 {
2897 const gridW = CHUNK_SIZE + 2;
2898 const intensity = chunkBaked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? fallbackLit;
2899 litCorners = { nw: intensity, ne: intensity, sw: intensity, se: intensity };
2900 }
2901 else
2902 { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); }
2903 }
2904 objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
2905 this.#syncWaterGroundSprite(
2906 objects.ground,
2907 litCorners,
2908 ambientDark,
2909 objects.waterEdges,
2910 timeSec,
2911 fallbackLit
2912 );
2913 }
2914
2915 #ambientDarkness ()
2916 {
2917 const hour = this.nightPreview ?? this.worldHour;
2918 const calendar = nightFactor(hour, this.settings.nightDarkness);
2919 let dark = resolveDimensionDarknessFactor(this.dimensionLightingMode, calendar);
2920 if (dark == null)
2921 { dark = calendar; }
2922 if (this.localBlind)
2923 { dark = Math.min(1, dark + 0.85); }
2924 return dark;
2925 }
2926
2927 setLocalBlind (blind)
2928 {
2929 this.localBlind = !!blind;
2930 }
2931
2932 /** Soft vision bubble while blinded (client-only; stacks with ambient). */
2933 #blindVisionLight ()
2934 {
2935 if (!this.localBlind)
2936 { return null; }
2937 const local = this.entities.get(this.localEntityId);
2938 if (!local)
2939 { return null; }
2940 const tileSize = this.tileSize();
2941 return {
2942 tileX: Math.floor(local.visualX / tileSize),
2943 tileY: Math.floor(local.visualY / tileSize),
2944 range: 2.25,
2945 intensity: 1
2946 };
2947 }
2948
2949 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY, dualTint = null)
2950 {
2951 const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;
2952 const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0;
2953 const dark = (fromAlpha + toAlpha) / 2;
2954 if (dualTint)
2955 {
2956 this.#syncDualTintLitSprite(object, dark, dualTint);
2957 return;
2958 }
2959 this.#syncLitSprite(object, dark);
2960 }
2961
2962 #dualTintFromPayload (payload)
2963 {
2964 if (!payload?.shaftTint || !payload?.tipTint)
2965 { return null; }
2966 return {
2967 shaft: payload.shaftTint,
2968 tip: payload.tipTint,
2969 ...(payload.coatTint ? { coat: payload.coatTint } : {})
2970 };
2971 }
2972
2973 #syncHpBar (entity)
2974 {
2975 const current = entity.health;
2976 const max = entity.maxHealth;
2977 const show = current != null
2978 && max != null
2979 && max > 0
2980 && current < max;
2981 if (!show)
2982 {
2983 entity.hpBar?.destroy();
2984 entity.hpBar = null;
2985 entity.hpBarCanvas = null;
2986 return;
2987 }
2988 if (!entity.hpBarCanvas)
2989 {
2990 entity.hpBarCanvas = document.createElement("canvas");
2991 entity.hpBarCanvas.width = HP_BAR_W;
2992 entity.hpBarCanvas.height = HP_BAR_H;
2993 const image = frameworkImageFromCanvas(entity.hpBarCanvas);
2994 entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR);
2995 this.#markUnlit(entity.hpBar);
2996 this.scene.addObject(entity.hpBar);
2997 }
2998 drawHpBar(entity.hpBarCanvas, current, max);
2999 invalidateCanvasTexture(this.scene, entity.hpBarCanvas);
3000 }
3001
3002 #placeHpBar (entity, pivotX, pivotY)
3003 {
3004 if (!entity.hpBar)
3005 { return; }
3006 const sprite = entity.object?.renderer?.sprite;
3007 if (!sprite)
3008 { return; }
3009 const zoom = this.zoom;
3010 const drawH = sprite.height * zoom;
3011 const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom);
3012 const spriteTop = centerY - drawH / 2;
3013 const barW = HP_BAR_W * zoom;
3014 const barH = HP_BAR_H * zoom;
3015 entity.hpBar.transform.position.x = pivotX;
3016 entity.hpBar.transform.position.y = spriteTop - barH / 2;
3017 entity.hpBar.transform.size = new vector(barW, barH);
3018 entity.hpBar.layer = ySortLayer(pivotY, SORT_HP_BAR);
3019 this.#markSortDirty();
3020 }
3021
3022 #syncSkullMarker (entity)
3023 {
3024 if (!entity?.characterId)
3025 {
3026 entity.skullMarker?.destroy();
3027 entity.skullMarker = null;
3028 return;
3029 }
3030 const tint = skullTintColor(entity.skullValue | 0);
3031 if (!tint)
3032 {
3033 entity.skullMarker?.destroy();
3034 entity.skullMarker = null;
3035 return;
3036 }
3037 const image = this.game.images[SKULL_SPRITE]
3038 ?? this.game.images["item:skull:skull"];
3039 if (!image)
3040 { return; }
3041 if (!entity.skullMarker)
3042 {
3043 entity.skullMarker = new GameObject(0, 0, image, SORT_HP_BAR);
3044 this.scene.addObject(entity.skullMarker);
3045 }
3046 entity.skullTint = tint;
3047 entity.skullMarker.renderer.sprite = image;
3048 }
3049
3050 /**
3051 * Bottom edge of the skull sprite sits exactly on the character sprite's top edge.
3052 */
3053 #placeSkullMarker (entity, pivotX, pivotY, darkness)
3054 {
3055 this.#syncSkullMarker(entity);
3056 if (!entity.skullMarker)
3057 { return; }
3058 const body = entity.object?.renderer?.sprite;
3059 const skull = entity.skullMarker.renderer?.sprite;
3060 if (!body || !skull)
3061 { return; }
3062 const zoom = this.zoom;
3063 const scale = entity.visualScale ?? 1;
3064 const bodyH = body.height * zoom * scale;
3065 const skullH = skull.height * zoom;
3066 const skullW = skull.width * zoom;
3067 const bodyCenterY = pivotY - (bodyH / 2 - PIVOT_FROM_BOTTOM_PX * zoom * scale);
3068 const bodyTop = bodyCenterY - bodyH / 2;
3069 // GameObject position is sprite center; bottom of skull at bodyTop ⇒ center at bodyTop - skullH/2
3070 entity.skullMarker.transform.position.x = pivotX;
3071 entity.skullMarker.transform.position.y = bodyTop - skullH / 2;
3072 entity.skullMarker.transform.size = new vector(skullW, skullH);
3073 entity.skullMarker.layer = ySortLayer(pivotY, SORT_HP_BAR);
3074 this.#syncLitSprite(entity.skullMarker, darkness, 0, false, entity.skullTint);
3075 this.#markSortDirty();
3076 }
3077
3078 #rebuildChunk (snapshot, { refreshSoftNeighbors = true } = {})
3079 {
3080 this.#bakeAndPlaceChunk(snapshot);
3081 this.#relayoutChunkTiles(snapshot);
3082 if (this.softTerrain && refreshSoftNeighbors)
3083 { this.#rebuildSoftTerrainNeighborChunks(snapshot); }
3084 }
3085
3086 #relayoutChunk (snapshot)
3087 {
3088 this.#layoutBakedChunk(snapshot);
3089 this.#relayoutChunkTiles(snapshot);
3090 }
3091
3092 #relayoutChunkTiles (snapshot)
3093 {
3094 for (let localY = 0; localY < CHUNK_SIZE; localY++)
3095 {
3096 for (let localX = 0; localX < CHUNK_SIZE; localX++)
3097 {
3098 const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
3099 const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
3100 this.#drawTile(tileX, tileY);
3101 }
3102 }
3103 }
3104
3105 #scheduleChunkRebuild (snapshot)
3106 {
3107 if (!snapshot)
3108 { return; }
3109 this.#chunkRebuildKeys.add(`${snapshot.chunkX},${snapshot.chunkY}`);
3110 this.#cancelIdlePrefetch();
3111 this.#ensureChunkFlushScheduled();
3112 }
3113
3114 #scheduleEdgeRebuild ()
3115 {
3116 this.#edgesDirty = true;
3117 this.#cancelIdlePrefetch();
3118 this.#ensureChunkFlushScheduled();
3119 }
3120
3121 #ensureChunkFlushScheduled ()
3122 {
3123 if (this.#chunkRebuildRaf)
3124 { return; }
3125 this.#cancelIdlePrefetch();
3126 this.#chunkRebuildRaf = requestAnimationFrame(() => this.#flushChunkWork());
3127 }
3128
3129 #notePlayerTile (tileX, tileY)
3130 {
3131 const chunkX = Math.floor(tileX / CHUNK_SIZE);
3132 const chunkY = Math.floor(tileY / CHUNK_SIZE);
3133 const prevX = this.#playerChunkX;
3134 const prevY = this.#playerChunkY;
3135 if (prevX != null
3136 && (chunkX !== prevX || chunkY !== prevY))
3137 {
3138 const dx = chunkX - prevX;
3139 const dy = chunkY - prevY;
3140 if (dx !== 0)
3141 { this.#playerMoveChunkDx = Math.sign(dx); }
3142 if (dy !== 0)
3143 { this.#playerMoveChunkDy = Math.sign(dy); }
3144 this.#onActiveLightingCenterChanged(prevX, prevY, chunkX, chunkY);
3145 }
3146 this.#playerChunkX = chunkX;
3147 this.#playerChunkY = chunkY;
3148 }
3149
3150 /** When the 3×3 lighting center moves: refresh door sprites (resting vs live) and lightmaps. */
3151 #onActiveLightingCenterChanged (prevChunkX, prevChunkY, chunkX, chunkY)
3152 {
3153 this.#invalidateNeighborLightmapCaches(prevChunkX, prevChunkY);
3154 this.#invalidateNeighborLightmapCaches(chunkX, chunkY);
3155 const doorChunks = new Set();
3156 for (const [cx, cy] of [[prevChunkX, prevChunkY], [chunkX, chunkY]])
3157 {
3158 for (let dy = -1; dy <= 1; dy++)
3159 {
3160 for (let dx = -1; dx <= 1; dx++)
3161 { doorChunks.add(`${cx + dx},${cy + dy}`); }
3162 }
3163 }
3164 for (const key of doorChunks)
3165 {
3166 const [cx, cy] = key.split(",").map(Number);
3167 this.#redrawDoorTilesInChunk(cx, cy);
3168 }
3169 }
3170
3171 #redrawDoorTilesInChunk (chunkX, chunkY)
3172 {
3173 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
3174 if (!snapshot?.blocks)
3175 { return; }
3176 for (let localY = 0; localY < CHUNK_SIZE; localY++)
3177 {
3178 for (let localX = 0; localX < CHUNK_SIZE; localX++)
3179 {
3180 const block = snapshot.blocks[localY * CHUNK_SIZE + localX];
3181 if (!blockDefinition(block?.typeId)?.door)
3182 { continue; }
3183 this.#drawTile(chunkX * CHUNK_SIZE + localX, chunkY * CHUNK_SIZE + localY);
3184 }
3185 }
3186 }
3187
3188 #playerChunkCoords ()
3189 {
3190 const local = this.entities.get(this.localEntityId);
3191 if (local)
3192 {
3193 return {
3194 chunkX: Math.floor(local.tileX / CHUNK_SIZE),
3195 chunkY: Math.floor(local.tileY / CHUNK_SIZE)
3196 };
3197 }
3198 if (this.#playerChunkX != null && this.#playerChunkY != null)
3199 {
3200 return { chunkX: this.#playerChunkX, chunkY: this.#playerChunkY };
3201 }
3202 return null;
3203 }
3204
3205 /** Lower score = bake sooner in urgent mode; idle mode inverts distance. */
3206 #chunkRebuildScore (key, mode = "urgent")
3207 {
3208 const [chunkX, chunkY] = key.split(",").map(Number);
3209 const player = this.#playerChunkCoords();
3210 if (!player)
3211 { return 0; }
3212 const dx = chunkX - player.chunkX;
3213 const dy = chunkY - player.chunkY;
3214 const dist = Math.abs(dx) + Math.abs(dy);
3215 let ahead = 0;
3216 if (this.#playerMoveChunkDx !== 0 || this.#playerMoveChunkDy !== 0)
3217 { ahead = dx * this.#playerMoveChunkDx + dy * this.#playerMoveChunkDy; }
3218 if (mode === "idle")
3219 {
3220 return -dist * 10 + (ahead > 0 ? -ahead * 2 : Math.max(ahead, 0));
3221 }
3222 return dist * 10 - Math.max(0, ahead) * 3;
3223 }
3224
3225 #sortedChunkRebuildKeys (mode = "urgent")
3226 {
3227 return [...this.#chunkRebuildKeys].sort((a, b) =>
3228 this.#chunkRebuildScore(a, mode) - this.#chunkRebuildScore(b, mode));
3229 }
3230
3231 #discoverUnbakedChunks ()
3232 {
3233 for (const key of this.chunks.keys())
3234 {
3235 if (!this.bakedChunks.has(key))
3236 { this.#chunkRebuildKeys.add(key); }
3237 }
3238 }
3239
3240 #hasUnbakedChunks ()
3241 {
3242 for (const key of this.chunks.keys())
3243 {
3244 if (!this.bakedChunks.has(key))
3245 { return true; }
3246 }
3247 return false;
3248 }
3249
3250 #pickIdlePrefetchSnapshot ()
3251 {
3252 let best = null;
3253 let bestScore = Infinity;
3254 for (const snapshot of this.chunks.values())
3255 {
3256 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
3257 if (this.bakedChunks.has(key) || this.#chunkRebuildKeys.has(key))
3258 { continue; }
3259 const score = this.#chunkRebuildScore(key, "idle");
3260 if (score < bestScore)
3261 {
3262 bestScore = score;
3263 best = snapshot;
3264 }
3265 }
3266 return best;
3267 }
3268
3269 #cancelIdlePrefetch ()
3270 {
3271 if (this.#idlePrefetchId && typeof cancelIdleCallback === "function")
3272 { cancelIdleCallback(this.#idlePrefetchId); }
3273 this.#idlePrefetchId = 0;
3274 }
3275
3276 #scheduleIdleChunkPrefetch ()
3277 {
3278 if (this.#idlePrefetchId || this.#chunkRebuildRaf || this.#chunkRebuildKeys.size)
3279 { return; }
3280 if (typeof requestIdleCallback !== "function")
3281 { return; }
3282 if (!this.#hasUnbakedChunks())
3283 { return; }
3284 this.#idlePrefetchId = requestIdleCallback(
3285 (deadline) => this.#runIdleChunkPrefetch(deadline),
3286 { timeout: 2500 }
3287 );
3288 }
3289
3290 #runIdleChunkPrefetch (deadline)
3291 {
3292 this.#idlePrefetchId = 0;
3293 if (this.#chunkRebuildRaf || this.#chunkRebuildKeys.size)
3294 { return; }
3295 this.#discoverUnbakedChunks();
3296 if (this.#chunkRebuildKeys.size)
3297 {
3298 this.#ensureChunkFlushScheduled();
3299 return;
3300 }
3301 const snapshot = this.#pickIdlePrefetchSnapshot();
3302 if (!snapshot)
3303 { return; }
3304 if (deadline.timeRemaining() <= 4 && !deadline.didTimeout)
3305 {
3306 this.#scheduleIdleChunkPrefetch();
3307 return;
3308 }
3309 this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false });
3310 if (this.#hasUnbakedChunks())
3311 { this.#scheduleIdleChunkPrefetch(); }
3312 }
3313
3314 #flushChunkWork ()
3315 {
3316 this.#chunkRebuildRaf = 0;
3317 const keys = this.#sortedChunkRebuildKeys("urgent");
3318 const batch = keys.slice(0, this.#CHUNK_REBUILD_BATCH);
3319 const rest = keys.slice(this.#CHUNK_REBUILD_BATCH);
3320 this.#chunkRebuildKeys.clear();
3321 for (const key of rest)
3322 { this.#chunkRebuildKeys.add(key); }
3323 for (const key of batch)
3324 {
3325 const snap = this.chunks.get(key);
3326 if (snap)
3327 { this.#rebuildChunk(snap, { refreshSoftNeighbors: false }); }
3328 }
3329 if (this.#chunkRebuildKeys.size)
3330 {
3331 this.#ensureChunkFlushScheduled();
3332 return;
3333 }
3334 if (this.#edgesDirty)
3335 {
3336 this.#rebuildAllEdges();
3337 this.#edgesDirty = false;
3338 }
3339 this.#scheduleIdleChunkPrefetch();
3340 }
3341
3342 #previewEqual (a, b)
3343 {
3344 if (a === b)
3345 { return true; }
3346 if (!a || !b)
3347 { return false; }
3348 return a.tileX === b.tileX
3349 && a.tileY === b.tileY
3350 && this.#previewPart(a.ground) === this.#previewPart(b.ground)
3351 && this.#previewPart(a.block) === this.#previewPart(b.block);
3352 }
3353
3354 #previewPart (value)
3355 {
3356 return value === undefined ? undefined : JSON.stringify(value);
3357 }
3358
3359 #rebuildSoftTerrainNeighborChunks (snapshot)
3360 {
3361 for (let dy = -1; dy <= 1; dy++)
3362 {
3363 for (let dx = -1; dx <= 1; dx++)
3364 {
3365 if (dx === 0 && dy === 0)
3366 { continue; }
3367 const neighbor = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
3368 if (neighbor)
3369 { this.#rebuildChunk(neighbor, { refreshSoftNeighbors: false }); }
3370 }
3371 }
3372 }
3373
3374 #rebakeAllChunks ()
3375 {
3376 for (const snapshot of this.chunks.values())
3377 { this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false }); }
3378 }
3379
3380 #bakeAndPlaceChunk (snapshot)
3381 {
3382 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
3383 const atlases = bakeChunkAtlases({
3384 snapshot,
3385 catalog: this.catalog,
3386 images: this.game.images,
3387 preview: this.preview,
3388 season: this.worldSeason,
3389 softTerrain: this.softTerrain,
3390 resolveGround: (tileX, tileY) => this.#groundAtTile(tileX, tileY),
3391 cache: this.#atlasCache
3392 });
3393 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
3394 let baked = this.bakedChunks.get(key);
3395 this.#releaseBakedAtlasRefs(baked);
3396
3397 const groundImage = this.#atlasCache.getImage(atlases.cacheRefs?.ground);
3398 const blockImages = atlases.cacheRefs?.blockRows.map((entry) => this.#atlasCache.getImage(entry))
3399 ?? atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas));
3400 const bloomImage = this.#atlasCache.getImage(atlases.cacheRefs?.bloom)
3401 ?? frameworkImageFromCanvas(atlases.bloom);
3402
3403 if (!baked)
3404 {
3405 const lightmapCanvas = makeLightmapCanvas(atlasPx);
3406 baked = {
3407 groundCanvas: atlases.ground,
3408 blockCanvases: atlases.blockRows,
3409 bloomCanvas: atlases.bloom,
3410 lightmapCanvas,
3411 groundImage,
3412 blockImages,
3413 bloomImage,
3414 lightmapImage: frameworkImageFromCanvas(lightmapCanvas),
3415 groundObject: null,
3416 blockObjects: [],
3417 bloomObject: null,
3418 tallBlocks: atlases.tallBlocks,
3419 animatedGrounds: atlases.animatedGrounds,
3420 lightmapPixels: null,
3421 atlasCacheRefs: atlases.cacheRefs
3422 };
3423 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
3424 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1);
3425 this.scene.addObject(baked.groundObject);
3426 for (let row = 0; row < CHUNK_SIZE; row++)
3427 {
3428 const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
3429 this.#applyAtlasLighting(object, baked.lightmapImage, row);
3430 this.scene.addObject(object);
3431 baked.blockObjects.push(object);
3432 }
3433 baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK);
3434 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
3435 this.#markUnlit(baked.bloomObject);
3436 this.scene.addObject(baked.bloomObject);
3437 this.bakedChunks.set(key, baked);
3438 }
3439 else
3440 {
3441 if (baked.groundCanvas !== atlases.ground)
3442 {
3443 baked.groundCanvas = atlases.ground;
3444 baked.groundImage = groundImage;
3445 baked.groundObject.renderer.sprite = groundImage;
3446 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1);
3447 }
3448 for (let row = 0; row < CHUNK_SIZE; row++)
3449 {
3450 if (baked.blockCanvases[row] !== atlases.blockRows[row])
3451 {
3452 baked.blockCanvases[row] = atlases.blockRows[row];
3453 baked.blockImages[row] = blockImages[row];
3454 baked.blockObjects[row].renderer.sprite = blockImages[row];
3455 }
3456 this.#applyAtlasLighting(
3457 baked.blockObjects[row],
3458 baked.lightmapImage,
3459 row
3460 );
3461 }
3462 if (baked.bloomCanvas !== atlases.bloom)
3463 {
3464 baked.bloomCanvas = atlases.bloom;
3465 baked.bloomImage = bloomImage;
3466 baked.bloomObject.renderer.sprite = bloomImage;
3467 }
3468 baked.tallBlocks = atlases.tallBlocks;
3469 baked.animatedGrounds = atlases.animatedGrounds;
3470 baked.atlasCacheRefs = atlases.cacheRefs;
3471 }
3472 baked.chunkX = snapshot.chunkX;
3473 baked.chunkY = snapshot.chunkY;
3474 baked.lightmapCacheKey = null;
3475 this.#invalidateNeighborLightmapCaches(snapshot.chunkX, snapshot.chunkY);
3476 this.#layoutBakedChunk(snapshot);
3477 this.#queueBakedChunkTextures(baked, snapshot.chunkX, snapshot.chunkY);
3478 }
3479
3480 #releaseBakedAtlasRefs (baked)
3481 {
3482 if (!baked?.atlasCacheRefs)
3483 { return; }
3484 this.#atlasCache.release(baked.atlasCacheRefs.ground);
3485 for (const entry of baked.atlasCacheRefs.blockRows ?? [])
3486 { this.#atlasCache.release(entry); }
3487 this.#atlasCache.release(baked.atlasCacheRefs.bloom);
3488 baked.atlasCacheRefs = null;
3489 }
3490
3491 #chunkTextureWarmPriority (chunkX, chunkY)
3492 {
3493 const local = this.entities.get(this.localEntityId);
3494 if (!local)
3495 { return 999; }
3496 const playerChunkX = Math.floor(local.tileX / CHUNK_SIZE);
3497 const playerChunkY = Math.floor(local.tileY / CHUNK_SIZE);
3498 return Math.abs(chunkX - playerChunkX) + Math.abs(chunkY - playerChunkY);
3499 }
3500
3501 #queueCanvasTextureWarm (canvas, chunkX, chunkY)
3502 {
3503 if (!canvas || this.#pendingTextureCanvasSet.has(canvas))
3504 { return; }
3505 this.#pendingTextureCanvasSet.add(canvas);
3506 this.#pendingTextureCanvases.push({
3507 canvas,
3508 priority: this.#chunkTextureWarmPriority(chunkX, chunkY)
3509 });
3510 this.#scheduleTextureWarm();
3511 }
3512
3513 #queueBakedChunkTextures (baked, chunkX, chunkY)
3514 {
3515 if (!baked)
3516 { return; }
3517 const refs = baked.atlasCacheRefs;
3518 const maybeWarm = (canvas, entry) =>
3519 {
3520 if (!canvas)
3521 { return; }
3522 if (entry && this.#atlasCache.isWarmed(canvas))
3523 { return; }
3524 this.#queueCanvasTextureWarm(canvas, chunkX, chunkY);
3525 };
3526 maybeWarm(baked.groundCanvas, refs?.ground);
3527 for (let row = 0; row < (baked.blockCanvases ?? []).length; row++)
3528 { maybeWarm(baked.blockCanvases[row], refs?.blockRows?.[row]); }
3529 maybeWarm(baked.bloomCanvas, refs?.bloom);
3530 this.#queueCanvasTextureWarm(baked.lightmapCanvas, chunkX, chunkY);
3531 }
3532
3533 #scheduleTextureWarm ()
3534 {
3535 if (this.#textureWarmRaf)
3536 { return; }
3537 this.#textureWarmRaf = requestAnimationFrame(() => this.#flushTextureWarm());
3538 }
3539
3540 #flushTextureWarm ()
3541 {
3542 this.#textureWarmRaf = 0;
3543 if (!this.#pendingTextureCanvases.length)
3544 { return; }
3545 this.#pendingTextureCanvases.sort((a, b) => a.priority - b.priority);
3546 const batch = this.#pendingTextureCanvases.splice(0, this.#TEXTURE_WARM_BATCH);
3547 for (const entry of batch)
3548 {
3549 this.#pendingTextureCanvasSet.delete(entry.canvas);
3550 setNearestFilter(this.scene, entry.canvas);
3551 this.#atlasCache.markWarmed(entry.canvas);
3552 }
3553 if (this.#pendingTextureCanvases.length)
3554 { this.#scheduleTextureWarm(); }
3555 }
3556
3557 #applyAtlasLighting (object, lightmapImage, lightRow)
3558 {
3559 if (!object?.renderer)
3560 { return; }
3561 object._lit = true;
3562 object.renderer.shader = getAtlasLightingShader();
3563 object.renderer.bumpMap = null;
3564 object.renderer.secondaryMap = lightmapImage;
3565 object.renderer.shaderUniforms = {
3566 u_ambientDark: 0,
3567 u_lightRow: lightRow
3568 };
3569 }
3570
3571 #syncCliffGroundTopSprite (object, darkness, groundImage, localX, localY)
3572 {
3573 if (!object?.renderer)
3574 { return; }
3575 object._lit = true;
3576 const dark = Math.min(1, Math.max(0, darkness ?? 0));
3577 object.renderer.shader = getCliffGroundTopShader();
3578 object.renderer.bumpMap = groundImage ?? null;
3579 object.renderer.secondaryMap = null;
3580 object.renderer.shaderUniforms = {
3581 u_darkness: dark,
3582 u_tileLocal: [localX, localY]
3583 };
3584 }
3585
3586 #layoutBakedChunk (snapshot)
3587 {
3588 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
3589 const baked = this.bakedChunks.get(key);
3590 if (!baked)
3591 { return; }
3592 const size = this.tileSize();
3593 const left = snapshot.chunkX * CHUNK_SIZE * size;
3594 const top = snapshot.chunkY * CHUNK_SIZE * size;
3595 const chunkPx = CHUNK_SIZE * size;
3596 baked.groundObject.transform.position.x = left + chunkPx / 2;
3597 baked.groundObject.transform.position.y = top + chunkPx / 2;
3598 baked.groundObject.transform.size = new vector(chunkPx, chunkPx);
3599 baked.groundObject.layer = LAYER_GROUND;
3600
3601 for (let row = 0; row < CHUNK_SIZE; row++)
3602 {
3603 const object = baked.blockObjects[row];
3604 const rowY = top + row * size + size / 2;
3605 object.transform.position.x = left + chunkPx / 2;
3606 object.transform.position.y = rowY;
3607 object.transform.size = new vector(chunkPx, size);
3608 object.layer = ySortLayer(rowY, SORT_BLOCK);
3609 }
3610
3611 baked.bloomObject.transform.position.x = left + chunkPx / 2;
3612 baked.bloomObject.transform.position.y = top + chunkPx / 2;
3613 baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);
3614 baked.bloomObject.layer = ySortLayer(top + chunkPx, SORT_BLOCK);
3615 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
3616 this.#markSortDirty();
3617 }
3618
3619 #destroyBakedChunk (key)
3620 {
3621 const baked = this.bakedChunks.get(key);
3622 if (!baked)
3623 { return; }
3624 this.#releaseBakedAtlasRefs(baked);
3625 baked.groundObject?.destroy();
3626 for (const object of baked.blockObjects ?? [])
3627 { object.destroy(); }
3628 baked.bloomObject?.destroy();
3629 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
3630 this.bakedChunks.delete(key);
3631 }
3632
3633 #redrawPreview ()
3634 {
3635 if (!this.preview)
3636 { return; }
3637 const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`);
3638 if (snapshot)
3639 { this.#rebuildChunk(snapshot); }
3640 }
3641
3642 #refreshWaterCoastsNear (chunkX, chunkY)
3643 {
3644 const timeSec = performance.now() / 1000;
3645 for (const objects of this.tiles.values())
3646 {
3647 if (!objects.ground || !isWaterGround(objects.groundTypeId))
3648 { continue; }
3649 if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1)
3650 { continue; }
3651 // Light intensity grid is visible light (1 − shade); water shader uses ambient=1.
3652 this.#syncGroundWaterFx(objects, 1, timeSec);
3653 }
3654 }
3655
3656 #drawTile (tileX, tileY)
3657 {
3658 const chunkX = Math.floor(tileX / CHUNK_SIZE);
3659 const chunkY = Math.floor(tileY / CHUNK_SIZE);
3660 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
3661 if (!snapshot)
3662 { return; }
3663 const localX = tileX - chunkX * CHUNK_SIZE;
3664 const localY = tileY - chunkY * CHUNK_SIZE;
3665 const index = localY * CHUNK_SIZE + localX;
3666 const key = `${tileX},${tileY}`;
3667 let objects = this.tiles.get(key);
3668 if (!objects)
3669 {
3670 objects = { chunkX, chunkY, tileX, tileY };
3671 this.tiles.set(key, objects);
3672 }
3673 objects.tileX = tileX;
3674 objects.tileY = tileY;
3675 objects.chunkX = chunkX;
3676 objects.chunkY = chunkY;
3677 objects.light = snapshot.light[index] ?? 0;
3678
3679 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
3680 const animatedGround = (baked?.animatedGrounds ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
3681 if (animatedGround)
3682 {
3683 objects.ground = this.#ensureSprite(objects.ground, animatedGround.sprite, LAYER_GROUND);
3684 if (objects.ground)
3685 {
3686 const size = this.tileSize();
3687 objects.ground.transform.position.x = tileX * size + size / 2;
3688 objects.ground.transform.position.y = tileY * size + size / 2;
3689 objects.ground.transform.size = new vector(size, size);
3690 objects.ground.layer = LAYER_GROUND;
3691 objects.groundTypeId = animatedGround.typeId;
3692 this.#syncGroundWaterFx(objects, 1, performance.now() / 1000);
3693 this.#markSortDirty();
3694 }
3695 if (animatedGround.bloom)
3696 { objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, animatedGround.bloom, tilePivot(tileX, tileY, this.tileSize()), LAYER_GROUND); }
3697 else
3698 {
3699 objects.groundBloom?.destroy();
3700 objects.groundBloom = null;
3701 }
3702 }
3703 else
3704 {
3705 objects.ground?.destroy();
3706 objects.ground = null;
3707 objects.groundBloom?.destroy();
3708 objects.groundBloom = null;
3709 objects.groundTypeId = null;
3710 objects.waterEdges = null;
3711 }
3712
3713 let blockSource = snapshot.blocks[index];
3714 if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY && this.preview.block !== undefined)
3715 { blockSource = this.preview.block; }
3716 // Outer map ring: always show doors at resting (matches baked light; no entities there).
3717 if (
3718 blockSource
3719 && blockDefinition(blockSource.typeId)?.door
3720 && !this.#isActiveLightingChunk(chunkX, chunkY)
3721 )
3722 {
3723 const resting = doorRestingState(blockSource);
3724 if (resting && resting !== blockSource.state)
3725 { blockSource = { ...blockSource, state: resting }; }
3726 }
3727 const tileBlock = tileBlockSpriteEntry(
3728 this.catalog,
3729 this.game.images,
3730 blockSource,
3731 this.worldSeason
3732 );
3733 if (tileBlock)
3734 {
3735 const pivot = tilePivot(tileX, tileY, this.tileSize());
3736 const blockEntry = normalizeBlock(blockSource);
3737 const blockDef = blockDefinition(blockEntry?.typeId);
3738 const blockSort = blockDef?.door
3739 ? doorSortSubOrder(blockEntry?.state, SORT_ENTITY)
3740 : SORT_ENTITY;
3741 objects.block = this.#ensureSprite(objects.block, tileBlock.sprite, blockSort);
3742 objects.cliffGroundTop = !!blockDef?.cliffGroundTop;
3743 if (objects.block)
3744 {
3745 this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, blockSort);
3746 if (objects.cliffGroundTop)
3747 {
3748 const localX = ((tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE;
3749 const localY = ((tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE;
3750 this.#syncCliffGroundTopSprite(
3751 objects.block,
3752 objects.shadeAlpha ?? 0,
3753 baked?.groundImage ?? null,
3754 localX,
3755 localY
3756 );
3757 }
3758 else
3759 { this.#syncLitSprite(objects.block, objects.shadeAlpha ?? 0); }
3760 }
3761 objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tileBlock.bloom, pivot, SORT_ENTITY);
3762 }
3763 else
3764 {
3765 objects.block?.destroy();
3766 objects.block = null;
3767 objects.blockBloom?.destroy();
3768 objects.blockBloom = null;
3769 objects.cliffGroundTop = false;
3770 }
3771 }
3772
3773 #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK)
3774 {
3775 if (!name)
3776 {
3777 existing?.destroy();
3778 return null;
3779 }
3780 const object = this.#ensureSprite(existing, name, sortOrder);
3781 if (!object)
3782 { return null; }
3783 object.renderer.layer = RENDER_LAYER_BLOOM;
3784 this.#markUnlit(object);
3785 this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder);
3786 return object;
3787 }
3788
3789 #placePivoted (object, pivotX, pivotY, sortY, subOrder, scale = 1, flight = false)
3790 {
3791 const sprite = object?.renderer?.sprite;
3792 if (!sprite)
3793 { return; }
3794 const zoom = this.zoom;
3795 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
3796 const factor = Math.max(0.1, Number(scale) || 1);
3797 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height * factor, zoom);
3798 object.transform.position.x = center.x;
3799 object.transform.position.y = center.y;
3800 object.transform.size = new vector(draw.w * factor, draw.h * factor);
3801 object.layer = flight
3802 ? flightSortLayer(sortY, subOrder)
3803 : ySortLayer(sortY, subOrder);
3804 this.#markSortDirty();
3805 }
3806
3807 #ensureSprite (existing, name, layer)
3808 {
3809 const sprite = this.game.images[name];
3810 if (!sprite)
3811 {
3812 existing?.destroy();
3813 return null;
3814 }
3815 if (!existing || existing.renderer.sprite !== sprite)
3816 {
3817 existing?.destroy();
3818 existing = new GameObject(0, 0, sprite, layer);
3819 this.#syncLitSprite(existing, 0);
3820 this.scene.addObject(existing);
3821 this.#startIdleAnimation(existing);
3822 }
3823 return existing;
3824 }
3825
3826 #startIdleAnimation (object)
3827 {
3828 const sprite = object?.renderer?.sprite;
3829 if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0)
3830 { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); }
3831 }
3832
3833 #neighborClosed (snapshot, dir, dx, dy)
3834 {
3835 const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
3836 if (other)
3837 { return !other.open; }
3838 return !!snapshot.closedEdges?.[dir];
3839 }
3840
3841 #rebuildAllEdges ()
3842 {
3843 const seen = new Set();
3844 for (const snapshot of this.chunks.values())
3845 {
3846 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
3847 seen.add(key);
3848 this.#rebuildChunkEdges(snapshot);
3849 }
3850 for (const key of [...this.edges.keys()])
3851 {
3852 if (!seen.has(key))
3853 { this.#destroyEdges(key); }
3854 }
3855 }
3856
3857 #rebuildChunkEdges (snapshot)
3858 {
3859 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
3860 let bars = this.edges.get(key);
3861 if (!bars)
3862 {
3863 bars = {};
3864 this.edges.set(key, bars);
3865 }
3866
3867 const size = this.tileSize();
3868 const chunkPx = CHUNK_SIZE * size;
3869 const left = snapshot.chunkX * CHUNK_SIZE * size;
3870 const top = snapshot.chunkY * CHUNK_SIZE * size;
3871 const centerX = left + chunkPx / 2;
3872 const centerY = top + chunkPx / 2;
3873 const thickness = Math.max(2, Math.round(2 * this.zoom));
3874 const draw = snapshot.open === true;
3875
3876 bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1),
3877 centerX, top, chunkPx, thickness, true);
3878 bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1),
3879 centerX, top + chunkPx, chunkPx, thickness, true);
3880 bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0),
3881 left, centerY, chunkPx, thickness, false);
3882 bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0),
3883 left + chunkPx, centerY, chunkPx, thickness, false);
3884 }
3885
3886 #edgeBar (existing, visible, x, y, length, thickness, horizontal)
3887 {
3888 if (!visible)
3889 {
3890 if (existing)
3891 { existing.renderer.visible = false; }
3892 return existing;
3893 }
3894
3895 existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE);
3896 this.#markUnlit(existing);
3897 existing.renderer.visible = true;
3898 existing.transform.position.x = x;
3899 existing.transform.position.y = y;
3900 existing.transform.size = horizontal
3901 ? new vector(length, thickness)
3902 : new vector(thickness, length);
3903 existing.layer = LAYER_EDGE;
3904 this.#markSortDirty();
3905 return existing;
3906 }
3907
3908 #destroyEdges (key)
3909 {
3910 const bars = this.edges.get(key);
3911 if (!bars)
3912 { return; }
3913 bars.north?.destroy();
3914 bars.east?.destroy();
3915 bars.south?.destroy();
3916 bars.west?.destroy();
3917 this.edges.delete(key);
3918 }
3919
3920 #entityShadeAlpha (entity, now)
3921 {
3922 const toAlpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;
3923 if (entity.lerpStarted == null || entity.shadeFromTileX == null || entity.shadeFromTileY == null)
3924 { return toAlpha; }
3925 const fromAlpha = this.tiles.get(`${entity.shadeFromTileX},${entity.shadeFromTileY}`)?.shadeAlpha ?? 0;
3926 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs ?? 1));
3927 return fromAlpha + (toAlpha - fromAlpha) * t;
3928 }
3929
3930 #markSortDirty ()
3931 {
3932 this.scene._sortDirty = true;
3933 }
3934
3935 /** Player chunk for dynamic lighting; null in editor / before spawn → no 3×3 limit. */
3936 #activeLightingCenterChunk ()
3937 {
3938 const local = this.entities.get(this.localEntityId);
3939 if (!local)
3940 { return null; }
3941 return {
3942 chunkX: Math.floor(local.tileX / CHUNK_SIZE),
3943 chunkY: Math.floor(local.tileY / CHUNK_SIZE)
3944 };
3945 }
3946
3947 #isActiveLightingChunk (chunkX, chunkY)
3948 {
3949 const center = this.#activeLightingCenterChunk();
3950 if (!center)
3951 { return true; }
3952 return Math.abs(chunkX - center.chunkX) <= 1 && Math.abs(chunkY - center.chunkY) <= 1;
3953 }
3954
3955 #isActiveLightingTile (tileX, tileY)
3956 {
3957 return this.#isActiveLightingChunk(
3958 Math.floor(tileX / CHUNK_SIZE),
3959 Math.floor(tileY / CHUNK_SIZE)
3960 );
3961 }
3962
3963 /** Dynamic light sources that originate inside the player 3×3 (never from the outer ring). */
3964 #innerDynamicLights (activeLights)
3965 {
3966 return activeLights.filter((light) => this.#isActiveLightingTile(light.tileX, light.tileY));
3967 }
3968
3969 /**
3970 * Lights to simulate for one chunk.
3971 * Inner 3×3: mobile lights from the inner region + authored block lights that reach the chunk.
3972 * Outer ring: baked base + spill from any dynamic source that originates inside the 3×3
3973 * (lanterns, spells, and torches) so the boundary stays seamless.
3974 */
3975 #dynamicLightsForChunk (chunkX, chunkY, mobileLights, blockLights = [])
3976 {
3977 const center = this.#activeLightingCenterChunk();
3978 if (!center)
3979 { return [...mobileLights, ...blockLights]; }
3980 if (this.#isActiveLightingChunk(chunkX, chunkY))
3981 {
3982 const inner = this.#innerDynamicLights(mobileLights);
3983 const blocks = blockLights.filter((light) => this.#lightAffectsChunkBounds(light, chunkX, chunkY));
3984 return [...inner, ...blocks];
3985 }
3986 const spill = this.#innerDynamicLights([...mobileLights, ...blockLights]);
3987 return spill.filter((light) => this.#lightAffectsChunkBounds(light, chunkX, chunkY));
3988 }
3989
3990 #dynamicLightsForTile (tileX, tileY, mobileLights, blockLights = [])
3991 {
3992 return this.#dynamicLightsForChunk(
3993 Math.floor(tileX / CHUNK_SIZE),
3994 Math.floor(tileY / CHUNK_SIZE),
3995 mobileLights,
3996 blockLights
3997 );
3998 }
3999
4000 /** Authored torches/furnaces in chunks that can light the active 3×3 (or all chunks in editor). */
4001 #collectBlockLightsForShading ()
4002 {
4003 const center = this.#activeLightingCenterChunk();
4004 const maxRange = maxBlockLightRangeTiles();
4005 const halo = Math.ceil(maxRange / CHUNK_SIZE) + 1;
4006 const sources = [];
4007 if (!center)
4008 {
4009 for (const snapshot of this.chunks.values())
4010 { sources.push(...collectBlockLightSources(snapshot.chunkX, snapshot.chunkY, snapshot.blocks)); }
4011 return sources;
4012 }
4013 for (let dy = -1 - halo; dy <= 1 + halo; dy++)
4014 {
4015 for (let dx = -1 - halo; dx <= 1 + halo; dx++)
4016 {
4017 const snapshot = this.chunks.get(`${center.chunkX + dx},${center.chunkY + dy}`);
4018 if (!snapshot?.blocks)
4019 { continue; }
4020 sources.push(...collectBlockLightSources(snapshot.chunkX, snapshot.chunkY, snapshot.blocks));
4021 }
4022 }
4023 return sources;
4024 }
4025
4026 #updateShade ()
4027 {
4028 const ambientDark = this.#ambientDarkness();
4029 const now = performance.now();
4030 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
4031
4032 const mobileLights = [...this.dynamicLights];
4033 for (const light of this.spellLights.values())
4034 {
4035 if (light.until <= now)
4036 { continue; }
4037 mobileLights.push({
4038 tileX: light.tileX,
4039 tileY: light.tileY,
4040 range: light.range,
4041 intensity: light.intensity
4042 });
4043 }
4044 for (const key of [...this.spellLights.keys()])
4045 {
4046 if (this.spellLights.get(key).until <= now)
4047 {
4048 const expired = this.spellLights.get(key);
4049 this.spellLights.delete(key);
4050 this.#invalidateNeighborLightmapCaches(
4051 Math.floor(expired.tileX / CHUNK_SIZE),
4052 Math.floor(expired.tileY / CHUNK_SIZE)
4053 );
4054 }
4055 }
4056 const activeDarks = [];
4057 for (const dark of this.spellDarks.values())
4058 {
4059 if (dark.until <= now)
4060 { continue; }
4061 activeDarks.push({
4062 tileX: dark.tileX,
4063 tileY: dark.tileY,
4064 range: dark.range,
4065 intensity: dark.intensity
4066 });
4067 }
4068 for (const key of [...this.spellDarks.keys()])
4069 {
4070 if (this.spellDarks.get(key).until <= now)
4071 {
4072 const expired = this.spellDarks.get(key);
4073 this.spellDarks.delete(key);
4074 this.#invalidateNeighborLightmapCaches(
4075 Math.floor(expired.tileX / CHUNK_SIZE),
4076 Math.floor(expired.tileY / CHUNK_SIZE)
4077 );
4078 }
4079 }
4080 this._activeSpellDarks = activeDarks;
4081 const tileSize = this.tileSize();
4082 const blindLight = this.#blindVisionLight();
4083 if (blindLight)
4084 { mobileLights.push(blindLight); }
4085 for (const entity of this.entities.values())
4086 {
4087 const range = entity.lightRadiusTiles ?? 0;
4088 if (range <= 0)
4089 { continue; }
4090 mobileLights.push({
4091 tileX: Math.floor(entity.visualX / tileSize),
4092 tileY: Math.floor(entity.visualY / tileSize),
4093 range,
4094 intensity: entity.lightIntensity ?? 1
4095 });
4096 }
4097 const blockLights = this.#collectBlockLightsForShading();
4098
4099 const lightOcclusion = makeSnapshotLightOcclusion(this.chunks);
4100
4101 for (const objects of this.tiles.values())
4102 {
4103 if (objects._inViewport === false)
4104 { continue; }
4105 const lights = this.#dynamicLightsForTile(objects.tileX, objects.tileY, mobileLights, blockLights);
4106 objects.shadeAlpha = this.#tileShadeAlpha(objects, lights, lightOcclusion, ambientDark);
4107 }
4108
4109 for (const baked of this.bakedChunks.values())
4110 {
4111 if (baked._inViewport === false)
4112 { continue; }
4113 const lights = this.#dynamicLightsForChunk(baked.chunkX, baked.chunkY, mobileLights, blockLights);
4114 this.#writeChunkLightmap(baked, lights, mobileLights, blockLights, lightOcclusion, ambientDark);
4115 // Lightmap stores visible light (1 − shade); shader applies darkness = 1 − lit.
4116 if (baked.groundObject?.renderer?.shaderUniforms)
4117 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = 1; }
4118 for (const object of baked.blockObjects ?? [])
4119 {
4120 if (object?.renderer?.shaderUniforms)
4121 { object.renderer.shaderUniforms.u_ambientDark = 1; }
4122 }
4123 }
4124
4125 const timeSec = now / 1000;
4126 for (const objects of this.tiles.values())
4127 {
4128 if (objects._inViewport === false)
4129 { continue; }
4130 if (objects.block)
4131 {
4132 if (objects.cliffGroundTop)
4133 {
4134 const baked = this.bakedChunks.get(`${objects.chunkX},${objects.chunkY}`);
4135 const localX = ((objects.tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE;
4136 const localY = ((objects.tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE;
4137 this.#syncCliffGroundTopSprite(
4138 objects.block,
4139 objects.shadeAlpha,
4140 baked?.groundImage ?? null,
4141 localX,
4142 localY
4143 );
4144 }
4145 else
4146 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
4147 }
4148 if (objects.ground && isWaterGround(objects.groundTypeId))
4149 {
4150 const baked = this.bakedChunks.get(`${objects.chunkX},${objects.chunkY}`);
4151 // Light intensity grid is visible light (1 − shade); water shader uses ambient=1.
4152 this.#syncGroundWaterFx(objects, 1, timeSec, baked);
4153 }
4154 else if (objects.ground)
4155 { this.#syncLitSprite(objects.ground, objects.shadeAlpha); }
4156 }
4157
4158 for (const item of this.groundItems.values())
4159 {
4160 const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;
4161 this.#syncGroundItemSprite(item, alpha);
4162 }
4163 }
4164
4165 #tileLightSources (objects, activeLights, lightOcclusion)
4166 {
4167 // Inner 3×3: ignore baked (stale behind doors); outer ring keeps authored lightmaps.
4168 const useBaked = !this.#isActiveLightingTile(objects.tileX, objects.tileY);
4169 const baked = useBaked ? lightIntensity(objects.light ?? 0) : 0;
4170 const dynamic = dynamicLightAtTile(
4171 objects.tileX,
4172 objects.tileY,
4173 activeLights,
4174 lightOcclusion
4175 );
4176 const dark = dynamicDarknessAtTile(
4177 objects.tileX,
4178 objects.tileY,
4179 this._activeSpellDarks ?? [],
4180 lightOcclusion
4181 );
4182 return { lights: Math.max(baked, dynamic), dark };
4183 }
4184
4185 /** Shade 0–1: night ambient over unlit tiles, plus Dark spell dimming daylight/torches. */
4186 #tileShadeAlpha (objects, activeLights, lightOcclusion, ambientDark)
4187 {
4188 const { lights, dark } = this.#tileLightSources(objects, activeLights, lightOcclusion);
4189 return Math.min(1, Math.max(0, ambientDark) * (1 - lights) + dark);
4190 }
4191
4192 #tileLightIntensity (objects, activeLights, lightOcclusion, ambientDark = this.#ambientDarkness())
4193 {
4194 return 1 - this.#tileShadeAlpha(objects, activeLights, lightOcclusion, ambientDark);
4195 }
4196
4197 /** Baked + dynamic light intensity (0–1) for any world tile, including across chunks. */
4198 #intensityAtTile (tileX, tileY, activeLights, lightOcclusion, ambientDark = this.#ambientDarkness())
4199 {
4200 const tileObjects = this.tiles.get(`${tileX},${tileY}`);
4201 if (tileObjects)
4202 { return this.#tileLightIntensity(tileObjects, activeLights, lightOcclusion, ambientDark); }
4203 const chunkX = Math.floor(tileX / CHUNK_SIZE);
4204 const chunkY = Math.floor(tileY / CHUNK_SIZE);
4205 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
4206 if (!snapshot)
4207 { return 1 - Math.min(1, Math.max(0, ambientDark)); }
4208 const localX = tileX - chunkX * CHUNK_SIZE;
4209 const localY = tileY - chunkY * CHUNK_SIZE;
4210 const index = localY * CHUNK_SIZE + localX;
4211 const useBaked = !this.#isActiveLightingTile(tileX, tileY);
4212 const bakedLit = useBaked ? lightIntensity(snapshot.light[index] ?? 0) : 0;
4213 const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion);
4214 const dark = dynamicDarknessAtTile(tileX, tileY, this._activeSpellDarks ?? [], lightOcclusion);
4215 const lights = Math.max(bakedLit, dynamic);
4216 const shade = Math.min(1, Math.max(0, ambientDark) * (1 - lights) + dark);
4217 return 1 - shade;
4218 }
4219
4220 /** True when ground or block on this tile occludes light rays (same rules as bake). */
4221 #tileOccludesLight (tileX, tileY)
4222 {
4223 const chunkX = Math.floor(tileX / CHUNK_SIZE);
4224 const chunkY = Math.floor(tileY / CHUNK_SIZE);
4225 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
4226 if (!snapshot)
4227 { return false; }
4228 const localX = tileX - chunkX * CHUNK_SIZE;
4229 const localY = tileY - chunkY * CHUNK_SIZE;
4230 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
4231 { return false; }
4232 const index = localY * CHUNK_SIZE + localX;
4233 const ground = normalizeGround(snapshot.grounds?.[index]);
4234 if (!isGroundPassable(ground.typeId))
4235 { return true; }
4236 return blockLightOcclusionForBlock(snapshot.blocks?.[index]) === LightOcclusion.solid;
4237 }
4238
4239 #fillChunkLightGrids (baked, mobileLights, blockLights, lightOcclusion, ambientDark)
4240 {
4241 const gridW = CHUNK_SIZE + 2;
4242 const gridSize = gridW * gridW;
4243 if (!baked.lightIntensityGrid || baked.lightIntensityGrid.length !== gridSize)
4244 { baked.lightIntensityGrid = new Float32Array(gridSize); }
4245 if (!baked.lightOccludeGrid || baked.lightOccludeGrid.length !== gridSize)
4246 { baked.lightOccludeGrid = new Uint8Array(gridSize); }
4247 const grid = baked.lightIntensityGrid;
4248 const occlude = baked.lightOccludeGrid;
4249 for (let ly = -1; ly <= CHUNK_SIZE; ly++)
4250 {
4251 for (let lx = -1; lx <= CHUNK_SIZE; lx++)
4252 {
4253 const tileX = baked.chunkX * CHUNK_SIZE + lx;
4254 const tileY = baked.chunkY * CHUNK_SIZE + ly;
4255 const gi = (ly + 1) * gridW + (lx + 1);
4256 // Halo tiles may sit in the other lighting region (3×3 vs outer). Resolve
4257 // sources per tile so corner blends match the neighbour chunk's shading.
4258 const lights = this.#dynamicLightsForTile(tileX, tileY, mobileLights, blockLights);
4259 grid[gi] = this.#intensityAtTile(tileX, tileY, lights, lightOcclusion, ambientDark);
4260 occlude[gi] = this.#tileOccludesLight(tileX, tileY) ? 1 : 0;
4261 }
4262 }
4263 return { grid, occlude, gridW };
4264 }
4265
4266 #makeLightCornerSampler (grid, occlude, gridW)
4267 {
4268 const sample = (lx, ly) => grid[(ly + 1) * gridW + (lx + 1)];
4269 const blocks = (lx, ly) => occlude[(ly + 1) * gridW + (lx + 1)] !== 0;
4270 const smoothCorner = (homeLx, homeLy, aLx, aLy, bLx, bLy, dLx, dLy) => smoothLitCorner({
4271 homeLit: sample(homeLx, homeLy),
4272 homeBlocks: blocks(homeLx, homeLy),
4273 aLit: sample(aLx, aLy),
4274 aBlocks: blocks(aLx, aLy),
4275 bLit: sample(bLx, bLy),
4276 bBlocks: blocks(bLx, bLy),
4277 dLit: sample(dLx, dLy),
4278 dBlocks: blocks(dLx, dLy)
4279 });
4280 return { smoothCorner };
4281 }
4282
4283 /** Corner lit intensities (0–1) for one tile — matches baked atlas lightmap corners. */
4284 #tileLitCorners (baked, localX, localY)
4285 {
4286 const grid = baked?.lightIntensityGrid;
4287 const occlude = baked?.lightOccludeGrid;
4288 if (!grid?.length || !occlude?.length)
4289 { return null; }
4290 const gridW = CHUNK_SIZE + 2;
4291 const { smoothCorner } = this.#makeLightCornerSampler(grid, occlude, gridW);
4292 return {
4293 nw: smoothCorner(
4294 localX, localY,
4295 localX - 1, localY,
4296 localX, localY - 1,
4297 localX - 1, localY - 1
4298 ),
4299 ne: smoothCorner(
4300 localX, localY,
4301 localX + 1, localY,
4302 localX, localY - 1,
4303 localX + 1, localY - 1
4304 ),
4305 sw: smoothCorner(
4306 localX, localY,
4307 localX - 1, localY,
4308 localX, localY + 1,
4309 localX - 1, localY + 1
4310 ),
4311 se: smoothCorner(
4312 localX, localY,
4313 localX + 1, localY,
4314 localX, localY + 1,
4315 localX + 1, localY + 1
4316 )
4317 };
4318 }
4319
4320 #hashUint8Array (values)
4321 {
4322 let hash = 2166136261;
4323 for (let i = 0; i < values.length; i++)
4324 {
4325 hash ^= values[i];
4326 hash = Math.imul(hash, 16777619);
4327 }
4328 return hash >>> 0;
4329 }
4330
4331 #lightAffectsChunkBounds (light, chunkX, chunkY)
4332 {
4333 const minX = chunkX * CHUNK_SIZE - 1;
4334 const minY = chunkY * CHUNK_SIZE - 1;
4335 const maxX = chunkX * CHUNK_SIZE + CHUNK_SIZE;
4336 const maxY = chunkY * CHUNK_SIZE + CHUNK_SIZE;
4337 const closestX = Math.max(minX, Math.min(light.tileX, maxX));
4338 const closestY = Math.max(minY, Math.min(light.tileY, maxY));
4339 return Math.hypot(light.tileX - closestX, light.tileY - closestY) <= light.range;
4340 }
4341
4342 #chunkLightmapCacheKey (baked, activeLights, ambientDark = this.#ambientDarkness())
4343 {
4344 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
4345 if (!snapshot?.light)
4346 { return null; }
4347 const bakedHash = this.#hashUint8Array(snapshot.light);
4348 // Caller already scoped lights for this chunk (incl. 3×3 spill onto the outer ring).
4349 const lights = activeLights;
4350 const darks = this._activeSpellDarks ?? [];
4351 const mode = this.lightingMode === "simple" ? "s" : "f";
4352 const ambientKey = Math.round(Math.max(0, ambientDark) * 1000);
4353 let lightsKey = "";
4354 for (const light of lights)
4355 {
4356 if (!this.#lightAffectsChunkBounds(light, baked.chunkX, baked.chunkY))
4357 { continue; }
4358 lightsKey += `l${light.tileX},${light.tileY},${light.range},${light.intensity ?? 1};`;
4359 }
4360 let darksKey = "";
4361 for (const dark of darks)
4362 {
4363 if (!this.#lightAffectsChunkBounds(dark, baked.chunkX, baked.chunkY))
4364 { continue; }
4365 darksKey += `d${dark.tileX},${dark.tileY},${dark.range},${dark.intensity ?? 1};`;
4366 }
4367 return `a:${mode}:${ambientKey}:${bakedHash}:${lightsKey}|${darksKey}`;
4368 }
4369
4370 #invalidateNeighborLightmapCaches (chunkX, chunkY)
4371 {
4372 // Halo grid is ±1 tile; outer map ring is ±2 chunks from the player.
4373 for (let dy = -2; dy <= 2; dy++)
4374 {
4375 for (let dx = -2; dx <= 2; dx++)
4376 {
4377 const baked = this.bakedChunks.get(`${chunkX + dx},${chunkY + dy}`);
4378 if (baked)
4379 { baked.lightmapCacheKey = null; }
4380 }
4381 }
4382 }
4383
4384 /**
4385 * Per-chunk lightmap for atlas ground/blocks. Open tiles blend into open neighbours;
4386 * occluding tiles stay flat and contribute 0 into others so light does not bleed
4387 * through a wall to the far side. Diagonals only when both cardinals are clear.
4388 * @param chunkLights Sources that affect this chunk (cache key + in-chunk samples).
4389 * @param mobileLights / blockLights Full lists so the ±1 halo can sample across the 3×3 boundary.
4390 */
4391 #writeChunkLightmap (
4392 baked,
4393 chunkLights,
4394 mobileLights,
4395 blockLights,
4396 lightOcclusion,
4397 ambientDark = this.#ambientDarkness()
4398 )
4399 {
4400 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
4401 if (!snapshot)
4402 { return; }
4403 const cacheKey = this.#chunkLightmapCacheKey(baked, chunkLights, ambientDark);
4404 if (cacheKey && baked.lightmapCacheKey === cacheKey)
4405 { return; }
4406 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
4407 const pixelCount = atlasPx * atlasPx * 4;
4408 if (!baked.lightmapPixels || baked.lightmapPixels.length !== pixelCount)
4409 { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); }
4410 const pixels = baked.lightmapPixels;
4411
4412 this.#fillChunkLightGrids(baked, mobileLights, blockLights, lightOcclusion, ambientDark);
4413 const simple = this.lightingMode === "simple";
4414
4415 for (let localY = 0; localY < CHUNK_SIZE; localY++)
4416 {
4417 for (let localX = 0; localX < CHUNK_SIZE; localX++)
4418 {
4419 const baseX = localX * SPRITE_SIZE_PX;
4420 const baseY = localY * SPRITE_SIZE_PX;
4421 if (simple)
4422 {
4423 const gridW = CHUNK_SIZE + 2;
4424 const intensity = baked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? 0;
4425 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
4426 for (let py = 0; py < SPRITE_SIZE_PX; py++)
4427 {
4428 for (let px = 0; px < SPRITE_SIZE_PX; px++)
4429 {
4430 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
4431 pixels[offset] = value;
4432 pixels[offset + 1] = value;
4433 pixels[offset + 2] = value;
4434 pixels[offset + 3] = 255;
4435 }
4436 }
4437 continue;
4438 }
4439 const corners = this.#tileLitCorners(baked, localX, localY);
4440 const nw = corners.nw;
4441 const ne = corners.ne;
4442 const sw = corners.sw;
4443 const se = corners.se;
4444 for (let py = 0; py < SPRITE_SIZE_PX; py++)
4445 {
4446 const v = (py + 0.5) / SPRITE_SIZE_PX;
4447 const left = nw + (sw - nw) * v;
4448 const right = ne + (se - ne) * v;
4449 for (let px = 0; px < SPRITE_SIZE_PX; px++)
4450 {
4451 const u = (px + 0.5) / SPRITE_SIZE_PX;
4452 const intensity = left + (right - left) * u;
4453 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
4454 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
4455 pixels[offset] = value;
4456 pixels[offset + 1] = value;
4457 pixels[offset + 2] = value;
4458 pixels[offset + 3] = 255;
4459 }
4460 }
4461 }
4462 }
4463 const ctx = baked.lightmapCanvas.getContext("2d");
4464 ctx.putImageData(new ImageData(pixels, atlasPx, atlasPx), 0, 0);
4465 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
4466 this.#queueCanvasTextureWarm(baked.lightmapCanvas, baked.chunkX, baked.chunkY);
4467 baked.lightmapCacheKey = cacheKey;
4468 }
4469
4470 #updateSwipes (now)
4471 {
4472 this.swipes = this.swipes.filter((swipe) =>
4473 {
4474 if (swipe.lerp && swipe.started != null)
4475 {
4476 const durationMs = swipe.durationMs ?? 400;
4477 const t = Math.min(1, (now - swipe.started) / durationMs);
4478 const fromPivot = this.#projectileLaunchPoint(
4479 swipe.attackerId ?? null,
4480 swipe.fromTileX,
4481 swipe.fromTileY
4482 );
4483 const toPivot = this.#projectileEndPivot(swipe);
4484 const x = fromPivot.x + (toPivot.x - fromPivot.x) * t;
4485 const y = fromPivot.y + (toPivot.y - fromPivot.y) * t;
4486 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
4487 if (swipe.object?.transform)
4488 {
4489 swipe.object.transform.rotation = Math.atan2(
4490 toPivot.y - fromPivot.y,
4491 toPivot.x - fromPivot.x
4492 ) * (180 / Math.PI);
4493 }
4494 if (swipe.spellProjectile && swipe.tint)
4495 { this.#syncUnlitTintSprite(swipe.object, swipe.tint); }
4496 this.#placePivoted(swipe.object, x, y, sortY, SORT_FX);
4497 if (!swipe.spellProjectile)
4498 {
4499 this.#applyPhysicalCombatFxDarkness(
4500 swipe.object,
4501 swipe.fromTileX,
4502 swipe.fromTileY,
4503 swipe.tileX,
4504 swipe.tileY,
4505 swipe.dualTint ?? null
4506 );
4507 }
4508 }
4509 else if (swipe.fromTileX != null && !swipe.spellProjectile)
4510 {
4511 this.#applyPhysicalCombatFxDarkness(
4512 swipe.object,
4513 swipe.fromTileX,
4514 swipe.fromTileY,
4515 swipe.tileX,
4516 swipe.tileY,
4517 swipe.dualTint ?? null
4518 );
4519 }
4520 if (swipe.fadeOpacity && swipe.started != null && swipe.object?.renderer)
4521 {
4522 const durationMs = swipe.durationMs ?? MELEE_SWIPE_MS;
4523 const t = Math.min(1, Math.max(0, (now - swipe.started) / durationMs));
4524 swipe.object.renderer.alpha = 1 - t;
4525 }
4526 if (swipe.until > now)
4527 { return true; }
4528 const onImpact = swipe.onImpact;
4529 swipe.onImpact = null;
4530 swipe.object?.destroy();
4531 if (typeof onImpact === "function")
4532 {
4533 try
4534 { onImpact(); }
4535 catch (_)
4536 { /* presentation only */ }
4537 }
4538 return false;
4539 });
4540 }
4541
4542 #projectileEndPivot (swipe)
4543 {
4544 if (swipe.trackTarget && swipe.targetId != null)
4545 { return this.#projectileAimPoint(swipe.targetId, swipe.tileX, swipe.tileY); }
4546 return this.#projectileAimPoint(null, swipe.tileX, swipe.tileY);
4547 }
4548
4549 /**
4550 * Launch point: 4px below the top of the caster sprite (falls back to tile centre).
4551 */
4552 #projectileLaunchPoint (entityId, tileX, tileY)
4553 {
4554 const entity = entityId != null ? this.entities.get(entityId) : null;
4555 if (entity && Number.isFinite(entity.visualX) && Number.isFinite(entity.visualY))
4556 {
4557 const zoom = this.zoom;
4558 const spriteH = entity.object?.renderer?.sprite?.height ?? SPRITE_SIZE_PX;
4559 const pivotX = entity.visualX + (entity.stackOffsetX ?? 0);
4560 const pivotY = entity.visualY + (entity.stackOffsetY ?? 0);
4561 const topY = pivotY - (spriteH - PIVOT_FROM_BOTTOM_PX) * zoom;
4562 return {
4563 x: pivotX,
4564 y: topY + PROJECTILE_LAUNCH_FROM_TOP_PX * zoom
4565 };
4566 }
4567 return tilePivot(tileX, tileY, this.tileSize());
4568 }
4569
4570 /**
4571 * Aim point: sprite centre for creatures, tile centre for tile targets.
4572 */
4573 #projectileAimPoint (entityId, tileX, tileY)
4574 {
4575 const entity = entityId != null ? this.entities.get(entityId) : null;
4576 if (entity && Number.isFinite(entity.visualX) && Number.isFinite(entity.visualY))
4577 {
4578 const zoom = this.zoom;
4579 const spriteH = entity.object?.renderer?.sprite?.height ?? SPRITE_SIZE_PX;
4580 const pivotX = entity.visualX + (entity.stackOffsetX ?? 0);
4581 const pivotY = entity.visualY + (entity.stackOffsetY ?? 0);
4582 return spriteCenterFromPivot(pivotX, pivotY, spriteH, zoom);
4583 }
4584 return tilePivot(tileX, tileY, this.tileSize());
4585 }
4586
4587 #updateDamageNumbers (now)
4588 {
4589 const layer = this.damageNumbersEl;
4590 if (!layer)
4591 { return; }
4592 this.damageFloats = this.damageFloats.filter((entry) =>
4593 {
4594 const elapsed = now - entry.started;
4595 if (elapsed >= DAMAGE_FLOAT_MS)
4596 {
4597 entry.element?.remove();
4598 return false;
4599 }
4600 const entity = this.entities.get(entry.entityId);
4601 if (!entity)
4602 {
4603 entry.element?.remove();
4604 return false;
4605 }
4606 if (!entry.element)
4607 {
4608 entry.element = document.createElement("span");
4609 entry.element.className = "damage-number";
4610 entry.element.textContent = String(entry.damage);
4611 layer.append(entry.element);
4612 }
4613 const anchor = this.nametagAnchor(entity);
4614 if (!anchor)
4615 { return true; }
4616 const t = elapsed / DAMAGE_FLOAT_MS;
4617 entry.element.style.left = `${anchor.x}px`;
4618 entry.element.style.top = `${anchor.y - 6 - t * 28}px`;
4619 entry.element.style.opacity = String(1 - t);
4620 return true;
4621 });
4622 }
4623
4624 #updateSkillLevelFloats (now)
4625 {
4626 const layer = this.skillLevelFloatsEl;
4627 if (!layer)
4628 { return; }
4629 this.skillLevelFloats = this.skillLevelFloats.filter((entry) =>
4630 {
4631 const elapsed = now - entry.started;
4632 if (elapsed >= SKILL_LEVEL_FLOAT_MS)
4633 {
4634 entry.element?.remove();
4635 return false;
4636 }
4637 const entity = this.entities.get(entry.entityId);
4638 if (!entity)
4639 {
4640 entry.element?.remove();
4641 return false;
4642 }
4643 if (!entry.element)
4644 {
4645 const root = document.createElement("div");
4646 root.className = "skill-level-float";
4647
4648 const levelEl = document.createElement("div");
4649 levelEl.className = "skill-level-float-level";
4650 levelEl.textContent = `↑${entry.level}↑`;
4651
4652 const icon = document.createElement("img");
4653 icon.className = "skill-level-float-icon";
4654 icon.src = entry.icon;
4655 icon.alt = entry.displayName || "";
4656
4657 root.append(levelEl, icon);
4658 entry.element = root;
4659 layer.append(entry.element);
4660 }
4661 const anchor = this.nametagAnchor(entity);
4662 if (!anchor)
4663 { return true; }
4664 const t = elapsed / SKILL_LEVEL_FLOAT_MS;
4665 entry.element.style.left = `${anchor.x}px`;
4666 entry.element.style.top = `${anchor.y - 10 - t * 18}px`;
4667 entry.element.style.opacity = String(Math.max(0, 1 - t * 0.85));
4668 return true;
4669 });
4670 }
4671
4672 #syncBloomLayer ()
4673 {
4674 if (!this.bloomEnabled)
4675 {
4676 this.scene.setLayers([{ name: "default" }]);
4677 return;
4678 }
4679 const settings = this.settings ?? DEFAULT_WORLD_SETTINGS;
4680 this.scene.setLayers([
4681 { name: "default" },
4682 {
4683 name: RENDER_LAYER_BLOOM,
4684 composite: "add",
4685 postShaders: Shader.getBloomPostChain({
4686 threshold: settings.bloomThreshold,
4687 softKnee: settings.bloomSoftKnee,
4688 intensity: settings.bloomIntensity,
4689 blurSize: settings.bloomBlurSize,
4690 saturation: settings.bloomSaturation,
4691 colorPreserve: settings.bloomColorPreserve,
4692 dilate: settings.bloomDilate,
4693 scales: Math.max(1, Math.round(settings.bloomScales ?? 1)),
4694 halfRes: (settings.bloomHalfRes ?? 1) >= 0.5
4695 })
4696 }
4697 ]);
4698 }
4699}
4700
4701export function nightFactor (hour, nightDarkness = 0.72)
4702{
4703 const peak = Math.min(1, Math.max(0, nightDarkness));
4704 if (hour >= 8 && hour <= 16)
4705 { return 0; }
4706 if (hour >= 22 || hour <= 5)
4707 { return peak; }
4708 if (hour < 8)
4709 { return lerp(peak, 0, (hour - 5) / 3); }
4710 return lerp(0, peak, (hour - 16) / 6);
4711}
4712
4713function bodySpriteName (sex)
4714{
4715 const key = sex === "female" ? "player-body-female" : "player-body-male";
4716 return spriteImageName("character", key, key);
4717}
4718
4719function lerp (a, b, t)
4720{
4721 return a + (b - a) * Math.min(1, Math.max(0, t));
4722}
4723
4724function makeLightmapCanvas (size)
4725{
4726 const canvas = document.createElement("canvas");
4727 canvas.width = size;
4728 canvas.height = size;
4729 return canvas;
4730}
4731
4732function copyCanvas (source, dest)
4733{
4734 const ctx = dest.getContext("2d");
4735 ctx.imageSmoothingEnabled = false;
4736 ctx.clearRect(0, 0, dest.width, dest.height);
4737 ctx.drawImage(source, 0, 0);
4738}
4739
4740function drawHpBar (canvas, current, max)
4741{
4742 const ctx = canvas.getContext("2d");
4743 ctx.clearRect(0, 0, HP_BAR_W, HP_BAR_H);
4744 ctx.fillStyle = "#000000";
4745 ctx.fillRect(0, 0, HP_BAR_W, HP_BAR_H);
4746 const ratio = max > 0 ? Math.max(0, Math.min(1, current / max)) : 0;
4747 const fillW = Math.round(12 * ratio);
4748 if (fillW > 0)
4749 {
4750 ctx.fillStyle = "#ff0000";
4751 ctx.fillRect(1, 1, fillW, 2);
4752 }
4753}