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