BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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