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