BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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