BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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