BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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