| 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, tileLightOcclusionAt } from "/shared/lighting/chunkOcclusion.js"; |
| 5 | import { enclosedAmbientDarkness } from "/shared/lighting/enclosed.js"; |
| 6 | import { collectBlockLightSources, collectGroundLightSources, maxBlockLightRangeTiles } from "/shared/lighting/blockLights.js"; |
| 7 | import { smoothLitCorner } from "/shared/lighting/lightCorners.js"; |
| 8 | import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js"; |
| 9 | import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemSpriteNameForStack, itemDefinition } from "/shared/definitions/items.js"; |
| 10 | import { chequeReservedGoodsStack, isFilledChequeStack } from "/shared/items/cheque.js"; |
| 11 | import |
| 12 | { |
| 13 | resolveItemTint, |
| 14 | resolveEquipTint, |
| 15 | resolveItemDualTint, |
| 16 | resolveEquipDualTint, |
| 17 | normalizeRgb |
| 18 | } from "/shared/render/tint.js"; |
| 19 | import { layersFromSpawnerConfig } from "/shared/appearance/layers.js"; |
| 20 | import { normalizeSpawnerConfig } from "/shared/definitions/mobs.js"; |
| 21 | import { isItemSpawnerConfig, itemSpawnerContainerSpriteName } from "/shared/definitions/itemSpawners.js"; |
| 22 | import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js"; |
| 23 | import { normalizeGround, normalizeBlock, isWadeGroundInSeason, isWaterGround, isLavaGround, isLiquidWaterGround, isGroundPassable, isBlockPassable, groundLightOcclusion, LightOcclusion, blockDefinition, blockLightOcclusionForBlock, GroundType, GROUND_DEFINITIONS, fluidCoastContinues } from "/shared/definitions/tiles.js"; |
| 24 | import { doorSortSubOrder, doorRestingState, isDoorTraversable } from "/shared/world/doors.js"; |
| 25 | import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer, flightSortLayer } from "/shared/render/pivot.js"; |
| 26 | import { bakeChunkAtlases, tileBlockSpriteEntry } from "./chunkBake.js"; |
| 27 | import { createChunkAtlasCache } from "./chunkAtlasCache.js"; |
| 28 | import |
| 29 | { |
| 30 | frameworkImageFromCanvas, |
| 31 | invalidateCanvasTexture, |
| 32 | uploadCanvasTextureRgba |
| 33 | } from "./canvasSprite.js"; |
| 34 | import { setNearestFilter } from "./sprites.js"; |
| 35 | import |
| 36 | { |
| 37 | createFluidAtlasTarget, |
| 38 | destroyFluidAtlasTarget, |
| 39 | withFluidAtlasPass, |
| 40 | drawFluidAtlasTile, |
| 41 | createFluidPackSet, |
| 42 | destroyFluidPackSet, |
| 43 | clearFluidPackPixels, |
| 44 | writeFluidPackTile, |
| 45 | uploadFluidPacks, |
| 46 | drawFluidAtlasChunkPass, |
| 47 | FLUID_KIND_WATER, |
| 48 | FLUID_KIND_LAVA |
| 49 | } from "./fluidChunkAtlas.js"; |
| 50 | import |
| 51 | { |
| 52 | WATER_ATLAS_CHUNK_FRAG, |
| 53 | LAVA_ATLAS_CHUNK_FRAG, |
| 54 | LAVA_BLOOM_ATLAS_CHUNK_FRAG |
| 55 | } from "./fluidAtlasChunkShaders.js"; |
| 56 | import { waterDebugUniforms, lavaDebugUniforms } from "../play/waterDebug.js"; |
| 57 | import { natureNoise01, natureTintUniforms, NATURE_TINT, NATURE_NOISE_SIZE, NATURE_NOISE_PAD } from "/shared/render/natureNoise.js"; |
| 58 | import { SeasonId, seasonIdAt, resolveSeasonalVisualState } from "/shared/world/season.js"; |
| 59 | import |
| 60 | { |
| 61 | OVERWORLD_ID, |
| 62 | normalizeDimensionId, |
| 63 | normalizeLightingMode, |
| 64 | normalizeSeasonMode, |
| 65 | resolveDimensionDarknessFactor, |
| 66 | resolveDimensionSeasonId |
| 67 | } from "/shared/world/dimensions.js"; |
| 68 | import { spellDefinition, spellProjectileTint } from "/shared/definitions/spells.js"; |
| 69 | import { skullTintColor } from "/shared/combat/skull.js"; |
| 70 | |
| 71 | const LAYER_GROUND = 0; |
| 72 | const LAYER_EDGE = 900000; |
| 73 | const SORT_BLOCK = 2; |
| 74 | const SORT_ENTITY = 3; |
| 75 | /** Equipment overlays use SORT_ENTITY + 1 + index (same sortY band). */ |
| 76 | const SORT_HP_BAR = 14; |
| 77 | const SORT_FX = 5; |
| 78 | const RENDER_LAYER_BLOOM = "bloom"; |
| 79 | const SKULL_SPRITE = "fx:skull:skull"; |
| 80 | |
| 81 | const HP_BAR_W = 14; |
| 82 | const HP_BAR_H = 4; |
| 83 | const WALK_TILT_DEG = 6; |
| 84 | const RUN_TILT_DEG = 8; |
| 85 | const SHOVE_TILE_FRACTION = 0.25; |
| 86 | const SHOVE_MS = 280; |
| 87 | /** Soft reflow when stack circle targets change (join/leave a shared tile). */ |
| 88 | const STACK_SPREAD_LERP_MS = 280; |
| 89 | /** Melee swipe fade: full opacity → transparent over this duration, then remove. */ |
| 90 | const MELEE_SWIPE_MS = 500; |
| 91 | /** Extra random yaw (±deg) on top of aim rotation. */ |
| 92 | const MELEE_SWIPE_JITTER_DEG = 10; |
| 93 | /** Hold gather-tool equip overlay slightly past swing interval so it stays visible between swings. */ |
| 94 | const GATHER_TOOL_HOLD_MS = 1100; |
| 95 | const DAMAGE_FLASH_MS = 180; |
| 96 | const FLASH_COLOR_DAMAGE = Object.freeze([1.0, 0.12, 0.12]); |
| 97 | const FLASH_COLOR_BLOCK = Object.freeze([1.0, 1.0, 1.0]); |
| 98 | /** Combat death: full red silhouette fades to transparent after the killing blow. */ |
| 99 | const DEATH_FADE_MS = 500; |
| 100 | /** Interest leave / non-combat despawn: plain alpha fade (still lit / darkened). */ |
| 101 | const DESPAWN_FADE_MS = 500; |
| 102 | const DAMAGE_FLOAT_MS = 900; |
| 103 | const SKILL_LEVEL_FLOAT_MS = 2800; |
| 104 | /** Projectiles spawn this many sprite-pixels below the caster sprite top. */ |
| 105 | const PROJECTILE_LAUNCH_FROM_TOP_PX = 4; |
| 106 | |
| 107 | const SPRITE_LIGHTING_FRAG = [ |
| 108 | "precision mediump float;", |
| 109 | "varying vec2 v_texCoord;", |
| 110 | "uniform sampler2D u_texture;", |
| 111 | "uniform float u_alpha;", |
| 112 | "uniform float u_darkness;", |
| 113 | "uniform float u_strength;", |
| 114 | "uniform vec3 u_flashColor;", |
| 115 | "uniform float u_wade;", |
| 116 | "uniform float u_spriteHeight;", |
| 117 | "void main() {", |
| 118 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 119 | " if (color.a <= 0.0) { discard; }", |
| 120 | " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);", |
| 121 | " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }", |
| 122 | " vec3 rgb = color.rgb;", |
| 123 | " if (u_wade > 0.5 && fromBottom < 5.0) {", |
| 124 | " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);", |
| 125 | " }", |
| 126 | " rgb = mix(rgb, vec3(0.0), u_darkness);", |
| 127 | " rgb = mix(rgb, u_flashColor, u_strength);", |
| 128 | " gl_FragColor = vec4(rgb, color.a * u_alpha);", |
| 129 | "}" |
| 130 | ].join("\n"); |
| 131 | |
| 132 | const WATER_GROUND_FRAG = [ |
| 133 | "precision mediump float;", |
| 134 | "varying vec2 v_texCoord;", |
| 135 | "uniform sampler2D u_texture;", |
| 136 | "uniform sampler2D u_secondary;", |
| 137 | "uniform float u_alpha;", |
| 138 | "uniform float u_ambientDark;", |
| 139 | "uniform float u_litNW;", |
| 140 | "uniform float u_litNE;", |
| 141 | "uniform float u_litSW;", |
| 142 | "uniform float u_litSE;", |
| 143 | "uniform float u_time;", |
| 144 | "uniform float u_tileX;", |
| 145 | "uniform float u_tileY;", |
| 146 | "uniform float u_deepNW;", |
| 147 | "uniform float u_deepNE;", |
| 148 | "uniform float u_deepSW;", |
| 149 | "uniform float u_deepSE;", |
| 150 | "uniform float u_edgeN;", |
| 151 | "uniform float u_edgeE;", |
| 152 | "uniform float u_edgeS;", |
| 153 | "uniform float u_edgeW;", |
| 154 | "uniform float u_edgeNE;", |
| 155 | "uniform float u_edgeNW;", |
| 156 | "uniform float u_edgeSE;", |
| 157 | "uniform float u_edgeSW;", |
| 158 | "uniform float u_hasShore;", |
| 159 | "uniform float u_shoreEdgeN;", |
| 160 | "uniform float u_shoreEdgeE;", |
| 161 | "uniform float u_shoreEdgeS;", |
| 162 | "uniform float u_shoreEdgeW;", |
| 163 | "uniform float u_shoreEdgeNE;", |
| 164 | "uniform float u_shoreEdgeNW;", |
| 165 | "uniform float u_shoreEdgeSE;", |
| 166 | "uniform float u_shoreEdgeSW;", |
| 167 | "uniform vec4 u_shoreUvRect;", |
| 168 | "uniform float u_flowX;", |
| 169 | "uniform float u_flowY;", |
| 170 | "uniform float u_flowZ;", |
| 171 | "uniform float u_waveScale;", |
| 172 | "uniform float u_fbmAmp;", |
| 173 | "uniform float u_texAmp;", |
| 174 | "uniform float u_distort;", |
| 175 | "uniform float u_normalZ;", |
| 176 | "uniform float u_waveGain;", |
| 177 | "uniform float u_crestLo;", |
| 178 | "uniform float u_crestHi;", |
| 179 | "uniform float u_crestPow;", |
| 180 | "uniform float u_glitterPow;", |
| 181 | "uniform float u_crestGlitter;", |
| 182 | "uniform float u_glitterCap;", |
| 183 | "uniform float u_glitterMix;", |
| 184 | "uniform float u_shadeLo;", |
| 185 | "uniform float u_shadeHi;", |
| 186 | "uniform float u_bodyLo;", |
| 187 | "uniform float u_bodyHi;", |
| 188 | "uniform float u_litLo;", |
| 189 | "uniform float u_litHi;", |
| 190 | "uniform float u_litMix;", |
| 191 | "uniform float u_edgeDark;", |
| 192 | "uniform float u_lightDirX;", |
| 193 | "uniform float u_lightDirY;", |
| 194 | "uniform float u_lightDirZ;", |
| 195 | "uniform float u_normalEps;", |
| 196 | "uniform float u_foamStrength;", |
| 197 | "uniform float u_shoreClip;", |
| 198 | "uniform float u_deepDark;", |
| 199 | "uniform float u_deepAbrupt;", |
| 200 | // 3D simplex (Ashima / Gustavson style — OpenSimplex-class continuous field). |
| 201 | "vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }", |
| 202 | "vec4 mod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }", |
| 203 | "vec4 permute(vec4 x) { return mod289(((x * 34.0) + 1.0) * x); }", |
| 204 | "vec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; }", |
| 205 | "float snoise(vec3 v) {", |
| 206 | " vec2 C = vec2(1.0 / 6.0, 1.0 / 3.0);", |
| 207 | " vec4 D = vec4(0.0, 0.5, 1.0, 2.0);", |
| 208 | " vec3 i = floor(v + dot(v, C.yyy));", |
| 209 | " vec3 x0 = v - i + dot(i, C.xxx);", |
| 210 | " vec3 g = step(x0.yzx, x0.xyz);", |
| 211 | " vec3 l = 1.0 - g;", |
| 212 | " vec3 i1 = min(g.xyz, l.zxy);", |
| 213 | " vec3 i2 = max(g.xyz, l.zxy);", |
| 214 | " vec3 x1 = x0 - i1 + C.xxx;", |
| 215 | " vec3 x2 = x0 - i2 + C.yyy;", |
| 216 | " vec3 x3 = x0 - D.yyy;", |
| 217 | " i = mod289(i);", |
| 218 | " vec4 p = permute(permute(permute(", |
| 219 | " i.z + vec4(0.0, i1.z, i2.z, 1.0))", |
| 220 | " + i.y + vec4(0.0, i1.y, i2.y, 1.0))", |
| 221 | " + i.x + vec4(0.0, i1.x, i2.x, 1.0));", |
| 222 | " float n_ = 0.142857142857;", |
| 223 | " vec3 ns = n_ * D.wyz - D.xzx;", |
| 224 | " vec4 j = p - 49.0 * floor(p * ns.z * ns.z);", |
| 225 | " vec4 x_ = floor(j * ns.z);", |
| 226 | " vec4 y_ = floor(j - 7.0 * x_);", |
| 227 | " vec4 x = x_ * ns.x + ns.yyyy;", |
| 228 | " vec4 y = y_ * ns.x + ns.yyyy;", |
| 229 | " vec4 h = 1.0 - abs(x) - abs(y);", |
| 230 | " vec4 b0 = vec4(x.xy, y.xy);", |
| 231 | " vec4 b1 = vec4(x.zw, y.zw);", |
| 232 | " vec4 s0 = floor(b0) * 2.0 + 1.0;", |
| 233 | " vec4 s1 = floor(b1) * 2.0 + 1.0;", |
| 234 | " vec4 sh = -step(h, vec4(0.0));", |
| 235 | " vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;", |
| 236 | " vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;", |
| 237 | " vec3 p0 = vec3(a0.xy, h.x);", |
| 238 | " vec3 p1 = vec3(a0.zw, h.y);", |
| 239 | " vec3 p2 = vec3(a1.xy, h.z);", |
| 240 | " vec3 p3 = vec3(a1.zw, h.w);", |
| 241 | " vec4 norm = taylorInvSqrt(vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3)));", |
| 242 | " p0 *= norm.x; p1 *= norm.y; p2 *= norm.z; p3 *= norm.w;", |
| 243 | " vec4 m = max(0.6 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0);", |
| 244 | " m = m * m;", |
| 245 | " return 42.0 * dot(m * m, vec4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3)));", |
| 246 | "}", |
| 247 | // 4-octave FBM: freq ×2, amp ×0.5 each layer; time in Z for continuous ripple. |
| 248 | "float fbm(vec3 p) {", |
| 249 | " float sum = 0.0;", |
| 250 | " float amp = 0.5;", |
| 251 | " sum += amp * snoise(p); p *= 2.0; amp *= 0.5;", |
| 252 | " sum += amp * snoise(p); p *= 2.0; amp *= 0.5;", |
| 253 | " sum += amp * snoise(p); p *= 2.0; amp *= 0.5;", |
| 254 | " sum += amp * snoise(p);", |
| 255 | " return sum;", |
| 256 | "}", |
| 257 | "vec2 wrapUv(vec2 uv) {", |
| 258 | " return fract(uv) * 0.998 + 0.001;", |
| 259 | "}", |
| 260 | "float sampleShore(", |
| 261 | " float enabled, float useShore, vec2 shoreNu,", |
| 262 | " inout vec3 shoreRgb, inout float shoreW", |
| 263 | ") {", |
| 264 | " if (enabled < 0.5 || useShore < 0.5 || u_hasShore < 0.5) { return 0.0; }", |
| 265 | " vec2 shoreUv = u_shoreUvRect.xy + shoreNu * (u_shoreUvRect.zw - u_shoreUvRect.xy);", |
| 266 | " vec4 shore = texture2D(u_secondary, shoreUv);", |
| 267 | " if (shore.a <= 0.1) { return 0.0; }", |
| 268 | " shoreRgb = shore.rgb;", |
| 269 | " shoreW = 1.0;", |
| 270 | " return 1.0;", |
| 271 | "}", |
| 272 | "void main() {", |
| 273 | " vec2 px = floor(v_texCoord * 16.0) + 0.5;", |
| 274 | " vec2 puv = px / 16.0;", |
| 275 | " vec2 world = vec2(u_tileX, u_tileY) + puv;", |
| 276 | " float t = u_time;", |
| 277 | " vec2 flow = vec2(t * u_flowX, t * u_flowY);", |
| 278 | " float eps = max(u_normalEps, 0.001);", |
| 279 | " vec3 base = vec3(world * u_waveScale + flow, t * u_flowZ);", |
| 280 | " float nC = fbm(base);", |
| 281 | " float nL = fbm(base + vec3(-eps, 0.0, 0.0));", |
| 282 | " float nR = fbm(base + vec3(eps, 0.0, 0.0));", |
| 283 | " float nD = fbm(base + vec3(0.0, -eps, 0.0));", |
| 284 | " float nU = fbm(base + vec3(0.0, eps, 0.0));", |
| 285 | " vec2 distort = vec2(nL - nR, nD - nU) * u_distort;", |
| 286 | " float texN = texture2D(u_texture, wrapUv(world * 0.28 + flow * 0.6 + distort)).r;", |
| 287 | " float h = nC * u_fbmAmp + (texN - 0.5) * u_texAmp;", |
| 288 | " vec3 normal = normalize(vec3(nL - nR, nD - nU, max(u_normalZ, 0.05)));", |
| 289 | " float ndotl = clamp(dot(normal, normalize(vec3(u_lightDirX, u_lightDirY, u_lightDirZ))), 0.0, 1.0);", |
| 290 | " float wave = clamp(h * u_waveGain + 0.5, 0.0, 1.0);", |
| 291 | " float crest = pow(smoothstep(u_crestLo, max(u_crestHi, u_crestLo + 0.01), wave), max(u_crestPow, 0.01));", |
| 292 | " float glitter = pow(max(0.0, ndotl), max(u_glitterPow, 0.01)) * crest;", |
| 293 | " glitter = max(glitter, pow(crest, 2.5) * u_crestGlitter);", |
| 294 | " float edgeProx = 0.0;", |
| 295 | " if (u_edgeN > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.y)); }", |
| 296 | " if (u_edgeS > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.y)); }", |
| 297 | " if (u_edgeW > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.x)); }", |
| 298 | " if (u_edgeE > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.x)); }", |
| 299 | " if (u_edgeNE > 0.5) {", |
| 300 | " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, puv.y))));", |
| 301 | " }", |
| 302 | " if (u_edgeNW > 0.5) {", |
| 303 | " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, puv.y))));", |
| 304 | " }", |
| 305 | " if (u_edgeSE > 0.5) {", |
| 306 | " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, 1.0 - puv.y))));", |
| 307 | " }", |
| 308 | " if (u_edgeSW > 0.5) {", |
| 309 | " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, 1.0 - puv.y))));", |
| 310 | " }", |
| 311 | " float waveBody = wave * (1.0 - edgeProx * 0.72);", |
| 312 | " float deepTop = mix(u_deepNW, u_deepNE, puv.x);", |
| 313 | " float deepBot = mix(u_deepSW, u_deepSE, puv.x);", |
| 314 | " float deepMix = mix(deepTop, deepBot, puv.y);", |
| 315 | " float deepAmt = pow(clamp(deepMix, 0.0, 1.0), max(u_deepAbrupt, 0.05));", |
| 316 | " float darkW = clamp(u_deepDark, 0.0, 1.0);", |
| 317 | " vec3 deepCol = mix(vec3(0.12, 0.34, 0.54), mix(vec3(0.05, 0.16, 0.34), vec3(0.015, 0.055, 0.14), darkW), deepAmt);", |
| 318 | " vec3 midCol = mix(vec3(0.24, 0.52, 0.70), mix(vec3(0.10, 0.30, 0.50), vec3(0.04, 0.14, 0.28), darkW), deepAmt);", |
| 319 | " vec3 litCol = mix(vec3(0.52, 0.78, 0.90), mix(vec3(0.26, 0.46, 0.66), vec3(0.12, 0.28, 0.46), darkW), deepAmt);", |
| 320 | " vec3 sparkCol = mix(vec3(0.98, 1.0, 1.0), mix(vec3(0.72, 0.88, 0.98), vec3(0.48, 0.68, 0.86), darkW), deepAmt);", |
| 321 | " vec3 foamCol = vec3(0.94, 0.99, 1.0);", |
| 322 | " float shade = mix(u_shadeLo, u_shadeHi, ndotl);", |
| 323 | " vec3 rgb = mix(deepCol, midCol, smoothstep(u_bodyLo, max(u_bodyHi, u_bodyLo + 0.01), waveBody));", |
| 324 | " rgb = mix(rgb, litCol, smoothstep(u_litLo, max(u_litHi, u_litLo + 0.01), waveBody) * u_litMix);", |
| 325 | " rgb *= shade;", |
| 326 | " rgb = mix(rgb, sparkCol, min(glitter, u_glitterCap) * u_glitterMix * (1.0 - edgeProx * 0.7));", |
| 327 | " rgb = mix(rgb, deepCol, edgeProx * u_edgeDark);", |
| 328 | " float shoreW = 0.0;", |
| 329 | " vec3 shoreRgb = rgb;", |
| 330 | " if (u_edgeN > 0.5) {", |
| 331 | " sampleShore(1.0, u_shoreEdgeN, vec2(puv.x, 1.0 - puv.y), shoreRgb, shoreW);", |
| 332 | " }", |
| 333 | " if (u_edgeS > 0.5) {", |
| 334 | " sampleShore(1.0, u_shoreEdgeS, vec2(puv.x, 1.0 - puv.y), shoreRgb, shoreW);", |
| 335 | " }", |
| 336 | " if (u_edgeW > 0.5) {", |
| 337 | " sampleShore(1.0, u_shoreEdgeW, vec2(1.0 - puv.x, puv.y), shoreRgb, shoreW);", |
| 338 | " }", |
| 339 | " if (u_edgeE > 0.5) {", |
| 340 | " sampleShore(1.0, u_shoreEdgeE, vec2(1.0 - puv.x, puv.y), shoreRgb, shoreW);", |
| 341 | " }", |
| 342 | " if (u_edgeNE > 0.5) {", |
| 343 | " sampleShore(1.0, max(u_shoreEdgeNE, u_hasShore), vec2(1.0 - puv.x, puv.y), shoreRgb, shoreW);", |
| 344 | " }", |
| 345 | " if (u_edgeNW > 0.5) {", |
| 346 | " sampleShore(1.0, max(u_shoreEdgeNW, u_hasShore), vec2(puv.x, puv.y), shoreRgb, shoreW);", |
| 347 | " }", |
| 348 | " if (u_edgeSE > 0.5) {", |
| 349 | " sampleShore(1.0, max(u_shoreEdgeSE, u_hasShore), vec2(1.0 - puv.x, 1.0 - puv.y), shoreRgb, shoreW);", |
| 350 | " }", |
| 351 | " if (u_edgeSW > 0.5) {", |
| 352 | " sampleShore(1.0, max(u_shoreEdgeSW, u_hasShore), vec2(puv.x, 1.0 - puv.y), shoreRgb, shoreW);", |
| 353 | " }", |
| 354 | " float darkAmt = 1.0 - smoothstep(0.18, 0.52, waveBody);", |
| 355 | " float retreat = edgeProx * (0.35 + 0.65 * darkAmt);", |
| 356 | " float shoreClip = u_shoreClip;", |
| 357 | " float shoreMask = step(shoreClip, retreat) * shoreW;", |
| 358 | " float foamAmt = (1.0 - shoreMask) * smoothstep(shoreClip - 0.24, shoreClip - 0.08, retreat)", |
| 359 | " * (1.0 - smoothstep(shoreClip - 0.08, shoreClip, retreat));", |
| 360 | " rgb = mix(rgb, foamCol, foamAmt * u_foamStrength);", |
| 361 | " rgb = mix(rgb, shoreRgb, shoreMask);", |
| 362 | " float litTop = mix(u_litNW, u_litNE, v_texCoord.x);", |
| 363 | " float litBottom = mix(u_litSW, u_litSE, v_texCoord.x);", |
| 364 | " float lit = mix(litTop, litBottom, v_texCoord.y);", |
| 365 | " float darkness = u_ambientDark * (1.0 - lit);", |
| 366 | " rgb = mix(rgb, vec3(0.0), darkness);", |
| 367 | " gl_FragColor = vec4(rgb, u_alpha);", |
| 368 | "}" |
| 369 | ].join("\n"); |
| 370 | |
| 371 | /** Lava heat: dark red → red → orange → yellow; yellow drives bloom companion. */ |
| 372 | const LAVA_FBM_COMMON = [ |
| 373 | "vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }", |
| 374 | "vec4 mod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }", |
| 375 | "vec4 permute(vec4 x) { return mod289(((x * 34.0) + 1.0) * x); }", |
| 376 | "vec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; }", |
| 377 | "float snoise(vec3 v) {", |
| 378 | " vec2 C = vec2(1.0 / 6.0, 1.0 / 3.0);", |
| 379 | " vec4 D = vec4(0.0, 0.5, 1.0, 2.0);", |
| 380 | " vec3 i = floor(v + dot(v, C.yyy));", |
| 381 | " vec3 x0 = v - i + dot(i, C.xxx);", |
| 382 | " vec3 g = step(x0.yzx, x0.xyz);", |
| 383 | " vec3 l = 1.0 - g;", |
| 384 | " vec3 i1 = min(g.xyz, l.zxy);", |
| 385 | " vec3 i2 = max(g.xyz, l.zxy);", |
| 386 | " vec3 x1 = x0 - i1 + C.xxx;", |
| 387 | " vec3 x2 = x0 - i2 + C.yyy;", |
| 388 | " vec3 x3 = x0 - D.yyy;", |
| 389 | " i = mod289(i);", |
| 390 | " vec4 p = permute(permute(permute(", |
| 391 | " i.z + vec4(0.0, i1.z, i2.z, 1.0))", |
| 392 | " + i.y + vec4(0.0, i1.y, i2.y, 1.0))", |
| 393 | " + i.x + vec4(0.0, i1.x, i2.x, 1.0));", |
| 394 | " float n_ = 0.142857142857;", |
| 395 | " vec3 ns = n_ * D.wyz - D.xzx;", |
| 396 | " vec4 j = p - 49.0 * floor(p * ns.z * ns.z);", |
| 397 | " vec4 x_ = floor(j * ns.z);", |
| 398 | " vec4 y_ = floor(j - 7.0 * x_);", |
| 399 | " vec4 x = x_ * ns.x + ns.yyyy;", |
| 400 | " vec4 y = y_ * ns.x + ns.yyyy;", |
| 401 | " vec4 h = 1.0 - abs(x) - abs(y);", |
| 402 | " vec4 b0 = vec4(x.xy, y.xy);", |
| 403 | " vec4 b1 = vec4(x.zw, y.zw);", |
| 404 | " vec4 s0 = floor(b0) * 2.0 + 1.0;", |
| 405 | " vec4 s1 = floor(b1) * 2.0 + 1.0;", |
| 406 | " vec4 sh = -step(h, vec4(0.0));", |
| 407 | " vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;", |
| 408 | " vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;", |
| 409 | " vec3 p0 = vec3(a0.xy, h.x);", |
| 410 | " vec3 p1 = vec3(a0.zw, h.y);", |
| 411 | " vec3 p2 = vec3(a1.xy, h.z);", |
| 412 | " vec3 p3 = vec3(a1.zw, h.w);", |
| 413 | " vec4 norm = taylorInvSqrt(vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3)));", |
| 414 | " p0 *= norm.x; p1 *= norm.y; p2 *= norm.z; p3 *= norm.w;", |
| 415 | " vec4 m = max(0.6 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0);", |
| 416 | " m = m * m;", |
| 417 | " return 42.0 * dot(m * m, vec4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3)));", |
| 418 | "}", |
| 419 | "float fbm(vec3 p) {", |
| 420 | " float sum = 0.0;", |
| 421 | " float amp = 0.5;", |
| 422 | " sum += amp * snoise(p); p *= 2.0; amp *= 0.5;", |
| 423 | " sum += amp * snoise(p); p *= 2.0; amp *= 0.5;", |
| 424 | " sum += amp * snoise(p); p *= 2.0; amp *= 0.5;", |
| 425 | " sum += amp * snoise(p);", |
| 426 | " return sum;", |
| 427 | "}", |
| 428 | "vec2 wrapUv(vec2 uv) {", |
| 429 | " return fract(uv) * 0.998 + 0.001;", |
| 430 | "}" |
| 431 | ]; |
| 432 | |
| 433 | const LAVA_GROUND_FRAG = [ |
| 434 | "precision mediump float;", |
| 435 | "varying vec2 v_texCoord;", |
| 436 | "uniform sampler2D u_texture;", |
| 437 | "uniform float u_alpha;", |
| 438 | "uniform float u_ambientDark;", |
| 439 | "uniform float u_litNW;", |
| 440 | "uniform float u_litNE;", |
| 441 | "uniform float u_litSW;", |
| 442 | "uniform float u_litSE;", |
| 443 | "uniform float u_time;", |
| 444 | "uniform float u_tileX;", |
| 445 | "uniform float u_tileY;", |
| 446 | "uniform float u_edgeN;", |
| 447 | "uniform float u_edgeE;", |
| 448 | "uniform float u_edgeS;", |
| 449 | "uniform float u_edgeW;", |
| 450 | "uniform float u_edgeNE;", |
| 451 | "uniform float u_edgeNW;", |
| 452 | "uniform float u_edgeSE;", |
| 453 | "uniform float u_edgeSW;", |
| 454 | "uniform float u_flowX;", |
| 455 | "uniform float u_flowY;", |
| 456 | "uniform float u_flowZ;", |
| 457 | "uniform float u_waveScale;", |
| 458 | "uniform float u_fbmAmp;", |
| 459 | "uniform float u_texAmp;", |
| 460 | "uniform float u_distort;", |
| 461 | "uniform float u_normalZ;", |
| 462 | "uniform float u_waveGain;", |
| 463 | "uniform float u_crestLo;", |
| 464 | "uniform float u_crestHi;", |
| 465 | "uniform float u_crestPow;", |
| 466 | "uniform float u_glitterPow;", |
| 467 | "uniform float u_crestGlitter;", |
| 468 | "uniform float u_glitterCap;", |
| 469 | "uniform float u_glitterMix;", |
| 470 | "uniform float u_shadeLo;", |
| 471 | "uniform float u_shadeHi;", |
| 472 | "uniform float u_bodyLo;", |
| 473 | "uniform float u_bodyHi;", |
| 474 | "uniform float u_litLo;", |
| 475 | "uniform float u_litHi;", |
| 476 | "uniform float u_litMix;", |
| 477 | "uniform float u_edgeDark;", |
| 478 | "uniform float u_lightDirX;", |
| 479 | "uniform float u_lightDirY;", |
| 480 | "uniform float u_lightDirZ;", |
| 481 | "uniform float u_normalEps;", |
| 482 | "uniform float u_shoreClip;", |
| 483 | "uniform float u_hasShore;", |
| 484 | "uniform float u_shoreEdgeN;", |
| 485 | "uniform float u_shoreEdgeE;", |
| 486 | "uniform float u_shoreEdgeS;", |
| 487 | "uniform float u_shoreEdgeW;", |
| 488 | "uniform float u_shoreEdgeNE;", |
| 489 | "uniform float u_shoreEdgeNW;", |
| 490 | "uniform float u_shoreEdgeSE;", |
| 491 | "uniform float u_shoreEdgeSW;", |
| 492 | "uniform vec4 u_shoreUvRect;", |
| 493 | "uniform sampler2D u_secondary;", |
| 494 | ...LAVA_FBM_COMMON, |
| 495 | "float sampleShore(", |
| 496 | " float enabled, float useShore, vec2 shoreNu,", |
| 497 | " inout vec3 shoreRgb, inout float shoreW", |
| 498 | ") {", |
| 499 | " if (enabled < 0.5 || useShore < 0.5 || u_hasShore < 0.5) { return 0.0; }", |
| 500 | " vec2 shoreUv = u_shoreUvRect.xy + shoreNu * (u_shoreUvRect.zw - u_shoreUvRect.xy);", |
| 501 | " vec4 shore = texture2D(u_secondary, shoreUv);", |
| 502 | " if (shore.a <= 0.1) { return 0.0; }", |
| 503 | " shoreRgb = shore.rgb;", |
| 504 | " shoreW = 1.0;", |
| 505 | " return 1.0;", |
| 506 | "}", |
| 507 | "void main() {", |
| 508 | " vec2 px = floor(v_texCoord * 16.0) + 0.5;", |
| 509 | " vec2 puv = px / 16.0;", |
| 510 | " vec2 world = vec2(u_tileX, u_tileY) + puv;", |
| 511 | " float t = u_time;", |
| 512 | " vec2 flow = vec2(t * u_flowX, t * u_flowY);", |
| 513 | " float eps = max(u_normalEps, 0.001);", |
| 514 | " vec3 base = vec3(world * u_waveScale + flow, t * u_flowZ);", |
| 515 | " float nC = fbm(base);", |
| 516 | " float nL = fbm(base + vec3(-eps, 0.0, 0.0));", |
| 517 | " float nR = fbm(base + vec3(eps, 0.0, 0.0));", |
| 518 | " float nD = fbm(base + vec3(0.0, -eps, 0.0));", |
| 519 | " float nU = fbm(base + vec3(0.0, eps, 0.0));", |
| 520 | " vec2 distort = vec2(nL - nR, nD - nU) * u_distort;", |
| 521 | " float texN = texture2D(u_texture, wrapUv(world * 0.28 + flow * 0.6 + distort)).r;", |
| 522 | " float h = nC * u_fbmAmp + (texN - 0.5) * u_texAmp;", |
| 523 | " vec3 normal = normalize(vec3(nL - nR, nD - nU, max(u_normalZ, 0.05)));", |
| 524 | " float ndotl = clamp(dot(normal, normalize(vec3(u_lightDirX, u_lightDirY, u_lightDirZ))), 0.0, 1.0);", |
| 525 | " float wave = clamp(h * u_waveGain + 0.5, 0.0, 1.0);", |
| 526 | " float crest = pow(smoothstep(u_crestLo, max(u_crestHi, u_crestLo + 0.01), wave), max(u_crestPow, 0.01));", |
| 527 | " float glitter = pow(max(0.0, ndotl), max(u_glitterPow, 0.01)) * crest;", |
| 528 | " glitter = max(glitter, pow(crest, 2.5) * u_crestGlitter);", |
| 529 | " float edgeProx = 0.0;", |
| 530 | " if (u_edgeN > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.y)); }", |
| 531 | " if (u_edgeS > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.y)); }", |
| 532 | " if (u_edgeW > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.x)); }", |
| 533 | " if (u_edgeE > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.x)); }", |
| 534 | " if (u_edgeNE > 0.5) {", |
| 535 | " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, puv.y))));", |
| 536 | " }", |
| 537 | " if (u_edgeNW > 0.5) {", |
| 538 | " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, puv.y))));", |
| 539 | " }", |
| 540 | " if (u_edgeSE > 0.5) {", |
| 541 | " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, 1.0 - puv.y))));", |
| 542 | " }", |
| 543 | " if (u_edgeSW > 0.5) {", |
| 544 | " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, 1.0 - puv.y))));", |
| 545 | " }", |
| 546 | " float waveBody = wave * (1.0 - edgeProx * 0.72);", |
| 547 | " float heat = smoothstep(u_bodyLo, max(u_bodyHi, u_bodyLo + 0.01), waveBody);", |
| 548 | " heat = mix(heat, 1.0, smoothstep(u_litLo, max(u_litHi, u_litLo + 0.01), waveBody) * u_litMix * 0.35);", |
| 549 | " heat = clamp(heat + min(glitter, u_glitterCap) * u_glitterMix * 0.45, 0.0, 1.0);", |
| 550 | " vec3 darkRed = vec3(0.16, 0.015, 0.01);", |
| 551 | " vec3 brightRed = vec3(0.78, 0.08, 0.02);", |
| 552 | " vec3 orange = vec3(0.98, 0.38, 0.04);", |
| 553 | " vec3 yellow = vec3(1.0, 0.9, 0.28);", |
| 554 | " vec3 rgb = mix(darkRed, brightRed, smoothstep(0.0, 0.38, heat));", |
| 555 | " rgb = mix(rgb, orange, smoothstep(0.28, 0.68, heat));", |
| 556 | " float yellowAmt = smoothstep(0.55, 0.98, heat);", |
| 557 | " rgb = mix(rgb, yellow, yellowAmt);", |
| 558 | " float shade = mix(u_shadeLo, u_shadeHi, ndotl);", |
| 559 | " rgb *= shade;", |
| 560 | " rgb = mix(rgb, darkRed, edgeProx * u_edgeDark * 0.35);", |
| 561 | " float shoreW = 0.0;", |
| 562 | " vec3 shoreRgb = rgb;", |
| 563 | " if (u_edgeN > 0.5) {", |
| 564 | " sampleShore(1.0, u_shoreEdgeN, vec2(puv.x, 1.0 - puv.y), shoreRgb, shoreW);", |
| 565 | " }", |
| 566 | " if (u_edgeS > 0.5) {", |
| 567 | " sampleShore(1.0, u_shoreEdgeS, vec2(puv.x, 1.0 - puv.y), shoreRgb, shoreW);", |
| 568 | " }", |
| 569 | " if (u_edgeW > 0.5) {", |
| 570 | " sampleShore(1.0, u_shoreEdgeW, vec2(1.0 - puv.x, puv.y), shoreRgb, shoreW);", |
| 571 | " }", |
| 572 | " if (u_edgeE > 0.5) {", |
| 573 | " sampleShore(1.0, u_shoreEdgeE, vec2(1.0 - puv.x, puv.y), shoreRgb, shoreW);", |
| 574 | " }", |
| 575 | " if (u_edgeNE > 0.5) {", |
| 576 | " sampleShore(1.0, max(u_shoreEdgeNE, u_hasShore), vec2(1.0 - puv.x, puv.y), shoreRgb, shoreW);", |
| 577 | " }", |
| 578 | " if (u_edgeNW > 0.5) {", |
| 579 | " sampleShore(1.0, max(u_shoreEdgeNW, u_hasShore), vec2(puv.x, puv.y), shoreRgb, shoreW);", |
| 580 | " }", |
| 581 | " if (u_edgeSE > 0.5) {", |
| 582 | " sampleShore(1.0, max(u_shoreEdgeSE, u_hasShore), vec2(1.0 - puv.x, 1.0 - puv.y), shoreRgb, shoreW);", |
| 583 | " }", |
| 584 | " if (u_edgeSW > 0.5) {", |
| 585 | " sampleShore(1.0, max(u_shoreEdgeSW, u_hasShore), vec2(puv.x, 1.0 - puv.y), shoreRgb, shoreW);", |
| 586 | " }", |
| 587 | " float darkAmt = 1.0 - smoothstep(0.12, 0.48, waveBody);", |
| 588 | " float retreat = edgeProx * mix(0.72, 1.0, darkAmt);", |
| 589 | " float shoreClip = u_shoreClip;", |
| 590 | " float shoreMask = step(shoreClip, retreat) * shoreW;", |
| 591 | " float crustAmt = (1.0 - shoreMask) * smoothstep(shoreClip - 0.2, shoreClip - 0.06, retreat)", |
| 592 | " * (1.0 - smoothstep(shoreClip - 0.06, shoreClip, retreat));", |
| 593 | " rgb = mix(rgb, vec3(0.05, 0.01, 0.0), crustAmt);", |
| 594 | " rgb = mix(rgb, shoreRgb, shoreMask);", |
| 595 | " float litTop = mix(u_litNW, u_litNE, v_texCoord.x);", |
| 596 | " float litBottom = mix(u_litSW, u_litSE, v_texCoord.x);", |
| 597 | " float lit = mix(litTop, litBottom, v_texCoord.y);", |
| 598 | " float darkness = u_ambientDark * (1.0 - lit);", |
| 599 | " rgb = mix(rgb, vec3(0.0), darkness);", |
| 600 | " gl_FragColor = vec4(rgb, u_alpha);", |
| 601 | "}" |
| 602 | ].join("\n"); |
| 603 | |
| 604 | /** Unlit bloom overlay — strength tracks yellow heat (exempt from world darkness). */ |
| 605 | const LAVA_BLOOM_FRAG = [ |
| 606 | "precision mediump float;", |
| 607 | "varying vec2 v_texCoord;", |
| 608 | "uniform sampler2D u_texture;", |
| 609 | "uniform float u_alpha;", |
| 610 | "uniform float u_time;", |
| 611 | "uniform float u_tileX;", |
| 612 | "uniform float u_tileY;", |
| 613 | "uniform float u_edgeN;", |
| 614 | "uniform float u_edgeE;", |
| 615 | "uniform float u_edgeS;", |
| 616 | "uniform float u_edgeW;", |
| 617 | "uniform float u_edgeNE;", |
| 618 | "uniform float u_edgeNW;", |
| 619 | "uniform float u_edgeSE;", |
| 620 | "uniform float u_edgeSW;", |
| 621 | "uniform float u_flowX;", |
| 622 | "uniform float u_flowY;", |
| 623 | "uniform float u_flowZ;", |
| 624 | "uniform float u_waveScale;", |
| 625 | "uniform float u_fbmAmp;", |
| 626 | "uniform float u_texAmp;", |
| 627 | "uniform float u_distort;", |
| 628 | "uniform float u_normalZ;", |
| 629 | "uniform float u_waveGain;", |
| 630 | "uniform float u_crestLo;", |
| 631 | "uniform float u_crestHi;", |
| 632 | "uniform float u_crestPow;", |
| 633 | "uniform float u_glitterPow;", |
| 634 | "uniform float u_crestGlitter;", |
| 635 | "uniform float u_glitterCap;", |
| 636 | "uniform float u_glitterMix;", |
| 637 | "uniform float u_bodyLo;", |
| 638 | "uniform float u_bodyHi;", |
| 639 | "uniform float u_litLo;", |
| 640 | "uniform float u_litHi;", |
| 641 | "uniform float u_litMix;", |
| 642 | "uniform float u_lightDirX;", |
| 643 | "uniform float u_lightDirY;", |
| 644 | "uniform float u_lightDirZ;", |
| 645 | "uniform float u_normalEps;", |
| 646 | "uniform float u_bloomStrength;", |
| 647 | "uniform float u_shoreClip;", |
| 648 | ...LAVA_FBM_COMMON, |
| 649 | "void main() {", |
| 650 | " vec2 px = floor(v_texCoord * 16.0) + 0.5;", |
| 651 | " vec2 puv = px / 16.0;", |
| 652 | " vec2 world = vec2(u_tileX, u_tileY) + puv;", |
| 653 | " float t = u_time;", |
| 654 | " vec2 flow = vec2(t * u_flowX, t * u_flowY);", |
| 655 | " float eps = max(u_normalEps, 0.001);", |
| 656 | " vec3 base = vec3(world * u_waveScale + flow, t * u_flowZ);", |
| 657 | " float nC = fbm(base);", |
| 658 | " float nL = fbm(base + vec3(-eps, 0.0, 0.0));", |
| 659 | " float nR = fbm(base + vec3(eps, 0.0, 0.0));", |
| 660 | " float nD = fbm(base + vec3(0.0, -eps, 0.0));", |
| 661 | " float nU = fbm(base + vec3(0.0, eps, 0.0));", |
| 662 | " vec2 distort = vec2(nL - nR, nD - nU) * u_distort;", |
| 663 | " float texN = texture2D(u_texture, wrapUv(world * 0.28 + flow * 0.6 + distort)).r;", |
| 664 | " float h = nC * u_fbmAmp + (texN - 0.5) * u_texAmp;", |
| 665 | " vec3 normal = normalize(vec3(nL - nR, nD - nU, max(u_normalZ, 0.05)));", |
| 666 | " float ndotl = clamp(dot(normal, normalize(vec3(u_lightDirX, u_lightDirY, u_lightDirZ))), 0.0, 1.0);", |
| 667 | " float wave = clamp(h * u_waveGain + 0.5, 0.0, 1.0);", |
| 668 | " float crest = pow(smoothstep(u_crestLo, max(u_crestHi, u_crestLo + 0.01), wave), max(u_crestPow, 0.01));", |
| 669 | " float glitter = pow(max(0.0, ndotl), max(u_glitterPow, 0.01)) * crest;", |
| 670 | " glitter = max(glitter, pow(crest, 2.5) * u_crestGlitter);", |
| 671 | " float edgeProx = 0.0;", |
| 672 | " if (u_edgeN > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.y)); }", |
| 673 | " if (u_edgeS > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.y)); }", |
| 674 | " if (u_edgeW > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, puv.x)); }", |
| 675 | " if (u_edgeE > 0.5) { edgeProx = max(edgeProx, smoothstep(0.55, 0.0, 1.0 - puv.x)); }", |
| 676 | " if (u_edgeNE > 0.5) {", |
| 677 | " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, puv.y))));", |
| 678 | " }", |
| 679 | " if (u_edgeNW > 0.5) {", |
| 680 | " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, puv.y))));", |
| 681 | " }", |
| 682 | " if (u_edgeSE > 0.5) {", |
| 683 | " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(1.0 - puv.x, 1.0 - puv.y))));", |
| 684 | " }", |
| 685 | " if (u_edgeSW > 0.5) {", |
| 686 | " edgeProx = max(edgeProx, 1.0 - smoothstep(0.0, 0.78, length(vec2(puv.x, 1.0 - puv.y))));", |
| 687 | " }", |
| 688 | " float waveBody = wave * (1.0 - edgeProx * 0.72);", |
| 689 | " float heat = smoothstep(u_bodyLo, max(u_bodyHi, u_bodyLo + 0.01), waveBody);", |
| 690 | " heat = mix(heat, 1.0, smoothstep(u_litLo, max(u_litHi, u_litLo + 0.01), waveBody) * u_litMix * 0.35);", |
| 691 | " heat = clamp(heat + min(glitter, u_glitterCap) * u_glitterMix * 0.45, 0.0, 1.0);", |
| 692 | " float darkAmt = 1.0 - smoothstep(0.12, 0.48, waveBody);", |
| 693 | " float retreat = edgeProx * mix(0.72, 1.0, darkAmt);", |
| 694 | " float hasEdge = max(max(u_edgeN, u_edgeE), max(u_edgeS, u_edgeW));", |
| 695 | " hasEdge = max(hasEdge, max(max(u_edgeNE, u_edgeNW), max(u_edgeSE, u_edgeSW)));", |
| 696 | " float shoreW = step(0.5, hasEdge);", |
| 697 | " float shoreMask = step(u_shoreClip, retreat) * shoreW;", |
| 698 | " float yellowAmt = smoothstep(0.55, 0.98, heat) * (1.0 - edgeProx * 0.85) * (1.0 - shoreMask);", |
| 699 | " float bloom = yellowAmt * max(u_bloomStrength, 0.0);", |
| 700 | " vec3 glow = vec3(1.0, 0.82, 0.28) * bloom;", |
| 701 | " gl_FragColor = vec4(glow, bloom * u_alpha);", |
| 702 | "}" |
| 703 | ].join("\n"); |
| 704 | |
| 705 | /** Magenta-tint (R==B, G < R) then lit effects; darkness always after tint. */ |
| 706 | const TINT_LIT_SPRITE_FRAG = [ |
| 707 | "precision mediump float;", |
| 708 | "varying vec2 v_texCoord;", |
| 709 | "uniform sampler2D u_texture;", |
| 710 | "uniform float u_alpha;", |
| 711 | "uniform float u_darkness;", |
| 712 | "uniform float u_strength;", |
| 713 | "uniform vec3 u_flashColor;", |
| 714 | "uniform float u_wade;", |
| 715 | "uniform float u_spriteHeight;", |
| 716 | "uniform float u_useTint;", |
| 717 | "uniform vec3 u_tintColor;", |
| 718 | "void main() {", |
| 719 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 720 | " if (color.a <= 0.0) { discard; }", |
| 721 | " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);", |
| 722 | " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }", |
| 723 | " vec3 rgb = color.rgb;", |
| 724 | " if (u_useTint > 0.5) {", |
| 725 | " if (abs(color.r - color.b) * 255.0 <= 2.01 && color.g < color.r) {", |
| 726 | " float L = color.r;", |
| 727 | " float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;", |
| 728 | " rgb = mix(u_tintColor, vec3(1.0), gBlend) * L;", |
| 729 | " }", |
| 730 | " }", |
| 731 | " if (u_wade > 0.5 && fromBottom < 5.0) {", |
| 732 | " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);", |
| 733 | " }", |
| 734 | " rgb = mix(rgb, vec3(0.0), u_darkness);", |
| 735 | " rgb = mix(rgb, u_flashColor, u_strength);", |
| 736 | " gl_FragColor = vec4(rgb, color.a * u_alpha);", |
| 737 | "}" |
| 738 | ].join("\n"); |
| 739 | |
| 740 | /** Dual/triple-channel tint: red = shaft, blue = tip, green = coat; then darkness. |
| 741 | * Only when the primary channel is highest and the other two are equal; |
| 742 | * equal non-zero secondaries lighten the assigned tint toward white. */ |
| 743 | const DUAL_TINT_LIT_SPRITE_FRAG = [ |
| 744 | "precision mediump float;", |
| 745 | "varying vec2 v_texCoord;", |
| 746 | "uniform sampler2D u_texture;", |
| 747 | "uniform float u_alpha;", |
| 748 | "uniform float u_darkness;", |
| 749 | "uniform float u_strength;", |
| 750 | "uniform vec3 u_flashColor;", |
| 751 | "uniform float u_wade;", |
| 752 | "uniform float u_spriteHeight;", |
| 753 | "uniform vec3 u_shaftTint;", |
| 754 | "uniform vec3 u_tipTint;", |
| 755 | "uniform vec3 u_coatTint;", |
| 756 | "uniform float u_hasCoat;", |
| 757 | "vec3 channelTint(float L, float secondary, vec3 tint) {", |
| 758 | " float blend = L > 0.0 ? clamp(secondary / L, 0.0, 1.0) : 0.0;", |
| 759 | " return mix(tint, vec3(1.0), blend) * L;", |
| 760 | "}", |
| 761 | "float channelMask(float primary, float o1, float o2) {", |
| 762 | " float equal = step(abs(o1 - o2), 0.04);", |
| 763 | " return clamp((primary - max(o1, o2)) * 1.75, 0.0, 1.0) * equal;", |
| 764 | "}", |
| 765 | "void main() {", |
| 766 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 767 | " if (color.a <= 0.0) { discard; }", |
| 768 | " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);", |
| 769 | " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }", |
| 770 | " vec3 rgb = color.rgb;", |
| 771 | " if (u_hasCoat > 0.5) {", |
| 772 | " float coatMask = channelMask(color.g, color.r, color.b);", |
| 773 | " if (coatMask > 0.0) {", |
| 774 | " vec3 coatCol = channelTint(color.g, color.r, u_coatTint);", |
| 775 | " rgb = mix(rgb, coatCol, coatMask);", |
| 776 | " }", |
| 777 | " }", |
| 778 | " float tipMask = channelMask(color.b, color.r, color.g);", |
| 779 | " if (tipMask > 0.0) {", |
| 780 | " vec3 tipCol = channelTint(color.b, color.r, u_tipTint);", |
| 781 | " rgb = mix(rgb, tipCol, tipMask);", |
| 782 | " }", |
| 783 | " float shaftMask = channelMask(color.r, color.g, color.b);", |
| 784 | " if (shaftMask > 0.0) {", |
| 785 | " vec3 shaftCol = channelTint(color.r, color.g, u_shaftTint);", |
| 786 | " rgb = mix(rgb, shaftCol, shaftMask);", |
| 787 | " }", |
| 788 | " if (u_wade > 0.5 && fromBottom < 5.0) {", |
| 789 | " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);", |
| 790 | " }", |
| 791 | " rgb = mix(rgb, vec3(0.0), u_darkness);", |
| 792 | " rgb = mix(rgb, u_flashColor, u_strength);", |
| 793 | " gl_FragColor = vec4(rgb, color.a * u_alpha);", |
| 794 | "}" |
| 795 | ].join("\n"); |
| 796 | |
| 797 | /** Magenta-tint equip overlay that clips alpha to the worn body silhouette. */ |
| 798 | /** |
| 799 | * Tight-fit: clip clothing alpha to the body silhouette in *pivot space* |
| 800 | * (sizes may differ: shirt 20×24 vs body 16×24). Sample body UV remapped from |
| 801 | * clothing frame coords; 1px dilate fills armpit/crotch gaps in the body art. |
| 802 | */ |
| 803 | const TIGHT_FIT_BODY_MASK_GLSL = [ |
| 804 | "uniform vec2 u_clothSize;", |
| 805 | "uniform vec2 u_bodySize;", |
| 806 | "uniform float u_pivotFromBottom;", |
| 807 | "uniform vec4 u_clothUvRect;", |
| 808 | "uniform vec4 u_bodyUvRect;", |
| 809 | "float tightFitBodyAlpha() {", |
| 810 | " vec2 clothSpan = max(u_clothUvRect.zw - u_clothUvRect.xy, vec2(1e-5));", |
| 811 | " vec2 nu = (v_texCoord - u_clothUvRect.xy) / clothSpan;", |
| 812 | " float ox = (nu.x - 0.5) * u_clothSize.x;", |
| 813 | " float oy = nu.y * u_clothSize.y - (u_clothSize.y - u_pivotFromBottom);", |
| 814 | " vec2 bodySize = max(u_bodySize, vec2(1.0));", |
| 815 | " vec2 bodyNu = vec2(0.5 + ox / bodySize.x, ((u_bodySize.y - u_pivotFromBottom) + oy) / bodySize.y);", |
| 816 | " vec2 bodySpan = max(u_bodyUvRect.zw - u_bodyUvRect.xy, vec2(1e-5));", |
| 817 | " vec2 texel = 1.0 / bodySize;", |
| 818 | " float bodyA = 0.0;", |
| 819 | " for (int dy = -1; dy <= 1; dy++) {", |
| 820 | " for (int dx = -1; dx <= 1; dx++) {", |
| 821 | " vec2 sampleNu = bodyNu + vec2(float(dx), float(dy)) * texel;", |
| 822 | " if (sampleNu.x < 0.0 || sampleNu.x > 1.0 || sampleNu.y < 0.0 || sampleNu.y > 1.0) { continue; }", |
| 823 | " vec2 sampleUv = u_bodyUvRect.xy + sampleNu * bodySpan;", |
| 824 | " bodyA = max(bodyA, texture2D(u_secondary, sampleUv).a);", |
| 825 | " }", |
| 826 | " }", |
| 827 | " return bodyA;", |
| 828 | "}" |
| 829 | ].join("\n"); |
| 830 | |
| 831 | const TIGHT_FIT_TINT_LIT_SPRITE_FRAG = [ |
| 832 | "precision mediump float;", |
| 833 | "varying vec2 v_texCoord;", |
| 834 | "uniform sampler2D u_texture;", |
| 835 | "uniform sampler2D u_secondary;", |
| 836 | "uniform float u_alpha;", |
| 837 | "uniform float u_darkness;", |
| 838 | "uniform float u_strength;", |
| 839 | "uniform vec3 u_flashColor;", |
| 840 | "uniform float u_wade;", |
| 841 | "uniform float u_spriteHeight;", |
| 842 | "uniform float u_useTint;", |
| 843 | "uniform vec3 u_tintColor;", |
| 844 | TIGHT_FIT_BODY_MASK_GLSL, |
| 845 | "void main() {", |
| 846 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 847 | " if (color.a <= 0.0) { discard; }", |
| 848 | " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);", |
| 849 | " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }", |
| 850 | " vec3 rgb = color.rgb;", |
| 851 | " if (u_useTint > 0.5) {", |
| 852 | " if (abs(color.r - color.b) * 255.0 <= 2.01 && color.g < color.r) {", |
| 853 | " float L = color.r;", |
| 854 | " float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;", |
| 855 | " rgb = mix(u_tintColor, vec3(1.0), gBlend) * L;", |
| 856 | " }", |
| 857 | " }", |
| 858 | " if (u_wade > 0.5 && fromBottom < 5.0) {", |
| 859 | " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);", |
| 860 | " }", |
| 861 | " rgb = mix(rgb, vec3(0.0), u_darkness);", |
| 862 | " rgb = mix(rgb, u_flashColor, u_strength);", |
| 863 | " float alpha = min(tightFitBodyAlpha(), color.a) * u_alpha;", |
| 864 | " if (alpha <= 0.0) { discard; }", |
| 865 | " gl_FragColor = vec4(rgb, alpha);", |
| 866 | "}" |
| 867 | ].join("\n"); |
| 868 | |
| 869 | /** Body-clipped equip overlay without dye recolour. */ |
| 870 | const TIGHT_FIT_LIT_SPRITE_FRAG = [ |
| 871 | "precision mediump float;", |
| 872 | "varying vec2 v_texCoord;", |
| 873 | "uniform sampler2D u_texture;", |
| 874 | "uniform sampler2D u_secondary;", |
| 875 | "uniform float u_alpha;", |
| 876 | "uniform float u_darkness;", |
| 877 | "uniform float u_strength;", |
| 878 | "uniform vec3 u_flashColor;", |
| 879 | "uniform float u_wade;", |
| 880 | "uniform float u_spriteHeight;", |
| 881 | TIGHT_FIT_BODY_MASK_GLSL, |
| 882 | "void main() {", |
| 883 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 884 | " if (color.a <= 0.0) { discard; }", |
| 885 | " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);", |
| 886 | " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }", |
| 887 | " vec3 rgb = color.rgb;", |
| 888 | " if (u_wade > 0.5 && fromBottom < 5.0) {", |
| 889 | " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);", |
| 890 | " }", |
| 891 | " rgb = mix(rgb, vec3(0.0), u_darkness);", |
| 892 | " rgb = mix(rgb, u_flashColor, u_strength);", |
| 893 | " float alpha = min(tightFitBodyAlpha(), color.a) * u_alpha;", |
| 894 | " if (alpha <= 0.0) { discard; }", |
| 895 | " gl_FragColor = vec4(rgb, alpha);", |
| 896 | "}" |
| 897 | ].join("\n"); |
| 898 | |
| 899 | const ATLAS_LIGHTING_FRAG = [ |
| 900 | "precision mediump float;", |
| 901 | "varying vec2 v_texCoord;", |
| 902 | "uniform sampler2D u_texture;", |
| 903 | "uniform sampler2D u_secondary;", |
| 904 | "uniform sampler2D u_bump;", |
| 905 | "uniform float u_alpha;", |
| 906 | "uniform float u_ambientDark;", |
| 907 | "uniform float u_lightRow;", |
| 908 | "uniform float u_useNature;", |
| 909 | "uniform float u_natureTint;", |
| 910 | "uniform float u_natureDark;", |
| 911 | "uniform float u_natureContrast;", |
| 912 | "void main() {", |
| 913 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 914 | " if (color.a <= 0.0) { discard; }", |
| 915 | " vec3 rgb = color.rgb;", |
| 916 | " if (u_useNature > 0.5) {", |
| 917 | // Soft bilinear over 18×18 noise (1-tile halo) so blend crosses chunk edges. |
| 918 | " vec2 texel = v_texCoord * 16.0 - 0.5;", |
| 919 | " vec2 i0 = floor(texel);", |
| 920 | " vec2 f = fract(texel);", |
| 921 | " vec2 i1 = i0 + 1.0;", |
| 922 | " vec2 c00 = (i0 + 1.5) / 18.0;", |
| 923 | " vec2 c10 = (vec2(i1.x, i0.y) + 1.5) / 18.0;", |
| 924 | " vec2 c01 = (vec2(i0.x, i1.y) + 1.5) / 18.0;", |
| 925 | " vec2 c11 = (i1 + 1.5) / 18.0;", |
| 926 | " vec4 s00 = texture2D(u_bump, c00);", |
| 927 | " vec4 s10 = texture2D(u_bump, c10);", |
| 928 | " vec4 s01 = texture2D(u_bump, c01);", |
| 929 | " vec4 s11 = texture2D(u_bump, c11);", |
| 930 | " float nRaw = mix(mix(s00.r, s10.r, f.x), mix(s01.r, s11.r, f.x), f.y);", |
| 931 | " float a = mix(mix(s00.a, s10.a, f.x), mix(s01.a, s11.a, f.x), f.y);", |
| 932 | " if (a > 0.01) {", |
| 933 | " float n = clamp((nRaw - 0.5) * max(u_natureContrast, 0.01) + 0.5, 0.0, 1.0);", |
| 934 | " float c = (n - 0.5) * 2.0;", |
| 935 | " vec3 tinted = rgb * (1.0 - c * u_natureDark);", |
| 936 | " vec3 cool = vec3(0.72, 1.14, 1.08);", |
| 937 | " vec3 warm = vec3(1.28, 1.06, 0.68);", |
| 938 | " vec3 tint = mix(cool, warm, n);", |
| 939 | " tinted *= mix(vec3(1.0), tint, clamp(u_natureTint, 0.0, 1.0));", |
| 940 | " rgb = mix(rgb, tinted, clamp(a, 0.0, 1.0));", |
| 941 | " }", |
| 942 | " }", |
| 943 | " vec2 lightUV = v_texCoord;", |
| 944 | " if (u_lightRow >= 0.0) {", |
| 945 | " lightUV.y = (u_lightRow + v_texCoord.y) / 16.0;", |
| 946 | " }", |
| 947 | " float lit = texture2D(u_secondary, lightUV).r;", |
| 948 | " float darkness = u_ambientDark * (1.0 - lit);", |
| 949 | " rgb = mix(rgb, vec3(0.0), darkness);", |
| 950 | " gl_FragColor = vec4(rgb, color.a * u_alpha);", |
| 951 | "}" |
| 952 | ].join("\n"); |
| 953 | |
| 954 | /** |
| 955 | * Per-tile cliff sprite: high-chroma / authored magenta top → sample this chunk's |
| 956 | * ground atlas (u_bump) at the cliff's tile-local UV. Only assigned to |
| 957 | * `cliffGroundTop` blocks — never to chunk block-row atlases (those keep normal |
| 958 | * lighting so magenta wood tints are not mistaken for cliff tops). |
| 959 | */ |
| 960 | const SPRITE_CLIFF_GROUND_TOP_FRAG = [ |
| 961 | "precision mediump float;", |
| 962 | "varying vec2 v_texCoord;", |
| 963 | "uniform sampler2D u_texture;", |
| 964 | "uniform sampler2D u_bump;", |
| 965 | "uniform float u_alpha;", |
| 966 | "uniform float u_darkness;", |
| 967 | "uniform vec2 u_tileLocal;", |
| 968 | "void main() {", |
| 969 | " vec4 color = texture2D(u_texture, v_texCoord);", |
| 970 | " if (color.a <= 0.0) { discard; }", |
| 971 | " vec3 rgb = color.rgb;", |
| 972 | " float rbDiff = abs(rgb.r - rgb.b);", |
| 973 | " if (rbDiff < 0.02 && rgb.g < rgb.r) {", |
| 974 | " vec2 groundUV = (u_tileLocal + v_texCoord) / 16.0;", |
| 975 | " rgb = texture2D(u_bump, groundUV).rgb;", |
| 976 | " }", |
| 977 | " rgb = mix(rgb, vec3(0.0), u_darkness);", |
| 978 | " gl_FragColor = vec4(rgb, color.a * u_alpha);", |
| 979 | "}" |
| 980 | ].join("\n"); |
| 981 | |
| 982 | let spriteLightingShader = null; |
| 983 | let atlasLightingShader = null; |
| 984 | let cliffGroundTopShader = null; |
| 985 | let waterGroundShader = null; |
| 986 | let lavaGroundShader = null; |
| 987 | let lavaBloomShader = null; |
| 988 | let waterAtlasChunkShader = null; |
| 989 | let lavaAtlasChunkShader = null; |
| 990 | let lavaBloomAtlasChunkShader = null; |
| 991 | let tintLitSpriteShader = null; |
| 992 | let dualTintLitSpriteShader = null; |
| 993 | let tightFitTintLitSpriteShader = null; |
| 994 | let tightFitLitSpriteShader = null; |
| 995 | |
| 996 | function getSpriteLightingShader () |
| 997 | { |
| 998 | if (!spriteLightingShader) |
| 999 | { spriteLightingShader = Shader.fragment(SPRITE_LIGHTING_FRAG); } |
| 1000 | return spriteLightingShader; |
| 1001 | } |
| 1002 | |
| 1003 | function getAtlasLightingShader () |
| 1004 | { |
| 1005 | if (!atlasLightingShader) |
| 1006 | { atlasLightingShader = Shader.fragment(ATLAS_LIGHTING_FRAG); } |
| 1007 | return atlasLightingShader; |
| 1008 | } |
| 1009 | |
| 1010 | function getCliffGroundTopShader () |
| 1011 | { |
| 1012 | if (!cliffGroundTopShader) |
| 1013 | { cliffGroundTopShader = Shader.fragment(SPRITE_CLIFF_GROUND_TOP_FRAG); } |
| 1014 | return cliffGroundTopShader; |
| 1015 | } |
| 1016 | |
| 1017 | function getWaterGroundShader () |
| 1018 | { |
| 1019 | if (!waterGroundShader) |
| 1020 | { waterGroundShader = Shader.fragment(WATER_GROUND_FRAG); } |
| 1021 | return waterGroundShader; |
| 1022 | } |
| 1023 | |
| 1024 | function getLavaGroundShader () |
| 1025 | { |
| 1026 | if (!lavaGroundShader) |
| 1027 | { lavaGroundShader = Shader.fragment(LAVA_GROUND_FRAG); } |
| 1028 | return lavaGroundShader; |
| 1029 | } |
| 1030 | |
| 1031 | function getLavaBloomShader () |
| 1032 | { |
| 1033 | if (!lavaBloomShader) |
| 1034 | { lavaBloomShader = Shader.fragment(LAVA_BLOOM_FRAG); } |
| 1035 | return lavaBloomShader; |
| 1036 | } |
| 1037 | |
| 1038 | function getWaterAtlasChunkShader () |
| 1039 | { |
| 1040 | if (!waterAtlasChunkShader) |
| 1041 | { waterAtlasChunkShader = Shader.fragment(WATER_ATLAS_CHUNK_FRAG); } |
| 1042 | return waterAtlasChunkShader; |
| 1043 | } |
| 1044 | |
| 1045 | function getLavaAtlasChunkShader () |
| 1046 | { |
| 1047 | if (!lavaAtlasChunkShader) |
| 1048 | { lavaAtlasChunkShader = Shader.fragment(LAVA_ATLAS_CHUNK_FRAG); } |
| 1049 | return lavaAtlasChunkShader; |
| 1050 | } |
| 1051 | |
| 1052 | function getLavaBloomAtlasChunkShader () |
| 1053 | { |
| 1054 | if (!lavaBloomAtlasChunkShader) |
| 1055 | { lavaBloomAtlasChunkShader = Shader.fragment(LAVA_BLOOM_ATLAS_CHUNK_FRAG); } |
| 1056 | return lavaBloomAtlasChunkShader; |
| 1057 | } |
| 1058 | |
| 1059 | function getTintLitSpriteShader () |
| 1060 | { |
| 1061 | if (!tintLitSpriteShader) |
| 1062 | { tintLitSpriteShader = Shader.fragment(TINT_LIT_SPRITE_FRAG); } |
| 1063 | return tintLitSpriteShader; |
| 1064 | } |
| 1065 | |
| 1066 | function getDualTintLitSpriteShader () |
| 1067 | { |
| 1068 | if (!dualTintLitSpriteShader) |
| 1069 | { dualTintLitSpriteShader = Shader.fragment(DUAL_TINT_LIT_SPRITE_FRAG); } |
| 1070 | return dualTintLitSpriteShader; |
| 1071 | } |
| 1072 | |
| 1073 | function getTightFitTintLitSpriteShader () |
| 1074 | { |
| 1075 | if (!tightFitTintLitSpriteShader) |
| 1076 | { tightFitTintLitSpriteShader = Shader.fragment(TIGHT_FIT_TINT_LIT_SPRITE_FRAG); } |
| 1077 | return tightFitTintLitSpriteShader; |
| 1078 | } |
| 1079 | |
| 1080 | function getTightFitLitSpriteShader () |
| 1081 | { |
| 1082 | if (!tightFitLitSpriteShader) |
| 1083 | { tightFitLitSpriteShader = Shader.fragment(TIGHT_FIT_LIT_SPRITE_FRAG); } |
| 1084 | return tightFitLitSpriteShader; |
| 1085 | } |
| 1086 | |
| 1087 | export class WorldView |
| 1088 | { |
| 1089 | #chunkRebuildKeys = new Set(); |
| 1090 | /** Soft-blend / wet-sand neighbor rebakes — deferred so they do not nest inside a primary bake. */ |
| 1091 | #chunkSoftNeighborKeys = new Set(); |
| 1092 | #chunkRebuildRaf = 0; |
| 1093 | #edgesDirty = false; |
| 1094 | #CHUNK_REBUILD_BATCH = 2; |
| 1095 | #pendingTextureCanvases = []; |
| 1096 | #pendingTextureCanvasSet = new Set(); |
| 1097 | #textureWarmRaf = 0; |
| 1098 | #TEXTURE_WARM_BATCH = 3; |
| 1099 | #atlasCache = createChunkAtlasCache(); |
| 1100 | #idlePrefetchId = 0; |
| 1101 | #playerChunkX = null; |
| 1102 | #playerChunkY = null; |
| 1103 | #playerMoveChunkDx = 0; |
| 1104 | #playerMoveChunkDy = 0; |
| 1105 | /** Reused by {@link #placePivoted} to avoid per-call `new vector()`. */ |
| 1106 | #placeSizeScratch = new vector(0, 0); |
| 1107 | /** When true, water/lava shade into per-chunk 16×16 atlases (set false if FBO init fails). */ |
| 1108 | #useFluidAtlas = true; |
| 1109 | /** Chunk-wide single-pass fluid atlas bake (pack textures). Set false or window.__QW_FLUID_ATLAS_SINGLE_PASS=false for per-tile fallback. */ |
| 1110 | #useFluidAtlasSinglePass = true; |
| 1111 | /** Bumped on chunk bake / season change — invalidates cached fluid coast topology. */ |
| 1112 | #fluidCoastEpoch = 0; |
| 1113 | |
| 1114 | constructor(game, scene, catalog = { grounds: {}, blocks: {} }) |
| 1115 | { |
| 1116 | this.game = game; |
| 1117 | this.scene = scene; |
| 1118 | // Framework defaults to white clear; unloaded map areas should read as void. |
| 1119 | if (scene?.backgroundColor) |
| 1120 | { |
| 1121 | scene.backgroundColor.r = 0; |
| 1122 | scene.backgroundColor.g = 0; |
| 1123 | scene.backgroundColor.b = 0; |
| 1124 | } |
| 1125 | this.catalog = catalog; |
| 1126 | this.preview = null; |
| 1127 | this.zoom = 2; |
| 1128 | /** Chunk-quantised world-Y origin for the depth sort (see {@link #depthLayer}). */ |
| 1129 | this.ySortOrigin = null; |
| 1130 | this.chunks = new Map(); |
| 1131 | this.bakedChunks = new Map(); |
| 1132 | this.tiles = new Map(); |
| 1133 | this.entities = new Map(); |
| 1134 | this.itemContainers = new Map(); |
| 1135 | this.groundItems = new Map(); |
| 1136 | this.edges = new Map(); |
| 1137 | this.localEntityId = null; |
| 1138 | this.localBlind = false; |
| 1139 | /** @type {string} */ |
| 1140 | this.dimensionId = OVERWORLD_ID; |
| 1141 | /** @type {string} */ |
| 1142 | this.dimensionLightingMode = "dayNight"; |
| 1143 | /** @type {string} */ |
| 1144 | this.dimensionSeasonMode = "auto"; |
| 1145 | /** Calendar season from worldStatus when dimension season is auto. */ |
| 1146 | this.calendarSeason = seasonIdAt(); |
| 1147 | /** @type {"soft"|"simple"} */ |
| 1148 | this.lightingMode = "soft"; |
| 1149 | /** @type {boolean} */ |
| 1150 | this.bloomEnabled = true; |
| 1151 | /** Soft edge blend for blendable grounds (grass, dirt, …). */ |
| 1152 | this.softTerrain = false; |
| 1153 | /** |
| 1154 | * Per-chunk nature Perlin tint. Off in the world editor while painting |
| 1155 | * (rebakes are frequent); editor enables a one-shot bake on chunk save. |
| 1156 | */ |
| 1157 | this.natureTintEnabled = true; |
| 1158 | this.settings = { ...DEFAULT_WORLD_SETTINGS }; |
| 1159 | this.worldHour = 12; |
| 1160 | /** Calendar season for seasonal ground/block visuals (`spring` / `summer` / `fall` / `winter`). */ |
| 1161 | this.worldSeason = seasonIdAt(); |
| 1162 | this.nightPreview = null; |
| 1163 | this.followPlayer = true; |
| 1164 | /** Play: only draw world-border segments on walkable tiles. Editor keeps full bars. */ |
| 1165 | this.worldBorderWalkableOnly = false; |
| 1166 | this.dynamicLights = []; |
| 1167 | /** Persistent Light-spell tile lights (server-driven). */ |
| 1168 | this.spellLights = new Map(); |
| 1169 | /** Persistent Dark-spell tile darkness (server-driven). */ |
| 1170 | this.spellDarks = new Map(); |
| 1171 | this.swipes = []; |
| 1172 | this.damageFloats = []; |
| 1173 | this.damageNumbersEl = document.getElementById("damage-numbers"); |
| 1174 | this.skillLevelFloats = []; |
| 1175 | this.skillLevelFloatsEl = document.getElementById("skill-level-floats"); |
| 1176 | /** @type {Map<string, { object: object, tileX: number, tileY: number, spriteName: string }>} */ |
| 1177 | this.editorSpawners = new Map(); |
| 1178 | this.spawnRangeHighlight = null; |
| 1179 | this.wanderRangeHighlight = null; |
| 1180 | this.spellTargetHighlight = null; |
| 1181 | this.#syncBloomLayer(); |
| 1182 | } |
| 1183 | |
| 1184 | setSettings (settings) |
| 1185 | { |
| 1186 | const previous = this.settings; |
| 1187 | this.settings = { ...DEFAULT_WORLD_SETTINGS, ...settings }; |
| 1188 | this.#syncBloomLayer(); |
| 1189 | const prevBand = Number(previous?.wetSandBand); |
| 1190 | const nextBand = Number(this.settings.wetSandBand); |
| 1191 | if (Number.isFinite(nextBand) && prevBand !== nextBand) |
| 1192 | { this.#rebakeAllChunks(); } |
| 1193 | } |
| 1194 | |
| 1195 | /** |
| 1196 | * Client graphics prefs (lighting Soft/Simple, bloom On/Off, soft terrain). |
| 1197 | * @param {{ lighting?: string, bloom?: string, softTerrain?: string }} prefs |
| 1198 | */ |
| 1199 | setGraphicsPrefs (prefs) |
| 1200 | { |
| 1201 | if (prefs?.lighting === "simple" || prefs?.lighting === "soft") |
| 1202 | { this.lightingMode = prefs.lighting; } |
| 1203 | if (prefs?.bloom === "off" || prefs?.bloom === "on") |
| 1204 | { |
| 1205 | const enabled = prefs.bloom !== "off"; |
| 1206 | if (enabled !== this.bloomEnabled) |
| 1207 | { |
| 1208 | this.bloomEnabled = enabled; |
| 1209 | this.#syncBloomLayer(); |
| 1210 | } |
| 1211 | else |
| 1212 | { this.bloomEnabled = enabled; } |
| 1213 | } |
| 1214 | if (prefs?.softTerrain === "on" || prefs?.softTerrain === "off") |
| 1215 | { |
| 1216 | const enabled = prefs.softTerrain === "on"; |
| 1217 | if (enabled !== this.softTerrain) |
| 1218 | { |
| 1219 | this.softTerrain = enabled; |
| 1220 | this.#rebakeAllChunks(); |
| 1221 | } |
| 1222 | } |
| 1223 | } |
| 1224 | |
| 1225 | /** Apply server (or local) calendar season; rebakes chunks when it changes. */ |
| 1226 | setWorldSeason (season) |
| 1227 | { |
| 1228 | const calendar = season === SeasonId.spring |
| 1229 | || season === SeasonId.fall |
| 1230 | || season === SeasonId.winter |
| 1231 | || season === SeasonId.summer |
| 1232 | ? season |
| 1233 | : seasonIdAt(); |
| 1234 | this.calendarSeason = calendar; |
| 1235 | const forced = resolveDimensionSeasonId(this.dimensionSeasonMode); |
| 1236 | const next = forced ?? calendar; |
| 1237 | if (next === this.worldSeason) |
| 1238 | { return; } |
| 1239 | this.worldSeason = next; |
| 1240 | this.#rebakeAllChunks(); |
| 1241 | } |
| 1242 | |
| 1243 | setDimensionId (dimensionId) |
| 1244 | { |
| 1245 | this.dimensionId = normalizeDimensionId(dimensionId); |
| 1246 | } |
| 1247 | |
| 1248 | setDimensionModes (lightingMode, seasonMode) |
| 1249 | { |
| 1250 | this.dimensionLightingMode = normalizeLightingMode(lightingMode); |
| 1251 | this.dimensionSeasonMode = normalizeSeasonMode(seasonMode); |
| 1252 | const forced = resolveDimensionSeasonId(this.dimensionSeasonMode); |
| 1253 | const next = forced ?? this.calendarSeason ?? seasonIdAt(); |
| 1254 | if (next !== this.worldSeason) |
| 1255 | { |
| 1256 | this.worldSeason = next; |
| 1257 | this.#rebakeAllChunks(); |
| 1258 | } |
| 1259 | } |
| 1260 | |
| 1261 | clearAllChunks () |
| 1262 | { |
| 1263 | for (const key of [...this.chunks.keys()]) |
| 1264 | { |
| 1265 | const [chunkX, chunkY] = key.split(",").map(Number); |
| 1266 | this.removeChunk(chunkX, chunkY); |
| 1267 | } |
| 1268 | for (const [id] of [...this.entities.entries()]) |
| 1269 | { |
| 1270 | if (id === this.localEntityId) |
| 1271 | { continue; } |
| 1272 | this.despawnEntity(id, { immediate: true }); |
| 1273 | } |
| 1274 | for (const [id] of [...this.groundItems.entries()]) |
| 1275 | { this.despawnGroundItem(id); } |
| 1276 | for (const [id] of [...this.itemContainers.entries()]) |
| 1277 | { this.despawnItemContainer(id); } |
| 1278 | for (const swipe of this.swipes) |
| 1279 | { swipe.object?.destroy(); } |
| 1280 | this.swipes = []; |
| 1281 | this.spellLights.clear(); |
| 1282 | this.spellDarks.clear(); |
| 1283 | this.dynamicLights = []; |
| 1284 | } |
| 1285 | |
| 1286 | /** Full client wipe when leaving the world (menu / disconnect). Includes the local player. */ |
| 1287 | clearPlaySession () |
| 1288 | { |
| 1289 | this.#cancelIdlePrefetch(); |
| 1290 | this.#chunkRebuildKeys.clear(); |
| 1291 | this.#chunkSoftNeighborKeys.clear(); |
| 1292 | this.#playerChunkX = null; |
| 1293 | this.#playerChunkY = null; |
| 1294 | this.#playerMoveChunkDx = 0; |
| 1295 | this.#playerMoveChunkDy = 0; |
| 1296 | this.localEntityId = null; |
| 1297 | for (const key of [...this.chunks.keys()]) |
| 1298 | { |
| 1299 | const [chunkX, chunkY] = key.split(",").map(Number); |
| 1300 | this.removeChunk(chunkX, chunkY); |
| 1301 | } |
| 1302 | for (const [id] of [...this.entities.entries()]) |
| 1303 | { this.despawnEntity(id, { immediate: true }); } |
| 1304 | for (const [id] of [...this.groundItems.entries()]) |
| 1305 | { this.despawnGroundItem(id); } |
| 1306 | for (const [id] of [...this.itemContainers.entries()]) |
| 1307 | { this.despawnItemContainer(id); } |
| 1308 | } |
| 1309 | |
| 1310 | applySnapshot (snapshot) |
| 1311 | { |
| 1312 | const snapDim = normalizeDimensionId(snapshot.dimensionId ?? this.dimensionId ?? OVERWORLD_ID); |
| 1313 | if (normalizeDimensionId(this.dimensionId) !== snapDim) |
| 1314 | { return; } |
| 1315 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 1316 | snapshot.occlusion = bakeChunkOcclusion(snapshot); |
| 1317 | this.chunks.set(key, snapshot); |
| 1318 | this.#scheduleChunkRebuild(snapshot); |
| 1319 | this.#redrawPreview(); |
| 1320 | this.#refreshWaterCoastsNear(snapshot.chunkX, snapshot.chunkY); |
| 1321 | if (snapshot.staticOnly) |
| 1322 | { |
| 1323 | this.#stripChunkDynamic(snapshot.chunkX, snapshot.chunkY); |
| 1324 | this.#scheduleEdgeRebuild(); |
| 1325 | return; |
| 1326 | } |
| 1327 | for (const entity of snapshot.entities ?? []) |
| 1328 | { this.#upsertEntity(entity); } |
| 1329 | for (const [id, item] of [...this.groundItems.entries()]) |
| 1330 | { |
| 1331 | if (Math.floor(item.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(item.tileY / CHUNK_SIZE) === snapshot.chunkY) |
| 1332 | { this.despawnGroundItem(id); } |
| 1333 | } |
| 1334 | for (const item of snapshot.groundItems ?? []) |
| 1335 | { this.upsertGroundItem(item); } |
| 1336 | for (const [id, entry] of [...this.itemContainers.entries()]) |
| 1337 | { |
| 1338 | if (Math.floor(entry.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(entry.tileY / CHUNK_SIZE) === snapshot.chunkY) |
| 1339 | { this.despawnItemContainer(id); } |
| 1340 | } |
| 1341 | for (const entry of snapshot.itemContainers ?? []) |
| 1342 | { this.upsertItemContainer(entry); } |
| 1343 | this.#scheduleEdgeRebuild(); |
| 1344 | } |
| 1345 | |
| 1346 | setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null, skullValue = 0) |
| 1347 | { |
| 1348 | this.localEntityId = entityId; |
| 1349 | this.#upsertEntity({ |
| 1350 | entityId, |
| 1351 | characterId, |
| 1352 | tileX, |
| 1353 | tileY, |
| 1354 | gait, |
| 1355 | sex, |
| 1356 | firstName, |
| 1357 | lastName, |
| 1358 | layers: layers ?? undefined, |
| 1359 | skullValue: skullValue | 0, |
| 1360 | ...(health != null ? { health } : {}), |
| 1361 | ...(maxHealth != null ? { maxHealth } : {}) |
| 1362 | }); |
| 1363 | this.#notePlayerTile(tileX, tileY); |
| 1364 | } |
| 1365 | |
| 1366 | #stripChunkDynamic (chunkX, chunkY) |
| 1367 | { |
| 1368 | for (const [id, item] of [...this.groundItems.entries()]) |
| 1369 | { |
| 1370 | if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY) |
| 1371 | { this.despawnGroundItem(id); } |
| 1372 | } |
| 1373 | for (const [id, entry] of [...this.itemContainers.entries()]) |
| 1374 | { |
| 1375 | if (Math.floor(entry.tileX / CHUNK_SIZE) === chunkX && Math.floor(entry.tileY / CHUNK_SIZE) === chunkY) |
| 1376 | { this.despawnItemContainer(id); } |
| 1377 | } |
| 1378 | for (const [id, entity] of [...this.entities.entries()]) |
| 1379 | { |
| 1380 | if (id === this.localEntityId) |
| 1381 | { continue; } |
| 1382 | if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX |
| 1383 | && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY) |
| 1384 | { this.despawnEntity(id, { immediate: true }); } |
| 1385 | } |
| 1386 | } |
| 1387 | |
| 1388 | removeChunk (chunkX, chunkY) |
| 1389 | { |
| 1390 | const key = `${chunkX},${chunkY}`; |
| 1391 | this.chunks.delete(key); |
| 1392 | this.#destroyBakedChunk(key); |
| 1393 | this.#destroyEdges(key); |
| 1394 | const prefix = `${chunkX},${chunkY}:`; |
| 1395 | for (const [spawnerKey, entry] of [...this.editorSpawners.entries()]) |
| 1396 | { |
| 1397 | if (!spawnerKey.startsWith(prefix)) |
| 1398 | { continue; } |
| 1399 | this.#destroyEditorSpawnerEntry(entry); |
| 1400 | this.editorSpawners.delete(spawnerKey); |
| 1401 | } |
| 1402 | for (const [tileKey, objects] of [...this.tiles.entries()]) |
| 1403 | { |
| 1404 | if (objects.chunkX === chunkX && objects.chunkY === chunkY) |
| 1405 | { |
| 1406 | objects.ground?.destroy(); |
| 1407 | objects.groundBloom?.destroy(); |
| 1408 | objects.lavaBloom?.destroy(); |
| 1409 | objects.block?.destroy(); |
| 1410 | objects.blockBloom?.destroy(); |
| 1411 | this.tiles.delete(tileKey); |
| 1412 | } |
| 1413 | } |
| 1414 | for (const [id, item] of [...this.groundItems.entries()]) |
| 1415 | { |
| 1416 | if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY) |
| 1417 | { this.despawnGroundItem(id); } |
| 1418 | } |
| 1419 | for (const [id, entry] of [...this.itemContainers.entries()]) |
| 1420 | { |
| 1421 | if (Math.floor(entry.tileX / CHUNK_SIZE) === chunkX && Math.floor(entry.tileY / CHUNK_SIZE) === chunkY) |
| 1422 | { this.despawnItemContainer(id); } |
| 1423 | } |
| 1424 | // Server sends unsubscribeChunk when a chunk leaves the static 5×5 ring. |
| 1425 | // Entity replication is limited to the inner 3×3; static-only chunks strip dynamics via staticOnly snapshots. |
| 1426 | for (const [id, entity] of [...this.entities.entries()]) |
| 1427 | { |
| 1428 | if (id === this.localEntityId) |
| 1429 | { continue; } |
| 1430 | if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX |
| 1431 | && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY) |
| 1432 | { this.despawnEntity(id, { immediate: true }); } |
| 1433 | } |
| 1434 | this.#rebuildAllEdges(); |
| 1435 | } |
| 1436 | |
| 1437 | setChunkOpen (chunkX, chunkY, open) |
| 1438 | { |
| 1439 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 1440 | if (!snapshot) |
| 1441 | { return; } |
| 1442 | snapshot.open = !!open; |
| 1443 | this.#rebuildAllEdges(); |
| 1444 | } |
| 1445 | |
| 1446 | spawnEntity (payload) |
| 1447 | { |
| 1448 | // Fresh spawn is authoritative; do not let an older deferred hit overwrite HP. |
| 1449 | this.cancelDeferredCombatHits(payload?.entityId); |
| 1450 | this.#upsertEntity(payload); |
| 1451 | } |
| 1452 | |
| 1453 | moveEntity (payload) |
| 1454 | { |
| 1455 | const existing = this.entities.get(payload.entityId); |
| 1456 | // Move payloads lack appearance/mobTypeId — never invent a stub entity |
| 1457 | // (that looked like a nameless humanoid "target"). Wait for entity-spawn. |
| 1458 | if (!existing) |
| 1459 | { return; } |
| 1460 | // Fading corpses stay put; respawn restores via reviveAfterDeath / spawn. |
| 1461 | if (existing.dying) |
| 1462 | { return; } |
| 1463 | const size = this.tileSize(); |
| 1464 | existing.fromX = existing.visualX; |
| 1465 | existing.fromY = existing.visualY; |
| 1466 | existing.shadeFromTileX = existing.tileX; |
| 1467 | existing.shadeFromTileY = existing.tileY; |
| 1468 | if (existing.tileX !== payload.tileX || existing.tileY !== payload.tileY) |
| 1469 | { |
| 1470 | existing.previousTileX = existing.tileX; |
| 1471 | existing.previousTileY = existing.tileY; |
| 1472 | } |
| 1473 | existing.tileX = payload.tileX; |
| 1474 | existing.tileY = payload.tileY; |
| 1475 | existing.gait = payload.gait; |
| 1476 | existing.freeFlight = !!payload.freeFlight || existing.freeFlight; |
| 1477 | if (payload.worldX != null && payload.worldY != null) |
| 1478 | { |
| 1479 | existing.worldX = payload.worldX; |
| 1480 | existing.worldY = payload.worldY; |
| 1481 | existing.targetX = payload.worldX * size; |
| 1482 | existing.targetY = payload.worldY * size; |
| 1483 | } |
| 1484 | else |
| 1485 | { |
| 1486 | const pivot = tilePivot(payload.tileX, payload.tileY, size); |
| 1487 | existing.targetX = pivot.x; |
| 1488 | existing.targetY = pivot.y; |
| 1489 | } |
| 1490 | existing.lerpStarted = performance.now(); |
| 1491 | existing.lerpMs = payload.lerpMs ?? this.#lerpMs(payload.gait); |
| 1492 | if (payload.entityId === this.localEntityId) |
| 1493 | { this.#notePlayerTile(payload.tileX, payload.tileY); } |
| 1494 | } |
| 1495 | |
| 1496 | despawnEntity (entityId, { immediate = false, combatDeath = false } = {}) |
| 1497 | { |
| 1498 | const existing = this.entities.get(entityId); |
| 1499 | if (!existing) |
| 1500 | { return; } |
| 1501 | if (existing.dying) |
| 1502 | { |
| 1503 | if (immediate) |
| 1504 | { this.#finishEntityFade(entityId); } |
| 1505 | else if (combatDeath) |
| 1506 | { this.#upgradeToDeathDissolve(existing); } |
| 1507 | return; |
| 1508 | } |
| 1509 | // Chunk unload / session wipe: drop instantly. |
| 1510 | if (immediate) |
| 1511 | { |
| 1512 | this.cancelDeferredCombatHits(entityId); |
| 1513 | this.#destroyEntityVisuals(existing); |
| 1514 | this.entities.delete(entityId); |
| 1515 | return; |
| 1516 | } |
| 1517 | // Combat death → red silhouette. Leaving 3×3 / summons / etc. → plain fade. |
| 1518 | if (combatDeath) |
| 1519 | { this.#beginDeathDissolve(existing); } |
| 1520 | else |
| 1521 | { this.#beginDespawnFade(existing); } |
| 1522 | } |
| 1523 | |
| 1524 | /** |
| 1525 | * Start the red silhouette fade without requiring a despawn message |
| 1526 | * (e.g. local playerDied arrives before entityDespawn). |
| 1527 | */ |
| 1528 | beginDeathDissolve (entityId) |
| 1529 | { |
| 1530 | const existing = this.entities.get(entityId); |
| 1531 | if (!existing) |
| 1532 | { return; } |
| 1533 | if (existing.dying) |
| 1534 | { |
| 1535 | this.#upgradeToDeathDissolve(existing); |
| 1536 | return; |
| 1537 | } |
| 1538 | this.#beginDeathDissolve(existing); |
| 1539 | } |
| 1540 | |
| 1541 | /** |
| 1542 | * Abort an in-progress (or finished) death fade and snap the sprite back. |
| 1543 | * Local players are never entity-despawned, so respawn must restore — not |
| 1544 | * destroy — the visual. Remotes get a fresh entity-spawn instead. |
| 1545 | */ |
| 1546 | reviveAfterDeath (entityId, { tileX, tileY, health, maxHealth, skullValue } = {}) |
| 1547 | { |
| 1548 | const entity = this.entities.get(entityId); |
| 1549 | if (!entity) |
| 1550 | { return false; } |
| 1551 | this.#abortEntityFade(entity); |
| 1552 | if (tileX != null && tileY != null) |
| 1553 | { this.#snapEntityToTile(entity, tileX, tileY); } |
| 1554 | if (health != null) |
| 1555 | { entity.health = health; } |
| 1556 | if (maxHealth != null) |
| 1557 | { entity.maxHealth = maxHealth; } |
| 1558 | if (skullValue != null) |
| 1559 | { entity.skullValue = Math.max(0, skullValue | 0); } |
| 1560 | this.#syncHpBar(entity); |
| 1561 | this.#syncSkullMarker(entity); |
| 1562 | this.#placeEntity(entity, performance.now()); |
| 1563 | return true; |
| 1564 | } |
| 1565 | |
| 1566 | #destroyEntityVisuals (existing) |
| 1567 | { |
| 1568 | existing.object?.destroy(); |
| 1569 | existing.hpBar?.destroy(); |
| 1570 | existing.skullMarker?.destroy(); |
| 1571 | for (const overlay of existing.overlays ?? []) |
| 1572 | { overlay.destroy(); } |
| 1573 | for (const overlay of existing.bloomOverlays ?? []) |
| 1574 | { overlay.destroy(); } |
| 1575 | } |
| 1576 | |
| 1577 | #stripEntityChrome (entity) |
| 1578 | { |
| 1579 | entity.hpBar?.destroy(); |
| 1580 | entity.hpBar = null; |
| 1581 | entity.skullMarker?.destroy(); |
| 1582 | entity.skullMarker = null; |
| 1583 | } |
| 1584 | |
| 1585 | #beginDespawnFade (entity) |
| 1586 | { |
| 1587 | const now = performance.now(); |
| 1588 | entity.dying = true; |
| 1589 | entity.deathDissolve = false; |
| 1590 | entity.untargetable = true; |
| 1591 | entity.deathFadeStarted = now; |
| 1592 | entity.deathFadeMs = DESPAWN_FADE_MS; |
| 1593 | this.#stripEntityChrome(entity); |
| 1594 | } |
| 1595 | |
| 1596 | #beginDeathDissolve (entity) |
| 1597 | { |
| 1598 | const now = performance.now(); |
| 1599 | entity.dying = true; |
| 1600 | entity.deathDissolve = true; |
| 1601 | entity.untargetable = true; |
| 1602 | entity.deathFadeStarted = now; |
| 1603 | entity.deathFadeMs = DEATH_FADE_MS; |
| 1604 | // Keep a full red silhouette for the whole fade (hit flash may already be running). |
| 1605 | entity.damageFlashUntil = now + DEATH_FADE_MS; |
| 1606 | entity.damageFlashColor = FLASH_COLOR_DAMAGE; |
| 1607 | this.#stripEntityChrome(entity); |
| 1608 | // Leave deferred projectile impacts queued so knockback / float still play on arrival. |
| 1609 | } |
| 1610 | |
| 1611 | /** Promote an in-progress plain despawn fade to the red combat dissolve. */ |
| 1612 | #upgradeToDeathDissolve (entity) |
| 1613 | { |
| 1614 | if (entity.deathDissolve) |
| 1615 | { return; } |
| 1616 | const now = performance.now(); |
| 1617 | const elapsed = Math.max(0, now - (entity.deathFadeStarted ?? now)); |
| 1618 | const remaining = Math.max(1, (entity.deathFadeMs ?? DESPAWN_FADE_MS) - elapsed); |
| 1619 | entity.deathDissolve = true; |
| 1620 | entity.deathFadeStarted = now; |
| 1621 | entity.deathFadeMs = Math.min(DEATH_FADE_MS, remaining); |
| 1622 | entity.damageFlashUntil = now + entity.deathFadeMs; |
| 1623 | entity.damageFlashColor = FLASH_COLOR_DAMAGE; |
| 1624 | } |
| 1625 | |
| 1626 | #abortEntityFade (entity) |
| 1627 | { |
| 1628 | entity.dying = false; |
| 1629 | entity.deathDissolve = false; |
| 1630 | entity.untargetable = false; |
| 1631 | entity.deathFadeStarted = null; |
| 1632 | entity.deathFadeMs = null; |
| 1633 | entity.damageFlashUntil = 0; |
| 1634 | entity.damageFlashColor = null; |
| 1635 | if (entity.object?.renderer) |
| 1636 | { entity.object.renderer.alpha = 1; } |
| 1637 | for (const overlay of entity.overlays ?? []) |
| 1638 | { |
| 1639 | if (overlay.renderer) |
| 1640 | { overlay.renderer.alpha = 1; } |
| 1641 | } |
| 1642 | for (const overlay of entity.bloomOverlays ?? []) |
| 1643 | { |
| 1644 | if (overlay.renderer) |
| 1645 | { overlay.renderer.alpha = 1; } |
| 1646 | } |
| 1647 | } |
| 1648 | |
| 1649 | #snapEntityToTile (entity, tileX, tileY) |
| 1650 | { |
| 1651 | const size = this.tileSize(); |
| 1652 | const pivot = tilePivot(tileX, tileY, size); |
| 1653 | entity.tileX = tileX; |
| 1654 | entity.tileY = tileY; |
| 1655 | entity.visualX = pivot.x; |
| 1656 | entity.visualY = pivot.y; |
| 1657 | entity.targetX = pivot.x; |
| 1658 | entity.targetY = pivot.y; |
| 1659 | entity.fromX = pivot.x; |
| 1660 | entity.fromY = pivot.y; |
| 1661 | entity.lerpStarted = null; |
| 1662 | entity.previousTileX = null; |
| 1663 | entity.previousTileY = null; |
| 1664 | entity.shadeFromTileX = null; |
| 1665 | entity.shadeFromTileY = null; |
| 1666 | entity.shoveOffsetX = 0; |
| 1667 | entity.shoveOffsetY = 0; |
| 1668 | if (entity.entityId === this.localEntityId) |
| 1669 | { this.#notePlayerTile(tileX, tileY); } |
| 1670 | } |
| 1671 | |
| 1672 | #finishEntityFade (entityId) |
| 1673 | { |
| 1674 | this.cancelDeferredCombatHits(entityId); |
| 1675 | const existing = this.entities.get(entityId); |
| 1676 | if (!existing) |
| 1677 | { return; } |
| 1678 | this.#destroyEntityVisuals(existing); |
| 1679 | this.entities.delete(entityId); |
| 1680 | } |
| 1681 | |
| 1682 | /** |
| 1683 | * Drop queued combat-hit/block presentation for a target. |
| 1684 | * Killing blows often defer health=0 until a projectile lands; if the |
| 1685 | * target already finished dissolving or respawned, that stale apply must not run. |
| 1686 | */ |
| 1687 | cancelDeferredCombatHits (targetId) |
| 1688 | { |
| 1689 | if (targetId == null) |
| 1690 | { return; } |
| 1691 | for (const swipe of this.swipes) |
| 1692 | { |
| 1693 | if (swipe.targetId !== targetId) |
| 1694 | { continue; } |
| 1695 | swipe.onImpact = null; |
| 1696 | swipe.trackTarget = false; |
| 1697 | } |
| 1698 | } |
| 1699 | |
| 1700 | updateEntitySkull (entityId, skullValue) |
| 1701 | { |
| 1702 | const entity = this.entities.get(entityId); |
| 1703 | if (!entity) |
| 1704 | { return; } |
| 1705 | entity.skullValue = Math.max(0, skullValue | 0); |
| 1706 | const pivotX = (entity.visualX ?? 0) + (entity.shoveOffsetX ?? 0) + (entity.stackOffsetX ?? 0); |
| 1707 | const pivotY = (entity.visualY ?? 0) + (entity.shoveOffsetY ?? 0) + (entity.stackOffsetY ?? 0); |
| 1708 | const tileShade = this.#entityShadeAlpha?.(entity, performance.now()) |
| 1709 | ?? this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha |
| 1710 | ?? 0; |
| 1711 | this.#placeSkullMarker(entity, pivotX, pivotY, tileShade); |
| 1712 | } |
| 1713 | |
| 1714 | updateEntityHealth (entityId, health, maxHealth) |
| 1715 | { |
| 1716 | const entity = this.entities.get(entityId); |
| 1717 | if (!entity || entity.dying) |
| 1718 | { return; } |
| 1719 | entity.health = health; |
| 1720 | entity.maxHealth = maxHealth; |
| 1721 | this.#syncHpBar(entity); |
| 1722 | } |
| 1723 | |
| 1724 | flashDamage (entityId) |
| 1725 | { |
| 1726 | this.#flashEntity(entityId, FLASH_COLOR_DAMAGE); |
| 1727 | } |
| 1728 | |
| 1729 | flashBlock (entityId) |
| 1730 | { |
| 1731 | this.#flashEntity(entityId, FLASH_COLOR_BLOCK); |
| 1732 | } |
| 1733 | |
| 1734 | #flashEntity (entityId, color) |
| 1735 | { |
| 1736 | const entity = this.entities.get(entityId); |
| 1737 | if (!entity) |
| 1738 | { return; } |
| 1739 | entity.damageFlashUntil = performance.now() + DAMAGE_FLASH_MS; |
| 1740 | entity.damageFlashColor = color ?? FLASH_COLOR_DAMAGE; |
| 1741 | } |
| 1742 | |
| 1743 | /** Target knocks back away from attacker (hit). */ |
| 1744 | spawnCombatKnockback (payload) |
| 1745 | { |
| 1746 | const attacker = this.entities.get(payload?.attackerId); |
| 1747 | const target = this.entities.get(payload?.targetId); |
| 1748 | if (!attacker || !target) |
| 1749 | { return; } |
| 1750 | const ax = attacker.visualX + (attacker.stackOffsetX ?? 0); |
| 1751 | const ay = attacker.visualY + (attacker.stackOffsetY ?? 0); |
| 1752 | const tx = target.visualX + (target.stackOffsetX ?? 0); |
| 1753 | const ty = target.visualY + (target.stackOffsetY ?? 0); |
| 1754 | this.#applyShoveInDirection(target, tx - ax, ty - ay); |
| 1755 | } |
| 1756 | |
| 1757 | /** Target sidesteps perpendicular to the attack (dodge / miss). */ |
| 1758 | spawnCombatDodge (payload) |
| 1759 | { |
| 1760 | const attacker = this.entities.get(payload?.attackerId); |
| 1761 | const target = this.entities.get(payload?.targetId); |
| 1762 | if (!attacker || !target) |
| 1763 | { return; } |
| 1764 | const ax = attacker.visualX + (attacker.stackOffsetX ?? 0); |
| 1765 | const ay = attacker.visualY + (attacker.stackOffsetY ?? 0); |
| 1766 | const tx = target.visualX + (target.stackOffsetX ?? 0); |
| 1767 | const ty = target.visualY + (target.stackOffsetY ?? 0); |
| 1768 | const dx = tx - ax; |
| 1769 | const dy = ty - ay; |
| 1770 | const side = Math.random() < 0.5 ? 1 : -1; |
| 1771 | this.#applyShoveInDirection(target, -dy * side, dx * side); |
| 1772 | } |
| 1773 | |
| 1774 | spawnDamageNumber (entityId, damage) |
| 1775 | { |
| 1776 | const amount = damage | 0; |
| 1777 | if (amount <= 0) |
| 1778 | { return; } |
| 1779 | this.damageFloats.push({ |
| 1780 | entityId, |
| 1781 | damage: amount, |
| 1782 | started: performance.now() |
| 1783 | }); |
| 1784 | } |
| 1785 | |
| 1786 | /** |
| 1787 | * Queue combat-hit presentation until a matching in-flight projectile lands. |
| 1788 | * Returns true when deferred; caller should apply immediately when false. |
| 1789 | */ |
| 1790 | deferCombatHit (message, apply) |
| 1791 | { |
| 1792 | if (typeof apply !== "function" || message?.targetId == null) |
| 1793 | { return false; } |
| 1794 | const attackerId = message.attackerId ?? null; |
| 1795 | const targetId = message.targetId; |
| 1796 | const swipe = this.swipes.find((entry) => |
| 1797 | entry.lerp |
| 1798 | && entry.onImpact == null |
| 1799 | && entry.targetId === targetId |
| 1800 | && (attackerId == null || entry.attackerId === attackerId) |
| 1801 | && (entry.until ?? 0) > performance.now()); |
| 1802 | if (!swipe) |
| 1803 | { return false; } |
| 1804 | swipe.onImpact = apply; |
| 1805 | swipe.trackTarget = true; |
| 1806 | return true; |
| 1807 | } |
| 1808 | |
| 1809 | /** Stop tracking a living target (misses fly to a fixed tile). */ |
| 1810 | markProjectileMiss (message) |
| 1811 | { |
| 1812 | const attackerId = message?.attackerId ?? null; |
| 1813 | const targetId = message?.targetId ?? null; |
| 1814 | for (const swipe of this.swipes) |
| 1815 | { |
| 1816 | if (!swipe.lerp || swipe.onImpact != null) |
| 1817 | { continue; } |
| 1818 | if (targetId != null && swipe.targetId !== targetId) |
| 1819 | { continue; } |
| 1820 | if (attackerId != null && swipe.attackerId !== attackerId) |
| 1821 | { continue; } |
| 1822 | swipe.trackTarget = false; |
| 1823 | if (message.tileX != null) |
| 1824 | { swipe.tileX = message.tileX; } |
| 1825 | if (message.tileY != null) |
| 1826 | { swipe.tileY = message.tileY; } |
| 1827 | } |
| 1828 | } |
| 1829 | |
| 1830 | spawnSkillLevelUp (entityId, payload) |
| 1831 | { |
| 1832 | const level = payload?.level | 0; |
| 1833 | if (level <= 0 || !payload?.icon) |
| 1834 | { return; } |
| 1835 | this.skillLevelFloats.push({ |
| 1836 | entityId, |
| 1837 | level, |
| 1838 | icon: payload.icon, |
| 1839 | displayName: payload.displayName ?? payload.skillId ?? "", |
| 1840 | started: performance.now() |
| 1841 | }); |
| 1842 | } |
| 1843 | |
| 1844 | setAppearance (payload) |
| 1845 | { |
| 1846 | const existing = this.entities.get(payload.entityId); |
| 1847 | if (!existing) |
| 1848 | { return; } |
| 1849 | existing.lightRadiusTiles = payload.lightRadiusTiles ?? 0; |
| 1850 | if (payload.lightIntensity != null) |
| 1851 | { existing.lightIntensity = Number(payload.lightIntensity) || 1; } |
| 1852 | if (payload.visualScale != null) |
| 1853 | { existing.visualScale = Number(payload.visualScale) || 1; } |
| 1854 | this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]); |
| 1855 | this.#placeEntity(existing); |
| 1856 | } |
| 1857 | |
| 1858 | /** |
| 1859 | * Render the live entity (body + overlays, same tint/tight-fit shaders as the |
| 1860 | * world, unlit) into an offscreen FBO, crop the top square, and return a |
| 1861 | * pixel-scaled canvas for UI (e.g. dialogue speaker icons). |
| 1862 | * @param {number} entityId |
| 1863 | * @param {{ size?: number }} [options] |
| 1864 | * @returns {HTMLCanvasElement | null} |
| 1865 | */ |
| 1866 | captureEntityPortrait (entityId, { size = 64 } = {}) |
| 1867 | { |
| 1868 | const entity = this.entities.get(entityId); |
| 1869 | const body = entity?.object?.renderer?.sprite; |
| 1870 | const glCtx = this.scene?.glContext; |
| 1871 | const gl = glCtx?.gl; |
| 1872 | if (!entity || !body || !gl) |
| 1873 | { return null; } |
| 1874 | |
| 1875 | const frameW = Math.max(1, body.width | 0 || SPRITE_SIZE_PX); |
| 1876 | const frameH = Math.max(1, body.height | 0 || SPRITE_SIZE_PX); |
| 1877 | if (!this.#ensurePortraitTarget(gl, frameW, frameH)) |
| 1878 | { return null; } |
| 1879 | |
| 1880 | const prevFb = gl.getParameter(gl.FRAMEBUFFER_BINDING); |
| 1881 | const prevViewport = gl.getParameter(gl.VIEWPORT); |
| 1882 | const prevW = glCtx._lastWidth; |
| 1883 | const prevH = glCtx._lastHeight; |
| 1884 | const prevBlend = gl.isEnabled(gl.BLEND); |
| 1885 | |
| 1886 | try |
| 1887 | { |
| 1888 | // drawSprite projects with _lastWidth/_lastHeight — match the FBO. |
| 1889 | glCtx._lastWidth = frameW; |
| 1890 | glCtx._lastHeight = frameH; |
| 1891 | gl.bindFramebuffer(gl.FRAMEBUFFER, this._portrait.fb); |
| 1892 | gl.viewport(0, 0, frameW, frameH); |
| 1893 | gl.enable(gl.BLEND); |
| 1894 | gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); |
| 1895 | gl.clearColor(0, 0, 0, 0); |
| 1896 | gl.clear(gl.COLOR_BUFFER_BIT); |
| 1897 | |
| 1898 | const pivotX = frameW * 0.5; |
| 1899 | const pivotY = frameH - PIVOT_FROM_BOTTOM_PX; |
| 1900 | this._portraitBodyMap = body.g_image ?? null; |
| 1901 | this._portraitTightFitEntity = entity; |
| 1902 | this.#drawPortraitLayer(glCtx, entity.object, pivotX, pivotY, null, false); |
| 1903 | |
| 1904 | const overlays = entity.overlays ?? []; |
| 1905 | const tints = entity.overlayTints ?? []; |
| 1906 | const dualTints = entity.overlayDualTints ?? []; |
| 1907 | const tight = entity.overlayTightFit ?? []; |
| 1908 | for (let index = 0; index < overlays.length; index++) |
| 1909 | { |
| 1910 | this.#drawPortraitLayer( |
| 1911 | glCtx, |
| 1912 | overlays[index], |
| 1913 | pivotX, |
| 1914 | pivotY, |
| 1915 | tints[index] ?? null, |
| 1916 | !!tight[index], |
| 1917 | dualTints[index] ?? null |
| 1918 | ); |
| 1919 | } |
| 1920 | this._portraitBodyMap = null; |
| 1921 | this._portraitTightFitEntity = null; |
| 1922 | |
| 1923 | const pixels = this._portrait.pixels; |
| 1924 | gl.readPixels(0, 0, frameW, frameH, gl.RGBA, gl.UNSIGNED_BYTE, pixels); |
| 1925 | } |
| 1926 | finally |
| 1927 | { |
| 1928 | glCtx._lastWidth = prevW; |
| 1929 | glCtx._lastHeight = prevH; |
| 1930 | gl.bindFramebuffer(gl.FRAMEBUFFER, prevFb); |
| 1931 | gl.viewport(prevViewport[0], prevViewport[1], prevViewport[2], prevViewport[3]); |
| 1932 | if (!prevBlend) |
| 1933 | { gl.disable(gl.BLEND); } |
| 1934 | gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); |
| 1935 | } |
| 1936 | |
| 1937 | return this.#portraitPixelsToCanvas(frameW, frameH, size); |
| 1938 | } |
| 1939 | |
| 1940 | #ensurePortraitTarget (gl, width, height) |
| 1941 | { |
| 1942 | const prev = this._portrait; |
| 1943 | if (prev && prev.w === width && prev.h === height && prev.fb && prev.tex) |
| 1944 | { return true; } |
| 1945 | if (prev?.fb) |
| 1946 | { gl.deleteFramebuffer(prev.fb); } |
| 1947 | if (prev?.tex) |
| 1948 | { gl.deleteTexture(prev.tex); } |
| 1949 | |
| 1950 | const tex = gl.createTexture(); |
| 1951 | gl.bindTexture(gl.TEXTURE_2D, tex); |
| 1952 | gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); |
| 1953 | gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); |
| 1954 | gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); |
| 1955 | gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); |
| 1956 | gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); |
| 1957 | |
| 1958 | const fb = gl.createFramebuffer(); |
| 1959 | gl.bindFramebuffer(gl.FRAMEBUFFER, fb); |
| 1960 | gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0); |
| 1961 | const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER); |
| 1962 | gl.bindFramebuffer(gl.FRAMEBUFFER, null); |
| 1963 | if (status !== gl.FRAMEBUFFER_COMPLETE) |
| 1964 | { |
| 1965 | gl.deleteFramebuffer(fb); |
| 1966 | gl.deleteTexture(tex); |
| 1967 | this._portrait = null; |
| 1968 | return false; |
| 1969 | } |
| 1970 | this._portrait = { |
| 1971 | fb, |
| 1972 | tex, |
| 1973 | w: width, |
| 1974 | h: height, |
| 1975 | pixels: new Uint8Array(width * height * 4), |
| 1976 | scratch: document.createElement("canvas") |
| 1977 | }; |
| 1978 | return true; |
| 1979 | } |
| 1980 | |
| 1981 | #drawPortraitLayer (glCtx, object, pivotX, pivotY, tintColor, tightFit, dualTint = null) |
| 1982 | { |
| 1983 | const sprite = object?.renderer?.sprite; |
| 1984 | if (!sprite?.g_image) |
| 1985 | { return; } |
| 1986 | const subImage = object.renderer.subImage | 0; |
| 1987 | const height = sprite.height || SPRITE_SIZE_PX; |
| 1988 | const draw = spriteDrawSize(sprite.width, sprite.height, 1); |
| 1989 | const center = spriteCenterFromPivot(pivotX, pivotY, height, 1); |
| 1990 | const tint = tintColor ? normalizeRgb(tintColor) : null; |
| 1991 | let shader = glCtx.defaultShader; |
| 1992 | let uniforms = null; |
| 1993 | let secondaryHtml = null; |
| 1994 | |
| 1995 | const bodyHtml = this._portraitBodyMap; |
| 1996 | const portraitEntity = this._portraitTightFitEntity; |
| 1997 | const maskUniforms = tightFit && portraitEntity |
| 1998 | ? this.#tightFitMaskUniforms(object, portraitEntity) |
| 1999 | : null; |
| 2000 | if (dualTint) |
| 2001 | { |
| 2002 | const shaft = normalizeRgb(dualTint.shaft); |
| 2003 | const tip = normalizeRgb(dualTint.tip); |
| 2004 | const coat = dualTint.coat ? normalizeRgb(dualTint.coat) : null; |
| 2005 | shader = getDualTintLitSpriteShader(); |
| 2006 | uniforms = { |
| 2007 | u_darkness: 0, |
| 2008 | u_strength: 0, |
| 2009 | u_flashColor: FLASH_COLOR_DAMAGE, |
| 2010 | u_wade: 0, |
| 2011 | u_spriteHeight: height, |
| 2012 | u_shaftTint: [shaft.r, shaft.g, shaft.b], |
| 2013 | u_tipTint: [tip.r, tip.g, tip.b], |
| 2014 | u_coatTint: coat ? [coat.r, coat.g, coat.b] : [0, 0, 0], |
| 2015 | u_hasCoat: coat ? 1 : 0 |
| 2016 | }; |
| 2017 | } |
| 2018 | else if (tightFit && bodyHtml && maskUniforms) |
| 2019 | { |
| 2020 | secondaryHtml = bodyHtml; |
| 2021 | if (tint) |
| 2022 | { |
| 2023 | shader = getTightFitTintLitSpriteShader(); |
| 2024 | uniforms = { |
| 2025 | u_darkness: 0, |
| 2026 | u_strength: 0, |
| 2027 | u_flashColor: FLASH_COLOR_DAMAGE, |
| 2028 | u_wade: 0, |
| 2029 | u_spriteHeight: height, |
| 2030 | u_useTint: 1, |
| 2031 | u_tintColor: [tint.r, tint.g, tint.b], |
| 2032 | ...maskUniforms |
| 2033 | }; |
| 2034 | } |
| 2035 | else |
| 2036 | { |
| 2037 | shader = getTightFitLitSpriteShader(); |
| 2038 | uniforms = { |
| 2039 | u_darkness: 0, |
| 2040 | u_strength: 0, |
| 2041 | u_flashColor: FLASH_COLOR_DAMAGE, |
| 2042 | u_wade: 0, |
| 2043 | u_spriteHeight: height, |
| 2044 | ...maskUniforms |
| 2045 | }; |
| 2046 | } |
| 2047 | } |
| 2048 | else if (tint) |
| 2049 | { |
| 2050 | shader = getTintLitSpriteShader(); |
| 2051 | uniforms = { |
| 2052 | u_darkness: 0, |
| 2053 | u_strength: 0, |
| 2054 | u_flashColor: FLASH_COLOR_DAMAGE, |
| 2055 | u_wade: 0, |
| 2056 | u_spriteHeight: height, |
| 2057 | u_useTint: 1, |
| 2058 | u_tintColor: [tint.r, tint.g, tint.b] |
| 2059 | }; |
| 2060 | } |
| 2061 | else |
| 2062 | { |
| 2063 | shader = getSpriteLightingShader(); |
| 2064 | uniforms = { |
| 2065 | u_darkness: 0, |
| 2066 | u_strength: 0, |
| 2067 | u_flashColor: FLASH_COLOR_DAMAGE, |
| 2068 | u_wade: 0, |
| 2069 | u_spriteHeight: height |
| 2070 | }; |
| 2071 | } |
| 2072 | |
| 2073 | glCtx.drawSprite({ |
| 2074 | texture: glCtx.getTexture(sprite.g_image), |
| 2075 | x: center.x, |
| 2076 | y: center.y, |
| 2077 | w: draw.w, |
| 2078 | h: draw.h, |
| 2079 | rotationDeg: 0, |
| 2080 | mirrorX: false, |
| 2081 | mirrorY: false, |
| 2082 | alpha: 1, |
| 2083 | uvRect: sprite.getUvRect(subImage), |
| 2084 | shader, |
| 2085 | uniforms, |
| 2086 | textures: secondaryHtml ? { u_secondary: glCtx.getTexture(secondaryHtml) } : null, |
| 2087 | lights: null |
| 2088 | }); |
| 2089 | } |
| 2090 | |
| 2091 | #portraitPixelsToCanvas (frameW, frameH, size) |
| 2092 | { |
| 2093 | const pixels = this._portrait?.pixels; |
| 2094 | if (!pixels) |
| 2095 | { return null; } |
| 2096 | const scratch = this._portrait.scratch; |
| 2097 | scratch.width = frameW; |
| 2098 | scratch.height = frameH; |
| 2099 | const sctx = scratch.getContext("2d"); |
| 2100 | const imageData = sctx.createImageData(frameW, frameH); |
| 2101 | // WebGL y=0 is bottom — flip to top-down image order. |
| 2102 | for (let y = 0; y < frameH; y++) |
| 2103 | { |
| 2104 | const src = (frameH - 1 - y) * frameW * 4; |
| 2105 | const dst = y * frameW * 4; |
| 2106 | imageData.data.set(pixels.subarray(src, src + frameW * 4), dst); |
| 2107 | } |
| 2108 | sctx.putImageData(imageData, 0, 0); |
| 2109 | |
| 2110 | const crop = Math.min(frameW, frameH); |
| 2111 | const out = document.createElement("canvas"); |
| 2112 | out.width = size; |
| 2113 | out.height = size; |
| 2114 | const octx = out.getContext("2d"); |
| 2115 | octx.imageSmoothingEnabled = false; |
| 2116 | octx.clearRect(0, 0, size, size); |
| 2117 | octx.drawImage(scratch, 0, 0, crop, crop, 0, 0, size, size); |
| 2118 | return out; |
| 2119 | } |
| 2120 | |
| 2121 | upsertGroundItem (payload) |
| 2122 | { |
| 2123 | if (payload?.dimensionId != null |
| 2124 | && normalizeDimensionId(payload.dimensionId) !== normalizeDimensionId(this.dimensionId)) |
| 2125 | { return; } |
| 2126 | const size = this.tileSize(); |
| 2127 | const pivot = tilePivot(payload.tileX, payload.tileY, size); |
| 2128 | const potion = payload.instance?.kind === "potion" ? payload.instance : null; |
| 2129 | const spriteName = potion |
| 2130 | ? spriteImageName("item", "potion", `potion-${Math.max(1, Math.min(5, potion.fillLevel | 0 || 4))}`) |
| 2131 | : (payload.sprite ?? itemSpriteNameForStack({ |
| 2132 | itemId: payload.itemId, |
| 2133 | instance: payload.instance, |
| 2134 | quantity: payload.quantity |
| 2135 | })); |
| 2136 | let item = this.groundItems.get(payload.groundItemId); |
| 2137 | if (!item) |
| 2138 | { |
| 2139 | const object = new GameObject(0, 0, this.game.images[spriteName] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK); |
| 2140 | this.scene.addObject(object); |
| 2141 | item = { object }; |
| 2142 | this.groundItems.set(payload.groundItemId, item); |
| 2143 | } |
| 2144 | else if (item.object?.renderer && this.game.images[spriteName]) |
| 2145 | { item.object.renderer.sprite = this.game.images[spriteName]; } |
| 2146 | item.groundItemId = payload.groundItemId; |
| 2147 | item.tileX = payload.tileX; |
| 2148 | item.tileY = payload.tileY; |
| 2149 | item.itemId = payload.itemId; |
| 2150 | item.quantity = payload.quantity; |
| 2151 | item.displayName = payload.displayName; |
| 2152 | item.sprite = spriteName; |
| 2153 | item.instance = payload.instance ?? null; |
| 2154 | const stack = { itemId: payload.itemId, instance: payload.instance ?? null, quantity: payload.quantity }; |
| 2155 | const def = itemDefinition(payload.itemId); |
| 2156 | item.dualTint = def?.iconTintFromTier ? null : resolveItemDualTint(stack, def); |
| 2157 | item.tintColor = item.dualTint ? null : resolveItemTint(stack, def); |
| 2158 | if (item.object?.renderer && itemMaxCharges(def) != null) |
| 2159 | { item.object.renderer.setSubImage?.(chargeSpriteFrameIndex(stack)); } |
| 2160 | this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK); |
| 2161 | this.#syncGroundChequeOverlay(item, pivot); |
| 2162 | this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0); |
| 2163 | } |
| 2164 | |
| 2165 | despawnGroundItem (groundItemId) |
| 2166 | { |
| 2167 | const item = this.groundItems.get(groundItemId); |
| 2168 | if (!item) |
| 2169 | { return; } |
| 2170 | item.chequeOverlay?.destroy(); |
| 2171 | item.object?.destroy(); |
| 2172 | this.groundItems.delete(groundItemId); |
| 2173 | } |
| 2174 | |
| 2175 | upsertItemContainer (payload) |
| 2176 | { |
| 2177 | if (payload?.dimensionId != null |
| 2178 | && normalizeDimensionId(payload.dimensionId) !== normalizeDimensionId(this.dimensionId)) |
| 2179 | { return; } |
| 2180 | const containerId = payload.containerId | 0; |
| 2181 | if (!containerId) |
| 2182 | { return; } |
| 2183 | const size = this.tileSize(); |
| 2184 | const pivot = tilePivot(payload.tileX, payload.tileY, size); |
| 2185 | const spriteName = payload.sprite |
| 2186 | ?? itemSpawnerContainerSpriteName(payload.appearance, payload.material); |
| 2187 | let entry = this.itemContainers.get(containerId); |
| 2188 | if (!entry) |
| 2189 | { |
| 2190 | const object = new GameObject( |
| 2191 | 0, |
| 2192 | 0, |
| 2193 | this.game.images[spriteName] ?? this.game.images[itemSpriteName(null)], |
| 2194 | SORT_BLOCK |
| 2195 | ); |
| 2196 | this.scene.addObject(object); |
| 2197 | entry = { object }; |
| 2198 | this.itemContainers.set(containerId, entry); |
| 2199 | } |
| 2200 | else if (entry.object?.renderer && this.game.images[spriteName]) |
| 2201 | { entry.object.renderer.sprite = this.game.images[spriteName]; } |
| 2202 | entry.containerId = containerId; |
| 2203 | entry.spawnerId = payload.spawnerId ?? null; |
| 2204 | entry.tileX = payload.tileX | 0; |
| 2205 | entry.tileY = payload.tileY | 0; |
| 2206 | entry.dimensionId = normalizeDimensionId(payload.dimensionId ?? this.dimensionId ?? OVERWORLD_ID); |
| 2207 | entry.appearance = payload.appearance; |
| 2208 | entry.material = payload.material; |
| 2209 | entry.displayName = payload.displayName; |
| 2210 | entry.sprite = spriteName; |
| 2211 | this.#placePivoted(entry.object, pivot.x, pivot.y, pivot.y - 0.02, SORT_BLOCK); |
| 2212 | } |
| 2213 | |
| 2214 | despawnItemContainer (containerId) |
| 2215 | { |
| 2216 | const entry = this.itemContainers.get(containerId); |
| 2217 | if (!entry) |
| 2218 | { return; } |
| 2219 | entry.object?.destroy(); |
| 2220 | this.itemContainers.delete(containerId); |
| 2221 | } |
| 2222 | |
| 2223 | itemContainerAtTile (tileX, tileY) |
| 2224 | { |
| 2225 | for (const entry of this.itemContainers.values()) |
| 2226 | { |
| 2227 | if (entry.tileX === tileX && entry.tileY === tileY) |
| 2228 | { return entry; } |
| 2229 | } |
| 2230 | return null; |
| 2231 | } |
| 2232 | |
| 2233 | #syncGroundChequeOverlay (item, pivot) |
| 2234 | { |
| 2235 | const stack = { |
| 2236 | itemId: item.itemId, |
| 2237 | instance: item.instance, |
| 2238 | quantity: item.quantity |
| 2239 | }; |
| 2240 | const goods = isFilledChequeStack(stack) ? chequeReservedGoodsStack(stack) : null; |
| 2241 | if (!goods?.itemId) |
| 2242 | { |
| 2243 | item.chequeOverlay?.destroy(); |
| 2244 | item.chequeOverlay = null; |
| 2245 | item.chequeOverlayTint = null; |
| 2246 | item.chequeOverlayDualTint = null; |
| 2247 | return; |
| 2248 | } |
| 2249 | const goodsPotion = goods.instance?.kind === "potion" ? goods.instance : null; |
| 2250 | const goodsSprite = goodsPotion |
| 2251 | ? spriteImageName("item", "potion", `potion-${Math.max(1, Math.min(5, goodsPotion.fillLevel | 0 || 4))}`) |
| 2252 | : itemSpriteNameForStack(goods); |
| 2253 | const sprite = this.game.images[goodsSprite] ?? this.game.images[itemSpriteName(null)]; |
| 2254 | if (!sprite) |
| 2255 | { |
| 2256 | item.chequeOverlay?.destroy(); |
| 2257 | item.chequeOverlay = null; |
| 2258 | return; |
| 2259 | } |
| 2260 | if (!item.chequeOverlay || item.chequeOverlay.renderer?.sprite !== sprite) |
| 2261 | { |
| 2262 | item.chequeOverlay?.destroy(); |
| 2263 | item.chequeOverlay = new GameObject(0, 0, sprite, SORT_BLOCK); |
| 2264 | this.scene.addObject(item.chequeOverlay); |
| 2265 | } |
| 2266 | const goodsDef = itemDefinition(goods.itemId); |
| 2267 | item.chequeOverlayDualTint = goodsDef?.iconTintFromTier |
| 2268 | ? null |
| 2269 | : resolveItemDualTint(goods, goodsDef); |
| 2270 | item.chequeOverlayTint = item.chequeOverlayDualTint |
| 2271 | ? null |
| 2272 | : resolveItemTint(goods, goodsDef); |
| 2273 | if (item.chequeOverlay?.renderer && itemMaxCharges(goodsDef) != null) |
| 2274 | { item.chequeOverlay.renderer.setSubImage?.(chargeSpriteFrameIndex(goods)); } |
| 2275 | this.#placePivoted(item.chequeOverlay, pivot.x, pivot.y, pivot.y - 0.005, SORT_BLOCK, 0.5); |
| 2276 | } |
| 2277 | |
| 2278 | groundItemAtTile (tileX, tileY) |
| 2279 | { |
| 2280 | return this.groundItemsAtTile(tileX, tileY)[0] ?? null; |
| 2281 | } |
| 2282 | |
| 2283 | groundItemsAtTile (tileX, tileY) |
| 2284 | { |
| 2285 | const items = []; |
| 2286 | for (const item of this.groundItems.values()) |
| 2287 | { |
| 2288 | if (item.tileX === tileX && item.tileY === tileY) |
| 2289 | { items.push(item); } |
| 2290 | } |
| 2291 | return items; |
| 2292 | } |
| 2293 | |
| 2294 | entitiesAtTile (tileX, tileY, options = {}) |
| 2295 | { |
| 2296 | const includePrevious = !!options.includePrevious; |
| 2297 | const matches = []; |
| 2298 | for (const entity of this.entities.values()) |
| 2299 | { |
| 2300 | if (entity.tileX === tileX && entity.tileY === tileY) |
| 2301 | { |
| 2302 | matches.push(entity); |
| 2303 | continue; |
| 2304 | } |
| 2305 | if ( |
| 2306 | includePrevious |
| 2307 | && entity.lerpStarted != null |
| 2308 | && entity.previousTileX === tileX |
| 2309 | && entity.previousTileY === tileY |
| 2310 | ) |
| 2311 | { matches.push(entity); } |
| 2312 | } |
| 2313 | matches.sort((a, b) => (b.object?.layer ?? 0) - (a.object?.layer ?? 0)); |
| 2314 | return matches; |
| 2315 | } |
| 2316 | |
| 2317 | setZoom (zoom, limits = { min: 2, max: 4 }) |
| 2318 | { |
| 2319 | const min = limits.min ?? 1; |
| 2320 | const max = limits.max ?? 4; |
| 2321 | this.zoom = Math.min(max, Math.max(min, zoom)); |
| 2322 | for (const snapshot of this.chunks.values()) |
| 2323 | { this.#relayoutChunk(snapshot); } |
| 2324 | const size = this.tileSize(); |
| 2325 | for (const entity of this.entities.values()) |
| 2326 | { |
| 2327 | entity.visualX = tilePivot(entity.tileX, entity.tileY, size).x; |
| 2328 | entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y; |
| 2329 | entity.fromX = entity.visualX; |
| 2330 | entity.fromY = entity.visualY; |
| 2331 | entity.targetX = entity.visualX; |
| 2332 | entity.targetY = entity.visualY; |
| 2333 | entity.lerpStarted = null; |
| 2334 | this.#placeEntity(entity); |
| 2335 | } |
| 2336 | for (const item of this.groundItems.values()) |
| 2337 | { |
| 2338 | const pivot = tilePivot(item.tileX, item.tileY, size); |
| 2339 | this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK); |
| 2340 | if (item.chequeOverlay) |
| 2341 | { this.#placePivoted(item.chequeOverlay, pivot.x, pivot.y, pivot.y - 0.005, SORT_BLOCK, 0.5); } |
| 2342 | } |
| 2343 | this.#rebuildAllEdges(); |
| 2344 | this.#relayoutEditorSpawners(); |
| 2345 | this.#relayoutSpawnRangeHighlight(); |
| 2346 | this.#relayoutSpellTargetHighlight(); |
| 2347 | // Play: recenter + refresh cull flags with the new tile size immediately. |
| 2348 | // Editor sets the camera via frameNeighborhood after setZoom — call refreshViewport there. |
| 2349 | if (this.followPlayer) |
| 2350 | { this.refreshViewport(); } |
| 2351 | } |
| 2352 | |
| 2353 | /** Recenter (when following) and refresh off-screen cull flags after zoom/layout. */ |
| 2354 | refreshViewport () |
| 2355 | { |
| 2356 | this.#centerCamera(); |
| 2357 | this.#syncYSortOrigin(); |
| 2358 | this.#refreshDepthLayers(); |
| 2359 | this.#cullOffscreenDrawables(); |
| 2360 | } |
| 2361 | |
| 2362 | tileSize () |
| 2363 | { |
| 2364 | return SPRITE_SIZE_PX * this.zoom; |
| 2365 | } |
| 2366 | |
| 2367 | screenToTile (mouseX, mouseY) |
| 2368 | { |
| 2369 | const size = this.tileSize(); |
| 2370 | const worldX = mouseX - this.scene.cameraPosition.x; |
| 2371 | const worldY = mouseY - this.scene.cameraPosition.y; |
| 2372 | return { |
| 2373 | tileX: Math.floor(worldX / size), |
| 2374 | tileY: Math.floor(worldY / size) |
| 2375 | }; |
| 2376 | } |
| 2377 | |
| 2378 | entityAtScreen (mouseX, mouseY) |
| 2379 | { |
| 2380 | let best = null; |
| 2381 | let bestLayer = -Infinity; |
| 2382 | for (const entity of this.entities.values()) |
| 2383 | { |
| 2384 | const box = this.#entityScreenBox(entity); |
| 2385 | if (!box) |
| 2386 | { continue; } |
| 2387 | if (mouseX >= box.left && mouseX < box.right && mouseY >= box.top && mouseY < box.bottom) |
| 2388 | { |
| 2389 | const layer = entity.object?.layer ?? 0; |
| 2390 | if (layer >= bestLayer) |
| 2391 | { |
| 2392 | best = entity; |
| 2393 | bestLayer = layer; |
| 2394 | } |
| 2395 | } |
| 2396 | } |
| 2397 | return best; |
| 2398 | } |
| 2399 | |
| 2400 | nametagAnchor (entity) |
| 2401 | { |
| 2402 | const box = this.#entityScreenBox(entity); |
| 2403 | if (!box) |
| 2404 | { return null; } |
| 2405 | return { x: (box.left + box.right) / 2, y: box.top }; |
| 2406 | } |
| 2407 | |
| 2408 | #entityScreenBox (entity) |
| 2409 | { |
| 2410 | const object = entity?.object; |
| 2411 | if (!object) |
| 2412 | { return null; } |
| 2413 | const size = object.transform.size; |
| 2414 | const x = object.transform.position.x + this.scene.cameraPosition.x; |
| 2415 | const y = object.transform.position.y + this.scene.cameraPosition.y; |
| 2416 | return { |
| 2417 | left: x - size.x / 2, |
| 2418 | right: x + size.x / 2, |
| 2419 | top: y - size.y / 2, |
| 2420 | bottom: y + size.y / 2 |
| 2421 | }; |
| 2422 | } |
| 2423 | |
| 2424 | update (deltaTime) |
| 2425 | { |
| 2426 | const now = performance.now(); |
| 2427 | const size = this.tileSize(); |
| 2428 | this.#refreshStackTargets(); |
| 2429 | for (const entity of this.entities.values()) |
| 2430 | { |
| 2431 | const target = entity.targetX != null && entity.targetY != null |
| 2432 | ? { x: entity.targetX, y: entity.targetY } |
| 2433 | : tilePivot(entity.tileX, entity.tileY, size); |
| 2434 | if (entity.lerpStarted != null) |
| 2435 | { |
| 2436 | const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs)); |
| 2437 | entity.visualX = entity.fromX + (target.x - entity.fromX) * t; |
| 2438 | entity.visualY = entity.fromY + (target.y - entity.fromY) * t; |
| 2439 | if (t >= 1) |
| 2440 | { |
| 2441 | entity.lerpStarted = null; |
| 2442 | entity.previousTileX = null; |
| 2443 | entity.previousTileY = null; |
| 2444 | } |
| 2445 | } |
| 2446 | else |
| 2447 | { |
| 2448 | entity.visualX = target.x; |
| 2449 | entity.visualY = target.y; |
| 2450 | } |
| 2451 | this.#updateStackOffset(entity, now); |
| 2452 | this.#updateShove(entity, now, size); |
| 2453 | this.#expireGatherToolOverlay(entity, now); |
| 2454 | } |
| 2455 | |
| 2456 | // The y-sort origin must settle before any layer is computed this frame, |
| 2457 | // otherwise entities and blocks end up sorted against different origins. |
| 2458 | // It only moves when the view crosses a chunk row; the static world then |
| 2459 | // needs one re-layer pass, and nothing at all on every other frame. |
| 2460 | this.#centerCamera(); |
| 2461 | if (this.#syncYSortOrigin()) |
| 2462 | { this.#refreshDepthLayers(); } |
| 2463 | |
| 2464 | for (const entity of this.entities.values()) |
| 2465 | { this.#placeEntity(entity, now); } |
| 2466 | |
| 2467 | this.#updateSwipes(now); |
| 2468 | this.#updateDamageNumbers(now); |
| 2469 | this.#updateSkillLevelFloats(now); |
| 2470 | this.#relayoutSpellTargetHighlight(); |
| 2471 | this.#cullOffscreenDrawables(); |
| 2472 | this.#updateShade(deltaTime); |
| 2473 | } |
| 2474 | |
| 2475 | /** |
| 2476 | * Desired circle offsets for stacked entities (applied via {@link #updateStackOffset}). |
| 2477 | * Stable assignment by entityId; free-flight entities stay unshifted. |
| 2478 | */ |
| 2479 | #refreshStackTargets () |
| 2480 | { |
| 2481 | const byTile = new Map(); |
| 2482 | for (const entity of this.entities.values()) |
| 2483 | { |
| 2484 | if (entity.freeFlight || entity.dying) |
| 2485 | { |
| 2486 | entity.stackTargetX = 0; |
| 2487 | entity.stackTargetY = 0; |
| 2488 | continue; |
| 2489 | } |
| 2490 | const key = `${entity.tileX},${entity.tileY}`; |
| 2491 | let list = byTile.get(key); |
| 2492 | if (!list) |
| 2493 | { |
| 2494 | list = []; |
| 2495 | byTile.set(key, list); |
| 2496 | } |
| 2497 | list.push(entity); |
| 2498 | } |
| 2499 | const radius = (ENTITY_STACK_SPREAD_DIAMETER_PX * this.zoom) / 2; |
| 2500 | for (const list of byTile.values()) |
| 2501 | { |
| 2502 | if (list.length <= 1) |
| 2503 | { |
| 2504 | for (const entity of list) |
| 2505 | { |
| 2506 | entity.stackTargetX = 0; |
| 2507 | entity.stackTargetY = 0; |
| 2508 | } |
| 2509 | continue; |
| 2510 | } |
| 2511 | list.sort((a, b) => String(a.entityId).localeCompare(String(b.entityId))); |
| 2512 | const n = list.length; |
| 2513 | for (let i = 0; i < n; i++) |
| 2514 | { |
| 2515 | const angle = -Math.PI / 2 + (Math.PI * 2 * i) / n; |
| 2516 | list[i].stackTargetX = Math.cos(angle) * radius; |
| 2517 | list[i].stackTargetY = Math.sin(angle) * radius; |
| 2518 | } |
| 2519 | } |
| 2520 | } |
| 2521 | |
| 2522 | #updateStackOffset (entity, now) |
| 2523 | { |
| 2524 | const tx = entity.stackTargetX ?? 0; |
| 2525 | const ty = entity.stackTargetY ?? 0; |
| 2526 | const cx = entity.stackOffsetX ?? 0; |
| 2527 | const cy = entity.stackOffsetY ?? 0; |
| 2528 | if (entity.stackLerpToX !== tx || entity.stackLerpToY !== ty) |
| 2529 | { |
| 2530 | entity.stackFromX = cx; |
| 2531 | entity.stackFromY = cy; |
| 2532 | entity.stackLerpToX = tx; |
| 2533 | entity.stackLerpToY = ty; |
| 2534 | entity.stackLerpStarted = now; |
| 2535 | } |
| 2536 | if (entity.stackLerpStarted == null) |
| 2537 | { |
| 2538 | entity.stackOffsetX = tx; |
| 2539 | entity.stackOffsetY = ty; |
| 2540 | return; |
| 2541 | } |
| 2542 | const t = Math.min(1, (now - entity.stackLerpStarted) / STACK_SPREAD_LERP_MS); |
| 2543 | entity.stackOffsetX = entity.stackFromX + (tx - entity.stackFromX) * t; |
| 2544 | entity.stackOffsetY = entity.stackFromY + (ty - entity.stackFromY) * t; |
| 2545 | if (t >= 1) |
| 2546 | { |
| 2547 | entity.stackOffsetX = tx; |
| 2548 | entity.stackOffsetY = ty; |
| 2549 | entity.stackLerpStarted = null; |
| 2550 | } |
| 2551 | } |
| 2552 | |
| 2553 | #updateShove (entity, now, tileSize) |
| 2554 | { |
| 2555 | if (!entity.shove) |
| 2556 | { |
| 2557 | entity.shoveOffsetX = 0; |
| 2558 | entity.shoveOffsetY = 0; |
| 2559 | return; |
| 2560 | } |
| 2561 | const elapsed = now - entity.shove.started; |
| 2562 | const t = Math.min(1, elapsed / entity.shove.durationMs); |
| 2563 | const maxDist = tileSize * SHOVE_TILE_FRACTION; |
| 2564 | const dx = entity.shove.targetVisualX - entity.shove.startVisualX; |
| 2565 | const dy = entity.shove.targetVisualY - entity.shove.startVisualY; |
| 2566 | const dist = Math.hypot(dx, dy) || 1; |
| 2567 | const ux = dx / dist; |
| 2568 | const uy = dy / dist; |
| 2569 | let phase; |
| 2570 | if (t < 0.45) |
| 2571 | { phase = t / 0.45; } |
| 2572 | else |
| 2573 | { phase = 1 - (t - 0.45) / 0.55; } |
| 2574 | entity.shoveOffsetX = ux * maxDist * phase; |
| 2575 | entity.shoveOffsetY = uy * maxDist * phase; |
| 2576 | if (t >= 1) |
| 2577 | { entity.shove = null; } |
| 2578 | } |
| 2579 | |
| 2580 | spawnCombatSwing (payload) |
| 2581 | { |
| 2582 | const attacker = this.entities.get(payload.attackerId); |
| 2583 | const target = this.entities.get(payload.targetId); |
| 2584 | if (!attacker || !target) |
| 2585 | { return; } |
| 2586 | const ax = attacker.visualX + (attacker.stackOffsetX ?? 0); |
| 2587 | const ay = attacker.visualY + (attacker.stackOffsetY ?? 0); |
| 2588 | const tx = target.visualX + (target.stackOffsetX ?? 0); |
| 2589 | const ty = target.visualY + (target.stackOffsetY ?? 0); |
| 2590 | this.#applyShove(attacker, tx, ty); |
| 2591 | const midX = (ax + tx) / 2; |
| 2592 | const midY = (ay + ty) / 2; |
| 2593 | const sortY = Math.max(ay, ty) + 0.02; |
| 2594 | const angle = Math.atan2(ty - ay, tx - ax) * (180 / Math.PI); |
| 2595 | const jitter = (Math.random() * 2 - 1) * MELEE_SWIPE_JITTER_DEG; |
| 2596 | const spriteName = "fx:melee-swipe:melee-swipe"; |
| 2597 | const object = new GameObject(0, 0, this.game.images[spriteName], SORT_FX); |
| 2598 | if (object.transform) |
| 2599 | { object.transform.rotation = angle + jitter; } |
| 2600 | if (object.renderer) |
| 2601 | { object.renderer.alpha = 1; } |
| 2602 | this.scene.addObject(object); |
| 2603 | this.#placePivoted(object, midX, midY, sortY, SORT_FX); |
| 2604 | this.#applyPhysicalCombatFxDarkness(object, payload.fromTileX, payload.fromTileY, payload.tileX, payload.tileY); |
| 2605 | const started = performance.now(); |
| 2606 | this.swipes.push({ |
| 2607 | object, |
| 2608 | until: started + MELEE_SWIPE_MS, |
| 2609 | started, |
| 2610 | durationMs: MELEE_SWIPE_MS, |
| 2611 | sortY, |
| 2612 | fadeOpacity: true, |
| 2613 | fromTileX: payload.fromTileX, |
| 2614 | fromTileY: payload.fromTileY, |
| 2615 | tileX: payload.tileX, |
| 2616 | tileY: payload.tileY |
| 2617 | }); |
| 2618 | } |
| 2619 | |
| 2620 | /** Mining / gathering lunge toward a tile — shove only, no swipe FX. */ |
| 2621 | spawnGatherSwing (payload) |
| 2622 | { |
| 2623 | const attacker = this.entities.get(payload.attackerId); |
| 2624 | if (!attacker) |
| 2625 | { return; } |
| 2626 | const pivot = tilePivot(payload.tileX, payload.tileY, this.tileSize()); |
| 2627 | this.#applyShove(attacker, pivot.x, pivot.y); |
| 2628 | if (payload.toolItemId != null) |
| 2629 | { this.#setGatherToolOverlay(attacker, payload.toolItemId); } |
| 2630 | } |
| 2631 | |
| 2632 | #applyShove (entity, targetVisualX, targetVisualY) |
| 2633 | { |
| 2634 | entity.shove = { |
| 2635 | startVisualX: entity.visualX, |
| 2636 | startVisualY: entity.visualY, |
| 2637 | targetVisualX, |
| 2638 | targetVisualY, |
| 2639 | started: performance.now(), |
| 2640 | durationMs: SHOVE_MS |
| 2641 | }; |
| 2642 | } |
| 2643 | |
| 2644 | #applyShoveInDirection (entity, dirX, dirY) |
| 2645 | { |
| 2646 | const len = Math.hypot(dirX, dirY); |
| 2647 | if (len < 1e-4) |
| 2648 | { return; } |
| 2649 | const tileSize = this.tileSize(); |
| 2650 | const ux = dirX / len; |
| 2651 | const uy = dirY / len; |
| 2652 | this.#applyShove( |
| 2653 | entity, |
| 2654 | entity.visualX + ux * tileSize, |
| 2655 | entity.visualY + uy * tileSize |
| 2656 | ); |
| 2657 | } |
| 2658 | |
| 2659 | /** Physical combat FX (melee swipes, ranged projectiles). Magic spells stay unshaded. */ |
| 2660 | spawnPhysicalProjectileFx (payload) |
| 2661 | { |
| 2662 | const spriteName = payload.sprite ?? "fx:projectile:arrow"; |
| 2663 | const image = this.game.images[spriteName]; |
| 2664 | if (!image) |
| 2665 | { return; } |
| 2666 | const dualTint = this.#dualTintFromPayload(payload); |
| 2667 | const fromPivot = this.#projectileLaunchPoint( |
| 2668 | payload.attackerId ?? null, |
| 2669 | payload.fromTileX, |
| 2670 | payload.fromTileY |
| 2671 | ); |
| 2672 | const toPivot = this.#projectileAimPoint( |
| 2673 | payload.targetId ?? null, |
| 2674 | payload.tileX, |
| 2675 | payload.tileY |
| 2676 | ); |
| 2677 | const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02; |
| 2678 | const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI); |
| 2679 | const object = new GameObject(0, 0, image, SORT_FX); |
| 2680 | if (object.transform) |
| 2681 | { object.transform.rotation = angle; } |
| 2682 | this.scene.addObject(object); |
| 2683 | this.#placePivoted(object, fromPivot.x, fromPivot.y, sortY, SORT_FX); |
| 2684 | this.#applyPhysicalCombatFxDarkness( |
| 2685 | object, |
| 2686 | payload.fromTileX, |
| 2687 | payload.fromTileY, |
| 2688 | payload.tileX, |
| 2689 | payload.tileY, |
| 2690 | dualTint |
| 2691 | ); |
| 2692 | const started = performance.now(); |
| 2693 | const durationMs = payload.durationMs ?? 400; |
| 2694 | const trackTarget = payload.trackTarget !== false && payload.targetId != null; |
| 2695 | this.swipes.push({ |
| 2696 | object, |
| 2697 | until: started + durationMs, |
| 2698 | started, |
| 2699 | durationMs, |
| 2700 | lerp: true, |
| 2701 | dualTint, |
| 2702 | fromTileX: payload.fromTileX, |
| 2703 | fromTileY: payload.fromTileY, |
| 2704 | tileX: payload.tileX, |
| 2705 | tileY: payload.tileY, |
| 2706 | attackerId: payload.attackerId ?? null, |
| 2707 | targetId: payload.targetId ?? null, |
| 2708 | trackTarget, |
| 2709 | onImpact: null |
| 2710 | }); |
| 2711 | } |
| 2712 | |
| 2713 | /** Bloom-layer spell projectiles — magenta-tinted, unique art per spell. */ |
| 2714 | spawnSpellProjectileFx (payload) |
| 2715 | { |
| 2716 | const spellId = payload.spellId ?? null; |
| 2717 | const def = spellId != null ? spellDefinition(spellId) : null; |
| 2718 | const spriteName = payload.sprite |
| 2719 | ?? def?.projectileSprite |
| 2720 | ?? "fx:projectile:spell-none-1-mana-bullet"; |
| 2721 | const image = this.game.images[spriteName]; |
| 2722 | if (!image) |
| 2723 | { return; } |
| 2724 | const tint = spellProjectileTint(def?.element); |
| 2725 | const fromPivot = this.#projectileLaunchPoint( |
| 2726 | payload.casterId ?? null, |
| 2727 | payload.fromTileX, |
| 2728 | payload.fromTileY |
| 2729 | ); |
| 2730 | const toPivot = this.#projectileAimPoint( |
| 2731 | payload.targetId ?? null, |
| 2732 | payload.tileX, |
| 2733 | payload.tileY |
| 2734 | ); |
| 2735 | // Spell casts push the caster visually toward the spell's target. |
| 2736 | // (Presentation only; server authority remains combat-resolution.) |
| 2737 | const caster = payload.casterId != null |
| 2738 | ? this.entities.get(payload.casterId) |
| 2739 | : null; |
| 2740 | if (caster && !caster.dying) |
| 2741 | { |
| 2742 | const casterPivotX = caster.visualX + (caster.stackOffsetX ?? 0); |
| 2743 | const casterPivotY = caster.visualY + (caster.stackOffsetY ?? 0); |
| 2744 | this.#applyShoveInDirection(caster, toPivot.x - casterPivotX, toPivot.y - casterPivotY); |
| 2745 | } |
| 2746 | const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02; |
| 2747 | const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI); |
| 2748 | const object = new GameObject(0, 0, image, SORT_FX); |
| 2749 | object.renderer.layer = RENDER_LAYER_BLOOM; |
| 2750 | this.#markUnlit(object); |
| 2751 | this.#syncUnlitTintSprite(object, tint); |
| 2752 | if (object.transform) |
| 2753 | { object.transform.rotation = angle; } |
| 2754 | this.scene.addObject(object); |
| 2755 | this.#placePivoted(object, fromPivot.x, fromPivot.y, sortY, SORT_FX); |
| 2756 | const started = performance.now(); |
| 2757 | const durationMs = payload.durationMs ?? 2000; |
| 2758 | this.swipes.push({ |
| 2759 | object, |
| 2760 | until: started + durationMs, |
| 2761 | started, |
| 2762 | durationMs, |
| 2763 | lerp: true, |
| 2764 | spellProjectile: true, |
| 2765 | tint, |
| 2766 | fromTileX: payload.fromTileX, |
| 2767 | fromTileY: payload.fromTileY, |
| 2768 | tileX: payload.tileX, |
| 2769 | tileY: payload.tileY, |
| 2770 | attackerId: payload.casterId ?? null, |
| 2771 | targetId: payload.targetId ?? null, |
| 2772 | trackTarget: payload.targetId != null, |
| 2773 | onImpact: null |
| 2774 | }); |
| 2775 | } |
| 2776 | |
| 2777 | spawnSpellFizzleFx (_payload) |
| 2778 | { |
| 2779 | // Visual-only fizzle; no dynamic light (cast flashes skip lightmap rebakes). |
| 2780 | } |
| 2781 | |
| 2782 | /** |
| 2783 | * Authoritative Light-spell tile light from the server. |
| 2784 | * Kept out of short-lived `dynamicLights` so duration follows `remainingMs` updates. |
| 2785 | */ |
| 2786 | setSpellLight (payload) |
| 2787 | { |
| 2788 | const key = `${payload.tileX},${payload.tileY}`; |
| 2789 | this.spellLights.set(key, { |
| 2790 | tileX: payload.tileX, |
| 2791 | tileY: payload.tileY, |
| 2792 | until: performance.now() + Math.max(0, payload.remainingMs ?? 0), |
| 2793 | range: payload.rangeTiles ?? 6, |
| 2794 | intensity: payload.intensity ?? 0.88 |
| 2795 | }); |
| 2796 | this.#invalidateNeighborLightmapCaches( |
| 2797 | Math.floor(payload.tileX / CHUNK_SIZE), |
| 2798 | Math.floor(payload.tileY / CHUNK_SIZE) |
| 2799 | ); |
| 2800 | } |
| 2801 | |
| 2802 | removeSpellLight (payload) |
| 2803 | { |
| 2804 | this.spellLights.delete(`${payload.tileX},${payload.tileY}`); |
| 2805 | this.#invalidateNeighborLightmapCaches( |
| 2806 | Math.floor(payload.tileX / CHUNK_SIZE), |
| 2807 | Math.floor(payload.tileY / CHUNK_SIZE) |
| 2808 | ); |
| 2809 | } |
| 2810 | |
| 2811 | setSpellDark (payload) |
| 2812 | { |
| 2813 | const key = `${payload.tileX},${payload.tileY}`; |
| 2814 | this.spellDarks.set(key, { |
| 2815 | tileX: payload.tileX, |
| 2816 | tileY: payload.tileY, |
| 2817 | until: performance.now() + Math.max(0, payload.remainingMs ?? 0), |
| 2818 | range: payload.rangeTiles ?? 6, |
| 2819 | intensity: payload.intensity ?? 0.88 |
| 2820 | }); |
| 2821 | this.#invalidateNeighborLightmapCaches( |
| 2822 | Math.floor(payload.tileX / CHUNK_SIZE), |
| 2823 | Math.floor(payload.tileY / CHUNK_SIZE) |
| 2824 | ); |
| 2825 | } |
| 2826 | |
| 2827 | removeSpellDark (payload) |
| 2828 | { |
| 2829 | this.spellDarks.delete(`${payload.tileX},${payload.tileY}`); |
| 2830 | this.#invalidateNeighborLightmapCaches( |
| 2831 | Math.floor(payload.tileX / CHUNK_SIZE), |
| 2832 | Math.floor(payload.tileY / CHUNK_SIZE) |
| 2833 | ); |
| 2834 | } |
| 2835 | |
| 2836 | addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 1, durationMs = 250 }) |
| 2837 | { |
| 2838 | this.dynamicLights.push({ |
| 2839 | tileX: Math.floor(worldX), |
| 2840 | tileY: Math.floor(worldY), |
| 2841 | range: radiusTiles, |
| 2842 | intensity, |
| 2843 | until: performance.now() + durationMs |
| 2844 | }); |
| 2845 | } |
| 2846 | |
| 2847 | updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {}) |
| 2848 | { |
| 2849 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 2850 | if (!snapshot) |
| 2851 | { return; } |
| 2852 | const index = localY * CHUNK_SIZE + localX; |
| 2853 | if (ground !== undefined) |
| 2854 | { snapshot.grounds[index] = ground; } |
| 2855 | if (block !== undefined) |
| 2856 | { snapshot.blocks[index] = block; } |
| 2857 | if (light !== undefined) |
| 2858 | { snapshot.light[index] = light; } |
| 2859 | if (ground !== undefined || block !== undefined) |
| 2860 | { |
| 2861 | if (!Array.isArray(snapshot.occlusion) || snapshot.occlusion.length < CHUNK_SIZE * CHUNK_SIZE) |
| 2862 | { snapshot.occlusion = bakeChunkOcclusion(snapshot); } |
| 2863 | else |
| 2864 | { snapshot.occlusion[index] = tileLightOcclusionAt(snapshot.grounds, snapshot.blocks, localX, localY); } |
| 2865 | if ( |
| 2866 | this.worldBorderWalkableOnly |
| 2867 | && (localX === 0 || localY === 0 || localX === CHUNK_SIZE - 1 || localY === CHUNK_SIZE - 1) |
| 2868 | ) |
| 2869 | { this.#scheduleEdgeRebuild(); } |
| 2870 | } |
| 2871 | const tileX = chunkX * CHUNK_SIZE + localX; |
| 2872 | const tileY = chunkY * CHUNK_SIZE + localY; |
| 2873 | if (block !== undefined) |
| 2874 | { |
| 2875 | this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false }); |
| 2876 | this.#drawTile(tileX, tileY); |
| 2877 | return; |
| 2878 | } |
| 2879 | this.#scheduleChunkRebuild(snapshot); |
| 2880 | if (ground !== undefined) |
| 2881 | { this.#drawTile(tileX, tileY); } |
| 2882 | } |
| 2883 | |
| 2884 | /** |
| 2885 | * Editor-only mob markers for authored spawners (invisible during play). |
| 2886 | * Humanoid / town guard / CE show body + equipment overlays. |
| 2887 | * Previews up to 10 bodies using the same stack circle as play. |
| 2888 | * @param {number} chunkX |
| 2889 | * @param {number} chunkY |
| 2890 | * @param {Array<{ localX: number, localY: number, config?: object }>} spawners |
| 2891 | * @param {(mobTypeId: number) => string} resolveSprite |
| 2892 | */ |
| 2893 | setEditorSpawners (chunkX, chunkY, spawners, resolveSprite) |
| 2894 | { |
| 2895 | const prefix = `${chunkX},${chunkY}:`; |
| 2896 | for (const [key, entry] of [...this.editorSpawners.entries()]) |
| 2897 | { |
| 2898 | if (!key.startsWith(prefix)) |
| 2899 | { continue; } |
| 2900 | this.#destroyEditorSpawnerEntry(entry); |
| 2901 | this.editorSpawners.delete(key); |
| 2902 | } |
| 2903 | const size = this.tileSize(); |
| 2904 | for (const spawner of spawners ?? []) |
| 2905 | { |
| 2906 | const tileX = chunkX * CHUNK_SIZE + spawner.localX; |
| 2907 | const tileY = chunkY * CHUNK_SIZE + spawner.localY; |
| 2908 | const config = normalizeSpawnerConfig(spawner.config ?? {}); |
| 2909 | if (isItemSpawnerConfig(config)) |
| 2910 | { |
| 2911 | const bodySpriteName = itemSpawnerContainerSpriteName( |
| 2912 | config.appearance === "item" ? "chest" : config.appearance, |
| 2913 | config.material |
| 2914 | ); |
| 2915 | const object = this.#ensureSprite(null, bodySpriteName, SORT_ENTITY); |
| 2916 | if (!object) |
| 2917 | { continue; } |
| 2918 | object.renderer.alpha = 0.85; |
| 2919 | this.#markUnlit(object); |
| 2920 | const key = `${prefix}${spawner.localX},${spawner.localY}`; |
| 2921 | const entry = { |
| 2922 | instances: [{ object, overlays: [] }], |
| 2923 | tileX, |
| 2924 | tileY, |
| 2925 | spriteName: bodySpriteName |
| 2926 | }; |
| 2927 | this.#placeEditorSpawnerEntry(entry, size); |
| 2928 | this.editorSpawners.set(key, entry); |
| 2929 | continue; |
| 2930 | } |
| 2931 | const layers = layersFromSpawnerConfig(config); |
| 2932 | const bodySpriteName = layers?.[0]?.sprite |
| 2933 | ?? resolveSprite?.(config.mobTypeId) |
| 2934 | ?? null; |
| 2935 | if (!bodySpriteName) |
| 2936 | { continue; } |
| 2937 | const previewCount = Math.min(10, Math.max(1, config.maxAlive | 0)); |
| 2938 | const instances = []; |
| 2939 | for (let n = 0; n < previewCount; n++) |
| 2940 | { |
| 2941 | const object = this.#ensureSprite(null, bodySpriteName, SORT_ENTITY); |
| 2942 | if (!object) |
| 2943 | { continue; } |
| 2944 | object.renderer.alpha = 0.85; |
| 2945 | const bodyTint = layers?.[0]?.tint ? normalizeRgb(layers[0].tint) : null; |
| 2946 | if (bodyTint) |
| 2947 | { this.#syncUnlitTintSprite(object, bodyTint); } |
| 2948 | else |
| 2949 | { this.#markUnlit(object); } |
| 2950 | const overlays = []; |
| 2951 | for (const layer of layers?.slice(1) ?? []) |
| 2952 | { |
| 2953 | const overlay = this.#ensureSprite(null, layer.sprite, SORT_ENTITY); |
| 2954 | if (!overlay) |
| 2955 | { continue; } |
| 2956 | overlay.renderer.alpha = 0.85; |
| 2957 | this.#applyEditorSpawnerOverlayLook(overlay, layer); |
| 2958 | overlays.push(overlay); |
| 2959 | } |
| 2960 | instances.push({ object, overlays }); |
| 2961 | } |
| 2962 | if (!instances.length) |
| 2963 | { continue; } |
| 2964 | const key = `${prefix}${spawner.localX},${spawner.localY}`; |
| 2965 | const entry = { |
| 2966 | instances, |
| 2967 | tileX, |
| 2968 | tileY, |
| 2969 | spriteName: bodySpriteName |
| 2970 | }; |
| 2971 | this.#placeEditorSpawnerEntry(entry, size); |
| 2972 | this.editorSpawners.set(key, entry); |
| 2973 | } |
| 2974 | } |
| 2975 | |
| 2976 | #destroyEditorSpawnerEntry (entry) |
| 2977 | { |
| 2978 | for (const instance of entry?.instances ?? []) |
| 2979 | { |
| 2980 | instance?.object?.destroy(); |
| 2981 | for (const overlay of instance?.overlays ?? []) |
| 2982 | { overlay?.destroy(); } |
| 2983 | } |
| 2984 | // Legacy single-body shape (pre multi-preview). |
| 2985 | entry?.object?.destroy(); |
| 2986 | for (const overlay of entry?.overlays ?? []) |
| 2987 | { overlay?.destroy(); } |
| 2988 | } |
| 2989 | |
| 2990 | #applyEditorSpawnerOverlayLook (overlay, layer) |
| 2991 | { |
| 2992 | const layerDef = layer.itemId != null ? itemDefinition(layer.itemId) : null; |
| 2993 | const dualTint = layerDef?.iconTintFromTier |
| 2994 | ? null |
| 2995 | : (layer.itemId != null |
| 2996 | ? resolveEquipDualTint({ itemId: layer.itemId }, layerDef) |
| 2997 | : null); |
| 2998 | const tint = layer.tint |
| 2999 | ? normalizeRgb(layer.tint) |
| 3000 | : (dualTint |
| 3001 | ? null |
| 3002 | : (layerDef?.iconTintFromTier |
| 3003 | ? resolveItemTint({ itemId: layer.itemId }, layerDef) |
| 3004 | : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null))); |
| 3005 | if (dualTint) |
| 3006 | { |
| 3007 | overlay._lit = true; |
| 3008 | this.#syncDualTintLitSprite(overlay, 0, dualTint, 0, false); |
| 3009 | return; |
| 3010 | } |
| 3011 | if (tint) |
| 3012 | { |
| 3013 | this.#syncUnlitTintSprite(overlay, tint); |
| 3014 | return; |
| 3015 | } |
| 3016 | this.#markUnlit(overlay); |
| 3017 | } |
| 3018 | |
| 3019 | clearEditorSpawners () |
| 3020 | { |
| 3021 | for (const entry of this.editorSpawners.values()) |
| 3022 | { this.#destroyEditorSpawnerEntry(entry); } |
| 3023 | this.editorSpawners.clear(); |
| 3024 | } |
| 3025 | |
| 3026 | #placeEditorSpawnerEntry (entry, size = this.tileSize()) |
| 3027 | { |
| 3028 | const instances = entry?.instances ?? []; |
| 3029 | if (!instances.length) |
| 3030 | { return; } |
| 3031 | const pivot = tilePivot(entry.tileX, entry.tileY, size); |
| 3032 | const n = instances.length; |
| 3033 | const radius = n <= 1 ? 0 : (ENTITY_STACK_SPREAD_DIAMETER_PX * this.zoom) / 2; |
| 3034 | for (let i = 0; i < n; i++) |
| 3035 | { |
| 3036 | const angle = -Math.PI / 2 + (Math.PI * 2 * i) / n; |
| 3037 | const x = pivot.x + Math.cos(angle) * radius; |
| 3038 | const y = pivot.y + Math.sin(angle) * radius; |
| 3039 | const instance = instances[i]; |
| 3040 | const depthBase = y + 0.05 + 0.0001 * i; |
| 3041 | this.#placePivoted(instance.object, x, y, depthBase, SORT_ENTITY); |
| 3042 | const overlays = instance.overlays ?? []; |
| 3043 | for (let o = 0; o < overlays.length; o++) |
| 3044 | { |
| 3045 | this.#placePivoted( |
| 3046 | overlays[o], |
| 3047 | x, |
| 3048 | y, |
| 3049 | depthBase + 0.001 * (o + 1), |
| 3050 | SORT_ENTITY |
| 3051 | ); |
| 3052 | } |
| 3053 | } |
| 3054 | } |
| 3055 | |
| 3056 | #relayoutEditorSpawners () |
| 3057 | { |
| 3058 | const size = this.tileSize(); |
| 3059 | for (const entry of this.editorSpawners.values()) |
| 3060 | { this.#placeEditorSpawnerEntry(entry, size); } |
| 3061 | } |
| 3062 | |
| 3063 | /** |
| 3064 | * Editor-only range overlays: spawn (inner) and wander (outer, Chebyshev squares). |
| 3065 | */ |
| 3066 | setSpawnRangeHighlight (tileX, tileY, spawnRange, wanderRange = null) |
| 3067 | { |
| 3068 | const spawnRadius = Math.max(0, spawnRange | 0); |
| 3069 | const wanderRadius = Math.max(spawnRadius, wanderRange == null ? spawnRadius : (wanderRange | 0)); |
| 3070 | if (this.spawnRangeHighlight |
| 3071 | && this.wanderRangeHighlight |
| 3072 | && this.spawnRangeHighlight.tileX === tileX |
| 3073 | && this.spawnRangeHighlight.tileY === tileY |
| 3074 | && this.spawnRangeHighlight.range === spawnRadius |
| 3075 | && this.wanderRangeHighlight.range === wanderRadius) |
| 3076 | { |
| 3077 | this.#relayoutSpawnRangeHighlight(); |
| 3078 | return; |
| 3079 | } |
| 3080 | this.clearSpawnRangeHighlight(); |
| 3081 | const wanderObject = this.#ensureSprite(null, "wander-range", LAYER_EDGE); |
| 3082 | const spawnObject = this.#ensureSprite(null, "spawn-range", LAYER_EDGE); |
| 3083 | if (wanderObject) |
| 3084 | { |
| 3085 | this.#markUnlit(wanderObject); |
| 3086 | wanderObject.renderer.alpha = 1; |
| 3087 | this.wanderRangeHighlight = { object: wanderObject, tileX, tileY, range: wanderRadius }; |
| 3088 | } |
| 3089 | if (spawnObject) |
| 3090 | { |
| 3091 | this.#markUnlit(spawnObject); |
| 3092 | spawnObject.renderer.alpha = 1; |
| 3093 | this.spawnRangeHighlight = { object: spawnObject, tileX, tileY, range: spawnRadius }; |
| 3094 | } |
| 3095 | this.#relayoutSpawnRangeHighlight(); |
| 3096 | } |
| 3097 | |
| 3098 | clearSpawnRangeHighlight () |
| 3099 | { |
| 3100 | this.spawnRangeHighlight?.object?.destroy(); |
| 3101 | this.wanderRangeHighlight?.object?.destroy(); |
| 3102 | this.spawnRangeHighlight = null; |
| 3103 | this.wanderRangeHighlight = null; |
| 3104 | } |
| 3105 | |
| 3106 | setSpellTargetHighlight (tileX, tileY, inRange = true) |
| 3107 | { |
| 3108 | if ( |
| 3109 | this.spellTargetHighlight |
| 3110 | && this.spellTargetHighlight.mode === "tile" |
| 3111 | && this.spellTargetHighlight.tileX === tileX |
| 3112 | && this.spellTargetHighlight.tileY === tileY |
| 3113 | && this.spellTargetHighlight.inRange === inRange |
| 3114 | ) |
| 3115 | { |
| 3116 | this.#relayoutSpellTargetHighlight(); |
| 3117 | return; |
| 3118 | } |
| 3119 | this.clearSpellTargetHighlight(); |
| 3120 | const spriteName = inRange ? "spell-target-tile" : "spell-target-invalid"; |
| 3121 | const object = this.#ensureSprite(null, spriteName, LAYER_EDGE - 1); |
| 3122 | if (!object) |
| 3123 | { return; } |
| 3124 | this.#markUnlit(object); |
| 3125 | object.renderer.alpha = 1; |
| 3126 | this.spellTargetHighlight = { |
| 3127 | mode: "tile", |
| 3128 | object, |
| 3129 | tileX, |
| 3130 | tileY, |
| 3131 | entityId: null, |
| 3132 | inRange, |
| 3133 | spriteName |
| 3134 | }; |
| 3135 | this.#relayoutSpellTargetHighlight(); |
| 3136 | } |
| 3137 | |
| 3138 | /** Outline box around a living entity (mob / player) for entity-target spells. */ |
| 3139 | setSpellEntityTargetHighlight (entityId, inRange = true) |
| 3140 | { |
| 3141 | const id = entityId | 0; |
| 3142 | if ( |
| 3143 | this.spellTargetHighlight |
| 3144 | && this.spellTargetHighlight.mode === "entity" |
| 3145 | && this.spellTargetHighlight.entityId === id |
| 3146 | && this.spellTargetHighlight.inRange === inRange |
| 3147 | ) |
| 3148 | { |
| 3149 | this.#relayoutSpellTargetHighlight(); |
| 3150 | return; |
| 3151 | } |
| 3152 | this.clearSpellTargetHighlight(); |
| 3153 | if (!this.entities.has(id)) |
| 3154 | { return; } |
| 3155 | const spriteName = inRange ? "spell-target-entity" : "spell-target-entity-invalid"; |
| 3156 | const object = this.#ensureSprite(null, spriteName, LAYER_EDGE - 1); |
| 3157 | if (!object) |
| 3158 | { return; } |
| 3159 | this.#markUnlit(object); |
| 3160 | object.renderer.alpha = 1; |
| 3161 | this.spellTargetHighlight = { |
| 3162 | mode: "entity", |
| 3163 | object, |
| 3164 | tileX: 0, |
| 3165 | tileY: 0, |
| 3166 | entityId: id, |
| 3167 | inRange, |
| 3168 | spriteName |
| 3169 | }; |
| 3170 | this.#relayoutSpellTargetHighlight(); |
| 3171 | } |
| 3172 | |
| 3173 | clearSpellTargetHighlight () |
| 3174 | { |
| 3175 | this.spellTargetHighlight?.object?.destroy(); |
| 3176 | this.spellTargetHighlight = null; |
| 3177 | } |
| 3178 | |
| 3179 | #relayoutSpellTargetHighlight () |
| 3180 | { |
| 3181 | const highlight = this.spellTargetHighlight; |
| 3182 | if (!highlight?.object) |
| 3183 | { return; } |
| 3184 | if (highlight.mode === "entity") |
| 3185 | { |
| 3186 | const entity = this.entities.get(highlight.entityId); |
| 3187 | if (!entity?.object) |
| 3188 | { |
| 3189 | this.clearSpellTargetHighlight(); |
| 3190 | return; |
| 3191 | } |
| 3192 | const pad = this.tileSize() * 0.12; |
| 3193 | const src = entity.object.transform; |
| 3194 | highlight.object.transform.position.x = src.position.x; |
| 3195 | highlight.object.transform.position.y = src.position.y; |
| 3196 | highlight.object.transform.size = new vector(src.size.x + pad, src.size.y + pad); |
| 3197 | this.#setLayer(highlight.object, LAYER_EDGE - 1); |
| 3198 | highlight.tileX = entity.tileX; |
| 3199 | highlight.tileY = entity.tileY; |
| 3200 | return; |
| 3201 | } |
| 3202 | const size = this.tileSize(); |
| 3203 | const left = highlight.tileX * size; |
| 3204 | const top = highlight.tileY * size; |
| 3205 | highlight.object.transform.position.x = left + size / 2; |
| 3206 | highlight.object.transform.position.y = top + size / 2; |
| 3207 | highlight.object.transform.size = new vector(size, size); |
| 3208 | this.#setLayer(highlight.object, LAYER_EDGE - 1); |
| 3209 | } |
| 3210 | |
| 3211 | #relayoutSpawnRangeHighlight () |
| 3212 | { |
| 3213 | this.#layoutRangeOverlay(this.wanderRangeHighlight, LAYER_EDGE - 2); |
| 3214 | this.#layoutRangeOverlay(this.spawnRangeHighlight, LAYER_EDGE - 1); |
| 3215 | } |
| 3216 | |
| 3217 | #layoutRangeOverlay (highlight, layer) |
| 3218 | { |
| 3219 | if (!highlight?.object) |
| 3220 | { return; } |
| 3221 | const size = this.tileSize(); |
| 3222 | const side = (2 * highlight.range + 1) * size; |
| 3223 | const left = (highlight.tileX - highlight.range) * size; |
| 3224 | const top = (highlight.tileY - highlight.range) * size; |
| 3225 | highlight.object.transform.position.x = left + side / 2; |
| 3226 | highlight.object.transform.position.y = top + side / 2; |
| 3227 | highlight.object.transform.size = new vector(side, side); |
| 3228 | this.#setLayer(highlight.object, layer); |
| 3229 | } |
| 3230 | |
| 3231 | setTilePreview (tileX, tileY, override) |
| 3232 | { |
| 3233 | const next = { tileX, tileY, ...override }; |
| 3234 | if (this.#previewEqual(this.preview, next)) |
| 3235 | { return; } |
| 3236 | const previous = this.preview; |
| 3237 | this.preview = next; |
| 3238 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 3239 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 3240 | this.#scheduleChunkRebuild(this.chunks.get(`${chunkX},${chunkY}`)); |
| 3241 | if (previous && (previous.tileX !== tileX || previous.tileY !== tileY)) |
| 3242 | { |
| 3243 | const prevKey = `${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`; |
| 3244 | if (prevKey !== `${chunkX},${chunkY}`) |
| 3245 | { this.#scheduleChunkRebuild(this.chunks.get(prevKey)); } |
| 3246 | // Per-tile blocks (doors, campfires, …) are not in the atlas — refresh sprites. |
| 3247 | this.#drawTile(previous.tileX, previous.tileY); |
| 3248 | } |
| 3249 | this.#drawTile(tileX, tileY); |
| 3250 | } |
| 3251 | |
| 3252 | clearTilePreview () |
| 3253 | { |
| 3254 | if (!this.preview) |
| 3255 | { return; } |
| 3256 | const previous = this.preview; |
| 3257 | this.preview = null; |
| 3258 | const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`); |
| 3259 | this.#scheduleChunkRebuild(snapshot); |
| 3260 | this.#drawTile(previous.tileX, previous.tileY); |
| 3261 | } |
| 3262 | |
| 3263 | #lerpMs (gait) |
| 3264 | { |
| 3265 | const walk = this.settings.walkTilesPerSecond || 2; |
| 3266 | const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk; |
| 3267 | return seconds * 1000; |
| 3268 | } |
| 3269 | |
| 3270 | #centerCamera () |
| 3271 | { |
| 3272 | if (!this.followPlayer) |
| 3273 | { return; } |
| 3274 | const local = this.entities.get(this.localEntityId); |
| 3275 | if (!local) |
| 3276 | { return; } |
| 3277 | const x = local.visualX + (local.stackOffsetX ?? 0); |
| 3278 | const y = local.visualY + (local.stackOffsetY ?? 0); |
| 3279 | this.scene.cameraPosition.x = this.scene.real_size.x / 2 - x; |
| 3280 | this.scene.cameraPosition.y = this.scene.real_size.y / 2 - y; |
| 3281 | } |
| 3282 | |
| 3283 | /** |
| 3284 | * World Y the depth sort is measured against, so layers stay bounded |
| 3285 | * (absolute tileY×zoom otherwise overflows past LAYER_EDGE). |
| 3286 | * |
| 3287 | * Quantised to the chunk row under the viewport centre: every sprite's layer |
| 3288 | * is relative to this, so an origin that moved with the camera would mean |
| 3289 | * re-layering the whole world every frame. Chunks only span the static 5×5 |
| 3290 | * ring, so relative sortY stays far inside LAYER_EDGE. |
| 3291 | * |
| 3292 | * @returns {boolean} whether the origin moved, i.e. callers must re-layer. |
| 3293 | */ |
| 3294 | #syncYSortOrigin () |
| 3295 | { |
| 3296 | const camY = this.scene.cameraPosition.y; |
| 3297 | const screenH = this.scene.real_size.y; |
| 3298 | const chunkPx = CHUNK_SIZE * this.tileSize(); |
| 3299 | const origin = Math.floor((-camY + screenH / 2) / chunkPx) * chunkPx; |
| 3300 | if (origin === this.ySortOrigin) |
| 3301 | { return false; } |
| 3302 | this.ySortOrigin = origin; |
| 3303 | return true; |
| 3304 | } |
| 3305 | |
| 3306 | /** Viewport-relative y-sort layer for world sprites. */ |
| 3307 | #depthLayer (sortY, subOrder, flight = false) |
| 3308 | { |
| 3309 | const relative = sortY - (this.ySortOrigin ?? 0); |
| 3310 | return flight ? flightSortLayer(relative, subOrder) : ySortLayer(relative, subOrder); |
| 3311 | } |
| 3312 | |
| 3313 | /** |
| 3314 | * Re-apply depth for every world sprite that is not repositioned each frame. |
| 3315 | * Their layer is relative to the y-sort origin, so a layer assigned once at |
| 3316 | * draw time goes stale as soon as that origin moves. |
| 3317 | * |
| 3318 | * Only run when {@link #syncYSortOrigin} reports a move (or after a zoom / |
| 3319 | * layout change) — entities carry their own per-frame layer via #placeEntity. |
| 3320 | */ |
| 3321 | #refreshDepthLayers () |
| 3322 | { |
| 3323 | const size = this.tileSize(); |
| 3324 | for (const baked of this.bakedChunks.values()) |
| 3325 | { |
| 3326 | const top = baked.chunkY * CHUNK_SIZE * size; |
| 3327 | const chunkPx = CHUNK_SIZE * size; |
| 3328 | for (let row = 0; row < CHUNK_SIZE; row++) |
| 3329 | { |
| 3330 | const rowY = top + row * size + size / 2; |
| 3331 | this.#setLayer(baked.blockObjects?.[row], this.#depthLayer(rowY, SORT_BLOCK)); |
| 3332 | } |
| 3333 | this.#setLayer(baked.bloomObject, this.#depthLayer(top + chunkPx, SORT_BLOCK)); |
| 3334 | this.#layoutFluidAtlasObject(baked, "ground"); |
| 3335 | this.#layoutFluidAtlasObject(baked, "bloom"); |
| 3336 | } |
| 3337 | // Unbaked tile sprites: tall blocks, doors and animated grounds. |
| 3338 | for (const objects of this.tiles.values()) |
| 3339 | { |
| 3340 | if (!objects.block && !objects.blockBloom && !objects.groundBloom) |
| 3341 | { continue; } |
| 3342 | const pivotY = objects.tileY * size + size / 2; |
| 3343 | this.#setLayer(objects.block, this.#depthLayer(pivotY, objects.blockSort ?? SORT_ENTITY)); |
| 3344 | this.#setLayer(objects.blockBloom, this.#depthLayer(pivotY, SORT_ENTITY)); |
| 3345 | this.#setLayer(objects.groundBloom, this.#depthLayer(pivotY, LAYER_GROUND)); |
| 3346 | } |
| 3347 | for (const item of this.groundItems.values()) |
| 3348 | { |
| 3349 | this.#setLayer( |
| 3350 | item.object, |
| 3351 | this.#depthLayer(item.tileY * size + size / 2 - 0.01, SORT_BLOCK) |
| 3352 | ); |
| 3353 | } |
| 3354 | for (const entry of this.itemContainers.values()) |
| 3355 | { |
| 3356 | this.#setLayer( |
| 3357 | entry.object, |
| 3358 | this.#depthLayer(entry.tileY * size + size / 2 - 0.02, SORT_BLOCK) |
| 3359 | ); |
| 3360 | } |
| 3361 | // Lerping FX are re-placed in #updateSwipes; static ones need the refresh. |
| 3362 | for (const swipe of this.swipes) |
| 3363 | { |
| 3364 | if (swipe.lerp || swipe.sortY == null) |
| 3365 | { continue; } |
| 3366 | this.#setLayer(swipe.object, this.#depthLayer(swipe.sortY, SORT_FX)); |
| 3367 | } |
| 3368 | for (const entry of this.editorSpawners.values()) |
| 3369 | { |
| 3370 | const pivotY = entry.tileY * size + size / 2; |
| 3371 | this.#setLayer(entry.object, this.#depthLayer(pivotY + 0.05, SORT_ENTITY)); |
| 3372 | const overlays = entry.overlays ?? []; |
| 3373 | for (let i = 0; i < overlays.length; i++) |
| 3374 | { |
| 3375 | this.#setLayer( |
| 3376 | overlays[i], |
| 3377 | this.#depthLayer(pivotY + 0.05 + 0.001 * (i + 1), SORT_ENTITY) |
| 3378 | ); |
| 3379 | } |
| 3380 | } |
| 3381 | } |
| 3382 | |
| 3383 | /** |
| 3384 | * World-pixel AABB of the screen, expanded for tall block sprites (zoom-aware). |
| 3385 | * Tiles fully outside this rect are not drawn. |
| 3386 | */ |
| 3387 | #drawBounds () |
| 3388 | { |
| 3389 | const pad = this.tileSize() * 2; |
| 3390 | const camX = this.scene.cameraPosition.x; |
| 3391 | const camY = this.scene.cameraPosition.y; |
| 3392 | const w = this.scene.real_size.x; |
| 3393 | const h = this.scene.real_size.y; |
| 3394 | return { |
| 3395 | left: -camX - pad, |
| 3396 | right: -camX + w + pad, |
| 3397 | top: -camY - pad, |
| 3398 | bottom: -camY + h + pad |
| 3399 | }; |
| 3400 | } |
| 3401 | |
| 3402 | #rectIntersects (left, top, right, bottom, bounds) |
| 3403 | { |
| 3404 | return right >= bounds.left |
| 3405 | && left <= bounds.right |
| 3406 | && bottom >= bounds.top |
| 3407 | && top <= bounds.bottom; |
| 3408 | } |
| 3409 | |
| 3410 | #setRendererVisible (object, visible) |
| 3411 | { |
| 3412 | if (object?.renderer) |
| 3413 | { object.renderer.visible = !!visible; } |
| 3414 | } |
| 3415 | |
| 3416 | /** Skip drawing (and lighting work) for tiles/chunks more than ½ tile off-screen. */ |
| 3417 | #cullOffscreenDrawables () |
| 3418 | { |
| 3419 | const bounds = this.#drawBounds(); |
| 3420 | const size = this.tileSize(); |
| 3421 | |
| 3422 | for (const baked of this.bakedChunks.values()) |
| 3423 | { |
| 3424 | const left = baked.chunkX * CHUNK_SIZE * size; |
| 3425 | const top = baked.chunkY * CHUNK_SIZE * size; |
| 3426 | const chunkPx = CHUNK_SIZE * size; |
| 3427 | const chunkVisible = this.#rectIntersects(left, top, left + chunkPx, top + chunkPx, bounds); |
| 3428 | this.#setRendererVisible(baked.groundObject, chunkVisible); |
| 3429 | this.#setRendererVisible(baked.bloomObject, chunkVisible && this.bloomEnabled); |
| 3430 | // Fluid atlas objects are shown/hidden in #syncFluidAtlases; keep offscreen ones off. |
| 3431 | if (!chunkVisible) |
| 3432 | { |
| 3433 | this.#setRendererVisible(baked.fluidGroundObject, false); |
| 3434 | this.#setRendererVisible(baked.fluidBloomObject, false); |
| 3435 | } |
| 3436 | baked._inViewport = chunkVisible; |
| 3437 | for (let row = 0; row < CHUNK_SIZE; row++) |
| 3438 | { |
| 3439 | const rowTop = top + row * size; |
| 3440 | const rowVisible = chunkVisible && this.#rectIntersects( |
| 3441 | left, rowTop, left + chunkPx, rowTop + size, bounds |
| 3442 | ); |
| 3443 | this.#setRendererVisible(baked.blockObjects?.[row], rowVisible); |
| 3444 | } |
| 3445 | } |
| 3446 | |
| 3447 | for (const objects of this.tiles.values()) |
| 3448 | { |
| 3449 | const left = objects.tileX * size; |
| 3450 | const top = objects.tileY * size; |
| 3451 | const visible = this.#rectIntersects(left, top, left + size, top + size, bounds); |
| 3452 | objects._inViewport = visible; |
| 3453 | const fluidAtlas = this.#useFluidAtlas && this.#tileUsesFluidAtlas(objects); |
| 3454 | this.#setRendererVisible(objects.ground, visible && !fluidAtlas); |
| 3455 | this.#setRendererVisible(objects.groundBloom, visible && this.bloomEnabled); |
| 3456 | this.#setRendererVisible(objects.block, visible); |
| 3457 | this.#setRendererVisible(objects.blockBloom, visible && this.bloomEnabled); |
| 3458 | this.#setRendererVisible(objects.lavaBloom, visible && this.bloomEnabled && !fluidAtlas); |
| 3459 | } |
| 3460 | } |
| 3461 | |
| 3462 | #upsertEntity (payload) |
| 3463 | { |
| 3464 | const size = this.tileSize(); |
| 3465 | const pivot = tilePivot(payload.tileX, payload.tileY, size); |
| 3466 | let entity = this.entities.get(payload.entityId); |
| 3467 | if (entity?.dying) |
| 3468 | { |
| 3469 | if (entity.entityId === this.localEntityId) |
| 3470 | { this.#abortEntityFade(entity); } |
| 3471 | else |
| 3472 | { |
| 3473 | this.#finishEntityFade(payload.entityId); |
| 3474 | entity = null; |
| 3475 | } |
| 3476 | } |
| 3477 | if (!entity) |
| 3478 | { |
| 3479 | const spriteName = payload.layers?.[0]?.sprite |
| 3480 | ?? payload.sprite |
| 3481 | ?? bodySpriteName(payload.sex); |
| 3482 | const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY); |
| 3483 | this.scene.addObject(object); |
| 3484 | this.#startIdleAnimation(object); |
| 3485 | entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y }; |
| 3486 | this.entities.set(payload.entityId, entity); |
| 3487 | } |
| 3488 | entity.entityId = payload.entityId; |
| 3489 | entity.tileX = payload.tileX; |
| 3490 | entity.tileY = payload.tileY; |
| 3491 | entity.gait = payload.gait; |
| 3492 | entity.sex = payload.sex ?? entity.sex; |
| 3493 | entity.characterId = payload.characterId ?? entity.characterId ?? null; |
| 3494 | entity.accountId = payload.accountId ?? entity.accountId ?? null; |
| 3495 | entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null; |
| 3496 | if (payload.level != null) |
| 3497 | { entity.level = payload.level | 0; } |
| 3498 | entity.hostile = payload.hostile != null ? !!payload.hostile : !!entity.hostile; |
| 3499 | entity.aggressive = payload.aggressive != null |
| 3500 | ? !!payload.aggressive |
| 3501 | : (payload.hostile != null ? !!payload.hostile : !!entity.aggressive); |
| 3502 | entity.canFight = payload.canFight != null |
| 3503 | ? !!payload.canFight |
| 3504 | : !!(entity.canFight || (payload.mobTypeId && !payload.talkable)); |
| 3505 | entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable; |
| 3506 | entity.hasDialogue = payload.hasDialogue != null ? !!payload.hasDialogue : !!entity.hasDialogue; |
| 3507 | entity.hasShop = payload.hasShop != null ? !!payload.hasShop : !!entity.hasShop; |
| 3508 | entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable; |
| 3509 | entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight; |
| 3510 | entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0; |
| 3511 | if (payload.lightIntensity != null) |
| 3512 | { entity.lightIntensity = Number(payload.lightIntensity) || 1; } |
| 3513 | else if (entity.lightIntensity == null) |
| 3514 | { entity.lightIntensity = 1; } |
| 3515 | if (payload.visualScale != null) |
| 3516 | { entity.visualScale = Number(payload.visualScale) || 1; } |
| 3517 | else if (entity.visualScale == null) |
| 3518 | { entity.visualScale = 1; } |
| 3519 | if (payload.health != null) |
| 3520 | { entity.health = payload.health; } |
| 3521 | if (payload.maxHealth != null) |
| 3522 | { entity.maxHealth = payload.maxHealth; } |
| 3523 | if (payload.skullValue != null) |
| 3524 | { entity.skullValue = Math.max(0, payload.skullValue | 0); } |
| 3525 | else if (entity.skullValue == null) |
| 3526 | { entity.skullValue = 0; } |
| 3527 | if (payload.firstName) |
| 3528 | { entity.firstName = payload.firstName; } |
| 3529 | if (payload.lastName) |
| 3530 | { entity.lastName = payload.lastName; } |
| 3531 | entity.firstName = entity.firstName ?? ""; |
| 3532 | entity.lastName = entity.lastName ?? ""; |
| 3533 | if (payload.worldX != null && payload.worldY != null) |
| 3534 | { |
| 3535 | entity.worldX = payload.worldX; |
| 3536 | entity.worldY = payload.worldY; |
| 3537 | entity.visualX = payload.worldX * size; |
| 3538 | entity.visualY = payload.worldY * size; |
| 3539 | entity.targetX = entity.visualX; |
| 3540 | entity.targetY = entity.visualY; |
| 3541 | } |
| 3542 | else |
| 3543 | { |
| 3544 | entity.visualX = pivot.x; |
| 3545 | entity.visualY = pivot.y; |
| 3546 | entity.targetX = pivot.x; |
| 3547 | entity.targetY = pivot.y; |
| 3548 | } |
| 3549 | entity.fromX = entity.visualX; |
| 3550 | entity.fromY = entity.visualY; |
| 3551 | if (payload.layers) |
| 3552 | { this.#applyLayers(entity, payload.layers); } |
| 3553 | this.#syncHpBar(entity); |
| 3554 | this.#syncSkullMarker(entity); |
| 3555 | this.#placeEntity(entity, performance.now()); |
| 3556 | } |
| 3557 | |
| 3558 | #applyLayers (entity, layers) |
| 3559 | { |
| 3560 | entity.appearanceLayers = layers ?? [{ sprite: bodySpriteName(entity.sex) }]; |
| 3561 | this.#rebuildOverlays(entity); |
| 3562 | } |
| 3563 | |
| 3564 | #setGatherToolOverlay (entity, toolItemId) |
| 3565 | { |
| 3566 | entity.gatherToolItemId = toolItemId; |
| 3567 | entity.gatherToolUntil = performance.now() + GATHER_TOOL_HOLD_MS; |
| 3568 | this.#rebuildOverlays(entity); |
| 3569 | this.#placeEntity(entity, performance.now()); |
| 3570 | } |
| 3571 | |
| 3572 | #expireGatherToolOverlay (entity, now) |
| 3573 | { |
| 3574 | if (entity.gatherToolItemId == null) |
| 3575 | { return; } |
| 3576 | if ((entity.gatherToolUntil ?? 0) > now) |
| 3577 | { return; } |
| 3578 | entity.gatherToolItemId = null; |
| 3579 | entity.gatherToolUntil = 0; |
| 3580 | this.#rebuildOverlays(entity); |
| 3581 | } |
| 3582 | |
| 3583 | /** Prefer the active gather tool's equip sprite over the worn weapon (all gather kinds). */ |
| 3584 | #layersForDisplay (entity) |
| 3585 | { |
| 3586 | const layers = (entity.appearanceLayers ?? []).map((layer) => ({ ...layer })); |
| 3587 | const toolId = entity.gatherToolItemId; |
| 3588 | if (toolId == null || (entity.gatherToolUntil ?? 0) <= performance.now()) |
| 3589 | { return layers; } |
| 3590 | const equip = itemEquipSprite(toolId); |
| 3591 | if (!equip || !this.game.images[equip]) |
| 3592 | { return layers; } |
| 3593 | const replacement = { |
| 3594 | sprite: equip, |
| 3595 | itemId: toolId, |
| 3596 | tint: resolveEquipTint(toolId) |
| 3597 | }; |
| 3598 | for (let index = layers.length - 1; index >= 1; index--) |
| 3599 | { |
| 3600 | const def = itemDefinition(layers[index].itemId); |
| 3601 | if (def?.equipment?.slot === EQUIPMENT_SLOT.weapon) |
| 3602 | { |
| 3603 | layers[index] = replacement; |
| 3604 | return layers; |
| 3605 | } |
| 3606 | } |
| 3607 | layers.push(replacement); |
| 3608 | return layers; |
| 3609 | } |
| 3610 | |
| 3611 | #rebuildOverlays (entity) |
| 3612 | { |
| 3613 | const layers = this.#layersForDisplay(entity); |
| 3614 | const base = layers[0]?.sprite |
| 3615 | ?? bodySpriteName(entity.sex); |
| 3616 | if (this.game.images[base]) |
| 3617 | { |
| 3618 | entity.object.renderer.sprite = this.game.images[base]; |
| 3619 | this.#startIdleAnimation(entity.object); |
| 3620 | } |
| 3621 | entity.bodyTint = layers[0]?.tint ? normalizeRgb(layers[0].tint) : null; |
| 3622 | entity.bodyDualTint = layers[0]?.dualTint |
| 3623 | ? { |
| 3624 | shaft: normalizeRgb(layers[0].dualTint.shaft), |
| 3625 | tip: normalizeRgb(layers[0].dualTint.tip), |
| 3626 | ...(layers[0].dualTint.coat |
| 3627 | ? { coat: normalizeRgb(layers[0].dualTint.coat) } |
| 3628 | : {}) |
| 3629 | } |
| 3630 | : null; |
| 3631 | entity.bloomBody = !!layers[0]?.bloomBody; |
| 3632 | for (const overlay of entity.overlays ?? []) |
| 3633 | { overlay.destroy(); } |
| 3634 | for (const overlay of entity.bloomOverlays ?? []) |
| 3635 | { overlay.destroy(); } |
| 3636 | entity.overlays = []; |
| 3637 | entity.overlayTints = []; |
| 3638 | entity.overlayDualTints = []; |
| 3639 | entity.overlayTightFit = []; |
| 3640 | entity.bloomOverlays = []; |
| 3641 | entity.bloomOverlayTints = []; |
| 3642 | entity.bloomOverlayDualTints = []; |
| 3643 | if (entity.bloomBody && this.game.images[base]) |
| 3644 | { |
| 3645 | const bloomName = bloomCompanionName(base); |
| 3646 | const bloomImage = this.game.images[bloomName] ?? this.game.images[base]; |
| 3647 | if (bloomImage) |
| 3648 | { |
| 3649 | const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY); |
| 3650 | bloom.renderer.layer = RENDER_LAYER_BLOOM; |
| 3651 | this.#markUnlit(bloom); |
| 3652 | this.#startIdleAnimation(bloom); |
| 3653 | this.scene.addObject(bloom); |
| 3654 | entity.bloomOverlays.push(bloom); |
| 3655 | entity.bloomOverlayTints.push(entity.bodyTint); |
| 3656 | entity.bloomOverlayDualTints.push(entity.bodyDualTint); |
| 3657 | } |
| 3658 | } |
| 3659 | for (const layer of layers.slice(1)) |
| 3660 | { |
| 3661 | const image = this.game.images[layer.sprite]; |
| 3662 | if (!image) |
| 3663 | { continue; } |
| 3664 | const object = new GameObject(0, 0, image, SORT_ENTITY); |
| 3665 | this.scene.addObject(object); |
| 3666 | entity.overlays.push(object); |
| 3667 | const layerDef = layer.itemId != null ? itemDefinition(layer.itemId) : null; |
| 3668 | entity.overlayTightFit.push(!!layerDef?.tightFit); |
| 3669 | const dualTint = layer.dualTint |
| 3670 | ? { |
| 3671 | shaft: normalizeRgb(layer.dualTint.shaft), |
| 3672 | tip: normalizeRgb(layer.dualTint.tip), |
| 3673 | ...(layer.dualTint.coat |
| 3674 | ? { coat: normalizeRgb(layer.dualTint.coat) } |
| 3675 | : {}) |
| 3676 | } |
| 3677 | : (layer.itemId != null |
| 3678 | ? resolveEquipDualTint({ itemId: layer.itemId }, layerDef) |
| 3679 | : null); |
| 3680 | entity.overlayDualTints.push(dualTint); |
| 3681 | entity.overlayTints.push( |
| 3682 | dualTint |
| 3683 | ? null |
| 3684 | : (layer.tint |
| 3685 | ? normalizeRgb(layer.tint) |
| 3686 | : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null)) |
| 3687 | ); |
| 3688 | const bloomName = bloomCompanionName(layer.sprite); |
| 3689 | const bloomImage = this.game.images[bloomName]; |
| 3690 | if (!bloomImage) |
| 3691 | { continue; } |
| 3692 | const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY); |
| 3693 | bloom.renderer.layer = RENDER_LAYER_BLOOM; |
| 3694 | this.#markUnlit(bloom); |
| 3695 | this.scene.addObject(bloom); |
| 3696 | entity.bloomOverlays.push(bloom); |
| 3697 | entity.bloomOverlayTints.push( |
| 3698 | layer.tint ? normalizeRgb(layer.tint) : null |
| 3699 | ); |
| 3700 | } |
| 3701 | } |
| 3702 | |
| 3703 | #placeEntity (entity, now = performance.now()) |
| 3704 | { |
| 3705 | const zoom = this.zoom; |
| 3706 | const offsetX = entity.shoveOffsetX ?? 0; |
| 3707 | const offsetY = entity.shoveOffsetY ?? 0; |
| 3708 | const pivotX = entity.visualX + offsetX + (entity.stackOffsetX ?? 0); |
| 3709 | const pivotY = entity.visualY + offsetY + (entity.stackOffsetY ?? 0); |
| 3710 | let walkTilt = 0; |
| 3711 | if (entity.lerpStarted != null) |
| 3712 | { |
| 3713 | const stepMs = Math.max(1, entity.lerpMs ?? this.#lerpMs(entity.gait)); |
| 3714 | const cycles = ((now - entity.lerpStarted) / stepMs) * Math.PI * 2; |
| 3715 | const tilt = entity.gait === GAIT.run ? RUN_TILT_DEG : WALK_TILT_DEG; |
| 3716 | walkTilt = Math.sin(cycles) * tilt; |
| 3717 | } |
| 3718 | let flashStrength = (entity.damageFlashUntil ?? 0) > now |
| 3719 | ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS |
| 3720 | : 0; |
| 3721 | let deathAlpha = 1; |
| 3722 | if (entity.dying) |
| 3723 | { |
| 3724 | const fadeMs = Math.max(1, entity.deathFadeMs ?? DEATH_FADE_MS); |
| 3725 | const fadeT = (now - (entity.deathFadeStarted ?? now)) / fadeMs; |
| 3726 | if (fadeT >= 1 && entity.entityId !== this.localEntityId) |
| 3727 | { |
| 3728 | this.#finishEntityFade(entity.entityId); |
| 3729 | return; |
| 3730 | } |
| 3731 | deathAlpha = Math.max(0, 1 - fadeT); |
| 3732 | // Red silhouette only for combat death; plain despawn keeps lit colours + darkness. |
| 3733 | if (entity.deathDissolve) |
| 3734 | { flashStrength = 1; } |
| 3735 | } |
| 3736 | const flashColor = entity.damageFlashColor ?? FLASH_COLOR_DAMAGE; |
| 3737 | const tileShade = this.#entityShadeAlpha(entity, now); |
| 3738 | const wade = isWadeGroundInSeason(this.#groundTypeAt(entity.tileX, entity.tileY), this.worldSeason); |
| 3739 | |
| 3740 | entity.object.transform.rotation = walkTilt; |
| 3741 | if (entity.object.renderer) |
| 3742 | { entity.object.renderer.alpha = deathAlpha; } |
| 3743 | if (entity.bodyDualTint) |
| 3744 | { |
| 3745 | this.#syncDualTintLitSprite( |
| 3746 | entity.object, |
| 3747 | tileShade, |
| 3748 | entity.bodyDualTint, |
| 3749 | flashStrength, |
| 3750 | wade, |
| 3751 | flashColor |
| 3752 | ); |
| 3753 | } |
| 3754 | else |
| 3755 | { |
| 3756 | this.#syncLitSprite(entity.object, tileShade, flashStrength, wade, entity.bodyTint ?? null, flashColor); |
| 3757 | } |
| 3758 | const flight = !!entity.freeFlight; |
| 3759 | this.#placePivoted(entity.object, pivotX, pivotY, pivotY, SORT_ENTITY, entity.visualScale ?? 1, flight); |
| 3760 | for (let index = 0; index < (entity.overlays ?? []).length; index++) |
| 3761 | { |
| 3762 | const overlay = entity.overlays[index]; |
| 3763 | const overlaySort = Math.min(SORT_HP_BAR - 2, SORT_ENTITY + 1 + index); |
| 3764 | overlay.transform.rotation = walkTilt; |
| 3765 | if (overlay.renderer) |
| 3766 | { overlay.renderer.alpha = deathAlpha; } |
| 3767 | const dualTint = entity.overlayDualTints?.[index] ?? null; |
| 3768 | if (dualTint) |
| 3769 | { |
| 3770 | this.#syncDualTintLitSprite(overlay, tileShade, dualTint, flashStrength, wade, flashColor); |
| 3771 | } |
| 3772 | else if (entity.overlayTightFit?.[index]) |
| 3773 | { |
| 3774 | this.#syncTightFitLitSprite( |
| 3775 | overlay, |
| 3776 | entity, |
| 3777 | tileShade, |
| 3778 | flashStrength, |
| 3779 | wade, |
| 3780 | entity.overlayTints?.[index] ?? null, |
| 3781 | flashColor |
| 3782 | ); |
| 3783 | } |
| 3784 | else |
| 3785 | { |
| 3786 | this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null, flashColor); |
| 3787 | } |
| 3788 | this.#placePivoted(overlay, pivotX, pivotY, pivotY, overlaySort, entity.visualScale ?? 1, flight); |
| 3789 | } |
| 3790 | for (let index = 0; index < (entity.bloomOverlays ?? []).length; index++) |
| 3791 | { |
| 3792 | const overlay = entity.bloomOverlays[index]; |
| 3793 | this.#setRendererVisible(overlay, this.bloomEnabled && deathAlpha > 0.02); |
| 3794 | if (!this.bloomEnabled) |
| 3795 | { continue; } |
| 3796 | /** Multi-frame body bloom locks to the base sprite; static bodies leave bloom free to animate. */ |
| 3797 | if (entity.bloomBody && index === 0 && entity.object?.renderer) |
| 3798 | { |
| 3799 | const bodySprite = entity.object.renderer.sprite; |
| 3800 | const bloomSprite = overlay.renderer.sprite; |
| 3801 | const bodyFrames = Number(bodySprite?.subImages) || Number(bodySprite?.subImgTotal) || 1; |
| 3802 | const bloomFrames = Number(bloomSprite?.subImages) || Number(bloomSprite?.subImgTotal) || 1; |
| 3803 | if (bodyFrames > 1 && bloomFrames === bodyFrames) |
| 3804 | { |
| 3805 | overlay.renderer.cycle = null; |
| 3806 | overlay.renderer.subImage = entity.object.renderer.subImage | 0; |
| 3807 | } |
| 3808 | } |
| 3809 | overlay.transform.rotation = walkTilt; |
| 3810 | if (overlay.renderer) |
| 3811 | { overlay.renderer.alpha = deathAlpha; } |
| 3812 | const bloomDual = entity.bloomOverlayDualTints?.[index] ?? null; |
| 3813 | const bloomTint = entity.bloomOverlayTints?.[index] ?? entity.bodyTint ?? null; |
| 3814 | if (bloomDual) |
| 3815 | { this.#syncDualTintLitSprite(overlay, 0, bloomDual); } |
| 3816 | else if (bloomTint) |
| 3817 | { this.#syncUnlitTintSprite(overlay, bloomTint); } |
| 3818 | else |
| 3819 | { this.#markUnlit(overlay); } |
| 3820 | this.#placePivoted(overlay, pivotX, pivotY, pivotY + 0.002, SORT_ENTITY, entity.visualScale ?? 1, flight); |
| 3821 | } |
| 3822 | if (!entity.dying) |
| 3823 | { |
| 3824 | this.#placeHpBar(entity, pivotX, pivotY); |
| 3825 | this.#placeSkullMarker(entity, pivotX, pivotY, tileShade); |
| 3826 | } |
| 3827 | } |
| 3828 | |
| 3829 | #markUnlit (object) |
| 3830 | { |
| 3831 | if (!object?.renderer) |
| 3832 | { return; } |
| 3833 | object._lit = false; |
| 3834 | object.renderer.shader = null; |
| 3835 | object.renderer.shaderUniforms = null; |
| 3836 | object.renderer._shaderUniformKind = null; |
| 3837 | object.renderer.secondaryMap = null; |
| 3838 | } |
| 3839 | |
| 3840 | #ensureUniformBag (renderer, shader, kind) |
| 3841 | { |
| 3842 | renderer.shader = shader; |
| 3843 | if (!renderer.shaderUniforms || renderer._shaderUniformKind !== kind) |
| 3844 | { |
| 3845 | renderer.shaderUniforms = {}; |
| 3846 | renderer._shaderUniformKind = kind; |
| 3847 | renderer._fluidStaticsReady = false; |
| 3848 | // Static water/lava tune uniforms — apply once per kind, not every frame. |
| 3849 | if (kind === "water") |
| 3850 | { Object.assign(renderer.shaderUniforms, waterDebugUniforms()); } |
| 3851 | else if (kind === "lava" || kind === "lavaBloom") |
| 3852 | { Object.assign(renderer.shaderUniforms, lavaDebugUniforms()); } |
| 3853 | } |
| 3854 | return renderer.shaderUniforms; |
| 3855 | } |
| 3856 | |
| 3857 | #writeUniformVec3 (uniforms, key, src) |
| 3858 | { |
| 3859 | let arr = uniforms[key]; |
| 3860 | if (!Array.isArray(arr) || arr.length !== 3) |
| 3861 | { |
| 3862 | arr = [0, 0, 0]; |
| 3863 | uniforms[key] = arr; |
| 3864 | } |
| 3865 | if (Array.isArray(src)) |
| 3866 | { |
| 3867 | arr[0] = src[0]; |
| 3868 | arr[1] = src[1]; |
| 3869 | arr[2] = src[2]; |
| 3870 | } |
| 3871 | else |
| 3872 | { |
| 3873 | arr[0] = src.r; |
| 3874 | arr[1] = src.g; |
| 3875 | arr[2] = src.b; |
| 3876 | } |
| 3877 | } |
| 3878 | |
| 3879 | #writeUniformVec2 (uniforms, key, a, b) |
| 3880 | { |
| 3881 | let arr = uniforms[key]; |
| 3882 | if (!Array.isArray(arr) || arr.length !== 2) |
| 3883 | { |
| 3884 | arr = [0, 0]; |
| 3885 | uniforms[key] = arr; |
| 3886 | } |
| 3887 | arr[0] = a; |
| 3888 | arr[1] = b; |
| 3889 | } |
| 3890 | |
| 3891 | #writeUniformVec4 (uniforms, key, a, b, c, d) |
| 3892 | { |
| 3893 | let arr = uniforms[key]; |
| 3894 | if (!Array.isArray(arr) || arr.length !== 4) |
| 3895 | { |
| 3896 | arr = [0, 0, 0, 0]; |
| 3897 | uniforms[key] = arr; |
| 3898 | } |
| 3899 | arr[0] = a; |
| 3900 | arr[1] = b; |
| 3901 | arr[2] = c; |
| 3902 | arr[3] = d; |
| 3903 | } |
| 3904 | |
| 3905 | /** Bloom / unlit overlays that still need magenta channel tint (e.g. elemental sprites). */ |
| 3906 | #syncUnlitTintSprite (object, tintColor) |
| 3907 | { |
| 3908 | if (!object?.renderer || !tintColor) |
| 3909 | { return; } |
| 3910 | const tint = normalizeRgb(tintColor); |
| 3911 | const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX; |
| 3912 | const uniforms = this.#ensureUniformBag(object.renderer, getTintLitSpriteShader(), "unlitTint"); |
| 3913 | uniforms.u_darkness = 0; |
| 3914 | uniforms.u_strength = 0; |
| 3915 | this.#writeUniformVec3(uniforms, "u_flashColor", FLASH_COLOR_DAMAGE); |
| 3916 | uniforms.u_wade = 0; |
| 3917 | uniforms.u_spriteHeight = height; |
| 3918 | uniforms.u_useTint = 1; |
| 3919 | this.#writeUniformVec3(uniforms, "u_tintColor", tint); |
| 3920 | object.renderer.secondaryMap = null; |
| 3921 | } |
| 3922 | |
| 3923 | #syncLitSprite (object, darkness, flashStrength = 0, wade = false, tintColor = null, flashColor = null) |
| 3924 | { |
| 3925 | if (!object?.renderer || object._lit === false) |
| 3926 | { return; } |
| 3927 | object._lit = true; |
| 3928 | const dark = Math.min(1, Math.max(0, darkness ?? 0)); |
| 3929 | const flash = Math.min(1, Math.max(0, flashStrength ?? 0)); |
| 3930 | const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX; |
| 3931 | const flashRgb = flashColor ?? FLASH_COLOR_DAMAGE; |
| 3932 | const tint = tintColor ? normalizeRgb(tintColor) : null; |
| 3933 | if (tint) |
| 3934 | { |
| 3935 | const uniforms = this.#ensureUniformBag(object.renderer, getTintLitSpriteShader(), "tintLit"); |
| 3936 | uniforms.u_darkness = dark; |
| 3937 | uniforms.u_strength = flash; |
| 3938 | this.#writeUniformVec3(uniforms, "u_flashColor", flashRgb); |
| 3939 | uniforms.u_wade = wade ? 1 : 0; |
| 3940 | uniforms.u_spriteHeight = height; |
| 3941 | uniforms.u_useTint = 1; |
| 3942 | this.#writeUniformVec3(uniforms, "u_tintColor", tint); |
| 3943 | } |
| 3944 | else |
| 3945 | { |
| 3946 | const uniforms = this.#ensureUniformBag(object.renderer, getSpriteLightingShader(), "lit"); |
| 3947 | uniforms.u_darkness = dark; |
| 3948 | uniforms.u_strength = flash; |
| 3949 | this.#writeUniformVec3(uniforms, "u_flashColor", flashRgb); |
| 3950 | uniforms.u_wade = wade ? 1 : 0; |
| 3951 | uniforms.u_spriteHeight = height; |
| 3952 | } |
| 3953 | object.renderer.secondaryMap = null; |
| 3954 | } |
| 3955 | |
| 3956 | #bodySecondaryMap (entity) |
| 3957 | { |
| 3958 | return entity?.object?.renderer?.sprite?.g_image ?? null; |
| 3959 | } |
| 3960 | |
| 3961 | #tightFitMaskUniforms (overlay, entity, into = null) |
| 3962 | { |
| 3963 | const bodyRenderer = entity?.object?.renderer; |
| 3964 | const clothRenderer = overlay?.renderer; |
| 3965 | const bodySprite = bodyRenderer?.sprite; |
| 3966 | const clothSprite = clothRenderer?.sprite; |
| 3967 | if (!bodySprite || !clothSprite) |
| 3968 | { return null; } |
| 3969 | const clothUv = clothSprite.getUvRect?.(clothRenderer.subImage | 0) |
| 3970 | ?? { u0: 0, v0: 0, u1: 1, v1: 1 }; |
| 3971 | const bodyUv = bodySprite.getUvRect?.(bodyRenderer.subImage | 0) |
| 3972 | ?? { u0: 0, v0: 0, u1: 1, v1: 1 }; |
| 3973 | const uniforms = into ?? {}; |
| 3974 | this.#writeUniformVec2(uniforms, "u_clothSize", clothSprite.width || SPRITE_SIZE_PX, clothSprite.height || SPRITE_SIZE_PX); |
| 3975 | this.#writeUniformVec2(uniforms, "u_bodySize", bodySprite.width || SPRITE_SIZE_PX, bodySprite.height || SPRITE_SIZE_PX); |
| 3976 | uniforms.u_pivotFromBottom = PIVOT_FROM_BOTTOM_PX; |
| 3977 | this.#writeUniformVec4(uniforms, "u_clothUvRect", clothUv.u0, clothUv.v0, clothUv.u1, clothUv.v1); |
| 3978 | this.#writeUniformVec4(uniforms, "u_bodyUvRect", bodyUv.u0, bodyUv.v0, bodyUv.u1, bodyUv.v1); |
| 3979 | return uniforms; |
| 3980 | } |
| 3981 | |
| 3982 | #syncTightFitLitSprite (overlay, entity, darkness, flashStrength = 0, wade = false, tintColor = null, flashColor = null) |
| 3983 | { |
| 3984 | if (!overlay?.renderer || entity?.object?.renderer == null) |
| 3985 | { return; } |
| 3986 | const bodyMap = this.#bodySecondaryMap(entity); |
| 3987 | const flashRgb = flashColor ?? FLASH_COLOR_DAMAGE; |
| 3988 | if (!bodyMap) |
| 3989 | { |
| 3990 | this.#syncLitSprite(overlay, darkness, flashStrength, wade, tintColor, flashRgb); |
| 3991 | return; |
| 3992 | } |
| 3993 | overlay._lit = true; |
| 3994 | const dark = Math.min(1, Math.max(0, darkness ?? 0)); |
| 3995 | const flash = Math.min(1, Math.max(0, flashStrength ?? 0)); |
| 3996 | const height = overlay.renderer.sprite?.height ?? SPRITE_SIZE_PX; |
| 3997 | const tint = tintColor ? normalizeRgb(tintColor) : null; |
| 3998 | overlay.renderer.secondaryMap = bodyMap; |
| 3999 | const kind = tint ? "tightFitTint" : "tightFit"; |
| 4000 | const shader = tint ? getTightFitTintLitSpriteShader() : getTightFitLitSpriteShader(); |
| 4001 | const uniforms = this.#ensureUniformBag(overlay.renderer, shader, kind); |
| 4002 | if (!this.#tightFitMaskUniforms(overlay, entity, uniforms)) |
| 4003 | { |
| 4004 | this.#syncLitSprite(overlay, darkness, flashStrength, wade, tintColor, flashRgb); |
| 4005 | return; |
| 4006 | } |
| 4007 | uniforms.u_darkness = dark; |
| 4008 | uniforms.u_strength = flash; |
| 4009 | this.#writeUniformVec3(uniforms, "u_flashColor", flashRgb); |
| 4010 | uniforms.u_wade = wade ? 1 : 0; |
| 4011 | uniforms.u_spriteHeight = height; |
| 4012 | if (tint) |
| 4013 | { |
| 4014 | uniforms.u_useTint = 1; |
| 4015 | this.#writeUniformVec3(uniforms, "u_tintColor", tint); |
| 4016 | } |
| 4017 | } |
| 4018 | |
| 4019 | #syncDualTintLitSprite (object, darkness, dualTint, flashStrength = 0, wade = false, flashColor = null) |
| 4020 | { |
| 4021 | if (!object?.renderer || !dualTint) |
| 4022 | { return; } |
| 4023 | const shaft = normalizeRgb(dualTint.shaft); |
| 4024 | const tip = normalizeRgb(dualTint.tip); |
| 4025 | const coat = dualTint.coat ? normalizeRgb(dualTint.coat) : null; |
| 4026 | const dark = object._lit === false |
| 4027 | ? 0 |
| 4028 | : Math.min(1, Math.max(0, darkness ?? 0)); |
| 4029 | if (object._lit !== false) |
| 4030 | { object._lit = true; } |
| 4031 | const flash = Math.min(1, Math.max(0, flashStrength ?? 0)); |
| 4032 | const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX; |
| 4033 | const uniforms = this.#ensureUniformBag(object.renderer, getDualTintLitSpriteShader(), "dualTint"); |
| 4034 | uniforms.u_darkness = dark; |
| 4035 | uniforms.u_strength = flash; |
| 4036 | this.#writeUniformVec3(uniforms, "u_flashColor", flashColor ?? FLASH_COLOR_DAMAGE); |
| 4037 | uniforms.u_wade = wade ? 1 : 0; |
| 4038 | uniforms.u_spriteHeight = height; |
| 4039 | this.#writeUniformVec3(uniforms, "u_shaftTint", shaft); |
| 4040 | this.#writeUniformVec3(uniforms, "u_tipTint", tip); |
| 4041 | this.#writeUniformVec3(uniforms, "u_coatTint", coat ?? { r: 0, g: 0, b: 0 }); |
| 4042 | uniforms.u_hasCoat = coat ? 1 : 0; |
| 4043 | object.renderer.secondaryMap = null; |
| 4044 | } |
| 4045 | |
| 4046 | #syncGroundItemSprite (item, darkness) |
| 4047 | { |
| 4048 | if (item?.dualTint) |
| 4049 | { |
| 4050 | this.#syncDualTintLitSprite(item.object, darkness, item.dualTint); |
| 4051 | } |
| 4052 | else |
| 4053 | { this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null); } |
| 4054 | if (!item?.chequeOverlay) |
| 4055 | { return; } |
| 4056 | if (item.chequeOverlayDualTint) |
| 4057 | { |
| 4058 | this.#syncDualTintLitSprite(item.chequeOverlay, darkness, item.chequeOverlayDualTint); |
| 4059 | return; |
| 4060 | } |
| 4061 | this.#syncLitSprite(item.chequeOverlay, darkness, 0, false, item.chequeOverlayTint ?? null); |
| 4062 | } |
| 4063 | |
| 4064 | #groundTypeAt (tileX, tileY) |
| 4065 | { |
| 4066 | const ground = this.#groundAtTile(tileX, tileY); |
| 4067 | return ground == null ? null : normalizeGround(ground).typeId; |
| 4068 | } |
| 4069 | |
| 4070 | /** Ground entry at a world tile, including editor hover preview when present. */ |
| 4071 | #groundAtTile (tileX, tileY) |
| 4072 | { |
| 4073 | if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY |
| 4074 | && this.preview.ground !== undefined) |
| 4075 | { return this.preview.ground; } |
| 4076 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 4077 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 4078 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 4079 | if (!snapshot) |
| 4080 | { return null; } |
| 4081 | const localX = tileX - chunkX * CHUNK_SIZE; |
| 4082 | const localY = tileY - chunkY * CHUNK_SIZE; |
| 4083 | const index = localY * CHUNK_SIZE + localX; |
| 4084 | return snapshot.grounds?.[index] ?? null; |
| 4085 | } |
| 4086 | |
| 4087 | #waterCoastEdges (tileX, tileY) |
| 4088 | { |
| 4089 | const season = this.worldSeason; |
| 4090 | const continues = (x, y) => fluidCoastContinues( |
| 4091 | this.#groundTypeAt(x, y), |
| 4092 | (typeId) => isLiquidWaterGround(typeId, season) |
| 4093 | ); |
| 4094 | const n = continues(tileX, tileY - 1); |
| 4095 | const e = continues(tileX + 1, tileY); |
| 4096 | const s = continues(tileX, tileY + 1); |
| 4097 | const w = continues(tileX - 1, tileY); |
| 4098 | const ne = continues(tileX + 1, tileY - 1); |
| 4099 | const nw = continues(tileX - 1, tileY - 1); |
| 4100 | const se = continues(tileX + 1, tileY + 1); |
| 4101 | const sw = continues(tileX - 1, tileY + 1); |
| 4102 | return { |
| 4103 | n: n ? 0 : 1, |
| 4104 | e: e ? 0 : 1, |
| 4105 | s: s ? 0 : 1, |
| 4106 | w: w ? 0 : 1, |
| 4107 | // Pure diagonal land pockets (e.g. WWW/WLL) — only when cardinals stay water. |
| 4108 | ne: (!ne && n && e) ? 1 : 0, |
| 4109 | nw: (!nw && n && w) ? 1 : 0, |
| 4110 | se: (!se && s && e) ? 1 : 0, |
| 4111 | sw: (!sw && s && w) ? 1 : 0 |
| 4112 | }; |
| 4113 | } |
| 4114 | |
| 4115 | /** |
| 4116 | * Corner deepness = average of liquid-water tiles meeting that corner. |
| 4117 | * Bilinear sampling of these corners is continuous across shared edges/corners. |
| 4118 | */ |
| 4119 | #waterDeepCorners (tileX, tileY, selfDeep) |
| 4120 | { |
| 4121 | const season = this.worldSeason; |
| 4122 | const fallback = selfDeep ? 1 : 0; |
| 4123 | const depthAt = (x, y) => |
| 4124 | { |
| 4125 | const typeId = this.#groundTypeAt(x, y); |
| 4126 | if (!isLiquidWaterGround(typeId, season)) |
| 4127 | { return null; } |
| 4128 | return typeId === GroundType.deepWater ? 1 : 0; |
| 4129 | }; |
| 4130 | const corner = (offsets) => |
| 4131 | { |
| 4132 | let sum = 0; |
| 4133 | let count = 0; |
| 4134 | for (const [dx, dy] of offsets) |
| 4135 | { |
| 4136 | const d = depthAt(tileX + dx, tileY + dy); |
| 4137 | if (d == null) |
| 4138 | { continue; } |
| 4139 | sum += d; |
| 4140 | count += 1; |
| 4141 | } |
| 4142 | return count ? sum / count : fallback; |
| 4143 | }; |
| 4144 | return { |
| 4145 | nw: corner([[0, 0], [-1, 0], [0, -1], [-1, -1]]), |
| 4146 | ne: corner([[0, 0], [1, 0], [0, -1], [1, -1]]), |
| 4147 | sw: corner([[0, 0], [-1, 0], [0, 1], [-1, 1]]), |
| 4148 | se: corner([[0, 0], [1, 0], [0, 1], [1, 1]]) |
| 4149 | }; |
| 4150 | } |
| 4151 | |
| 4152 | /** |
| 4153 | * Neighbor ground sprite for coast retreat peeks. |
| 4154 | * Water prefers wet-shore (sand-wet); lava uses dry land only. |
| 4155 | */ |
| 4156 | #fluidCoastShore (tileX, tileY, edges, { preferWet = true } = {}) |
| 4157 | { |
| 4158 | const season = this.worldSeason; |
| 4159 | const candidates = []; |
| 4160 | if (edges?.n) |
| 4161 | { candidates.push({ edge: "n", tileX, tileY: tileY - 1 }); } |
| 4162 | if (edges?.e) |
| 4163 | { candidates.push({ edge: "e", tileX: tileX + 1, tileY }); } |
| 4164 | if (edges?.s) |
| 4165 | { candidates.push({ edge: "s", tileX, tileY: tileY + 1 }); } |
| 4166 | if (edges?.w) |
| 4167 | { candidates.push({ edge: "w", tileX: tileX - 1, tileY }); } |
| 4168 | if (edges?.ne) |
| 4169 | { candidates.push({ edge: "ne", tileX: tileX + 1, tileY: tileY - 1 }); } |
| 4170 | if (edges?.nw) |
| 4171 | { candidates.push({ edge: "nw", tileX: tileX - 1, tileY: tileY - 1 }); } |
| 4172 | if (edges?.se) |
| 4173 | { candidates.push({ edge: "se", tileX: tileX + 1, tileY: tileY + 1 }); } |
| 4174 | if (edges?.sw) |
| 4175 | { candidates.push({ edge: "sw", tileX: tileX - 1, tileY: tileY + 1 }); } |
| 4176 | let pick = null; |
| 4177 | for (const candidate of candidates) |
| 4178 | { |
| 4179 | const ground = this.#groundAtTile(candidate.tileX, candidate.tileY); |
| 4180 | if (ground == null) |
| 4181 | { continue; } |
| 4182 | const entry = normalizeGround(ground); |
| 4183 | const def = GROUND_DEFINITIONS[entry.typeId]; |
| 4184 | if (!def || def.proceduralWaves || !def.blendable) |
| 4185 | { continue; } |
| 4186 | let spriteName = null; |
| 4187 | if (preferWet && def.wetShore) |
| 4188 | { |
| 4189 | const wetState = `${def.key}-wet`; |
| 4190 | const states = this.catalog?.grounds?.[def.key]?.states ?? []; |
| 4191 | if (states.includes(wetState)) |
| 4192 | { spriteName = spriteImageName("ground", def.key, wetState); } |
| 4193 | } |
| 4194 | if (!spriteName) |
| 4195 | { |
| 4196 | const states = this.catalog?.grounds?.[def.key]?.states ?? []; |
| 4197 | const state = resolveSeasonalVisualState(states, entry.state, season) ?? def.key; |
| 4198 | spriteName = spriteImageName("ground", def.key, state); |
| 4199 | } |
| 4200 | const sprite = spriteName ? this.game.images[spriteName] : null; |
| 4201 | if (!sprite) |
| 4202 | { continue; } |
| 4203 | const ranked = { ...candidate, sprite, wet: !!(preferWet && def.wetShore) }; |
| 4204 | if (ranked.wet) |
| 4205 | { |
| 4206 | pick = ranked; |
| 4207 | break; |
| 4208 | } |
| 4209 | if (!pick) |
| 4210 | { pick = ranked; } |
| 4211 | } |
| 4212 | const shore = { |
| 4213 | sprite: pick?.sprite ?? null, |
| 4214 | edgeN: 0, |
| 4215 | edgeE: 0, |
| 4216 | edgeS: 0, |
| 4217 | edgeW: 0, |
| 4218 | edgeNE: 0, |
| 4219 | edgeNW: 0, |
| 4220 | edgeSE: 0, |
| 4221 | edgeSW: 0 |
| 4222 | }; |
| 4223 | if (pick?.edge === "n") |
| 4224 | { shore.edgeN = 1; } |
| 4225 | else if (pick?.edge === "e") |
| 4226 | { shore.edgeE = 1; } |
| 4227 | else if (pick?.edge === "s") |
| 4228 | { shore.edgeS = 1; } |
| 4229 | else if (pick?.edge === "w") |
| 4230 | { shore.edgeW = 1; } |
| 4231 | else if (pick?.edge === "ne") |
| 4232 | { shore.edgeNE = 1; } |
| 4233 | else if (pick?.edge === "nw") |
| 4234 | { shore.edgeNW = 1; } |
| 4235 | else if (pick?.edge === "se") |
| 4236 | { shore.edgeSE = 1; } |
| 4237 | else if (pick?.edge === "sw") |
| 4238 | { shore.edgeSW = 1; } |
| 4239 | return shore; |
| 4240 | } |
| 4241 | |
| 4242 | #waterCoastShore (tileX, tileY, edges) |
| 4243 | { |
| 4244 | return this.#fluidCoastShore(tileX, tileY, edges, { preferWet: true }); |
| 4245 | } |
| 4246 | |
| 4247 | #syncWaterGroundSprite (object, { |
| 4248 | corners = null, |
| 4249 | ambientDark = 0, |
| 4250 | edges = null, |
| 4251 | shore = null, |
| 4252 | timeSec = 0, |
| 4253 | fallbackLit = 1, |
| 4254 | tileX = 0, |
| 4255 | tileY = 0, |
| 4256 | deepCorners = null, |
| 4257 | staticsDirty = true |
| 4258 | } = {}) |
| 4259 | { |
| 4260 | if (!object?.renderer) |
| 4261 | { return; } |
| 4262 | const lit = corners ?? { |
| 4263 | nw: fallbackLit, |
| 4264 | ne: fallbackLit, |
| 4265 | sw: fallbackLit, |
| 4266 | se: fallbackLit |
| 4267 | }; |
| 4268 | const dark = Math.min(1, Math.max(0, ambientDark ?? 0)); |
| 4269 | object._lit = true; |
| 4270 | const uniforms = this.#ensureUniformBag(object.renderer, getWaterGroundShader(), "water"); |
| 4271 | // Dynamic every frame: time + lighting. |
| 4272 | uniforms.u_ambientDark = dark; |
| 4273 | uniforms.u_litNW = lit.nw; |
| 4274 | uniforms.u_litNE = lit.ne; |
| 4275 | uniforms.u_litSW = lit.sw; |
| 4276 | uniforms.u_litSE = lit.se; |
| 4277 | uniforms.u_time = timeSec; |
| 4278 | if (!staticsDirty && object.renderer._fluidStaticsReady) |
| 4279 | { return; } |
| 4280 | const shoreSprite = shore?.sprite ?? null; |
| 4281 | const shoreUv = shoreSprite?.getUvRect?.(0) |
| 4282 | ?? { u0: 0, v0: 0, u1: 1, v1: 1 }; |
| 4283 | const dNW = deepCorners?.nw ?? 0; |
| 4284 | const dNE = deepCorners?.ne ?? 0; |
| 4285 | const dSW = deepCorners?.sw ?? 0; |
| 4286 | const dSE = deepCorners?.se ?? 0; |
| 4287 | // Shallow + deep share one noise atlas so texAmp seams don't hard-cut at depth edges. |
| 4288 | const sharedNoise = this.game.images[spriteImageName("ground", "water", "water")]; |
| 4289 | if (sharedNoise) |
| 4290 | { object.renderer.sprite = sharedNoise; } |
| 4291 | object.renderer.secondaryMap = shoreSprite?.g_image ?? null; |
| 4292 | uniforms.u_tileX = tileX | 0; |
| 4293 | uniforms.u_tileY = tileY | 0; |
| 4294 | uniforms.u_deepNW = dNW; |
| 4295 | uniforms.u_deepNE = dNE; |
| 4296 | uniforms.u_deepSW = dSW; |
| 4297 | uniforms.u_deepSE = dSE; |
| 4298 | uniforms.u_edgeN = edges?.n ?? 0; |
| 4299 | uniforms.u_edgeE = edges?.e ?? 0; |
| 4300 | uniforms.u_edgeS = edges?.s ?? 0; |
| 4301 | uniforms.u_edgeW = edges?.w ?? 0; |
| 4302 | uniforms.u_edgeNE = edges?.ne ?? 0; |
| 4303 | uniforms.u_edgeNW = edges?.nw ?? 0; |
| 4304 | uniforms.u_edgeSE = edges?.se ?? 0; |
| 4305 | uniforms.u_edgeSW = edges?.sw ?? 0; |
| 4306 | uniforms.u_hasShore = shoreSprite ? 1 : 0; |
| 4307 | uniforms.u_shoreEdgeN = shore?.edgeN ?? 0; |
| 4308 | uniforms.u_shoreEdgeE = shore?.edgeE ?? 0; |
| 4309 | uniforms.u_shoreEdgeS = shore?.edgeS ?? 0; |
| 4310 | uniforms.u_shoreEdgeW = shore?.edgeW ?? 0; |
| 4311 | uniforms.u_shoreEdgeNE = shore?.edgeNE ?? 0; |
| 4312 | uniforms.u_shoreEdgeNW = shore?.edgeNW ?? 0; |
| 4313 | uniforms.u_shoreEdgeSE = shore?.edgeSE ?? 0; |
| 4314 | uniforms.u_shoreEdgeSW = shore?.edgeSW ?? 0; |
| 4315 | this.#writeUniformVec4(uniforms, "u_shoreUvRect", shoreUv.u0, shoreUv.v0, shoreUv.u1, shoreUv.v1); |
| 4316 | object.renderer._fluidStaticsReady = true; |
| 4317 | } |
| 4318 | |
| 4319 | /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. Lava is procedural heat. */ |
| 4320 | #syncGroundWaterFx (objects, ambientDark, timeSec, baked = null) |
| 4321 | { |
| 4322 | if (!objects?.ground) |
| 4323 | { return; } |
| 4324 | if (isLavaGround(objects.groundTypeId)) |
| 4325 | { |
| 4326 | objects.waterEdges = null; |
| 4327 | this.#syncLavaGroundFx(objects, ambientDark, timeSec, baked); |
| 4328 | return; |
| 4329 | } |
| 4330 | this.#clearLavaBloom(objects); |
| 4331 | if (!isLiquidWaterGround(objects.groundTypeId, this.worldSeason)) |
| 4332 | { |
| 4333 | objects.waterEdges = null; |
| 4334 | this.#syncLitSprite(objects.ground, objects.shadeAlpha ?? 0); |
| 4335 | return; |
| 4336 | } |
| 4337 | const fallbackLit = 1 - (objects.shadeAlpha ?? 0); |
| 4338 | const chunkX = Math.floor(objects.tileX / CHUNK_SIZE); |
| 4339 | const chunkY = Math.floor(objects.tileY / CHUNK_SIZE); |
| 4340 | const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`); |
| 4341 | const localX = objects.tileX - chunkX * CHUNK_SIZE; |
| 4342 | const localY = objects.tileY - chunkY * CHUNK_SIZE; |
| 4343 | let litCorners = null; |
| 4344 | if (chunkBaked) |
| 4345 | { |
| 4346 | if (this.lightingMode === "simple") |
| 4347 | { |
| 4348 | const gridW = CHUNK_SIZE + 2; |
| 4349 | const intensity = chunkBaked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? fallbackLit; |
| 4350 | litCorners = { nw: intensity, ne: intensity, sw: intensity, se: intensity }; |
| 4351 | } |
| 4352 | else |
| 4353 | { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); } |
| 4354 | } |
| 4355 | const coast = this.#cachedWaterCoast(objects); |
| 4356 | objects.waterEdges = coast.edges; |
| 4357 | this.#syncWaterGroundSprite(objects.ground, { |
| 4358 | corners: litCorners, |
| 4359 | ambientDark, |
| 4360 | edges: coast.edges, |
| 4361 | shore: coast.shore, |
| 4362 | timeSec, |
| 4363 | fallbackLit, |
| 4364 | tileX: objects.tileX, |
| 4365 | tileY: objects.tileY, |
| 4366 | deepCorners: coast.deepCorners, |
| 4367 | staticsDirty: coast.staticsDirty |
| 4368 | }); |
| 4369 | } |
| 4370 | |
| 4371 | #lavaCoastEdges (tileX, tileY) |
| 4372 | { |
| 4373 | const continues = (x, y) => fluidCoastContinues( |
| 4374 | this.#groundTypeAt(x, y), |
| 4375 | (typeId) => isLavaGround(typeId) |
| 4376 | ); |
| 4377 | const n = continues(tileX, tileY - 1); |
| 4378 | const e = continues(tileX + 1, tileY); |
| 4379 | const s = continues(tileX, tileY + 1); |
| 4380 | const w = continues(tileX - 1, tileY); |
| 4381 | const ne = continues(tileX + 1, tileY - 1); |
| 4382 | const nw = continues(tileX - 1, tileY - 1); |
| 4383 | const se = continues(tileX + 1, tileY + 1); |
| 4384 | const sw = continues(tileX - 1, tileY + 1); |
| 4385 | return { |
| 4386 | n: n ? 0 : 1, |
| 4387 | e: e ? 0 : 1, |
| 4388 | s: s ? 0 : 1, |
| 4389 | w: w ? 0 : 1, |
| 4390 | ne: (!ne && n && e) ? 1 : 0, |
| 4391 | nw: (!nw && n && w) ? 1 : 0, |
| 4392 | se: (!se && s && e) ? 1 : 0, |
| 4393 | sw: (!sw && s && w) ? 1 : 0 |
| 4394 | }; |
| 4395 | } |
| 4396 | |
| 4397 | #clearLavaBloom (objects) |
| 4398 | { |
| 4399 | if (!objects) |
| 4400 | { return; } |
| 4401 | objects.lavaBloom?.destroy(); |
| 4402 | objects.lavaBloom = null; |
| 4403 | } |
| 4404 | |
| 4405 | #ensureLavaBloom (objects) |
| 4406 | { |
| 4407 | const sprite = objects.ground?.renderer?.sprite; |
| 4408 | if (!sprite) |
| 4409 | { return null; } |
| 4410 | if (!objects.lavaBloom) |
| 4411 | { |
| 4412 | const bloom = new GameObject(0, 0, sprite, LAYER_GROUND); |
| 4413 | bloom.renderer.layer = RENDER_LAYER_BLOOM; |
| 4414 | this.#markUnlit(bloom); |
| 4415 | this.scene.addObject(bloom); |
| 4416 | objects.lavaBloom = bloom; |
| 4417 | } |
| 4418 | else if (objects.lavaBloom.renderer) |
| 4419 | { objects.lavaBloom.renderer.sprite = sprite; } |
| 4420 | const size = this.tileSize(); |
| 4421 | objects.lavaBloom.transform.position.x = objects.tileX * size + size / 2; |
| 4422 | objects.lavaBloom.transform.position.y = objects.tileY * size + size / 2; |
| 4423 | objects.lavaBloom.transform.size = new vector(size, size); |
| 4424 | this.#setLayer(objects.lavaBloom, LAYER_GROUND); |
| 4425 | return objects.lavaBloom; |
| 4426 | } |
| 4427 | |
| 4428 | #syncLavaGroundFx (objects, ambientDark, timeSec, baked = null) |
| 4429 | { |
| 4430 | const fallbackLit = 1 - (objects.shadeAlpha ?? 0); |
| 4431 | const chunkX = Math.floor(objects.tileX / CHUNK_SIZE); |
| 4432 | const chunkY = Math.floor(objects.tileY / CHUNK_SIZE); |
| 4433 | const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`); |
| 4434 | const localX = objects.tileX - chunkX * CHUNK_SIZE; |
| 4435 | const localY = objects.tileY - chunkY * CHUNK_SIZE; |
| 4436 | let litCorners = null; |
| 4437 | if (chunkBaked) |
| 4438 | { |
| 4439 | if (this.lightingMode === "simple") |
| 4440 | { |
| 4441 | const gridW = CHUNK_SIZE + 2; |
| 4442 | const intensity = chunkBaked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? fallbackLit; |
| 4443 | litCorners = { nw: intensity, ne: intensity, sw: intensity, se: intensity }; |
| 4444 | } |
| 4445 | else |
| 4446 | { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); } |
| 4447 | } |
| 4448 | const coast = this.#cachedLavaCoast(objects); |
| 4449 | this.#syncLavaGroundSprite(objects.ground, { |
| 4450 | corners: litCorners, |
| 4451 | ambientDark, |
| 4452 | edges: coast.edges, |
| 4453 | shore: coast.shore, |
| 4454 | timeSec, |
| 4455 | fallbackLit, |
| 4456 | tileX: objects.tileX, |
| 4457 | tileY: objects.tileY, |
| 4458 | staticsDirty: coast.staticsDirty |
| 4459 | }); |
| 4460 | const bloom = this.#ensureLavaBloom(objects); |
| 4461 | if (bloom) |
| 4462 | { |
| 4463 | this.#syncLavaBloomSprite(bloom, { |
| 4464 | edges: coast.edges, |
| 4465 | timeSec, |
| 4466 | tileX: objects.tileX, |
| 4467 | tileY: objects.tileY, |
| 4468 | staticsDirty: coast.staticsDirty |
| 4469 | }); |
| 4470 | } |
| 4471 | } |
| 4472 | |
| 4473 | #syncLavaGroundSprite (object, { |
| 4474 | corners = null, |
| 4475 | ambientDark = 0, |
| 4476 | edges = null, |
| 4477 | shore = null, |
| 4478 | timeSec = 0, |
| 4479 | fallbackLit = 1, |
| 4480 | tileX = 0, |
| 4481 | tileY = 0, |
| 4482 | staticsDirty = true |
| 4483 | } = {}) |
| 4484 | { |
| 4485 | if (!object?.renderer) |
| 4486 | { return; } |
| 4487 | const lit = corners ?? { |
| 4488 | nw: fallbackLit, |
| 4489 | ne: fallbackLit, |
| 4490 | sw: fallbackLit, |
| 4491 | se: fallbackLit |
| 4492 | }; |
| 4493 | const dark = Math.min(1, Math.max(0, ambientDark ?? 0)); |
| 4494 | object._lit = true; |
| 4495 | const uniforms = this.#ensureUniformBag(object.renderer, getLavaGroundShader(), "lava"); |
| 4496 | uniforms.u_ambientDark = dark; |
| 4497 | uniforms.u_litNW = lit.nw; |
| 4498 | uniforms.u_litNE = lit.ne; |
| 4499 | uniforms.u_litSW = lit.sw; |
| 4500 | uniforms.u_litSE = lit.se; |
| 4501 | uniforms.u_time = timeSec; |
| 4502 | if (!staticsDirty && object.renderer._fluidStaticsReady) |
| 4503 | { return; } |
| 4504 | const shoreSprite = shore?.sprite ?? null; |
| 4505 | const shoreUv = shoreSprite?.getUvRect?.(0) |
| 4506 | ?? { u0: 0, v0: 0, u1: 1, v1: 1 }; |
| 4507 | object.renderer.secondaryMap = shoreSprite?.g_image ?? null; |
| 4508 | uniforms.u_tileX = tileX | 0; |
| 4509 | uniforms.u_tileY = tileY | 0; |
| 4510 | uniforms.u_edgeN = edges?.n ?? 0; |
| 4511 | uniforms.u_edgeE = edges?.e ?? 0; |
| 4512 | uniforms.u_edgeS = edges?.s ?? 0; |
| 4513 | uniforms.u_edgeW = edges?.w ?? 0; |
| 4514 | uniforms.u_edgeNE = edges?.ne ?? 0; |
| 4515 | uniforms.u_edgeNW = edges?.nw ?? 0; |
| 4516 | uniforms.u_edgeSE = edges?.se ?? 0; |
| 4517 | uniforms.u_edgeSW = edges?.sw ?? 0; |
| 4518 | uniforms.u_hasShore = shoreSprite ? 1 : 0; |
| 4519 | uniforms.u_shoreEdgeN = shore?.edgeN ?? 0; |
| 4520 | uniforms.u_shoreEdgeE = shore?.edgeE ?? 0; |
| 4521 | uniforms.u_shoreEdgeS = shore?.edgeS ?? 0; |
| 4522 | uniforms.u_shoreEdgeW = shore?.edgeW ?? 0; |
| 4523 | uniforms.u_shoreEdgeNE = shore?.edgeNE ?? 0; |
| 4524 | uniforms.u_shoreEdgeNW = shore?.edgeNW ?? 0; |
| 4525 | uniforms.u_shoreEdgeSE = shore?.edgeSE ?? 0; |
| 4526 | uniforms.u_shoreEdgeSW = shore?.edgeSW ?? 0; |
| 4527 | this.#writeUniformVec4(uniforms, "u_shoreUvRect", shoreUv.u0, shoreUv.v0, shoreUv.u1, shoreUv.v1); |
| 4528 | object.renderer._fluidStaticsReady = true; |
| 4529 | } |
| 4530 | |
| 4531 | #syncLavaBloomSprite (object, { |
| 4532 | edges = null, |
| 4533 | timeSec = 0, |
| 4534 | tileX = 0, |
| 4535 | tileY = 0, |
| 4536 | staticsDirty = true |
| 4537 | } = {}) |
| 4538 | { |
| 4539 | if (!object?.renderer) |
| 4540 | { return; } |
| 4541 | const uniforms = this.#ensureUniformBag(object.renderer, getLavaBloomShader(), "lavaBloom"); |
| 4542 | uniforms.u_time = timeSec; |
| 4543 | if (!staticsDirty && object.renderer._fluidStaticsReady) |
| 4544 | { return; } |
| 4545 | uniforms.u_tileX = tileX | 0; |
| 4546 | uniforms.u_tileY = tileY | 0; |
| 4547 | uniforms.u_edgeN = edges?.n ?? 0; |
| 4548 | uniforms.u_edgeE = edges?.e ?? 0; |
| 4549 | uniforms.u_edgeS = edges?.s ?? 0; |
| 4550 | uniforms.u_edgeW = edges?.w ?? 0; |
| 4551 | uniforms.u_edgeNE = edges?.ne ?? 0; |
| 4552 | uniforms.u_edgeNW = edges?.nw ?? 0; |
| 4553 | uniforms.u_edgeSE = edges?.se ?? 0; |
| 4554 | uniforms.u_edgeSW = edges?.sw ?? 0; |
| 4555 | object.renderer._fluidStaticsReady = true; |
| 4556 | } |
| 4557 | |
| 4558 | |
| 4559 | #cachedWaterCoast (objects) |
| 4560 | { |
| 4561 | const epoch = this.#fluidCoastEpoch; |
| 4562 | const typeId = objects.groundTypeId; |
| 4563 | const season = this.worldSeason; |
| 4564 | const cache = objects._fluidCoastCache; |
| 4565 | if ( |
| 4566 | cache |
| 4567 | && cache.epoch === epoch |
| 4568 | && cache.typeId === typeId |
| 4569 | && cache.season === season |
| 4570 | && cache.kind === "water" |
| 4571 | ) |
| 4572 | { return { edges: cache.edges, shore: cache.shore, deepCorners: cache.deepCorners, staticsDirty: false }; } |
| 4573 | const edges = this.#waterCoastEdges(objects.tileX, objects.tileY); |
| 4574 | const shore = this.#waterCoastShore(objects.tileX, objects.tileY, edges); |
| 4575 | const deep = typeId === GroundType.deepWater; |
| 4576 | const deepCorners = this.#waterDeepCorners(objects.tileX, objects.tileY, deep); |
| 4577 | objects._fluidCoastCache = { epoch, typeId, season, kind: "water", edges, shore, deepCorners }; |
| 4578 | if (objects.ground?.renderer) |
| 4579 | { objects.ground.renderer._fluidStaticsReady = false; } |
| 4580 | return { edges, shore, deepCorners, staticsDirty: true }; |
| 4581 | } |
| 4582 | |
| 4583 | #cachedLavaCoast (objects) |
| 4584 | { |
| 4585 | const epoch = this.#fluidCoastEpoch; |
| 4586 | const typeId = objects.groundTypeId; |
| 4587 | const season = this.worldSeason; |
| 4588 | const cache = objects._fluidCoastCache; |
| 4589 | if ( |
| 4590 | cache |
| 4591 | && cache.epoch === epoch |
| 4592 | && cache.typeId === typeId |
| 4593 | && cache.season === season |
| 4594 | && cache.kind === "lava" |
| 4595 | ) |
| 4596 | { return { edges: cache.edges, shore: cache.shore, staticsDirty: false }; } |
| 4597 | const edges = this.#lavaCoastEdges(objects.tileX, objects.tileY); |
| 4598 | const shore = this.#fluidCoastShore(objects.tileX, objects.tileY, edges, { preferWet: false }); |
| 4599 | objects._fluidCoastCache = { epoch, typeId, season, kind: "lava", edges, shore, deepCorners: null }; |
| 4600 | if (objects.ground?.renderer) |
| 4601 | { objects.ground.renderer._fluidStaticsReady = false; } |
| 4602 | if (objects.lavaBloom?.renderer) |
| 4603 | { objects.lavaBloom.renderer._fluidStaticsReady = false; } |
| 4604 | return { edges, shore, staticsDirty: true }; |
| 4605 | } |
| 4606 | |
| 4607 | #tileUsesFluidAtlas (objects) |
| 4608 | { |
| 4609 | if (!objects?.groundTypeId) |
| 4610 | { return false; } |
| 4611 | if (isLavaGround(objects.groundTypeId)) |
| 4612 | { return true; } |
| 4613 | return isLiquidWaterGround(objects.groundTypeId, this.worldSeason); |
| 4614 | } |
| 4615 | |
| 4616 | #ensureFluidAtlasSlot (baked, kind) |
| 4617 | { |
| 4618 | const glCtx = this.scene?.glContext; |
| 4619 | if (!glCtx?.gl || !baked) |
| 4620 | { return null; } |
| 4621 | const key = kind === "bloom" ? "_fluidBloomTarget" : "_fluidGroundTarget"; |
| 4622 | const objKey = kind === "bloom" ? "fluidBloomObject" : "fluidGroundObject"; |
| 4623 | if (!baked[key]) |
| 4624 | { |
| 4625 | const target = createFluidAtlasTarget(glCtx); |
| 4626 | if (!target) |
| 4627 | { |
| 4628 | this.#useFluidAtlas = false; |
| 4629 | return null; |
| 4630 | } |
| 4631 | baked[key] = target; |
| 4632 | setNearestFilter(this.scene, target.canvas); |
| 4633 | } |
| 4634 | const target = baked[key]; |
| 4635 | if (!baked[objKey]) |
| 4636 | { |
| 4637 | const object = new GameObject(0, 0, target.image, LAYER_GROUND); |
| 4638 | if (kind === "bloom") |
| 4639 | { |
| 4640 | object.renderer.layer = RENDER_LAYER_BLOOM; |
| 4641 | } |
| 4642 | this.#markUnlit(object); |
| 4643 | this.scene.addObject(object); |
| 4644 | baked[objKey] = object; |
| 4645 | this.#layoutFluidAtlasObject(baked, kind); |
| 4646 | } |
| 4647 | else if (baked[objKey].renderer) |
| 4648 | { baked[objKey].renderer.sprite = target.image; } |
| 4649 | return { target, object: baked[objKey] }; |
| 4650 | } |
| 4651 | |
| 4652 | #layoutFluidAtlasObject (baked, kind = "ground") |
| 4653 | { |
| 4654 | const object = kind === "bloom" ? baked.fluidBloomObject : baked.fluidGroundObject; |
| 4655 | if (!object || baked.chunkX == null || baked.chunkY == null) |
| 4656 | { return; } |
| 4657 | const size = this.tileSize(); |
| 4658 | const layoutKey = `${baked.chunkX},${baked.chunkY},${size},${kind}`; |
| 4659 | if (baked._fluidLayoutKey === layoutKey && object.renderer?.mirrorY) |
| 4660 | { return; } |
| 4661 | baked._fluidLayoutKey = layoutKey; |
| 4662 | const left = baked.chunkX * CHUNK_SIZE * size; |
| 4663 | const top = baked.chunkY * CHUNK_SIZE * size; |
| 4664 | const chunkPx = CHUNK_SIZE * size; |
| 4665 | // Pixel-snap: subpixel atlas placement + NEAREST causes grid cracks. |
| 4666 | object.transform.position.x = Math.round(left + chunkPx / 2); |
| 4667 | object.transform.position.y = Math.round(top + chunkPx / 2); |
| 4668 | object.transform.size = new vector(chunkPx, chunkPx); |
| 4669 | // FBO color attachment is V-flipped vs Framework sprite UVs — one atlas |
| 4670 | // mirrorY restores N/S hole placement without breaking noise continuity. |
| 4671 | if (object.renderer) |
| 4672 | { object.renderer.mirrorY = true; } |
| 4673 | if (kind === "bloom") |
| 4674 | { |
| 4675 | this.#setLayer(object, this.#depthLayer(top + chunkPx, SORT_BLOCK)); |
| 4676 | object.renderer.layer = RENDER_LAYER_BLOOM; |
| 4677 | } |
| 4678 | else |
| 4679 | { this.#setLayer(object, LAYER_GROUND); } |
| 4680 | } |
| 4681 | |
| 4682 | #destroyFluidAtlasSlot (baked) |
| 4683 | { |
| 4684 | const glCtx = this.scene?.glContext; |
| 4685 | if (!baked) |
| 4686 | { return; } |
| 4687 | baked.fluidGroundObject?.destroy(); |
| 4688 | baked.fluidGroundObject = null; |
| 4689 | baked.fluidBloomObject?.destroy(); |
| 4690 | baked.fluidBloomObject = null; |
| 4691 | destroyFluidAtlasTarget(glCtx, baked._fluidGroundTarget); |
| 4692 | destroyFluidAtlasTarget(glCtx, baked._fluidBloomTarget); |
| 4693 | destroyFluidPackSet(glCtx, baked._fluidPacks); |
| 4694 | baked._fluidGroundTarget = null; |
| 4695 | baked._fluidBloomTarget = null; |
| 4696 | baked._fluidPacks = null; |
| 4697 | } |
| 4698 | |
| 4699 | #ensureFluidPacks (baked) |
| 4700 | { |
| 4701 | const glCtx = this.scene?.glContext; |
| 4702 | if (!glCtx?.gl || !baked) |
| 4703 | { return null; } |
| 4704 | if (!baked._fluidPacks) |
| 4705 | { |
| 4706 | const packs = createFluidPackSet(glCtx); |
| 4707 | if (!packs) |
| 4708 | { return null; } |
| 4709 | baked._fluidPacks = packs; |
| 4710 | } |
| 4711 | return baked._fluidPacks; |
| 4712 | } |
| 4713 | |
| 4714 | #fluidAtlasSinglePassEnabled () |
| 4715 | { |
| 4716 | if (!this.#useFluidAtlasSinglePass) |
| 4717 | { return false; } |
| 4718 | if (globalThis.__QW_FLUID_ATLAS_SINGLE_PASS === false) |
| 4719 | { return false; } |
| 4720 | return true; |
| 4721 | } |
| 4722 | |
| 4723 | /** |
| 4724 | * Render liquid water + lava into per-chunk 16×16 atlases; hide per-tile fluid sprites. |
| 4725 | * Lighting/time uniforms stay on the (hidden) tile renderers and are sampled here. |
| 4726 | */ |
| 4727 | #syncFluidAtlases () |
| 4728 | { |
| 4729 | if (!this.#useFluidAtlas) |
| 4730 | { return; } |
| 4731 | const glCtx = this.scene?.glContext; |
| 4732 | if (!glCtx?.gl) |
| 4733 | { return; } |
| 4734 | |
| 4735 | const byChunk = new Map(); |
| 4736 | for (const objects of this.tiles.values()) |
| 4737 | { |
| 4738 | if (!objects.ground) |
| 4739 | { continue; } |
| 4740 | if (!this.#tileUsesFluidAtlas(objects)) |
| 4741 | { continue; } |
| 4742 | // Hide per-tile fluid sprites (keep objects + uniforms for atlas + lighting data). |
| 4743 | if (!objects._fluidAtlasHidden) |
| 4744 | { |
| 4745 | this.#setRendererVisible(objects.ground, false); |
| 4746 | this.#setRendererVisible(objects.lavaBloom, false); |
| 4747 | objects._fluidAtlasHidden = true; |
| 4748 | } |
| 4749 | if (objects._inViewport === false) |
| 4750 | { continue; } |
| 4751 | const key = `${objects.chunkX},${objects.chunkY}`; |
| 4752 | let list = byChunk.get(key); |
| 4753 | if (!list) |
| 4754 | { |
| 4755 | list = []; |
| 4756 | byChunk.set(key, list); |
| 4757 | } |
| 4758 | list.push(objects); |
| 4759 | } |
| 4760 | |
| 4761 | const active = new Set(); |
| 4762 | for (const [key, list] of byChunk) |
| 4763 | { |
| 4764 | const baked = this.bakedChunks.get(key); |
| 4765 | if (!baked || baked._inViewport === false) |
| 4766 | { continue; } |
| 4767 | active.add(key); |
| 4768 | this.#renderFluidAtlasChunk(baked, list); |
| 4769 | } |
| 4770 | |
| 4771 | for (const baked of this.bakedChunks.values()) |
| 4772 | { |
| 4773 | const key = `${baked.chunkX},${baked.chunkY}`; |
| 4774 | if (active.has(key)) |
| 4775 | { continue; } |
| 4776 | this.#setRendererVisible(baked.fluidGroundObject, false); |
| 4777 | this.#setRendererVisible(baked.fluidBloomObject, false); |
| 4778 | } |
| 4779 | } |
| 4780 | |
| 4781 | #showFluidTilesFallback (tileObjects) |
| 4782 | { |
| 4783 | for (const objects of tileObjects) |
| 4784 | { |
| 4785 | const vis = objects._inViewport !== false; |
| 4786 | objects._fluidAtlasHidden = false; |
| 4787 | this.#setRendererVisible(objects.ground, vis); |
| 4788 | this.#setRendererVisible(objects.lavaBloom, vis && this.bloomEnabled); |
| 4789 | } |
| 4790 | } |
| 4791 | |
| 4792 | #renderFluidAtlasChunk (baked, tileObjects) |
| 4793 | { |
| 4794 | const glCtx = this.scene?.glContext; |
| 4795 | const groundSlot = this.#ensureFluidAtlasSlot(baked, "ground"); |
| 4796 | if (!groundSlot || !this.#useFluidAtlas) |
| 4797 | { |
| 4798 | this.#showFluidTilesFallback(tileObjects); |
| 4799 | return; |
| 4800 | } |
| 4801 | |
| 4802 | const usedSingle = this.#fluidAtlasSinglePassEnabled() |
| 4803 | && this.#renderFluidAtlasChunkSinglePass(baked, tileObjects, groundSlot); |
| 4804 | if (!usedSingle) |
| 4805 | { this.#renderFluidAtlasChunkPerTile(baked, tileObjects, groundSlot); } |
| 4806 | } |
| 4807 | |
| 4808 | #renderFluidAtlasChunkPerTile (baked, tileObjects, groundSlot) |
| 4809 | { |
| 4810 | const glCtx = this.scene?.glContext; |
| 4811 | const bloomTiles = []; |
| 4812 | withFluidAtlasPass(glCtx, groundSlot.target, () => |
| 4813 | { |
| 4814 | for (const objects of tileObjects) |
| 4815 | { |
| 4816 | const renderer = objects.ground?.renderer; |
| 4817 | if (!renderer?.shader || !renderer.shaderUniforms || !renderer.sprite?.g_image) |
| 4818 | { continue; } |
| 4819 | const localX = objects.tileX - baked.chunkX * CHUNK_SIZE; |
| 4820 | const localY = objects.tileY - baked.chunkY * CHUNK_SIZE; |
| 4821 | drawFluidAtlasTile(glCtx, { |
| 4822 | textureHtml: renderer.sprite.g_image, |
| 4823 | secondaryHtml: renderer.secondaryMap ?? null, |
| 4824 | localX, |
| 4825 | localY, |
| 4826 | shader: renderer.shader, |
| 4827 | uniforms: renderer.shaderUniforms, |
| 4828 | uvRect: renderer.sprite.getUvRect?.(renderer.subImage | 0) ?? null |
| 4829 | }); |
| 4830 | if (objects.lavaBloom?.renderer?.shader) |
| 4831 | { bloomTiles.push(objects); } |
| 4832 | } |
| 4833 | }); |
| 4834 | this.#layoutFluidAtlasObject(baked, "ground"); |
| 4835 | this.#setRendererVisible(groundSlot.object, true); |
| 4836 | |
| 4837 | if (!bloomTiles.length || !this.bloomEnabled) |
| 4838 | { |
| 4839 | this.#setRendererVisible(baked.fluidBloomObject, false); |
| 4840 | return; |
| 4841 | } |
| 4842 | |
| 4843 | const bloomSlot = this.#ensureFluidAtlasSlot(baked, "bloom"); |
| 4844 | if (!bloomSlot || !this.#useFluidAtlas) |
| 4845 | { return; } |
| 4846 | withFluidAtlasPass(glCtx, bloomSlot.target, () => |
| 4847 | { |
| 4848 | for (const objects of bloomTiles) |
| 4849 | { |
| 4850 | const renderer = objects.lavaBloom?.renderer; |
| 4851 | if (!renderer?.shader || !renderer.shaderUniforms) |
| 4852 | { continue; } |
| 4853 | const tex = renderer.sprite?.g_image ?? objects.ground?.renderer?.sprite?.g_image; |
| 4854 | if (!tex) |
| 4855 | { continue; } |
| 4856 | const localX = objects.tileX - baked.chunkX * CHUNK_SIZE; |
| 4857 | const localY = objects.tileY - baked.chunkY * CHUNK_SIZE; |
| 4858 | drawFluidAtlasTile(glCtx, { |
| 4859 | textureHtml: tex, |
| 4860 | secondaryHtml: null, |
| 4861 | localX, |
| 4862 | localY, |
| 4863 | shader: renderer.shader, |
| 4864 | uniforms: renderer.shaderUniforms, |
| 4865 | uvRect: renderer.sprite?.getUvRect?.(renderer.subImage | 0) ?? null |
| 4866 | }); |
| 4867 | } |
| 4868 | }); |
| 4869 | this.#layoutFluidAtlasObject(baked, "bloom"); |
| 4870 | this.#setRendererVisible(bloomSlot.object, true); |
| 4871 | } |
| 4872 | |
| 4873 | /** |
| 4874 | * Pack per-tile uniforms into 16×16 textures and bake with 1–2 chunk draws. |
| 4875 | * @returns {boolean} true when single-pass succeeded |
| 4876 | */ |
| 4877 | #renderFluidAtlasChunkSinglePass (baked, tileObjects, groundSlot) |
| 4878 | { |
| 4879 | const glCtx = this.scene?.glContext; |
| 4880 | const packs = this.#ensureFluidPacks(baked); |
| 4881 | if (!packs || !glCtx?.gl) |
| 4882 | { return false; } |
| 4883 | |
| 4884 | const waterShader = getWaterAtlasChunkShader(); |
| 4885 | const lavaShader = getLavaAtlasChunkShader(); |
| 4886 | const bloomShader = getLavaBloomAtlasChunkShader(); |
| 4887 | if (!waterShader?.getProgramInfo(glCtx.gl) |
| 4888 | || !lavaShader?.getProgramInfo(glCtx.gl) |
| 4889 | || !bloomShader?.getProgramInfo(glCtx.gl)) |
| 4890 | { return false; } |
| 4891 | |
| 4892 | clearFluidPackPixels(packs); |
| 4893 | const waterTiles = []; |
| 4894 | const lavaTiles = []; |
| 4895 | const bloomTiles = []; |
| 4896 | let waterNoise = null; |
| 4897 | let lavaNoise = null; |
| 4898 | let waterSecondary = null; |
| 4899 | let lavaSecondary = null; |
| 4900 | let waterUniforms = null; |
| 4901 | let lavaUniforms = null; |
| 4902 | let bloomUniforms = null; |
| 4903 | let ambientDark = 0; |
| 4904 | let timeSec = 0; |
| 4905 | |
| 4906 | for (const objects of tileObjects) |
| 4907 | { |
| 4908 | const renderer = objects.ground?.renderer; |
| 4909 | if (!renderer?.shaderUniforms || !renderer.sprite?.g_image) |
| 4910 | { continue; } |
| 4911 | const kindName = renderer._shaderUniformKind; |
| 4912 | const kind = kindName === "lava" ? FLUID_KIND_LAVA |
| 4913 | : kindName === "water" ? FLUID_KIND_WATER |
| 4914 | : null; |
| 4915 | if (!kind) |
| 4916 | { continue; } |
| 4917 | const localX = objects.tileX - baked.chunkX * CHUNK_SIZE; |
| 4918 | const localY = objects.tileY - baked.chunkY * CHUNK_SIZE; |
| 4919 | writeFluidPackTile(packs, localX, localY, kind, renderer.shaderUniforms); |
| 4920 | const noise = renderer.sprite.g_image; |
| 4921 | const secondary = renderer.secondaryMap ?? null; |
| 4922 | const u = renderer.shaderUniforms; |
| 4923 | ambientDark = u.u_ambientDark ?? ambientDark; |
| 4924 | timeSec = u.u_time ?? timeSec; |
| 4925 | if (kind === FLUID_KIND_WATER) |
| 4926 | { |
| 4927 | waterTiles.push(objects); |
| 4928 | if (!waterNoise) |
| 4929 | { waterNoise = noise; } |
| 4930 | else if (waterNoise !== noise) |
| 4931 | { return false; } |
| 4932 | if (secondary) |
| 4933 | { |
| 4934 | if (!waterSecondary) |
| 4935 | { waterSecondary = secondary; } |
| 4936 | else if (waterSecondary !== secondary) |
| 4937 | { return false; } |
| 4938 | } |
| 4939 | if (!waterUniforms) |
| 4940 | { waterUniforms = u; } |
| 4941 | } |
| 4942 | else |
| 4943 | { |
| 4944 | lavaTiles.push(objects); |
| 4945 | if (!lavaNoise) |
| 4946 | { lavaNoise = noise; } |
| 4947 | else if (lavaNoise !== noise) |
| 4948 | { return false; } |
| 4949 | if (secondary) |
| 4950 | { |
| 4951 | if (!lavaSecondary) |
| 4952 | { lavaSecondary = secondary; } |
| 4953 | else if (lavaSecondary !== secondary) |
| 4954 | { return false; } |
| 4955 | } |
| 4956 | if (!lavaUniforms) |
| 4957 | { lavaUniforms = u; } |
| 4958 | if (objects.lavaBloom?.renderer?.shaderUniforms) |
| 4959 | { |
| 4960 | bloomTiles.push(objects); |
| 4961 | if (!bloomUniforms) |
| 4962 | { bloomUniforms = objects.lavaBloom.renderer.shaderUniforms; } |
| 4963 | } |
| 4964 | } |
| 4965 | } |
| 4966 | |
| 4967 | if (!waterTiles.length && !lavaTiles.length) |
| 4968 | { return false; } |
| 4969 | |
| 4970 | uploadFluidPacks(glCtx, packs); |
| 4971 | const chunkOriginX = baked.chunkX * CHUNK_SIZE; |
| 4972 | const chunkOriginY = baked.chunkY * CHUNK_SIZE; |
| 4973 | |
| 4974 | withFluidAtlasPass(glCtx, groundSlot.target, () => |
| 4975 | { |
| 4976 | if (waterTiles.length && waterNoise && waterUniforms) |
| 4977 | { |
| 4978 | drawFluidAtlasChunkPass(glCtx, { |
| 4979 | textureHtml: waterNoise, |
| 4980 | secondaryHtml: waterSecondary, |
| 4981 | shader: waterShader, |
| 4982 | uniforms: { |
| 4983 | ...waterDebugUniforms(), |
| 4984 | u_chunkOrigin: [chunkOriginX, chunkOriginY], |
| 4985 | u_time: timeSec, |
| 4986 | u_ambientDark: ambientDark, |
| 4987 | u_alpha: 1 |
| 4988 | }, |
| 4989 | packs, |
| 4990 | kindFilter: FLUID_KIND_WATER, |
| 4991 | includeShorePacks: true |
| 4992 | }); |
| 4993 | } |
| 4994 | if (lavaTiles.length && lavaNoise && lavaUniforms) |
| 4995 | { |
| 4996 | drawFluidAtlasChunkPass(glCtx, { |
| 4997 | textureHtml: lavaNoise, |
| 4998 | secondaryHtml: lavaSecondary, |
| 4999 | shader: lavaShader, |
| 5000 | uniforms: { |
| 5001 | ...lavaDebugUniforms(), |
| 5002 | u_chunkOrigin: [chunkOriginX, chunkOriginY], |
| 5003 | u_time: timeSec, |
| 5004 | u_ambientDark: ambientDark, |
| 5005 | u_alpha: 1 |
| 5006 | }, |
| 5007 | packs, |
| 5008 | kindFilter: FLUID_KIND_LAVA, |
| 5009 | includeShorePacks: true |
| 5010 | }); |
| 5011 | } |
| 5012 | }); |
| 5013 | this.#layoutFluidAtlasObject(baked, "ground"); |
| 5014 | this.#setRendererVisible(groundSlot.object, true); |
| 5015 | |
| 5016 | if (!bloomTiles.length || !this.bloomEnabled || !bloomUniforms || !lavaNoise) |
| 5017 | { |
| 5018 | this.#setRendererVisible(baked.fluidBloomObject, false); |
| 5019 | return true; |
| 5020 | } |
| 5021 | |
| 5022 | const bloomSlot = this.#ensureFluidAtlasSlot(baked, "bloom"); |
| 5023 | if (!bloomSlot || !this.#useFluidAtlas) |
| 5024 | { return true; } |
| 5025 | withFluidAtlasPass(glCtx, bloomSlot.target, () => |
| 5026 | { |
| 5027 | drawFluidAtlasChunkPass(glCtx, { |
| 5028 | textureHtml: lavaNoise, |
| 5029 | secondaryHtml: null, |
| 5030 | shader: bloomShader, |
| 5031 | uniforms: { |
| 5032 | ...lavaDebugUniforms(), |
| 5033 | u_chunkOrigin: [chunkOriginX, chunkOriginY], |
| 5034 | u_time: bloomUniforms.u_time ?? timeSec, |
| 5035 | u_alpha: 1 |
| 5036 | }, |
| 5037 | packs, |
| 5038 | kindFilter: FLUID_KIND_LAVA, |
| 5039 | includeShorePacks: false |
| 5040 | }); |
| 5041 | }); |
| 5042 | this.#layoutFluidAtlasObject(baked, "bloom"); |
| 5043 | this.#setRendererVisible(bloomSlot.object, true); |
| 5044 | return true; |
| 5045 | } |
| 5046 | |
| 5047 | #ambientDarkness () |
| 5048 | { |
| 5049 | const hour = this.nightPreview ?? this.worldHour; |
| 5050 | const calendar = nightFactor(hour, this.settings.nightDarkness); |
| 5051 | let dark = resolveDimensionDarknessFactor(this.dimensionLightingMode, calendar); |
| 5052 | if (dark == null) |
| 5053 | { dark = calendar; } |
| 5054 | if (this.localBlind) |
| 5055 | { dark = Math.min(1, dark + 0.85); } |
| 5056 | return dark; |
| 5057 | } |
| 5058 | |
| 5059 | #tileEnclosedFlag (tileX, tileY) |
| 5060 | { |
| 5061 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 5062 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 5063 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 5064 | if (!snapshot) |
| 5065 | { return 0; } |
| 5066 | const enclosed = snapshot.enclosed; |
| 5067 | if (!Array.isArray(enclosed) || enclosed.length < CHUNK_SIZE * CHUNK_SIZE) |
| 5068 | { return 0; } |
| 5069 | const localX = tileX - chunkX * CHUNK_SIZE; |
| 5070 | const localY = tileY - chunkY * CHUNK_SIZE; |
| 5071 | if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE) |
| 5072 | { return 0; } |
| 5073 | return enclosed[localY * CHUNK_SIZE + localX] ? 1 : 0; |
| 5074 | } |
| 5075 | |
| 5076 | /** Base ambient plus enclosed bonus, clamped to nightDarkness peak. */ |
| 5077 | #ambientDarknessForTile (tileX, tileY, baseAmbient = this.#ambientDarkness()) |
| 5078 | { |
| 5079 | return enclosedAmbientDarkness(baseAmbient, this.#tileEnclosedFlag(tileX, tileY), { |
| 5080 | enclosedDarknessBonus: this.settings.enclosedDarknessBonus ?? 0.10, |
| 5081 | nightDarkness: this.settings.nightDarkness ?? 0.72 |
| 5082 | }); |
| 5083 | } |
| 5084 | |
| 5085 | setLocalBlind (blind) |
| 5086 | { |
| 5087 | this.localBlind = !!blind; |
| 5088 | } |
| 5089 | |
| 5090 | /** Soft vision bubble while blinded (client-only; stacks with ambient). */ |
| 5091 | #blindVisionLight () |
| 5092 | { |
| 5093 | if (!this.localBlind) |
| 5094 | { return null; } |
| 5095 | const local = this.entities.get(this.localEntityId); |
| 5096 | if (!local) |
| 5097 | { return null; } |
| 5098 | const tileSize = this.tileSize(); |
| 5099 | return { |
| 5100 | tileX: Math.floor(local.visualX / tileSize), |
| 5101 | tileY: Math.floor(local.visualY / tileSize), |
| 5102 | range: 2.25, |
| 5103 | intensity: 1 |
| 5104 | }; |
| 5105 | } |
| 5106 | |
| 5107 | #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY, dualTint = null) |
| 5108 | { |
| 5109 | const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0; |
| 5110 | const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0; |
| 5111 | const dark = (fromAlpha + toAlpha) / 2; |
| 5112 | if (dualTint) |
| 5113 | { |
| 5114 | this.#syncDualTintLitSprite(object, dark, dualTint); |
| 5115 | return; |
| 5116 | } |
| 5117 | this.#syncLitSprite(object, dark); |
| 5118 | } |
| 5119 | |
| 5120 | #dualTintFromPayload (payload) |
| 5121 | { |
| 5122 | if (!payload?.shaftTint || !payload?.tipTint) |
| 5123 | { return null; } |
| 5124 | return { |
| 5125 | shaft: payload.shaftTint, |
| 5126 | tip: payload.tipTint, |
| 5127 | ...(payload.coatTint ? { coat: payload.coatTint } : {}) |
| 5128 | }; |
| 5129 | } |
| 5130 | |
| 5131 | #syncHpBar (entity) |
| 5132 | { |
| 5133 | const current = entity.health; |
| 5134 | const max = entity.maxHealth; |
| 5135 | const show = current != null |
| 5136 | && max != null |
| 5137 | && max > 0 |
| 5138 | && current < max; |
| 5139 | if (!show) |
| 5140 | { |
| 5141 | entity.hpBar?.destroy(); |
| 5142 | entity.hpBar = null; |
| 5143 | entity.hpBarCanvas = null; |
| 5144 | return; |
| 5145 | } |
| 5146 | if (!entity.hpBarCanvas) |
| 5147 | { |
| 5148 | entity.hpBarCanvas = document.createElement("canvas"); |
| 5149 | entity.hpBarCanvas.width = HP_BAR_W; |
| 5150 | entity.hpBarCanvas.height = HP_BAR_H; |
| 5151 | const image = frameworkImageFromCanvas(entity.hpBarCanvas); |
| 5152 | entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR); |
| 5153 | this.#markUnlit(entity.hpBar); |
| 5154 | this.scene.addObject(entity.hpBar); |
| 5155 | } |
| 5156 | drawHpBar(entity.hpBarCanvas, current, max); |
| 5157 | invalidateCanvasTexture(this.scene, entity.hpBarCanvas); |
| 5158 | } |
| 5159 | |
| 5160 | #placeHpBar (entity, pivotX, pivotY) |
| 5161 | { |
| 5162 | if (!entity.hpBar) |
| 5163 | { return; } |
| 5164 | const sprite = entity.object?.renderer?.sprite; |
| 5165 | if (!sprite) |
| 5166 | { return; } |
| 5167 | const zoom = this.zoom; |
| 5168 | const drawH = sprite.height * zoom; |
| 5169 | const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom); |
| 5170 | const spriteTop = centerY - drawH / 2; |
| 5171 | const barW = HP_BAR_W * zoom; |
| 5172 | const barH = HP_BAR_H * zoom; |
| 5173 | entity.hpBar.transform.position.x = pivotX; |
| 5174 | entity.hpBar.transform.position.y = spriteTop - barH / 2; |
| 5175 | entity.hpBar.transform.size = new vector(barW, barH); |
| 5176 | this.#setLayer(entity.hpBar, this.#depthLayer(pivotY, SORT_HP_BAR)); |
| 5177 | } |
| 5178 | |
| 5179 | #syncSkullMarker (entity) |
| 5180 | { |
| 5181 | if (!entity?.characterId) |
| 5182 | { |
| 5183 | entity.skullMarker?.destroy(); |
| 5184 | entity.skullMarker = null; |
| 5185 | return; |
| 5186 | } |
| 5187 | const tint = skullTintColor(entity.skullValue | 0, this.settings); |
| 5188 | if (!tint) |
| 5189 | { |
| 5190 | entity.skullMarker?.destroy(); |
| 5191 | entity.skullMarker = null; |
| 5192 | return; |
| 5193 | } |
| 5194 | const image = this.game.images[SKULL_SPRITE] |
| 5195 | ?? this.game.images["item:skull:skull"]; |
| 5196 | if (!image) |
| 5197 | { return; } |
| 5198 | if (!entity.skullMarker) |
| 5199 | { |
| 5200 | entity.skullMarker = new GameObject(0, 0, image, SORT_HP_BAR); |
| 5201 | this.scene.addObject(entity.skullMarker); |
| 5202 | } |
| 5203 | entity.skullTint = tint; |
| 5204 | entity.skullMarker.renderer.sprite = image; |
| 5205 | } |
| 5206 | |
| 5207 | /** |
| 5208 | * Bottom edge of the skull sprite sits exactly on the character sprite's top edge. |
| 5209 | */ |
| 5210 | #placeSkullMarker (entity, pivotX, pivotY, darkness) |
| 5211 | { |
| 5212 | this.#syncSkullMarker(entity); |
| 5213 | if (!entity.skullMarker) |
| 5214 | { return; } |
| 5215 | const body = entity.object?.renderer?.sprite; |
| 5216 | const skull = entity.skullMarker.renderer?.sprite; |
| 5217 | if (!body || !skull) |
| 5218 | { return; } |
| 5219 | const zoom = this.zoom; |
| 5220 | const scale = entity.visualScale ?? 1; |
| 5221 | const bodyH = body.height * zoom * scale; |
| 5222 | const skullH = skull.height * zoom; |
| 5223 | const skullW = skull.width * zoom; |
| 5224 | const bodyCenterY = pivotY - (bodyH / 2 - PIVOT_FROM_BOTTOM_PX * zoom * scale); |
| 5225 | const bodyTop = bodyCenterY - bodyH / 2; |
| 5226 | // GameObject position is sprite center; bottom of skull at bodyTop ⇒ center at bodyTop - skullH/2 |
| 5227 | entity.skullMarker.transform.position.x = pivotX; |
| 5228 | entity.skullMarker.transform.position.y = bodyTop - skullH / 2; |
| 5229 | entity.skullMarker.transform.size = new vector(skullW, skullH); |
| 5230 | this.#setLayer(entity.skullMarker, this.#depthLayer(pivotY, SORT_HP_BAR)); |
| 5231 | this.#syncLitSprite(entity.skullMarker, darkness, 0, false, entity.skullTint); |
| 5232 | } |
| 5233 | |
| 5234 | #rebuildChunk (snapshot, { refreshSoftNeighbors = true } = {}) |
| 5235 | { |
| 5236 | this.#bakeAndPlaceChunk(snapshot); |
| 5237 | this.#relayoutChunkTiles(snapshot); |
| 5238 | // Soft terrain and wet-sand shorelines both sample cross-chunk neighbors. |
| 5239 | if (refreshSoftNeighbors && this.#needsSoftTerrainNeighborRefresh()) |
| 5240 | { this.#rebuildSoftTerrainNeighborChunks(snapshot); } |
| 5241 | } |
| 5242 | |
| 5243 | /** Soft blend / wet-sand atlas borders need a rebake when an adjacent chunk arrives. */ |
| 5244 | #needsSoftTerrainNeighborRefresh () |
| 5245 | { |
| 5246 | if (this.softTerrain) |
| 5247 | { return true; } |
| 5248 | return Math.max(0, Number(this.settings?.wetSandBand) || 0) > 0; |
| 5249 | } |
| 5250 | |
| 5251 | #relayoutChunk (snapshot) |
| 5252 | { |
| 5253 | this.#layoutBakedChunk(snapshot); |
| 5254 | this.#relayoutChunkTiles(snapshot); |
| 5255 | } |
| 5256 | |
| 5257 | #relayoutChunkTiles (snapshot) |
| 5258 | { |
| 5259 | for (let localY = 0; localY < CHUNK_SIZE; localY++) |
| 5260 | { |
| 5261 | for (let localX = 0; localX < CHUNK_SIZE; localX++) |
| 5262 | { |
| 5263 | const tileX = snapshot.chunkX * CHUNK_SIZE + localX; |
| 5264 | const tileY = snapshot.chunkY * CHUNK_SIZE + localY; |
| 5265 | this.#drawTile(tileX, tileY); |
| 5266 | } |
| 5267 | } |
| 5268 | } |
| 5269 | |
| 5270 | #scheduleChunkRebuild (snapshot) |
| 5271 | { |
| 5272 | if (!snapshot) |
| 5273 | { return; } |
| 5274 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 5275 | this.#chunkRebuildKeys.add(key); |
| 5276 | this.#chunkSoftNeighborKeys.delete(key); |
| 5277 | this.#cancelIdlePrefetch(); |
| 5278 | this.#ensureChunkFlushScheduled(); |
| 5279 | } |
| 5280 | |
| 5281 | /** Queue a neighbor atlas rebake without cascading further soft-neighbor work. */ |
| 5282 | #scheduleSoftNeighborChunkRebuild (snapshot) |
| 5283 | { |
| 5284 | if (!snapshot) |
| 5285 | { return; } |
| 5286 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 5287 | if (this.#chunkRebuildKeys.has(key)) |
| 5288 | { return; } |
| 5289 | this.#chunkSoftNeighborKeys.add(key); |
| 5290 | this.#cancelIdlePrefetch(); |
| 5291 | this.#ensureChunkFlushScheduled(); |
| 5292 | } |
| 5293 | |
| 5294 | #scheduleEdgeRebuild () |
| 5295 | { |
| 5296 | this.#edgesDirty = true; |
| 5297 | this.#cancelIdlePrefetch(); |
| 5298 | this.#ensureChunkFlushScheduled(); |
| 5299 | } |
| 5300 | |
| 5301 | #pendingChunkRebuildCount () |
| 5302 | { |
| 5303 | return this.#chunkRebuildKeys.size + this.#chunkSoftNeighborKeys.size; |
| 5304 | } |
| 5305 | |
| 5306 | #ensureChunkFlushScheduled () |
| 5307 | { |
| 5308 | if (this.#chunkRebuildRaf) |
| 5309 | { return; } |
| 5310 | this.#cancelIdlePrefetch(); |
| 5311 | this.#chunkRebuildRaf = requestAnimationFrame(() => this.#flushChunkWork()); |
| 5312 | } |
| 5313 | |
| 5314 | #notePlayerTile (tileX, tileY) |
| 5315 | { |
| 5316 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 5317 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 5318 | const prevX = this.#playerChunkX; |
| 5319 | const prevY = this.#playerChunkY; |
| 5320 | if (prevX != null |
| 5321 | && (chunkX !== prevX || chunkY !== prevY)) |
| 5322 | { |
| 5323 | const dx = chunkX - prevX; |
| 5324 | const dy = chunkY - prevY; |
| 5325 | if (dx !== 0) |
| 5326 | { this.#playerMoveChunkDx = Math.sign(dx); } |
| 5327 | if (dy !== 0) |
| 5328 | { this.#playerMoveChunkDy = Math.sign(dy); } |
| 5329 | this.#onActiveLightingCenterChanged(prevX, prevY, chunkX, chunkY); |
| 5330 | } |
| 5331 | this.#playerChunkX = chunkX; |
| 5332 | this.#playerChunkY = chunkY; |
| 5333 | } |
| 5334 | |
| 5335 | /** When the 3×3 lighting center moves: refresh door sprites (resting vs live) and lightmaps. */ |
| 5336 | #onActiveLightingCenterChanged (prevChunkX, prevChunkY, chunkX, chunkY) |
| 5337 | { |
| 5338 | this.#invalidateActiveLightingMoveCaches(prevChunkX, prevChunkY, chunkX, chunkY); |
| 5339 | const doorChunks = new Set(); |
| 5340 | for (const [cx, cy] of [[prevChunkX, prevChunkY], [chunkX, chunkY]]) |
| 5341 | { |
| 5342 | for (let dy = -1; dy <= 1; dy++) |
| 5343 | { |
| 5344 | for (let dx = -1; dx <= 1; dx++) |
| 5345 | { doorChunks.add(`${cx + dx},${cy + dy}`); } |
| 5346 | } |
| 5347 | } |
| 5348 | for (const key of doorChunks) |
| 5349 | { |
| 5350 | const [cx, cy] = key.split(",").map(Number); |
| 5351 | this.#redrawDoorTilesInChunk(cx, cy); |
| 5352 | } |
| 5353 | } |
| 5354 | |
| 5355 | /** |
| 5356 | * Only bust lightmaps for chunks whose active-3×3 membership (or ±1 halo) changed. |
| 5357 | * Cache keys already track light positions; a full ±2 wipe around both centers was redundant. |
| 5358 | */ |
| 5359 | #invalidateActiveLightingMoveCaches (prevChunkX, prevChunkY, nextChunkX, nextChunkY) |
| 5360 | { |
| 5361 | const prev = new Set(); |
| 5362 | const next = new Set(); |
| 5363 | for (let dy = -1; dy <= 1; dy++) |
| 5364 | { |
| 5365 | for (let dx = -1; dx <= 1; dx++) |
| 5366 | { |
| 5367 | prev.add(`${prevChunkX + dx},${prevChunkY + dy}`); |
| 5368 | next.add(`${nextChunkX + dx},${nextChunkY + dy}`); |
| 5369 | } |
| 5370 | } |
| 5371 | const changed = []; |
| 5372 | for (const key of prev) |
| 5373 | { |
| 5374 | if (!next.has(key)) |
| 5375 | { changed.push(key); } |
| 5376 | } |
| 5377 | for (const key of next) |
| 5378 | { |
| 5379 | if (!prev.has(key)) |
| 5380 | { changed.push(key); } |
| 5381 | } |
| 5382 | const bust = new Set(); |
| 5383 | for (const key of changed) |
| 5384 | { |
| 5385 | const [cx, cy] = key.split(",").map(Number); |
| 5386 | for (let dy = -1; dy <= 1; dy++) |
| 5387 | { |
| 5388 | for (let dx = -1; dx <= 1; dx++) |
| 5389 | { bust.add(`${cx + dx},${cy + dy}`); } |
| 5390 | } |
| 5391 | } |
| 5392 | for (const key of bust) |
| 5393 | { |
| 5394 | const baked = this.bakedChunks.get(key); |
| 5395 | if (baked) |
| 5396 | { baked.lightmapCacheKey = null; } |
| 5397 | } |
| 5398 | } |
| 5399 | |
| 5400 | #redrawDoorTilesInChunk (chunkX, chunkY) |
| 5401 | { |
| 5402 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 5403 | if (!snapshot?.blocks) |
| 5404 | { return; } |
| 5405 | for (let localY = 0; localY < CHUNK_SIZE; localY++) |
| 5406 | { |
| 5407 | for (let localX = 0; localX < CHUNK_SIZE; localX++) |
| 5408 | { |
| 5409 | const block = snapshot.blocks[localY * CHUNK_SIZE + localX]; |
| 5410 | if (!blockDefinition(block?.typeId)?.door) |
| 5411 | { continue; } |
| 5412 | this.#drawTile(chunkX * CHUNK_SIZE + localX, chunkY * CHUNK_SIZE + localY); |
| 5413 | } |
| 5414 | } |
| 5415 | } |
| 5416 | |
| 5417 | #playerChunkCoords () |
| 5418 | { |
| 5419 | const local = this.entities.get(this.localEntityId); |
| 5420 | if (local) |
| 5421 | { |
| 5422 | return { |
| 5423 | chunkX: Math.floor(local.tileX / CHUNK_SIZE), |
| 5424 | chunkY: Math.floor(local.tileY / CHUNK_SIZE) |
| 5425 | }; |
| 5426 | } |
| 5427 | if (this.#playerChunkX != null && this.#playerChunkY != null) |
| 5428 | { |
| 5429 | return { chunkX: this.#playerChunkX, chunkY: this.#playerChunkY }; |
| 5430 | } |
| 5431 | return null; |
| 5432 | } |
| 5433 | |
| 5434 | /** Lower score = bake sooner in urgent mode; idle mode inverts distance. */ |
| 5435 | #chunkRebuildScore (key, mode = "urgent") |
| 5436 | { |
| 5437 | const [chunkX, chunkY] = key.split(",").map(Number); |
| 5438 | const player = this.#playerChunkCoords(); |
| 5439 | if (!player) |
| 5440 | { return 0; } |
| 5441 | const dx = chunkX - player.chunkX; |
| 5442 | const dy = chunkY - player.chunkY; |
| 5443 | const dist = Math.abs(dx) + Math.abs(dy); |
| 5444 | let ahead = 0; |
| 5445 | if (this.#playerMoveChunkDx !== 0 || this.#playerMoveChunkDy !== 0) |
| 5446 | { ahead = dx * this.#playerMoveChunkDx + dy * this.#playerMoveChunkDy; } |
| 5447 | if (mode === "idle") |
| 5448 | { |
| 5449 | return -dist * 10 + (ahead > 0 ? -ahead * 2 : Math.max(ahead, 0)); |
| 5450 | } |
| 5451 | return dist * 10 - Math.max(0, ahead) * 3; |
| 5452 | } |
| 5453 | |
| 5454 | #sortedChunkRebuildKeys (keySet, mode = "urgent") |
| 5455 | { |
| 5456 | return [...keySet].sort((a, b) => |
| 5457 | this.#chunkRebuildScore(a, mode) - this.#chunkRebuildScore(b, mode)); |
| 5458 | } |
| 5459 | |
| 5460 | #discoverUnbakedChunks () |
| 5461 | { |
| 5462 | for (const key of this.chunks.keys()) |
| 5463 | { |
| 5464 | if (!this.bakedChunks.has(key)) |
| 5465 | { this.#chunkRebuildKeys.add(key); } |
| 5466 | } |
| 5467 | } |
| 5468 | |
| 5469 | #hasUnbakedChunks () |
| 5470 | { |
| 5471 | for (const key of this.chunks.keys()) |
| 5472 | { |
| 5473 | if (!this.bakedChunks.has(key)) |
| 5474 | { return true; } |
| 5475 | } |
| 5476 | return false; |
| 5477 | } |
| 5478 | |
| 5479 | #pickIdlePrefetchSnapshot () |
| 5480 | { |
| 5481 | let best = null; |
| 5482 | let bestScore = Infinity; |
| 5483 | for (const snapshot of this.chunks.values()) |
| 5484 | { |
| 5485 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 5486 | if (this.bakedChunks.has(key) |
| 5487 | || this.#chunkRebuildKeys.has(key) |
| 5488 | || this.#chunkSoftNeighborKeys.has(key)) |
| 5489 | { continue; } |
| 5490 | const score = this.#chunkRebuildScore(key, "idle"); |
| 5491 | if (score < bestScore) |
| 5492 | { |
| 5493 | bestScore = score; |
| 5494 | best = snapshot; |
| 5495 | } |
| 5496 | } |
| 5497 | return best; |
| 5498 | } |
| 5499 | |
| 5500 | #cancelIdlePrefetch () |
| 5501 | { |
| 5502 | if (this.#idlePrefetchId && typeof cancelIdleCallback === "function") |
| 5503 | { cancelIdleCallback(this.#idlePrefetchId); } |
| 5504 | this.#idlePrefetchId = 0; |
| 5505 | } |
| 5506 | |
| 5507 | #scheduleIdleChunkPrefetch () |
| 5508 | { |
| 5509 | if (this.#idlePrefetchId || this.#chunkRebuildRaf || this.#pendingChunkRebuildCount()) |
| 5510 | { return; } |
| 5511 | if (typeof requestIdleCallback !== "function") |
| 5512 | { return; } |
| 5513 | if (!this.#hasUnbakedChunks()) |
| 5514 | { return; } |
| 5515 | this.#idlePrefetchId = requestIdleCallback( |
| 5516 | (deadline) => this.#runIdleChunkPrefetch(deadline), |
| 5517 | { timeout: 2500 } |
| 5518 | ); |
| 5519 | } |
| 5520 | |
| 5521 | #runIdleChunkPrefetch (deadline) |
| 5522 | { |
| 5523 | this.#idlePrefetchId = 0; |
| 5524 | if (this.#chunkRebuildRaf || this.#pendingChunkRebuildCount()) |
| 5525 | { return; } |
| 5526 | this.#discoverUnbakedChunks(); |
| 5527 | if (this.#pendingChunkRebuildCount()) |
| 5528 | { |
| 5529 | this.#ensureChunkFlushScheduled(); |
| 5530 | return; |
| 5531 | } |
| 5532 | const snapshot = this.#pickIdlePrefetchSnapshot(); |
| 5533 | if (!snapshot) |
| 5534 | { return; } |
| 5535 | if (deadline.timeRemaining() <= 4 && !deadline.didTimeout) |
| 5536 | { |
| 5537 | this.#scheduleIdleChunkPrefetch(); |
| 5538 | return; |
| 5539 | } |
| 5540 | this.#rebuildChunk(snapshot, { refreshSoftNeighbors: true }); |
| 5541 | if (this.#hasUnbakedChunks()) |
| 5542 | { this.#scheduleIdleChunkPrefetch(); } |
| 5543 | } |
| 5544 | |
| 5545 | #flushChunkWork () |
| 5546 | { |
| 5547 | this.#chunkRebuildRaf = 0; |
| 5548 | const primary = this.#sortedChunkRebuildKeys(this.#chunkRebuildKeys, "urgent"); |
| 5549 | const soft = this.#sortedChunkRebuildKeys(this.#chunkSoftNeighborKeys, "urgent"); |
| 5550 | let budget = this.#CHUNK_REBUILD_BATCH; |
| 5551 | const primaryBatch = primary.slice(0, budget); |
| 5552 | budget -= primaryBatch.length; |
| 5553 | const softBatch = soft.slice(0, Math.max(0, budget)); |
| 5554 | |
| 5555 | for (const key of primaryBatch) |
| 5556 | { this.#chunkRebuildKeys.delete(key); } |
| 5557 | for (const key of softBatch) |
| 5558 | { this.#chunkSoftNeighborKeys.delete(key); } |
| 5559 | |
| 5560 | for (const key of primaryBatch) |
| 5561 | { |
| 5562 | const snap = this.chunks.get(key); |
| 5563 | if (snap) |
| 5564 | { this.#rebuildChunk(snap, { refreshSoftNeighbors: true }); } |
| 5565 | } |
| 5566 | for (const key of softBatch) |
| 5567 | { |
| 5568 | const snap = this.chunks.get(key); |
| 5569 | if (snap) |
| 5570 | { this.#rebuildChunk(snap, { refreshSoftNeighbors: false }); } |
| 5571 | } |
| 5572 | |
| 5573 | if (this.#pendingChunkRebuildCount()) |
| 5574 | { |
| 5575 | this.#ensureChunkFlushScheduled(); |
| 5576 | return; |
| 5577 | } |
| 5578 | if (this.#edgesDirty) |
| 5579 | { |
| 5580 | this.#rebuildAllEdges(); |
| 5581 | this.#edgesDirty = false; |
| 5582 | } |
| 5583 | this.#scheduleIdleChunkPrefetch(); |
| 5584 | } |
| 5585 | |
| 5586 | #previewEqual (a, b) |
| 5587 | { |
| 5588 | if (a === b) |
| 5589 | { return true; } |
| 5590 | if (!a || !b) |
| 5591 | { return false; } |
| 5592 | return a.tileX === b.tileX |
| 5593 | && a.tileY === b.tileY |
| 5594 | && this.#previewPart(a.ground) === this.#previewPart(b.ground) |
| 5595 | && this.#previewPart(a.block) === this.#previewPart(b.block); |
| 5596 | } |
| 5597 | |
| 5598 | #previewPart (value) |
| 5599 | { |
| 5600 | return value === undefined ? undefined : JSON.stringify(value); |
| 5601 | } |
| 5602 | |
| 5603 | #rebuildSoftTerrainNeighborChunks (snapshot) |
| 5604 | { |
| 5605 | for (let dy = -1; dy <= 1; dy++) |
| 5606 | { |
| 5607 | for (let dx = -1; dx <= 1; dx++) |
| 5608 | { |
| 5609 | if (dx === 0 && dy === 0) |
| 5610 | { continue; } |
| 5611 | const neighbor = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`); |
| 5612 | if (neighbor) |
| 5613 | { this.#scheduleSoftNeighborChunkRebuild(neighbor); } |
| 5614 | } |
| 5615 | } |
| 5616 | } |
| 5617 | |
| 5618 | #rebakeAllChunks () |
| 5619 | { |
| 5620 | for (const snapshot of this.chunks.values()) |
| 5621 | { this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false }); } |
| 5622 | } |
| 5623 | |
| 5624 | #bakeAndPlaceChunk (snapshot) |
| 5625 | { |
| 5626 | this.#fluidCoastEpoch = (this.#fluidCoastEpoch + 1) | 0; |
| 5627 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 5628 | const atlases = bakeChunkAtlases({ |
| 5629 | snapshot, |
| 5630 | catalog: this.catalog, |
| 5631 | images: this.game.images, |
| 5632 | preview: this.preview, |
| 5633 | season: this.worldSeason, |
| 5634 | softTerrain: this.softTerrain, |
| 5635 | wetSandBandFraction: Math.max(0, Math.min(1, Number(this.settings?.wetSandBand) || 0)), |
| 5636 | resolveGround: (tileX, tileY) => this.#groundAtTile(tileX, tileY), |
| 5637 | cache: this.#atlasCache |
| 5638 | }); |
| 5639 | const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX; |
| 5640 | let baked = this.bakedChunks.get(key); |
| 5641 | this.#releaseBakedAtlasRefs(baked); |
| 5642 | |
| 5643 | const groundImage = this.#atlasCache.getImage(atlases.cacheRefs?.ground); |
| 5644 | const blockImages = atlases.cacheRefs?.blockRows.map((entry) => this.#atlasCache.getImage(entry)) |
| 5645 | ?? atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)); |
| 5646 | const bloomImage = this.#atlasCache.getImage(atlases.cacheRefs?.bloom) |
| 5647 | ?? frameworkImageFromCanvas(atlases.bloom); |
| 5648 | |
| 5649 | if (!baked) |
| 5650 | { |
| 5651 | const lightmapCanvas = makeLightmapCanvas(atlasPx); |
| 5652 | const natureCanvas = makeNatureNoiseCanvas(); |
| 5653 | baked = { |
| 5654 | groundCanvas: atlases.ground, |
| 5655 | blockCanvases: atlases.blockRows, |
| 5656 | bloomCanvas: atlases.bloom, |
| 5657 | lightmapCanvas, |
| 5658 | natureCanvas, |
| 5659 | groundImage, |
| 5660 | blockImages, |
| 5661 | bloomImage, |
| 5662 | lightmapImage: frameworkImageFromCanvas(lightmapCanvas), |
| 5663 | natureImage: frameworkImageFromCanvas(natureCanvas), |
| 5664 | groundObject: null, |
| 5665 | blockObjects: [], |
| 5666 | bloomObject: null, |
| 5667 | tallBlocks: atlases.tallBlocks, |
| 5668 | animatedGrounds: atlases.animatedGrounds, |
| 5669 | lightmapPixels: null, |
| 5670 | atlasCacheRefs: atlases.cacheRefs, |
| 5671 | chunkX: snapshot.chunkX, |
| 5672 | chunkY: snapshot.chunkY |
| 5673 | }; |
| 5674 | baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND); |
| 5675 | this.#applyAtlasLighting( |
| 5676 | baked.groundObject, |
| 5677 | baked.lightmapImage, |
| 5678 | -1, |
| 5679 | this.#groundNatureImage(baked) |
| 5680 | ); |
| 5681 | this.scene.addObject(baked.groundObject); |
| 5682 | for (let row = 0; row < CHUNK_SIZE; row++) |
| 5683 | { |
| 5684 | const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK); |
| 5685 | this.#applyAtlasLighting(object, baked.lightmapImage, row, null); |
| 5686 | this.scene.addObject(object); |
| 5687 | baked.blockObjects.push(object); |
| 5688 | } |
| 5689 | baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK); |
| 5690 | baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM; |
| 5691 | this.#markUnlit(baked.bloomObject); |
| 5692 | this.scene.addObject(baked.bloomObject); |
| 5693 | this.bakedChunks.set(key, baked); |
| 5694 | } |
| 5695 | else |
| 5696 | { |
| 5697 | baked.chunkX = snapshot.chunkX; |
| 5698 | baked.chunkY = snapshot.chunkY; |
| 5699 | if (!baked.natureCanvas) |
| 5700 | { |
| 5701 | baked.natureCanvas = makeNatureNoiseCanvas(); |
| 5702 | baked.natureImage = frameworkImageFromCanvas(baked.natureCanvas); |
| 5703 | } |
| 5704 | if (baked.groundCanvas !== atlases.ground) |
| 5705 | { |
| 5706 | baked.groundCanvas = atlases.ground; |
| 5707 | baked.groundImage = groundImage; |
| 5708 | baked.groundObject.renderer.sprite = groundImage; |
| 5709 | } |
| 5710 | this.#applyAtlasLighting( |
| 5711 | baked.groundObject, |
| 5712 | baked.lightmapImage, |
| 5713 | -1, |
| 5714 | this.#groundNatureImage(baked) |
| 5715 | ); |
| 5716 | for (let row = 0; row < CHUNK_SIZE; row++) |
| 5717 | { |
| 5718 | if (baked.blockCanvases[row] !== atlases.blockRows[row]) |
| 5719 | { |
| 5720 | baked.blockCanvases[row] = atlases.blockRows[row]; |
| 5721 | baked.blockImages[row] = blockImages[row]; |
| 5722 | baked.blockObjects[row].renderer.sprite = blockImages[row]; |
| 5723 | } |
| 5724 | this.#applyAtlasLighting( |
| 5725 | baked.blockObjects[row], |
| 5726 | baked.lightmapImage, |
| 5727 | row, |
| 5728 | null |
| 5729 | ); |
| 5730 | } |
| 5731 | if (baked.bloomCanvas !== atlases.bloom) |
| 5732 | { |
| 5733 | baked.bloomCanvas = atlases.bloom; |
| 5734 | baked.bloomImage = bloomImage; |
| 5735 | baked.bloomObject.renderer.sprite = bloomImage; |
| 5736 | } |
| 5737 | baked.tallBlocks = atlases.tallBlocks; |
| 5738 | baked.animatedGrounds = atlases.animatedGrounds; |
| 5739 | baked.atlasCacheRefs = atlases.cacheRefs; |
| 5740 | } |
| 5741 | baked.chunkX = snapshot.chunkX; |
| 5742 | baked.chunkY = snapshot.chunkY; |
| 5743 | if (this.natureTintEnabled) |
| 5744 | { this.#refreshNatureNoiseAround(snapshot.chunkX, snapshot.chunkY); } |
| 5745 | baked.lightmapCacheKey = null; |
| 5746 | this.#invalidateNeighborLightmapCaches(snapshot.chunkX, snapshot.chunkY); |
| 5747 | this.#layoutBakedChunk(snapshot); |
| 5748 | this.#queueBakedChunkTextures(baked, snapshot.chunkX, snapshot.chunkY); |
| 5749 | } |
| 5750 | |
| 5751 | #groundNatureImage (baked) |
| 5752 | { |
| 5753 | if (!baked?.natureImage) |
| 5754 | { return null; } |
| 5755 | if (this.natureTintEnabled || baked.natureTintReady) |
| 5756 | { return baked.natureImage; } |
| 5757 | return null; |
| 5758 | } |
| 5759 | |
| 5760 | #releaseBakedAtlasRefs (baked) |
| 5761 | { |
| 5762 | if (!baked?.atlasCacheRefs) |
| 5763 | { return; } |
| 5764 | this.#atlasCache.release(baked.atlasCacheRefs.ground); |
| 5765 | for (const entry of baked.atlasCacheRefs.blockRows ?? []) |
| 5766 | { this.#atlasCache.release(entry); } |
| 5767 | this.#atlasCache.release(baked.atlasCacheRefs.bloom); |
| 5768 | baked.atlasCacheRefs = null; |
| 5769 | } |
| 5770 | |
| 5771 | #chunkTextureWarmPriority (chunkX, chunkY) |
| 5772 | { |
| 5773 | const local = this.entities.get(this.localEntityId); |
| 5774 | if (!local) |
| 5775 | { return 999; } |
| 5776 | const playerChunkX = Math.floor(local.tileX / CHUNK_SIZE); |
| 5777 | const playerChunkY = Math.floor(local.tileY / CHUNK_SIZE); |
| 5778 | return Math.abs(chunkX - playerChunkX) + Math.abs(chunkY - playerChunkY); |
| 5779 | } |
| 5780 | |
| 5781 | #queueCanvasTextureWarm (canvas, chunkX, chunkY) |
| 5782 | { |
| 5783 | if (!canvas || this.#pendingTextureCanvasSet.has(canvas)) |
| 5784 | { return; } |
| 5785 | this.#pendingTextureCanvasSet.add(canvas); |
| 5786 | this.#pendingTextureCanvases.push({ |
| 5787 | canvas, |
| 5788 | priority: this.#chunkTextureWarmPriority(chunkX, chunkY) |
| 5789 | }); |
| 5790 | this.#scheduleTextureWarm(); |
| 5791 | } |
| 5792 | |
| 5793 | #queueBakedChunkTextures (baked, chunkX, chunkY) |
| 5794 | { |
| 5795 | if (!baked) |
| 5796 | { return; } |
| 5797 | const refs = baked.atlasCacheRefs; |
| 5798 | const maybeWarm = (canvas, entry) => |
| 5799 | { |
| 5800 | if (!canvas) |
| 5801 | { return; } |
| 5802 | if (entry && this.#atlasCache.isWarmed(canvas)) |
| 5803 | { return; } |
| 5804 | this.#queueCanvasTextureWarm(canvas, chunkX, chunkY); |
| 5805 | }; |
| 5806 | maybeWarm(baked.groundCanvas, refs?.ground); |
| 5807 | for (let row = 0; row < (baked.blockCanvases ?? []).length; row++) |
| 5808 | { maybeWarm(baked.blockCanvases[row], refs?.blockRows?.[row]); } |
| 5809 | maybeWarm(baked.bloomCanvas, refs?.bloom); |
| 5810 | this.#queueCanvasTextureWarm(baked.lightmapCanvas, chunkX, chunkY); |
| 5811 | this.#queueCanvasTextureWarm(baked.natureCanvas, chunkX, chunkY); |
| 5812 | } |
| 5813 | |
| 5814 | #scheduleTextureWarm () |
| 5815 | { |
| 5816 | if (this.#textureWarmRaf) |
| 5817 | { return; } |
| 5818 | this.#textureWarmRaf = requestAnimationFrame(() => this.#flushTextureWarm()); |
| 5819 | } |
| 5820 | |
| 5821 | #flushTextureWarm () |
| 5822 | { |
| 5823 | this.#textureWarmRaf = 0; |
| 5824 | if (!this.#pendingTextureCanvases.length) |
| 5825 | { return; } |
| 5826 | this.#pendingTextureCanvases.sort((a, b) => a.priority - b.priority); |
| 5827 | const batch = this.#pendingTextureCanvases.splice(0, this.#TEXTURE_WARM_BATCH); |
| 5828 | for (const entry of batch) |
| 5829 | { |
| 5830 | this.#pendingTextureCanvasSet.delete(entry.canvas); |
| 5831 | setNearestFilter(this.scene, entry.canvas); |
| 5832 | this.#atlasCache.markWarmed(entry.canvas); |
| 5833 | } |
| 5834 | if (this.#pendingTextureCanvases.length) |
| 5835 | { this.#scheduleTextureWarm(); } |
| 5836 | } |
| 5837 | |
| 5838 | #applyAtlasLighting (object, lightmapImage, lightRow, natureImage = null) |
| 5839 | { |
| 5840 | if (!object?.renderer) |
| 5841 | { return; } |
| 5842 | object._lit = true; |
| 5843 | object.renderer.shader = getAtlasLightingShader(); |
| 5844 | const useNature = natureImage != null && lightRow < 0; |
| 5845 | object.renderer.bumpMap = useNature ? natureImage : null; |
| 5846 | object.renderer.secondaryMap = lightmapImage; |
| 5847 | object.renderer.shaderUniforms = { |
| 5848 | u_ambientDark: 0, |
| 5849 | u_lightRow: lightRow, |
| 5850 | u_useNature: useNature ? 1 : 0, |
| 5851 | u_natureTint: 0, |
| 5852 | u_natureDark: 0, |
| 5853 | u_natureContrast: 1, |
| 5854 | ...(useNature ? natureTintUniforms() : {}) |
| 5855 | }; |
| 5856 | } |
| 5857 | |
| 5858 | /** |
| 5859 | * One-shot nature tint bake (editor chunk-save). Fills noise for each chunk |
| 5860 | * and its halo neighbors, and enables tint on the ground atlas. |
| 5861 | * @param {Iterable<{ chunkX: number, chunkY: number }>} chunks |
| 5862 | */ |
| 5863 | bakeNatureTintForChunks (chunks) |
| 5864 | { |
| 5865 | const seen = new Set(); |
| 5866 | for (const entry of chunks ?? []) |
| 5867 | { |
| 5868 | const chunkX = entry?.chunkX; |
| 5869 | const chunkY = entry?.chunkY; |
| 5870 | if (!Number.isFinite(chunkX) || !Number.isFinite(chunkY)) |
| 5871 | { continue; } |
| 5872 | for (let dy = -1; dy <= 1; dy++) |
| 5873 | { |
| 5874 | for (let dx = -1; dx <= 1; dx++) |
| 5875 | { |
| 5876 | const key = `${chunkX + dx},${chunkY + dy}`; |
| 5877 | if (seen.has(key)) |
| 5878 | { continue; } |
| 5879 | seen.add(key); |
| 5880 | const baked = this.bakedChunks.get(key); |
| 5881 | const snapshot = this.chunks.get(key); |
| 5882 | if (!baked?.natureCanvas || !snapshot) |
| 5883 | { continue; } |
| 5884 | if (this.#fillNatureNoise(baked, snapshot) || baked.natureTintReady) |
| 5885 | { |
| 5886 | if (baked.groundObject) |
| 5887 | { |
| 5888 | this.#applyAtlasLighting( |
| 5889 | baked.groundObject, |
| 5890 | baked.lightmapImage, |
| 5891 | -1, |
| 5892 | baked.natureImage |
| 5893 | ); |
| 5894 | } |
| 5895 | } |
| 5896 | } |
| 5897 | } |
| 5898 | } |
| 5899 | } |
| 5900 | |
| 5901 | /** Rebuild nature noise for a chunk and neighbors (halo needs adjacent grounds). */ |
| 5902 | #refreshNatureNoiseAround (chunkX, chunkY) |
| 5903 | { |
| 5904 | if (!this.natureTintEnabled) |
| 5905 | { return; } |
| 5906 | for (let dy = -1; dy <= 1; dy++) |
| 5907 | { |
| 5908 | for (let dx = -1; dx <= 1; dx++) |
| 5909 | { |
| 5910 | const cx = chunkX + dx; |
| 5911 | const cy = chunkY + dy; |
| 5912 | const baked = this.bakedChunks.get(`${cx},${cy}`); |
| 5913 | const snapshot = this.chunks.get(`${cx},${cy}`); |
| 5914 | if (!baked?.natureCanvas || !snapshot) |
| 5915 | { continue; } |
| 5916 | if (this.#fillNatureNoise(baked, snapshot) && baked.groundObject) |
| 5917 | { this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1, baked.natureImage); } |
| 5918 | } |
| 5919 | } |
| 5920 | } |
| 5921 | |
| 5922 | /** |
| 5923 | * Hash of grounds sampled by the nature canvas (chunk + pad halo). |
| 5924 | * Used to skip Perlin refill when nothing under the noise map changed. |
| 5925 | */ |
| 5926 | #natureSourceHash (snapshot) |
| 5927 | { |
| 5928 | let hash = 2166136261; |
| 5929 | const baseX = snapshot.chunkX * CHUNK_SIZE; |
| 5930 | const baseY = snapshot.chunkY * CHUNK_SIZE; |
| 5931 | const pad = NATURE_NOISE_PAD; |
| 5932 | for (let ly = -pad; ly < CHUNK_SIZE + pad; ly++) |
| 5933 | { |
| 5934 | for (let lx = -pad; lx < CHUNK_SIZE + pad; lx++) |
| 5935 | { |
| 5936 | const ground = this.#groundAtTile(baseX + lx, baseY + ly); |
| 5937 | const typeId = ground == null ? -1 : (normalizeGround(ground).typeId ?? -1); |
| 5938 | hash ^= (typeId + 1) >>> 0; |
| 5939 | hash = Math.imul(hash, 16777619); |
| 5940 | } |
| 5941 | } |
| 5942 | return hash >>> 0; |
| 5943 | } |
| 5944 | |
| 5945 | /** |
| 5946 | * @returns {boolean} true when the nature canvas was rewritten |
| 5947 | */ |
| 5948 | #fillNatureNoise (baked, snapshot) |
| 5949 | { |
| 5950 | if (!baked?.natureCanvas || !snapshot) |
| 5951 | { return false; } |
| 5952 | const sourceHash = this.#natureSourceHash(snapshot); |
| 5953 | if (baked.natureSourceHash === sourceHash && baked.natureTintReady && baked.natureImage) |
| 5954 | { return false; } |
| 5955 | |
| 5956 | const canvas = baked.natureCanvas; |
| 5957 | if (canvas.width !== NATURE_NOISE_SIZE || canvas.height !== NATURE_NOISE_SIZE) |
| 5958 | { |
| 5959 | canvas.width = NATURE_NOISE_SIZE; |
| 5960 | canvas.height = NATURE_NOISE_SIZE; |
| 5961 | } |
| 5962 | const scale = NATURE_TINT.scale; |
| 5963 | const ctx = canvas.getContext("2d"); |
| 5964 | const pixelCount = NATURE_NOISE_SIZE * NATURE_NOISE_SIZE * 4; |
| 5965 | if (!baked.naturePixels || baked.naturePixels.length !== pixelCount) |
| 5966 | { baked.naturePixels = new Uint8ClampedArray(pixelCount); } |
| 5967 | const pixels = baked.naturePixels; |
| 5968 | if (!baked.natureImageData || baked.natureImageData.data !== pixels) |
| 5969 | { baked.natureImageData = new ImageData(pixels, NATURE_NOISE_SIZE, NATURE_NOISE_SIZE); } |
| 5970 | const baseX = snapshot.chunkX * CHUNK_SIZE; |
| 5971 | const baseY = snapshot.chunkY * CHUNK_SIZE; |
| 5972 | const pad = NATURE_NOISE_PAD; |
| 5973 | for (let py = 0; py < NATURE_NOISE_SIZE; py++) |
| 5974 | { |
| 5975 | for (let px = 0; px < NATURE_NOISE_SIZE; px++) |
| 5976 | { |
| 5977 | const lx = px - pad; |
| 5978 | const ly = py - pad; |
| 5979 | const worldX = baseX + lx; |
| 5980 | const worldY = baseY + ly; |
| 5981 | const ground = this.#groundAtTile(worldX, worldY); |
| 5982 | const typeId = ground == null ? null : normalizeGround(ground).typeId; |
| 5983 | const blendable = typeId != null && !!GROUND_DEFINITIONS[typeId]?.blendable; |
| 5984 | const n = natureNoise01(worldX, worldY, scale); |
| 5985 | const i = (py * NATURE_NOISE_SIZE + px) * 4; |
| 5986 | const v = Math.round(n * 255); |
| 5987 | pixels[i] = v; |
| 5988 | pixels[i + 1] = v; |
| 5989 | pixels[i + 2] = v; |
| 5990 | pixels[i + 3] = blendable ? 255 : 0; |
| 5991 | } |
| 5992 | } |
| 5993 | ctx.putImageData(baked.natureImageData, 0, 0); |
| 5994 | invalidateCanvasTexture(this.scene, baked.natureCanvas); |
| 5995 | this.#queueCanvasTextureWarm(baked.natureCanvas, snapshot.chunkX, snapshot.chunkY); |
| 5996 | if (!baked.natureImage) |
| 5997 | { baked.natureImage = frameworkImageFromCanvas(baked.natureCanvas); } |
| 5998 | baked.natureSourceHash = sourceHash; |
| 5999 | baked.natureTintReady = true; |
| 6000 | return true; |
| 6001 | } |
| 6002 | |
| 6003 | #syncCliffGroundTopSprite (object, darkness, groundImage, localX, localY) |
| 6004 | { |
| 6005 | if (!object?.renderer) |
| 6006 | { return; } |
| 6007 | object._lit = true; |
| 6008 | const dark = Math.min(1, Math.max(0, darkness ?? 0)); |
| 6009 | object.renderer.bumpMap = groundImage ?? null; |
| 6010 | object.renderer.secondaryMap = null; |
| 6011 | const uniforms = this.#ensureUniformBag(object.renderer, getCliffGroundTopShader(), "cliffTop"); |
| 6012 | uniforms.u_darkness = dark; |
| 6013 | this.#writeUniformVec2(uniforms, "u_tileLocal", localX, localY); |
| 6014 | } |
| 6015 | |
| 6016 | #layoutBakedChunk (snapshot) |
| 6017 | { |
| 6018 | const key = `${snapshot.chunkX},${snapshot.chunkY}`; |
| 6019 | const baked = this.bakedChunks.get(key); |
| 6020 | if (!baked) |
| 6021 | { return; } |
| 6022 | const size = this.tileSize(); |
| 6023 | const left = snapshot.chunkX * CHUNK_SIZE * size; |
| 6024 | const top = snapshot.chunkY * CHUNK_SIZE * size; |
| 6025 | const chunkPx = CHUNK_SIZE * size; |
| 6026 | baked.groundObject.transform.position.x = left + chunkPx / 2; |
| 6027 | baked.groundObject.transform.position.y = top + chunkPx / 2; |
| 6028 | baked.groundObject.transform.size = new vector(chunkPx, chunkPx); |
| 6029 | this.#setLayer(baked.groundObject, LAYER_GROUND); |
| 6030 | |
| 6031 | for (let row = 0; row < CHUNK_SIZE; row++) |
| 6032 | { |
| 6033 | const object = baked.blockObjects[row]; |
| 6034 | const rowY = top + row * size + size / 2; |
| 6035 | object.transform.position.x = left + chunkPx / 2; |
| 6036 | object.transform.position.y = rowY; |
| 6037 | object.transform.size = new vector(chunkPx, size); |
| 6038 | this.#setLayer(object, this.#depthLayer(rowY, SORT_BLOCK)); |
| 6039 | } |
| 6040 | |
| 6041 | baked.bloomObject.transform.position.x = left + chunkPx / 2; |
| 6042 | baked.bloomObject.transform.position.y = top + chunkPx / 2; |
| 6043 | baked.bloomObject.transform.size = new vector(chunkPx, chunkPx); |
| 6044 | this.#setLayer(baked.bloomObject, this.#depthLayer(top + chunkPx, SORT_BLOCK)); |
| 6045 | baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM; |
| 6046 | this.#layoutFluidAtlasObject(baked, "ground"); |
| 6047 | this.#layoutFluidAtlasObject(baked, "bloom"); |
| 6048 | } |
| 6049 | |
| 6050 | #destroyBakedChunk (key) |
| 6051 | { |
| 6052 | const baked = this.bakedChunks.get(key); |
| 6053 | if (!baked) |
| 6054 | { return; } |
| 6055 | this.#releaseBakedAtlasRefs(baked); |
| 6056 | this.#destroyFluidAtlasSlot(baked); |
| 6057 | baked.groundObject?.destroy(); |
| 6058 | for (const object of baked.blockObjects ?? []) |
| 6059 | { object.destroy(); } |
| 6060 | baked.bloomObject?.destroy(); |
| 6061 | invalidateCanvasTexture(this.scene, baked.lightmapCanvas); |
| 6062 | invalidateCanvasTexture(this.scene, baked.natureCanvas); |
| 6063 | this.bakedChunks.delete(key); |
| 6064 | } |
| 6065 | |
| 6066 | #redrawPreview () |
| 6067 | { |
| 6068 | if (!this.preview) |
| 6069 | { return; } |
| 6070 | const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`); |
| 6071 | if (snapshot) |
| 6072 | { this.#rebuildChunk(snapshot); } |
| 6073 | } |
| 6074 | |
| 6075 | #refreshWaterCoastsNear (chunkX, chunkY) |
| 6076 | { |
| 6077 | const timeSec = performance.now() / 1000; |
| 6078 | for (const objects of this.tiles.values()) |
| 6079 | { |
| 6080 | if (!objects.ground) |
| 6081 | { continue; } |
| 6082 | const fluid = isWaterGround(objects.groundTypeId) || isLavaGround(objects.groundTypeId); |
| 6083 | if (!fluid) |
| 6084 | { continue; } |
| 6085 | if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1) |
| 6086 | { continue; } |
| 6087 | // Light intensity grid is visible light (1 − shade); fluid shaders use ambient=1. |
| 6088 | this.#syncGroundWaterFx(objects, 1, timeSec); |
| 6089 | } |
| 6090 | } |
| 6091 | |
| 6092 | #drawTile (tileX, tileY) |
| 6093 | { |
| 6094 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 6095 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 6096 | const snapshot = this.chunks.get(`${chunkX},${chunkY}`); |
| 6097 | if (!snapshot) |
| 6098 | { return; } |
| 6099 | const localX = tileX - chunkX * CHUNK_SIZE; |
| 6100 | const localY = tileY - chunkY * CHUNK_SIZE; |
| 6101 | const index = localY * CHUNK_SIZE + localX; |
| 6102 | const key = `${tileX},${tileY}`; |
| 6103 | let objects = this.tiles.get(key); |
| 6104 | if (!objects) |
| 6105 | { |
| 6106 | objects = { chunkX, chunkY, tileX, tileY }; |
| 6107 | this.tiles.set(key, objects); |
| 6108 | } |
| 6109 | objects.tileX = tileX; |
| 6110 | objects.tileY = tileY; |
| 6111 | objects.chunkX = chunkX; |
| 6112 | objects.chunkY = chunkY; |
| 6113 | objects.light = snapshot.light[index] ?? 0; |
| 6114 | |
| 6115 | const baked = this.bakedChunks.get(`${chunkX},${chunkY}`); |
| 6116 | const animatedGround = (baked?.animatedGrounds ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY); |
| 6117 | if (animatedGround) |
| 6118 | { |
| 6119 | objects.ground = this.#ensureSprite(objects.ground, animatedGround.sprite, LAYER_GROUND); |
| 6120 | if (objects.ground) |
| 6121 | { |
| 6122 | const size = this.tileSize(); |
| 6123 | objects.ground.transform.position.x = tileX * size + size / 2; |
| 6124 | objects.ground.transform.position.y = tileY * size + size / 2; |
| 6125 | objects.ground.transform.size = new vector(size, size); |
| 6126 | this.#setLayer(objects.ground, LAYER_GROUND); |
| 6127 | objects.groundTypeId = animatedGround.typeId; |
| 6128 | this.#syncGroundWaterFx(objects, 1, performance.now() / 1000); |
| 6129 | } |
| 6130 | if (animatedGround.bloom) |
| 6131 | { objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, animatedGround.bloom, tilePivot(tileX, tileY, this.tileSize()), LAYER_GROUND); } |
| 6132 | else if (!isLavaGround(animatedGround.typeId)) |
| 6133 | { |
| 6134 | objects.groundBloom?.destroy(); |
| 6135 | objects.groundBloom = null; |
| 6136 | } |
| 6137 | } |
| 6138 | else |
| 6139 | { |
| 6140 | objects.ground?.destroy(); |
| 6141 | objects.ground = null; |
| 6142 | objects.groundBloom?.destroy(); |
| 6143 | objects.groundBloom = null; |
| 6144 | this.#clearLavaBloom(objects); |
| 6145 | objects.groundTypeId = null; |
| 6146 | objects.waterEdges = null; |
| 6147 | objects._fluidCoastCache = null; |
| 6148 | objects._fluidAtlasHidden = false; |
| 6149 | } |
| 6150 | |
| 6151 | let blockSource = snapshot.blocks[index]; |
| 6152 | if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY && this.preview.block !== undefined) |
| 6153 | { bl |
| 6154 | … afgekapt |