import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX, ENTITY_STACK_SPREAD_DIAMETER_PX } from "/shared/protocol/constants.js"; import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js"; import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js"; import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js"; import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemDefinition } from "/shared/definitions/items.js"; import { resolveItemTint, resolveEquipTint, resolveItemDualTint, normalizeRgb } from "/shared/render/tint.js"; import { normalizeGround, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, isBlockOccludingLight } from "/shared/definitions/tiles.js"; import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js"; import { bakeChunkAtlases } from "./chunkBake.js"; import { frameworkImageFromCanvas, invalidateCanvasTexture } from "./canvasSprite.js"; import { applyNearestToAllTextures, setNearestFilter } from "./sprites.js"; import { SeasonId, seasonIdAt } from "/shared/world/season.js"; const LAYER_GROUND = 0; const LAYER_EDGE = 900000; const SORT_BLOCK = 2; const SORT_ENTITY = 3; const SORT_HP_BAR = 4; const SORT_FX = 5; const RENDER_LAYER_BLOOM = "bloom"; const HP_BAR_W = 14; const HP_BAR_H = 4; const WALK_TILT_DEG = 6; const RUN_TILT_DEG = 8; const SHOVE_TILE_FRACTION = 0.25; const SHOVE_MS = 280; /** Soft reflow when stack circle targets change (join/leave a shared tile). */ const STACK_SPREAD_LERP_MS = 280; /** Hold gather-tool equip overlay slightly past swing interval so it stays visible between swings. */ const GATHER_TOOL_HOLD_MS = 1100; const DAMAGE_FLASH_MS = 180; const DAMAGE_FLOAT_MS = 900; const SKILL_LEVEL_FLOAT_MS = 2800; const SPRITE_LIGHTING_FRAG = [ "precision mediump float;", "varying vec2 v_texCoord;", "uniform sampler2D u_texture;", "uniform float u_darkness;", "uniform float u_strength;", "uniform float u_wade;", "uniform float u_spriteHeight;", "void main() {", " vec4 color = texture2D(u_texture, v_texCoord);", " if (color.a <= 0.0) { discard; }", " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);", " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }", " vec3 rgb = color.rgb;", " if (u_wade > 0.5 && fromBottom < 5.0) {", " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);", " }", " rgb = mix(rgb, vec3(0.0), u_darkness);", " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);", " gl_FragColor = vec4(rgb, color.a);", "}" ].join("\n"); const WATER_GROUND_FRAG = [ "precision mediump float;", "varying vec2 v_texCoord;", "uniform sampler2D u_texture;", "uniform float u_ambientDark;", "uniform float u_litNW;", "uniform float u_litNE;", "uniform float u_litSW;", "uniform float u_litSE;", "uniform float u_time;", "uniform float u_edgeN;", "uniform float u_edgeE;", "uniform float u_edgeS;", "uniform float u_edgeW;", "void main() {", " vec4 color = texture2D(u_texture, v_texCoord);", " if (color.a <= 0.0) { discard; }", " vec3 rgb = color.rgb;", " float foam = 0.0;", " float pulse = 0.55 + 0.45 * sin(u_time * 3.2 + v_texCoord.x * 18.0 + v_texCoord.y * 10.0);", " if (u_edgeN > 0.5 && v_texCoord.y < 0.22) {", " foam = max(foam, (1.0 - v_texCoord.y / 0.22) * pulse);", " }", " if (u_edgeS > 0.5 && v_texCoord.y > 0.78) {", " foam = max(foam, ((v_texCoord.y - 0.78) / 0.22) * pulse);", " }", " if (u_edgeW > 0.5 && v_texCoord.x < 0.22) {", " foam = max(foam, (1.0 - v_texCoord.x / 0.22) * pulse);", " }", " if (u_edgeE > 0.5 && v_texCoord.x > 0.78) {", " foam = max(foam, ((v_texCoord.x - 0.78) / 0.22) * pulse);", " }", " rgb = mix(rgb, vec3(0.78, 0.92, 1.0), clamp(foam, 0.0, 0.85));", " float litTop = mix(u_litNW, u_litNE, v_texCoord.x);", " float litBottom = mix(u_litSW, u_litSE, v_texCoord.x);", " float lit = mix(litTop, litBottom, v_texCoord.y);", " float darkness = u_ambientDark * (1.0 - lit);", " rgb = mix(rgb, vec3(0.0), darkness);", " gl_FragColor = vec4(rgb, color.a);", "}" ].join("\n"); /** Magenta-tint (R==B, G < R) then lit effects; darkness always after tint. */ const TINT_LIT_SPRITE_FRAG = [ "precision mediump float;", "varying vec2 v_texCoord;", "uniform sampler2D u_texture;", "uniform float u_darkness;", "uniform float u_strength;", "uniform float u_wade;", "uniform float u_spriteHeight;", "uniform float u_useTint;", "uniform vec3 u_tintColor;", "void main() {", " vec4 color = texture2D(u_texture, v_texCoord);", " if (color.a <= 0.0) { discard; }", " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);", " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }", " vec3 rgb = color.rgb;", " if (u_useTint > 0.5) {", " if (abs(color.r - color.b) * 255.0 <= 2.01 && color.g < color.r) {", " float L = color.r;", " float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;", " float tintLuma = dot(u_tintColor, vec3(0.2126, 0.7152, 0.0722));", " rgb = mix(u_tintColor, vec3(tintLuma), gBlend) * L;", " }", " }", " if (u_wade > 0.5 && fromBottom < 5.0) {", " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);", " }", " rgb = mix(rgb, vec3(0.0), u_darkness);", " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);", " gl_FragColor = vec4(rgb, color.a);", "}" ].join("\n"); /** Dual-channel arrow tint: red = shaft, blue = tip, white unchanged; then darkness. */ const DUAL_TINT_LIT_SPRITE_FRAG = [ "precision mediump float;", "varying vec2 v_texCoord;", "uniform sampler2D u_texture;", "uniform float u_darkness;", "uniform float u_strength;", "uniform float u_wade;", "uniform float u_spriteHeight;", "uniform vec3 u_shaftTint;", "uniform vec3 u_tipTint;", "void main() {", " vec4 color = texture2D(u_texture, v_texCoord);", " if (color.a <= 0.0) { discard; }", " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);", " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }", " vec3 rgb = color.rgb;", " float tipMask = clamp((color.b - max(color.r, color.g)) * 1.75, 0.0, 1.0);", " if (tipMask > 0.0) {", " float L = color.b;", " float gBlend = L > 0.0 ? clamp(color.g / L, 0.0, 1.0) : 0.0;", " float tipLuma = dot(u_tipTint, vec3(0.2126, 0.7152, 0.0722));", " vec3 tipCol = mix(u_tipTint, vec3(tipLuma), gBlend) * L;", " rgb = mix(rgb, tipCol, tipMask);", " }", " float shaftMask = clamp((color.r - max(color.g, color.b)) * 1.75, 0.0, 1.0);", " if (shaftMask > 0.0) {", " float L = color.r;", " float gBlend = L > 0.0 ? clamp(color.g / L, 0.0, 1.0) : 0.0;", " float shaftLuma = dot(u_shaftTint, vec3(0.2126, 0.7152, 0.0722));", " vec3 shaftCol = mix(u_shaftTint, vec3(shaftLuma), gBlend) * L;", " rgb = mix(rgb, shaftCol, shaftMask);", " }", " if (u_wade > 0.5 && fromBottom < 5.0) {", " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);", " }", " rgb = mix(rgb, vec3(0.0), u_darkness);", " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);", " gl_FragColor = vec4(rgb, color.a);", "}" ].join("\n"); const ATLAS_LIGHTING_FRAG = [ "precision mediump float;", "varying vec2 v_texCoord;", "uniform sampler2D u_texture;", "uniform sampler2D u_secondary;", "uniform float u_ambientDark;", "uniform float u_lightRow;", "void main() {", " vec4 color = texture2D(u_texture, v_texCoord);", " if (color.a <= 0.0) { discard; }", " vec2 lightUV = v_texCoord;", " if (u_lightRow >= 0.0) {", " lightUV.y = (u_lightRow + v_texCoord.y) / 16.0;", " }", " float lit = texture2D(u_secondary, lightUV).r;", " float darkness = u_ambientDark * (1.0 - lit);", " vec3 rgb = mix(color.rgb, vec3(0.0), darkness);", " gl_FragColor = vec4(rgb, color.a);", "}" ].join("\n"); let spriteLightingShader = null; let atlasLightingShader = null; let waterGroundShader = null; let tintLitSpriteShader = null; let dualTintLitSpriteShader = null; function getSpriteLightingShader () { if (!spriteLightingShader) { spriteLightingShader = Shader.fragment(SPRITE_LIGHTING_FRAG); } return spriteLightingShader; } function getAtlasLightingShader () { if (!atlasLightingShader) { atlasLightingShader = Shader.fragment(ATLAS_LIGHTING_FRAG); } return atlasLightingShader; } function getWaterGroundShader () { if (!waterGroundShader) { waterGroundShader = Shader.fragment(WATER_GROUND_FRAG); } return waterGroundShader; } function getTintLitSpriteShader () { if (!tintLitSpriteShader) { tintLitSpriteShader = Shader.fragment(TINT_LIT_SPRITE_FRAG); } return tintLitSpriteShader; } function getDualTintLitSpriteShader () { if (!dualTintLitSpriteShader) { dualTintLitSpriteShader = Shader.fragment(DUAL_TINT_LIT_SPRITE_FRAG); } return dualTintLitSpriteShader; } export class WorldView { constructor (game, scene, catalog = { grounds: {}, blocks: {} }) { this.game = game; this.scene = scene; this.catalog = catalog; this.preview = null; this.zoom = 2; this.chunks = new Map(); this.bakedChunks = new Map(); this.tiles = new Map(); this.entities = new Map(); this.groundItems = new Map(); this.edges = new Map(); this.localEntityId = null; this.localBlind = false; /** @type {"soft"|"simple"} */ this.lightingMode = "soft"; /** @type {boolean} */ this.bloomEnabled = true; this.settings = { ...DEFAULT_WORLD_SETTINGS }; this.worldHour = 12; /** Calendar season for seasonal ground/block visuals (`summer` / `fall` / `winter`). */ this.worldSeason = seasonIdAt(); this.nightPreview = null; this.followPlayer = true; this.dynamicLights = []; this.swipes = []; this.damageFloats = []; this.damageNumbersEl = document.getElementById("damage-numbers"); this.skillLevelFloats = []; this.skillLevelFloatsEl = document.getElementById("skill-level-floats"); /** @type {Map} */ this.editorSpawners = new Map(); this.spawnRangeHighlight = null; this.wanderRangeHighlight = null; this.#syncBloomLayer(); } setSettings (settings) { this.settings = { ...DEFAULT_WORLD_SETTINGS, ...settings }; this.#syncBloomLayer(); } /** * Client graphics prefs (lighting Soft/Simple, bloom On/Off). * @param {{ lighting?: string, bloom?: string }} prefs */ setGraphicsPrefs (prefs) { if (prefs?.lighting === "simple" || prefs?.lighting === "soft") { this.lightingMode = prefs.lighting; } if (prefs?.bloom === "off" || prefs?.bloom === "on") { const enabled = prefs.bloom !== "off"; if (enabled !== this.bloomEnabled) { this.bloomEnabled = enabled; this.#syncBloomLayer(); } else { this.bloomEnabled = enabled; } } } /** Apply server (or local) calendar season; rebakes chunks when it changes. */ setWorldSeason (season) { const next = season === SeasonId.fall || season === SeasonId.winter || season === SeasonId.summer ? season : seasonIdAt(); if (next === this.worldSeason) { return; } this.worldSeason = next; this.#rebakeAllChunks(); } setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null) { this.localEntityId = entityId; this.#upsertEntity({ entityId, characterId, tileX, tileY, gait, sex, firstName, lastName, layers: layers ?? undefined, ...(health != null ? { health } : {}), ...(maxHealth != null ? { maxHealth } : {}) }); } applySnapshot (snapshot) { const key = `${snapshot.chunkX},${snapshot.chunkY}`; this.chunks.set(key, snapshot); this.#rebuildChunk(snapshot); this.#redrawPreview(); this.#refreshWaterCoastsNear(snapshot.chunkX, snapshot.chunkY); if (snapshot.staticOnly) { this.#stripChunkDynamic(snapshot.chunkX, snapshot.chunkY); this.#rebuildAllEdges(); return; } for (const entity of snapshot.entities ?? []) { this.#upsertEntity(entity); } const chunkPrefix = `${snapshot.chunkX},${snapshot.chunkY}`; for (const [id, item] of [...this.groundItems.entries()]) { if (Math.floor(item.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(item.tileY / CHUNK_SIZE) === snapshot.chunkY) { this.despawnGroundItem(id); } } for (const item of snapshot.groundItems ?? []) { this.upsertGroundItem(item); } this.#rebuildAllEdges(); } #stripChunkDynamic (chunkX, chunkY) { for (const [id, item] of [...this.groundItems.entries()]) { if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY) { this.despawnGroundItem(id); } } for (const [id, entity] of [...this.entities.entries()]) { if (id === this.localEntityId) { continue; } if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY) { this.despawnEntity(id); } } } removeChunk (chunkX, chunkY) { const key = `${chunkX},${chunkY}`; this.chunks.delete(key); this.#destroyBakedChunk(key); this.#destroyEdges(key); const prefix = `${chunkX},${chunkY}:`; for (const [spawnerKey, entry] of [...this.editorSpawners.entries()]) { if (!spawnerKey.startsWith(prefix)) { continue; } entry.object?.destroy(); this.editorSpawners.delete(spawnerKey); } for (const [tileKey, objects] of [...this.tiles.entries()]) { if (objects.chunkX === chunkX && objects.chunkY === chunkY) { objects.ground?.destroy(); objects.groundBloom?.destroy(); objects.block?.destroy(); objects.blockBloom?.destroy(); this.tiles.delete(tileKey); } } for (const [id, item] of [...this.groundItems.entries()]) { if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY) { this.despawnGroundItem(id); } } // Server sends unsubscribeChunk when a chunk leaves the static 5×5 ring. // Entity replication is limited to the inner 3×3; static-only chunks strip dynamics via staticOnly snapshots. for (const [id, entity] of [...this.entities.entries()]) { if (id === this.localEntityId) { continue; } if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY) { this.despawnEntity(id); } } this.#rebuildAllEdges(); } setChunkOpen (chunkX, chunkY, open) { const snapshot = this.chunks.get(`${chunkX},${chunkY}`); if (!snapshot) { return; } snapshot.open = !!open; this.#rebuildAllEdges(); } spawnEntity (payload) { this.#upsertEntity(payload); } moveEntity (payload) { const existing = this.entities.get(payload.entityId); if (!existing) { this.#upsertEntity(payload); return; } const size = this.tileSize(); existing.fromX = existing.visualX; existing.fromY = existing.visualY; existing.shadeFromTileX = existing.tileX; existing.shadeFromTileY = existing.tileY; existing.tileX = payload.tileX; existing.tileY = payload.tileY; existing.gait = payload.gait; existing.freeFlight = !!payload.freeFlight || existing.freeFlight; if (payload.worldX != null && payload.worldY != null) { existing.worldX = payload.worldX; existing.worldY = payload.worldY; existing.targetX = payload.worldX * size; existing.targetY = payload.worldY * size; } else { const pivot = tilePivot(payload.tileX, payload.tileY, size); existing.targetX = pivot.x; existing.targetY = pivot.y; } existing.lerpStarted = performance.now(); existing.lerpMs = payload.lerpMs ?? this.#lerpMs(payload.gait); } despawnEntity (entityId) { const existing = this.entities.get(entityId); if (!existing) { return; } existing.object?.destroy(); existing.hpBar?.destroy(); for (const overlay of existing.overlays ?? []) { overlay.destroy(); } for (const overlay of existing.bloomOverlays ?? []) { overlay.destroy(); } this.entities.delete(entityId); } updateEntityHealth (entityId, health, maxHealth) { const entity = this.entities.get(entityId); if (!entity) { return; } entity.health = health; entity.maxHealth = maxHealth; this.#syncHpBar(entity); } flashDamage (entityId) { const entity = this.entities.get(entityId); if (!entity) { return; } entity.damageFlashUntil = performance.now() + DAMAGE_FLASH_MS; } spawnDamageNumber (entityId, damage) { const amount = damage | 0; if (amount <= 0) { return; } this.damageFloats.push({ entityId, damage: amount, started: performance.now() }); } spawnSkillLevelUp (entityId, payload) { const level = payload?.level | 0; if (level <= 0 || !payload?.icon) { return; } this.skillLevelFloats.push({ entityId, level, icon: payload.icon, displayName: payload.displayName ?? payload.skillId ?? "", started: performance.now() }); } setAppearance (payload) { const existing = this.entities.get(payload.entityId); if (!existing) { return; } existing.lightRadiusTiles = payload.lightRadiusTiles ?? 0; if (payload.visualScale != null) { existing.visualScale = Number(payload.visualScale) || 1; } this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]); this.#placeEntity(existing); } upsertGroundItem (payload) { const size = this.tileSize(); const pivot = tilePivot(payload.tileX, payload.tileY, size); const potion = payload.instance?.kind === "potion" ? payload.instance : null; const spriteName = potion ? spriteImageName("item", "potion", `potion-${Math.max(1, Math.min(5, potion.fillLevel | 0 || 4))}`) : (payload.sprite ?? itemSpriteName(payload.itemId, payload.instance)); let item = this.groundItems.get(payload.groundItemId); if (!item) { const object = new GameObject(0, 0, this.game.images[spriteName] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK); this.scene.addObject(object); item = { object }; this.groundItems.set(payload.groundItemId, item); } else if (item.object && this.game.images[spriteName]) { item.object.image = this.game.images[spriteName]; } item.groundItemId = payload.groundItemId; item.tileX = payload.tileX; item.tileY = payload.tileY; item.itemId = payload.itemId; item.quantity = payload.quantity; item.displayName = payload.displayName; item.sprite = spriteName; item.instance = payload.instance ?? null; const stack = { itemId: payload.itemId, instance: payload.instance ?? null }; item.dualTint = resolveItemDualTint(stack, itemDefinition(payload.itemId)); item.tintColor = item.dualTint ? null : resolveItemTint(stack, itemDefinition(payload.itemId)); this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK); this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0); } despawnGroundItem (groundItemId) { const item = this.groundItems.get(groundItemId); if (!item) { return; } item.object?.destroy(); this.groundItems.delete(groundItemId); } groundItemAtTile (tileX, tileY) { return this.groundItemsAtTile(tileX, tileY)[0] ?? null; } groundItemsAtTile (tileX, tileY) { const items = []; for (const item of this.groundItems.values()) { if (item.tileX === tileX && item.tileY === tileY) { items.push(item); } } return items; } entitiesAtTile (tileX, tileY) { const matches = []; for (const entity of this.entities.values()) { if (entity.tileX === tileX && entity.tileY === tileY) { matches.push(entity); } } matches.sort((a, b) => (b.object?.layer ?? 0) - (a.object?.layer ?? 0)); return matches; } setZoom (zoom, limits = { min: 2, max: 4 }) { const min = limits.min ?? 1; const max = limits.max ?? 4; this.zoom = Math.min(max, Math.max(min, zoom)); for (const snapshot of this.chunks.values()) { this.#layoutBakedChunk(snapshot); this.#rebuildChunk(snapshot); } const size = this.tileSize(); for (const entity of this.entities.values()) { entity.visualX = tilePivot(entity.tileX, entity.tileY, size).x; entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y; entity.fromX = entity.visualX; entity.fromY = entity.visualY; entity.targetX = entity.visualX; entity.targetY = entity.visualY; entity.lerpStarted = null; this.#placeEntity(entity); } for (const item of this.groundItems.values()) { const pivot = tilePivot(item.tileX, item.tileY, size); this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK); } this.#rebuildAllEdges(); this.#redrawPreview(); this.#relayoutEditorSpawners(); this.#relayoutSpawnRangeHighlight(); applyNearestToAllTextures(this.scene, this.game.images); } tileSize () { return SPRITE_SIZE_PX * this.zoom; } screenToTile (mouseX, mouseY) { const size = this.tileSize(); const worldX = mouseX - this.scene.cameraPosition.x; const worldY = mouseY - this.scene.cameraPosition.y; return { tileX: Math.floor(worldX / size), tileY: Math.floor(worldY / size) }; } entityAtScreen (mouseX, mouseY) { let best = null; let bestLayer = -Infinity; for (const entity of this.entities.values()) { const box = this.#entityScreenBox(entity); if (!box) { continue; } if (mouseX >= box.left && mouseX < box.right && mouseY >= box.top && mouseY < box.bottom) { const layer = entity.object?.layer ?? 0; if (layer >= bestLayer) { best = entity; bestLayer = layer; } } } return best; } nametagAnchor (entity) { const box = this.#entityScreenBox(entity); if (!box) { return null; } return { x: (box.left + box.right) / 2, y: box.top }; } #entityScreenBox (entity) { const object = entity?.object; if (!object) { return null; } const size = object.transform.size; const x = object.transform.position.x + this.scene.cameraPosition.x; const y = object.transform.position.y + this.scene.cameraPosition.y; return { left: x - size.x / 2, right: x + size.x / 2, top: y - size.y / 2, bottom: y + size.y / 2 }; } update (deltaTime) { const now = performance.now(); const size = this.tileSize(); this.#refreshStackTargets(); for (const entity of this.entities.values()) { const target = entity.targetX != null && entity.targetY != null ? { x: entity.targetX, y: entity.targetY } : tilePivot(entity.tileX, entity.tileY, size); if (entity.lerpStarted != null) { const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs)); entity.visualX = entity.fromX + (target.x - entity.fromX) * t; entity.visualY = entity.fromY + (target.y - entity.fromY) * t; if (t >= 1) { entity.lerpStarted = null; } } else { entity.visualX = target.x; entity.visualY = target.y; } this.#updateStackOffset(entity, now); this.#updateShove(entity, now, size); this.#expireGatherToolOverlay(entity, now); this.#placeEntity(entity, now); } this.#updateSwipes(now); this.#updateDamageNumbers(now); this.#updateSkillLevelFloats(now); this.#centerCamera(); this.#cullOffscreenDrawables(); this.#updateShade(deltaTime); } /** * Desired circle offsets for stacked entities (applied via {@link #updateStackOffset}). * Stable assignment by entityId; free-flight entities stay unshifted. */ #refreshStackTargets () { const byTile = new Map(); for (const entity of this.entities.values()) { if (entity.freeFlight) { entity.stackTargetX = 0; entity.stackTargetY = 0; continue; } const key = `${entity.tileX},${entity.tileY}`; let list = byTile.get(key); if (!list) { list = []; byTile.set(key, list); } list.push(entity); } const radius = (ENTITY_STACK_SPREAD_DIAMETER_PX * this.zoom) / 2; for (const list of byTile.values()) { if (list.length <= 1) { for (const entity of list) { entity.stackTargetX = 0; entity.stackTargetY = 0; } continue; } list.sort((a, b) => String(a.entityId).localeCompare(String(b.entityId))); const n = list.length; for (let i = 0; i < n; i++) { const angle = -Math.PI / 2 + (Math.PI * 2 * i) / n; list[i].stackTargetX = Math.cos(angle) * radius; list[i].stackTargetY = Math.sin(angle) * radius; } } } #updateStackOffset (entity, now) { const tx = entity.stackTargetX ?? 0; const ty = entity.stackTargetY ?? 0; const cx = entity.stackOffsetX ?? 0; const cy = entity.stackOffsetY ?? 0; if (entity.stackLerpToX !== tx || entity.stackLerpToY !== ty) { entity.stackFromX = cx; entity.stackFromY = cy; entity.stackLerpToX = tx; entity.stackLerpToY = ty; entity.stackLerpStarted = now; } if (entity.stackLerpStarted == null) { entity.stackOffsetX = tx; entity.stackOffsetY = ty; return; } const t = Math.min(1, (now - entity.stackLerpStarted) / STACK_SPREAD_LERP_MS); entity.stackOffsetX = entity.stackFromX + (tx - entity.stackFromX) * t; entity.stackOffsetY = entity.stackFromY + (ty - entity.stackFromY) * t; if (t >= 1) { entity.stackOffsetX = tx; entity.stackOffsetY = ty; entity.stackLerpStarted = null; } } #updateShove (entity, now, tileSize) { if (!entity.shove) { entity.shoveOffsetX = 0; entity.shoveOffsetY = 0; return; } const elapsed = now - entity.shove.started; const t = Math.min(1, elapsed / entity.shove.durationMs); const maxDist = tileSize * SHOVE_TILE_FRACTION; const dx = entity.shove.targetVisualX - entity.shove.startVisualX; const dy = entity.shove.targetVisualY - entity.shove.startVisualY; const dist = Math.hypot(dx, dy) || 1; const ux = dx / dist; const uy = dy / dist; let phase; if (t < 0.45) { phase = t / 0.45; } else { phase = 1 - (t - 0.45) / 0.55; } entity.shoveOffsetX = ux * maxDist * phase; entity.shoveOffsetY = uy * maxDist * phase; if (t >= 1) { entity.shove = null; } } spawnCombatSwing (payload) { const attacker = this.entities.get(payload.attackerId); const target = this.entities.get(payload.targetId); if (!attacker || !target) { return; } const ax = attacker.visualX + (attacker.stackOffsetX ?? 0); const ay = attacker.visualY + (attacker.stackOffsetY ?? 0); const tx = target.visualX + (target.stackOffsetX ?? 0); const ty = target.visualY + (target.stackOffsetY ?? 0); this.#applyShove(attacker, tx, ty); const midX = (ax + tx) / 2; const midY = (ay + ty) / 2; const sortY = Math.max(ay, ty) + 0.02; const angle = Math.atan2(ty - ay, tx - ax) * (180 / Math.PI); const spriteName = "fx:melee-swipe:melee-swipe"; const object = new GameObject(0, 0, this.game.images[spriteName], SORT_FX); if (object.transform) { object.transform.rotation = angle; } this.scene.addObject(object); this.#placePivoted(object, midX, midY, sortY, SORT_FX); this.#applyPhysicalCombatFxDarkness(object, payload.fromTileX, payload.fromTileY, payload.tileX, payload.tileY); this.swipes.push({ object, until: performance.now() + 500, fromTileX: payload.fromTileX, fromTileY: payload.fromTileY, tileX: payload.tileX, tileY: payload.tileY }); } /** Mining / gathering lunge toward a tile — shove only, no swipe FX. */ spawnGatherSwing (payload) { const attacker = this.entities.get(payload.attackerId); if (!attacker) { return; } const pivot = tilePivot(payload.tileX, payload.tileY, this.tileSize()); this.#applyShove(attacker, pivot.x, pivot.y); if (payload.toolItemId != null) { this.#setGatherToolOverlay(attacker, payload.toolItemId); } } #applyShove (entity, targetVisualX, targetVisualY) { entity.shove = { startVisualX: entity.visualX, startVisualY: entity.visualY, targetVisualX, targetVisualY, started: performance.now(), durationMs: SHOVE_MS }; } /** Physical combat FX (melee swipes, ranged projectiles). Magic spells stay unshaded. */ spawnPhysicalProjectileFx (payload) { const spriteName = payload.sprite ?? "fx:projectile:arrow"; const image = this.game.images[spriteName]; if (!image) { return; } const dualTint = this.#dualTintFromPayload(payload); const fromPivot = tilePivot(payload.fromTileX, payload.fromTileY, this.tileSize()); const toPivot = tilePivot(payload.tileX, payload.tileY, this.tileSize()); const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02; const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI); const object = new GameObject(0, 0, image, SORT_FX); if (object.transform) { object.transform.rotation = angle; } this.scene.addObject(object); this.#placePivoted(object, fromPivot.x, fromPivot.y, sortY, SORT_FX); this.#applyPhysicalCombatFxDarkness( object, payload.fromTileX, payload.fromTileY, payload.tileX, payload.tileY, dualTint ); const started = performance.now(); const durationMs = payload.durationMs ?? 400; this.swipes.push({ object, until: started + durationMs, started, durationMs, lerp: true, dualTint, fromTileX: payload.fromTileX, fromTileY: payload.fromTileY, tileX: payload.tileX, tileY: payload.tileY }); } addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 1, durationMs = 250 }) { this.dynamicLights.push({ tileX: Math.floor(worldX), tileY: Math.floor(worldY), range: radiusTiles, intensity, until: performance.now() + durationMs }); } updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {}) { const snapshot = this.chunks.get(`${chunkX},${chunkY}`); if (!snapshot) { return; } const index = localY * CHUNK_SIZE + localX; if (ground !== undefined) { snapshot.grounds[index] = ground; } if (block !== undefined) { snapshot.blocks[index] = block; } if (light !== undefined) { snapshot.light[index] = light; } this.#rebuildChunk(snapshot); } /** * Editor-only mob markers for authored spawners (invisible during play). * @param {number} chunkX * @param {number} chunkY * @param {Array<{ localX: number, localY: number, config?: { mobTypeId?: string } }>} spawners * @param {(mobTypeId: string) => string} resolveSprite */ setEditorSpawners (chunkX, chunkY, spawners, resolveSprite) { const prefix = `${chunkX},${chunkY}:`; for (const [key, entry] of [...this.editorSpawners.entries()]) { if (!key.startsWith(prefix)) { continue; } entry.object?.destroy(); this.editorSpawners.delete(key); } for (const spawner of spawners ?? []) { const tileX = chunkX * CHUNK_SIZE + spawner.localX; const tileY = chunkY * CHUNK_SIZE + spawner.localY; const spriteName = resolveSprite?.(spawner.config?.mobTypeId) ?? null; if (!spriteName) { continue; } const key = `${prefix}${spawner.localX},${spawner.localY}`; const object = this.#ensureSprite(null, spriteName, SORT_ENTITY); if (!object) { continue; } object.renderer.alpha = 0.85; const pivot = tilePivot(tileX, tileY, this.tileSize()); this.#placePivoted(object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY); this.#markUnlit(object); this.editorSpawners.set(key, { object, tileX, tileY, spriteName }); } } clearEditorSpawners () { for (const entry of this.editorSpawners.values()) { entry.object?.destroy(); } this.editorSpawners.clear(); } #relayoutEditorSpawners () { const size = this.tileSize(); for (const entry of this.editorSpawners.values()) { if (!entry.object) { continue; } const pivot = tilePivot(entry.tileX, entry.tileY, size); this.#placePivoted(entry.object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY); } } /** * Editor-only range overlays: spawn (inner) and wander (outer, Chebyshev squares). */ setSpawnRangeHighlight (tileX, tileY, spawnRange, wanderRange = null) { const spawnRadius = Math.max(0, spawnRange | 0); const wanderRadius = Math.max(spawnRadius, wanderRange == null ? spawnRadius : (wanderRange | 0)); if (this.spawnRangeHighlight && this.wanderRangeHighlight && this.spawnRangeHighlight.tileX === tileX && this.spawnRangeHighlight.tileY === tileY && this.spawnRangeHighlight.range === spawnRadius && this.wanderRangeHighlight.range === wanderRadius) { this.#relayoutSpawnRangeHighlight(); return; } this.clearSpawnRangeHighlight(); const wanderObject = this.#ensureSprite(null, "wander-range", LAYER_EDGE); const spawnObject = this.#ensureSprite(null, "spawn-range", LAYER_EDGE); if (wanderObject) { this.#markUnlit(wanderObject); wanderObject.renderer.alpha = 1; this.wanderRangeHighlight = { object: wanderObject, tileX, tileY, range: wanderRadius }; } if (spawnObject) { this.#markUnlit(spawnObject); spawnObject.renderer.alpha = 1; this.spawnRangeHighlight = { object: spawnObject, tileX, tileY, range: spawnRadius }; } this.#relayoutSpawnRangeHighlight(); } clearSpawnRangeHighlight () { this.spawnRangeHighlight?.object?.destroy(); this.wanderRangeHighlight?.object?.destroy(); this.spawnRangeHighlight = null; this.wanderRangeHighlight = null; } #relayoutSpawnRangeHighlight () { this.#layoutRangeOverlay(this.wanderRangeHighlight, LAYER_EDGE - 2); this.#layoutRangeOverlay(this.spawnRangeHighlight, LAYER_EDGE - 1); } #layoutRangeOverlay (highlight, layer) { if (!highlight?.object) { return; } const size = this.tileSize(); const side = (2 * highlight.range + 1) * size; const left = (highlight.tileX - highlight.range) * size; const top = (highlight.tileY - highlight.range) * size; highlight.object.transform.position.x = left + side / 2; highlight.object.transform.position.y = top + side / 2; highlight.object.transform.size = new vector(side, side); highlight.object.layer = layer; this.#markSortDirty(); } setTilePreview (tileX, tileY, override) { const previous = this.preview; this.preview = { tileX, tileY, ...override }; const chunkX = Math.floor(tileX / CHUNK_SIZE); const chunkY = Math.floor(tileY / CHUNK_SIZE); const snapshot = this.chunks.get(`${chunkX},${chunkY}`); if (snapshot) { this.#rebuildChunk(snapshot); } if (previous && (previous.tileX !== tileX || previous.tileY !== tileY)) { const prevSnapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`); if (prevSnapshot && prevSnapshot !== snapshot) { this.#rebuildChunk(prevSnapshot); } } } clearTilePreview () { const previous = this.preview; this.preview = null; if (previous) { const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`); if (snapshot) { this.#rebuildChunk(snapshot); } } } #lerpMs (gait) { const walk = this.settings.walkTilesPerSecond || 2; const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk; return seconds * 1000; } #centerCamera () { if (!this.followPlayer) { return; } const local = this.entities.get(this.localEntityId); if (!local) { return; } const x = local.visualX + (local.stackOffsetX ?? 0); const y = local.visualY + (local.stackOffsetY ?? 0); this.scene.cameraPosition.x = this.scene.real_size.x / 2 - x; this.scene.cameraPosition.y = this.scene.real_size.y / 2 - y; } /** * World-pixel AABB of the screen, expanded by half a tile (zoom-aware). * Tiles fully outside this rect are not drawn. */ #drawBounds () { const pad = this.tileSize() * 0.5; const camX = this.scene.cameraPosition.x; const camY = this.scene.cameraPosition.y; const w = this.scene.real_size.x; const h = this.scene.real_size.y; return { left: -camX - pad, right: -camX + w + pad, top: -camY - pad, bottom: -camY + h + pad }; } #rectIntersects (left, top, right, bottom, bounds) { return right >= bounds.left && left <= bounds.right && bottom >= bounds.top && top <= bounds.bottom; } #setRendererVisible (object, visible) { if (object?.renderer) { object.renderer.visible = !!visible; } } /** Skip drawing (and lighting work) for tiles/chunks more than ½ tile off-screen. */ #cullOffscreenDrawables () { const bounds = this.#drawBounds(); const size = this.tileSize(); for (const baked of this.bakedChunks.values()) { const left = baked.chunkX * CHUNK_SIZE * size; const top = baked.chunkY * CHUNK_SIZE * size; const chunkPx = CHUNK_SIZE * size; const chunkVisible = this.#rectIntersects(left, top, left + chunkPx, top + chunkPx, bounds); this.#setRendererVisible(baked.groundObject, chunkVisible); this.#setRendererVisible(baked.bloomObject, chunkVisible && this.bloomEnabled); baked._inViewport = chunkVisible; for (let row = 0; row < CHUNK_SIZE; row++) { const rowTop = top + row * size; const rowVisible = chunkVisible && this.#rectIntersects( left, rowTop, left + chunkPx, rowTop + size, bounds ); this.#setRendererVisible(baked.blockObjects?.[row], rowVisible); } } for (const objects of this.tiles.values()) { const left = objects.tileX * size; const top = objects.tileY * size; const visible = this.#rectIntersects(left, top, left + size, top + size, bounds); objects._inViewport = visible; this.#setRendererVisible(objects.ground, visible); this.#setRendererVisible(objects.groundBloom, visible && this.bloomEnabled); this.#setRendererVisible(objects.block, visible); this.#setRendererVisible(objects.blockBloom, visible && this.bloomEnabled); if (objects.waterEdges) { for (const edge of Object.values(objects.waterEdges)) { this.#setRendererVisible(edge, visible); } } } } #upsertEntity (payload) { const size = this.tileSize(); const pivot = tilePivot(payload.tileX, payload.tileY, size); let entity = this.entities.get(payload.entityId); if (!entity) { const spriteName = payload.layers?.[0]?.sprite ?? payload.sprite ?? bodySpriteName(payload.sex); const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY); this.scene.addObject(object); this.#startIdleAnimation(object); entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y }; this.entities.set(payload.entityId, entity); } entity.entityId = payload.entityId; entity.tileX = payload.tileX; entity.tileY = payload.tileY; entity.gait = payload.gait; entity.sex = payload.sex ?? entity.sex; entity.characterId = payload.characterId ?? entity.characterId ?? null; entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null; entity.hostile = payload.hostile != null ? !!payload.hostile : !!entity.hostile; entity.canFight = payload.canFight != null ? !!payload.canFight : !!(entity.canFight || (payload.mobTypeId && !payload.talkable)); entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable; entity.hasShop = payload.hasShop != null ? !!payload.hasShop : !!entity.hasShop; entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable; entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight; entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0; if (payload.visualScale != null) { entity.visualScale = Number(payload.visualScale) || 1; } else if (entity.visualScale == null) { entity.visualScale = 1; } if (payload.health != null) { entity.health = payload.health; } if (payload.maxHealth != null) { entity.maxHealth = payload.maxHealth; } if (payload.firstName) { entity.firstName = payload.firstName; } if (payload.lastName) { entity.lastName = payload.lastName; } entity.firstName = entity.firstName ?? ""; entity.lastName = entity.lastName ?? ""; if (payload.worldX != null && payload.worldY != null) { entity.worldX = payload.worldX; entity.worldY = payload.worldY; entity.visualX = payload.worldX * size; entity.visualY = payload.worldY * size; entity.targetX = entity.visualX; entity.targetY = entity.visualY; } else { entity.visualX = pivot.x; entity.visualY = pivot.y; entity.targetX = pivot.x; entity.targetY = pivot.y; } entity.fromX = entity.visualX; entity.fromY = entity.visualY; if (payload.layers) { this.#applyLayers(entity, payload.layers); } this.#syncHpBar(entity); this.#placeEntity(entity, performance.now()); } #applyLayers (entity, layers) { entity.appearanceLayers = layers ?? [{ sprite: bodySpriteName(entity.sex) }]; this.#rebuildOverlays(entity); } #setGatherToolOverlay (entity, toolItemId) { entity.gatherToolItemId = toolItemId; entity.gatherToolUntil = performance.now() + GATHER_TOOL_HOLD_MS; this.#rebuildOverlays(entity); this.#placeEntity(entity, performance.now()); } #expireGatherToolOverlay (entity, now) { if (entity.gatherToolItemId == null) { return; } if ((entity.gatherToolUntil ?? 0) > now) { return; } entity.gatherToolItemId = null; entity.gatherToolUntil = 0; this.#rebuildOverlays(entity); } /** Prefer the active gather tool's equip sprite over the worn weapon (all gather kinds). */ #layersForDisplay (entity) { const layers = (entity.appearanceLayers ?? []).map((layer) => ({ ...layer })); const toolId = entity.gatherToolItemId; if (toolId == null || (entity.gatherToolUntil ?? 0) <= performance.now()) { return layers; } const equip = itemEquipSprite(toolId); if (!equip || !this.game.images[equip]) { return layers; } const replacement = { sprite: equip, itemId: toolId, tint: resolveEquipTint(toolId) }; for (let index = layers.length - 1; index >= 1; index--) { const def = itemDefinition(layers[index].itemId); if (def?.equipment?.slot === EQUIPMENT_SLOT.weapon) { layers[index] = replacement; return layers; } } layers.push(replacement); return layers; } #rebuildOverlays (entity) { const layers = this.#layersForDisplay(entity); const base = layers[0]?.sprite ?? bodySpriteName(entity.sex); if (this.game.images[base]) { entity.object.renderer.sprite = this.game.images[base]; this.#startIdleAnimation(entity.object); } for (const overlay of entity.overlays ?? []) { overlay.destroy(); } for (const overlay of entity.bloomOverlays ?? []) { overlay.destroy(); } entity.overlays = []; entity.overlayTints = []; entity.bloomOverlays = []; for (const layer of layers.slice(1)) { const image = this.game.images[layer.sprite]; if (!image) { continue; } const object = new GameObject(0, 0, image, SORT_ENTITY); this.scene.addObject(object); entity.overlays.push(object); entity.overlayTints.push( layer.tint ? normalizeRgb(layer.tint) : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null) ); const bloomName = bloomCompanionName(layer.sprite); const bloomImage = this.game.images[bloomName]; if (!bloomImage) { continue; } const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY); bloom.renderer.layer = RENDER_LAYER_BLOOM; this.#markUnlit(bloom); this.scene.addObject(bloom); entity.bloomOverlays.push(bloom); } } #placeEntity (entity, now = performance.now()) { const zoom = this.zoom; const offsetX = entity.shoveOffsetX ?? 0; const offsetY = entity.shoveOffsetY ?? 0; const pivotX = entity.visualX + offsetX + (entity.stackOffsetX ?? 0); const pivotY = entity.visualY + offsetY + (entity.stackOffsetY ?? 0); let walkTilt = 0; if (entity.lerpStarted != null) { const stepMs = Math.max(1, entity.lerpMs ?? this.#lerpMs(entity.gait)); const cycles = ((now - entity.lerpStarted) / stepMs) * Math.PI * 2; const tilt = entity.gait === GAIT.run ? RUN_TILT_DEG : WALK_TILT_DEG; walkTilt = Math.sin(cycles) * tilt; } const flashStrength = (entity.damageFlashUntil ?? 0) > now ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS : 0; const tileShade = this.#entityShadeAlpha(entity, now); const wade = isWadeGroundInSeason(this.#groundTypeAt(entity.tileX, entity.tileY), this.worldSeason); entity.object.transform.rotation = walkTilt; this.#syncLitSprite(entity.object, tileShade, flashStrength, wade); this.#placePivoted(entity.object, pivotX, pivotY, pivotY, SORT_ENTITY, entity.visualScale ?? 1); for (let index = 0; index < (entity.overlays ?? []).length; index++) { const overlay = entity.overlays[index]; const overlaySortY = pivotY + 0.5 * (index + 1); overlay.transform.rotation = walkTilt; this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null); this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY, entity.visualScale ?? 1); } for (const overlay of entity.bloomOverlays ?? []) { this.#setRendererVisible(overlay, this.bloomEnabled); if (!this.bloomEnabled) { continue; } overlay.transform.rotation = walkTilt; this.#syncLitSprite(overlay, tileShade, flashStrength, wade); this.#placePivoted(overlay, pivotX, pivotY, pivotY + 0.002, SORT_ENTITY, entity.visualScale ?? 1); } this.#placeHpBar(entity, pivotX, pivotY); } #markUnlit (object) { if (!object?.renderer) { return; } object._lit = false; object.renderer.shader = null; object.renderer.shaderUniforms = null; object.renderer.secondaryMap = null; } #syncLitSprite (object, darkness, flashStrength = 0, wade = false, tintColor = null) { if (!object?.renderer || object._lit === false) { return; } object._lit = true; const dark = Math.min(1, Math.max(0, darkness ?? 0)); const flash = Math.min(1, Math.max(0, flashStrength ?? 0)); const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX; const tint = tintColor ? normalizeRgb(tintColor) : null; if (tint) { object.renderer.shader = getTintLitSpriteShader(); object.renderer.shaderUniforms = { u_darkness: dark, u_strength: flash, u_wade: wade ? 1 : 0, u_spriteHeight: height, u_useTint: 1, u_tintColor: [tint.r, tint.g, tint.b] }; } else { object.renderer.shader = getSpriteLightingShader(); object.renderer.shaderUniforms = { u_darkness: dark, u_strength: flash, u_wade: wade ? 1 : 0, u_spriteHeight: height }; } object.renderer.secondaryMap = null; } #syncDualTintLitSprite (object, darkness, dualTint, flashStrength = 0, wade = false) { if (!object?.renderer || object._lit === false || !dualTint) { return; } object._lit = true; const shaft = normalizeRgb(dualTint.shaft); const tip = normalizeRgb(dualTint.tip); const dark = Math.min(1, Math.max(0, darkness ?? 0)); const flash = Math.min(1, Math.max(0, flashStrength ?? 0)); const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX; object.renderer.shader = getDualTintLitSpriteShader(); object.renderer.shaderUniforms = { u_darkness: dark, u_strength: flash, u_wade: wade ? 1 : 0, u_spriteHeight: height, u_shaftTint: [shaft.r, shaft.g, shaft.b], u_tipTint: [tip.r, tip.g, tip.b] }; object.renderer.secondaryMap = null; } #syncGroundItemSprite (item, darkness) { if (item?.dualTint) { this.#syncDualTintLitSprite(item.object, darkness, item.dualTint); return; } this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null); } #groundTypeAt (tileX, tileY) { const chunkX = Math.floor(tileX / CHUNK_SIZE); const chunkY = Math.floor(tileY / CHUNK_SIZE); const snapshot = this.chunks.get(`${chunkX},${chunkY}`); if (!snapshot) { return null; } const localX = tileX - chunkX * CHUNK_SIZE; const localY = tileY - chunkY * CHUNK_SIZE; const index = localY * CHUNK_SIZE + localX; return normalizeGround(snapshot.grounds?.[index]).typeId; } #waterCoastEdges (tileX, tileY) { const season = this.worldSeason; return { n: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY - 1), season) ? 1 : 0, e: !isLiquidWaterGround(this.#groundTypeAt(tileX + 1, tileY), season) ? 1 : 0, s: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY + 1), season) ? 1 : 0, w: !isLiquidWaterGround(this.#groundTypeAt(tileX - 1, tileY), season) ? 1 : 0 }; } #syncWaterGroundSprite (object, corners, ambientDark, edges, timeSec, fallbackLit = 1) { if (!object?.renderer) { return; } const lit = corners ?? { nw: fallbackLit, ne: fallbackLit, sw: fallbackLit, se: fallbackLit }; const dark = Math.min(1, Math.max(0, ambientDark ?? 0)); object._lit = true; object.renderer.shader = getWaterGroundShader(); object.renderer.secondaryMap = null; object.renderer.shaderUniforms = { u_ambientDark: dark, u_litNW: lit.nw, u_litNE: lit.ne, u_litSW: lit.sw, u_litSE: lit.se, u_time: timeSec, u_edgeN: edges?.n ?? 0, u_edgeE: edges?.e ?? 0, u_edgeS: edges?.s ?? 0, u_edgeW: edges?.w ?? 0 }; } /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. */ #syncGroundWaterFx (objects, ambientDark, timeSec, baked = null) { if (!objects?.ground) { return; } if (!isLiquidWaterGround(objects.groundTypeId, this.worldSeason)) { objects.waterEdges = null; this.#syncLitSprite(objects.ground, objects.shadeAlpha ?? 0); return; } const fallbackLit = ambientDark > 0 ? 1 - (objects.shadeAlpha ?? 0) / ambientDark : 1; const chunkX = Math.floor(objects.tileX / CHUNK_SIZE); const chunkY = Math.floor(objects.tileY / CHUNK_SIZE); const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`); const localX = objects.tileX - chunkX * CHUNK_SIZE; const localY = objects.tileY - chunkY * CHUNK_SIZE; let litCorners = null; if (chunkBaked) { if (this.lightingMode === "simple") { const gridW = CHUNK_SIZE + 2; const intensity = chunkBaked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? fallbackLit; litCorners = { nw: intensity, ne: intensity, sw: intensity, se: intensity }; } else { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); } } objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY); this.#syncWaterGroundSprite( objects.ground, litCorners, ambientDark, objects.waterEdges, timeSec, fallbackLit ); } #ambientDarkness () { const hour = this.nightPreview ?? this.worldHour; let dark = nightFactor(hour, this.settings.nightDarkness); if (this.localBlind) { dark = Math.min(1, dark + 0.85); } return dark; } setLocalBlind (blind) { this.localBlind = !!blind; } /** Soft vision bubble while blinded (client-only; stacks with ambient). */ #blindVisionLight () { if (!this.localBlind) { return null; } const local = this.entities.get(this.localEntityId); if (!local) { return null; } const tileSize = this.tileSize(); return { tileX: Math.floor(local.visualX / tileSize), tileY: Math.floor(local.visualY / tileSize), range: 2.25, intensity: 1 }; } #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY, dualTint = null) { const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0; const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0; const dark = (fromAlpha + toAlpha) / 2; if (dualTint) { this.#syncDualTintLitSprite(object, dark, dualTint); return; } this.#syncLitSprite(object, dark); } #dualTintFromPayload (payload) { if (!payload?.shaftTint || !payload?.tipTint) { return null; } return { shaft: payload.shaftTint, tip: payload.tipTint }; } #syncHpBar (entity) { const current = entity.health; const max = entity.maxHealth; const show = current != null && max != null && max > 0 && current < max; if (!show) { entity.hpBar?.destroy(); entity.hpBar = null; entity.hpBarCanvas = null; return; } if (!entity.hpBarCanvas) { entity.hpBarCanvas = document.createElement("canvas"); entity.hpBarCanvas.width = HP_BAR_W; entity.hpBarCanvas.height = HP_BAR_H; const image = frameworkImageFromCanvas(entity.hpBarCanvas); entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR); this.#markUnlit(entity.hpBar); this.scene.addObject(entity.hpBar); } drawHpBar(entity.hpBarCanvas, current, max); invalidateCanvasTexture(this.scene, entity.hpBarCanvas); } #placeHpBar (entity, pivotX, pivotY) { if (!entity.hpBar) { return; } const sprite = entity.object?.renderer?.sprite; if (!sprite) { return; } const zoom = this.zoom; const drawH = sprite.height * zoom; const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom); const spriteTop = centerY - drawH / 2; const barW = HP_BAR_W * zoom; const barH = HP_BAR_H * zoom; entity.hpBar.transform.position.x = pivotX; entity.hpBar.transform.position.y = spriteTop - barH / 2; entity.hpBar.transform.size = new vector(barW, barH); entity.hpBar.layer = ySortLayer(pivotY, SORT_HP_BAR); this.#markSortDirty(); } #rebuildChunk (snapshot) { this.#bakeAndPlaceChunk(snapshot); const tall = new Set( (this.bakedChunks.get(`${snapshot.chunkX},${snapshot.chunkY}`)?.tallBlocks ?? []) .map((entry) => `${entry.tileX},${entry.tileY}`) ); for (let localY = 0; localY < CHUNK_SIZE; localY++) { for (let localX = 0; localX < CHUNK_SIZE; localX++) { const tileX = snapshot.chunkX * CHUNK_SIZE + localX; const tileY = snapshot.chunkY * CHUNK_SIZE + localY; this.#drawTile(tileX, tileY, tall.has(`${tileX},${tileY}`)); } } } #rebakeAllChunks () { for (const snapshot of this.chunks.values()) { this.#rebuildChunk(snapshot); } } #bakeAndPlaceChunk (snapshot) { const key = `${snapshot.chunkX},${snapshot.chunkY}`; const atlases = bakeChunkAtlases({ snapshot, catalog: this.catalog, images: this.game.images, preview: this.preview, season: this.worldSeason }); const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX; let baked = this.bakedChunks.get(key); if (!baked) { const lightmapCanvas = makeLightmapCanvas(atlasPx); baked = { groundCanvas: atlases.ground, blockCanvases: atlases.blockRows, bloomCanvas: atlases.bloom, lightmapCanvas, groundImage: frameworkImageFromCanvas(atlases.ground), blockImages: atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)), bloomImage: frameworkImageFromCanvas(atlases.bloom), lightmapImage: frameworkImageFromCanvas(lightmapCanvas), groundObject: null, blockObjects: [], bloomObject: null, tallBlocks: atlases.tallBlocks, animatedGrounds: atlases.animatedGrounds, lightmapPixels: null }; baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND); this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1); this.scene.addObject(baked.groundObject); for (let row = 0; row < CHUNK_SIZE; row++) { const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK); this.#applyAtlasLighting(object, baked.lightmapImage, row); this.scene.addObject(object); baked.blockObjects.push(object); } baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK); baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM; this.#markUnlit(baked.bloomObject); this.scene.addObject(baked.bloomObject); this.bakedChunks.set(key, baked); } else { copyCanvas(atlases.ground, baked.groundCanvas); for (let row = 0; row < CHUNK_SIZE; row++) { copyCanvas(atlases.blockRows[row], baked.blockCanvases[row]); } copyCanvas(atlases.bloom, baked.bloomCanvas); invalidateCanvasTexture(this.scene, baked.groundCanvas); for (const canvas of baked.blockCanvases) { invalidateCanvasTexture(this.scene, canvas); } invalidateCanvasTexture(this.scene, baked.bloomCanvas); baked.tallBlocks = atlases.tallBlocks; baked.animatedGrounds = atlases.animatedGrounds; } baked.chunkX = snapshot.chunkX; baked.chunkY = snapshot.chunkY; this.#layoutBakedChunk(snapshot); } #applyAtlasLighting (object, lightmapImage, lightRow) { if (!object?.renderer) { return; } object._lit = true; object.renderer.shader = getAtlasLightingShader(); object.renderer.secondaryMap = lightmapImage; object.renderer.shaderUniforms = { u_ambientDark: 0, u_lightRow: lightRow }; } #layoutBakedChunk (snapshot) { const key = `${snapshot.chunkX},${snapshot.chunkY}`; const baked = this.bakedChunks.get(key); if (!baked) { return; } const size = this.tileSize(); const left = snapshot.chunkX * CHUNK_SIZE * size; const top = snapshot.chunkY * CHUNK_SIZE * size; const chunkPx = CHUNK_SIZE * size; baked.groundObject.transform.position.x = left + chunkPx / 2; baked.groundObject.transform.position.y = top + chunkPx / 2; baked.groundObject.transform.size = new vector(chunkPx, chunkPx); baked.groundObject.layer = LAYER_GROUND; for (let row = 0; row < CHUNK_SIZE; row++) { const object = baked.blockObjects[row]; const rowY = top + row * size + size / 2; object.transform.position.x = left + chunkPx / 2; object.transform.position.y = rowY; object.transform.size = new vector(chunkPx, size); object.layer = ySortLayer(rowY, SORT_BLOCK); } baked.bloomObject.transform.position.x = left + chunkPx / 2; baked.bloomObject.transform.position.y = top + chunkPx / 2; baked.bloomObject.transform.size = new vector(chunkPx, chunkPx); baked.bloomObject.layer = ySortLayer(top + chunkPx, SORT_BLOCK); baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM; this.#markSortDirty(); setNearestFilter(this.scene, baked.groundCanvas); for (const canvas of baked.blockCanvases) { setNearestFilter(this.scene, canvas); } setNearestFilter(this.scene, baked.bloomCanvas); setNearestFilter(this.scene, baked.lightmapCanvas); } #destroyBakedChunk (key) { const baked = this.bakedChunks.get(key); if (!baked) { return; } baked.groundObject?.destroy(); for (const object of baked.blockObjects ?? []) { object.destroy(); } baked.bloomObject?.destroy(); invalidateCanvasTexture(this.scene, baked.groundCanvas); for (const canvas of baked.blockCanvases ?? []) { invalidateCanvasTexture(this.scene, canvas); } invalidateCanvasTexture(this.scene, baked.bloomCanvas); invalidateCanvasTexture(this.scene, baked.lightmapCanvas); this.bakedChunks.delete(key); } #redrawPreview () { if (!this.preview) { return; } const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`); if (snapshot) { this.#rebuildChunk(snapshot); } } #refreshWaterCoastsNear (chunkX, chunkY) { const timeSec = performance.now() / 1000; for (const objects of this.tiles.values()) { if (!objects.ground || !isWaterGround(objects.groundTypeId)) { continue; } if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1) { continue; } this.#syncGroundWaterFx(objects, this.#ambientDarkness(), timeSec); } } #drawTile (tileX, tileY, forceTall = null) { const chunkX = Math.floor(tileX / CHUNK_SIZE); const chunkY = Math.floor(tileY / CHUNK_SIZE); const snapshot = this.chunks.get(`${chunkX},${chunkY}`); if (!snapshot) { return; } const localX = tileX - chunkX * CHUNK_SIZE; const localY = tileY - chunkY * CHUNK_SIZE; const index = localY * CHUNK_SIZE + localX; const key = `${tileX},${tileY}`; let objects = this.tiles.get(key); if (!objects) { objects = { chunkX, chunkY, tileX, tileY }; this.tiles.set(key, objects); } objects.tileX = tileX; objects.tileY = tileY; objects.chunkX = chunkX; objects.chunkY = chunkY; objects.light = snapshot.light[index] ?? 0; const baked = this.bakedChunks.get(`${chunkX},${chunkY}`); const animatedGround = (baked?.animatedGrounds ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY); if (animatedGround) { objects.ground = this.#ensureSprite(objects.ground, animatedGround.sprite, LAYER_GROUND); if (objects.ground) { const size = this.tileSize(); objects.ground.transform.position.x = tileX * size + size / 2; objects.ground.transform.position.y = tileY * size + size / 2; objects.ground.transform.size = new vector(size, size); objects.ground.layer = LAYER_GROUND; objects.groundTypeId = animatedGround.typeId; this.#syncGroundWaterFx(objects, this.#ambientDarkness(), performance.now() / 1000); this.#markSortDirty(); } if (animatedGround.bloom) { objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, animatedGround.bloom, tilePivot(tileX, tileY, this.tileSize()), LAYER_GROUND); } else { objects.groundBloom?.destroy(); objects.groundBloom = null; } } else { objects.ground?.destroy(); objects.ground = null; objects.groundBloom?.destroy(); objects.groundBloom = null; objects.groundTypeId = null; objects.waterEdges = null; } const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY); const isTall = forceTall === true || !!tallEntry; if (isTall && tallEntry) { const pivot = tilePivot(tileX, tileY, this.tileSize()); objects.block = this.#ensureSprite(objects.block, tallEntry.sprite, SORT_ENTITY); if (objects.block) { this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY); this.#syncLitSprite(objects.block, objects.shadeAlpha ?? 0); } objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tallEntry.bloom, pivot, SORT_ENTITY); } else { objects.block?.destroy(); objects.block = null; objects.blockBloom?.destroy(); objects.blockBloom = null; } } #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK) { if (!name) { existing?.destroy(); return null; } const object = this.#ensureSprite(existing, name, sortOrder); if (!object) { return null; } object.renderer.layer = RENDER_LAYER_BLOOM; this.#markUnlit(object); this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder); return object; } #placePivoted (object, pivotX, pivotY, sortY, subOrder, scale = 1) { const sprite = object?.renderer?.sprite; if (!sprite) { return; } const zoom = this.zoom; const draw = spriteDrawSize(sprite.width, sprite.height, zoom); const factor = Math.max(0.1, Number(scale) || 1); const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height * factor, zoom); object.transform.position.x = center.x; object.transform.position.y = center.y; object.transform.size = new vector(draw.w * factor, draw.h * factor); object.layer = ySortLayer(sortY, subOrder); this.#markSortDirty(); } #ensureSprite (existing, name, layer) { const sprite = this.game.images[name]; if (!sprite) { existing?.destroy(); return null; } if (!existing || existing.renderer.sprite !== sprite) { existing?.destroy(); existing = new GameObject(0, 0, sprite, layer); this.#syncLitSprite(existing, 0); this.scene.addObject(existing); this.#startIdleAnimation(existing); } return existing; } #startIdleAnimation (object) { const sprite = object?.renderer?.sprite; if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0) { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); } } #neighborClosed (snapshot, dir, dx, dy) { const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`); if (other) { return !other.open; } return !!snapshot.closedEdges?.[dir]; } #rebuildAllEdges () { const seen = new Set(); for (const snapshot of this.chunks.values()) { const key = `${snapshot.chunkX},${snapshot.chunkY}`; seen.add(key); this.#rebuildChunkEdges(snapshot); } for (const key of [...this.edges.keys()]) { if (!seen.has(key)) { this.#destroyEdges(key); } } } #rebuildChunkEdges (snapshot) { const key = `${snapshot.chunkX},${snapshot.chunkY}`; let bars = this.edges.get(key); if (!bars) { bars = {}; this.edges.set(key, bars); } const size = this.tileSize(); const chunkPx = CHUNK_SIZE * size; const left = snapshot.chunkX * CHUNK_SIZE * size; const top = snapshot.chunkY * CHUNK_SIZE * size; const centerX = left + chunkPx / 2; const centerY = top + chunkPx / 2; const thickness = Math.max(2, Math.round(2 * this.zoom)); const draw = snapshot.open === true; bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1), centerX, top, chunkPx, thickness, true); bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1), centerX, top + chunkPx, chunkPx, thickness, true); bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0), left, centerY, chunkPx, thickness, false); bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0), left + chunkPx, centerY, chunkPx, thickness, false); } #edgeBar (existing, visible, x, y, length, thickness, horizontal) { if (!visible) { if (existing) { existing.renderer.visible = false; } return existing; } existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE); this.#markUnlit(existing); existing.renderer.visible = true; existing.transform.position.x = x; existing.transform.position.y = y; existing.transform.size = horizontal ? new vector(length, thickness) : new vector(thickness, length); existing.layer = LAYER_EDGE; this.#markSortDirty(); return existing; } #destroyEdges (key) { const bars = this.edges.get(key); if (!bars) { return; } bars.north?.destroy(); bars.east?.destroy(); bars.south?.destroy(); bars.west?.destroy(); this.edges.delete(key); } #entityShadeAlpha (entity, now) { const toAlpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0; if (entity.lerpStarted == null || entity.shadeFromTileX == null || entity.shadeFromTileY == null) { return toAlpha; } const fromAlpha = this.tiles.get(`${entity.shadeFromTileX},${entity.shadeFromTileY}`)?.shadeAlpha ?? 0; const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs ?? 1)); return fromAlpha + (toAlpha - fromAlpha) * t; } #markSortDirty () { this.scene._sortDirty = true; } #updateShade () { const ambientDark = this.#ambientDarkness(); const now = performance.now(); this.dynamicLights = this.dynamicLights.filter((light) => light.until > now); const activeLights = [...this.dynamicLights]; const tileSize = this.tileSize(); const blindLight = this.#blindVisionLight(); if (blindLight) { activeLights.push(blindLight); } for (const entity of this.entities.values()) { const range = entity.lightRadiusTiles ?? 0; if (range <= 0) { continue; } activeLights.push({ tileX: Math.floor(entity.visualX / tileSize), tileY: Math.floor(entity.visualY / tileSize), range, intensity: 1 }); } const lightOcclusion = makeSnapshotLightOcclusion(this.chunks); for (const objects of this.tiles.values()) { if (objects._inViewport === false) { continue; } const intensity = this.#tileLightIntensity(objects, activeLights, lightOcclusion); objects.shadeAlpha = ambientDark * (1 - intensity); } for (const baked of this.bakedChunks.values()) { if (baked._inViewport === false) { continue; } this.#writeChunkLightmap(baked, activeLights, lightOcclusion); if (baked.groundObject?.renderer?.shaderUniforms) { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; } for (const object of baked.blockObjects ?? []) { if (object?.renderer?.shaderUniforms) { object.renderer.shaderUniforms.u_ambientDark = ambientDark; } } } const timeSec = now / 1000; for (const objects of this.tiles.values()) { if (objects._inViewport === false) { continue; } if (objects.block) { this.#syncLitSprite(objects.block, objects.shadeAlpha); } if (objects.ground && isWaterGround(objects.groundTypeId)) { const baked = this.bakedChunks.get(`${objects.chunkX},${objects.chunkY}`); this.#syncGroundWaterFx(objects, ambientDark, timeSec, baked); } else if (objects.ground) { this.#syncLitSprite(objects.ground, objects.shadeAlpha); } } for (const item of this.groundItems.values()) { const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0; this.#syncGroundItemSprite(item, alpha); } } #tileLightIntensity (objects, activeLights, lightOcclusion) { const baked = lightIntensity(objects.light ?? 0); const dynamic = dynamicLightAtTile( objects.tileX, objects.tileY, activeLights, lightOcclusion ); return Math.max(baked, dynamic); } /** Baked + dynamic light intensity (0–1) for any world tile, including across chunks. */ #intensityAtTile (tileX, tileY, activeLights, lightOcclusion) { const tileObjects = this.tiles.get(`${tileX},${tileY}`); if (tileObjects) { return this.#tileLightIntensity(tileObjects, activeLights, lightOcclusion); } const chunkX = Math.floor(tileX / CHUNK_SIZE); const chunkY = Math.floor(tileY / CHUNK_SIZE); const snapshot = this.chunks.get(`${chunkX},${chunkY}`); if (!snapshot) { return 0; } const localX = tileX - chunkX * CHUNK_SIZE; const localY = tileY - chunkY * CHUNK_SIZE; const index = localY * CHUNK_SIZE + localX; const bakedLit = lightIntensity(snapshot.light[index] ?? 0); const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion); return Math.max(bakedLit, dynamic); } /** True when ground or block on this tile occludes light rays (same rules as bake). */ #tileOccludesLight (tileX, tileY) { const chunkX = Math.floor(tileX / CHUNK_SIZE); const chunkY = Math.floor(tileY / CHUNK_SIZE); const snapshot = this.chunks.get(`${chunkX},${chunkY}`); if (!snapshot) { return false; } const localX = tileX - chunkX * CHUNK_SIZE; const localY = tileY - chunkY * CHUNK_SIZE; if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE) { return false; } const index = localY * CHUNK_SIZE + localX; const ground = normalizeGround(snapshot.grounds?.[index]); if (!isGroundPassable(ground.typeId)) { return true; } return isBlockOccludingLight(snapshot.blocks?.[index]?.typeId ?? null); } #fillChunkLightGrids (baked, activeLights, lightOcclusion) { const gridW = CHUNK_SIZE + 2; const gridSize = gridW * gridW; if (!baked.lightIntensityGrid || baked.lightIntensityGrid.length !== gridSize) { baked.lightIntensityGrid = new Float32Array(gridSize); } if (!baked.lightOccludeGrid || baked.lightOccludeGrid.length !== gridSize) { baked.lightOccludeGrid = new Uint8Array(gridSize); } const grid = baked.lightIntensityGrid; const occlude = baked.lightOccludeGrid; for (let ly = -1; ly <= CHUNK_SIZE; ly++) { for (let lx = -1; lx <= CHUNK_SIZE; lx++) { const tileX = baked.chunkX * CHUNK_SIZE + lx; const tileY = baked.chunkY * CHUNK_SIZE + ly; const gi = (ly + 1) * gridW + (lx + 1); grid[gi] = this.#intensityAtTile(tileX, tileY, activeLights, lightOcclusion); occlude[gi] = this.#tileOccludesLight(tileX, tileY) ? 1 : 0; } } return { grid, occlude, gridW }; } #makeLightCornerSampler (grid, occlude, gridW) { const sample = (lx, ly) => grid[(ly + 1) * gridW + (lx + 1)]; const blocks = (lx, ly) => occlude[(ly + 1) * gridW + (lx + 1)] !== 0; const openSample = (lx, ly) => (blocks(lx, ly) ? 0 : sample(lx, ly)); const smoothCorner = (homeLx, homeLy, aLx, aLy, bLx, bLy, dLx, dLy) => { const home = sample(homeLx, homeLy); if (blocks(homeLx, homeLy)) { return home; } let sum = home; let count = 1; sum += openSample(aLx, aLy); count += 1; sum += openSample(bLx, bLy); count += 1; if (!blocks(aLx, aLy) && !blocks(bLx, bLy)) { sum += openSample(dLx, dLy); count += 1; } return sum / count; }; return { smoothCorner }; } /** Corner lit intensities (0–1) for one tile — matches baked atlas lightmap corners. */ #tileLitCorners (baked, localX, localY) { const grid = baked?.lightIntensityGrid; const occlude = baked?.lightOccludeGrid; if (!grid?.length || !occlude?.length) { return null; } const gridW = CHUNK_SIZE + 2; const { smoothCorner } = this.#makeLightCornerSampler(grid, occlude, gridW); return { nw: smoothCorner( localX, localY, localX - 1, localY, localX, localY - 1, localX - 1, localY - 1 ), ne: smoothCorner( localX, localY, localX + 1, localY, localX, localY - 1, localX + 1, localY - 1 ), sw: smoothCorner( localX, localY, localX - 1, localY, localX, localY + 1, localX - 1, localY + 1 ), se: smoothCorner( localX, localY, localX + 1, localY, localX, localY + 1, localX + 1, localY + 1 ) }; } /** * Per-chunk lightmap for atlas ground/blocks. Open tiles blend into open neighbours; * occluding tiles stay flat and contribute 0 into others so light does not bleed * through a wall to the far side. Diagonals only when both cardinals are clear. */ #writeChunkLightmap (baked, activeLights, lightOcclusion) { const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`); if (!snapshot) { return; } const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX; const pixelCount = atlasPx * atlasPx * 4; if (!baked.lightmapPixels || baked.lightmapPixels.length !== pixelCount) { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); } const pixels = baked.lightmapPixels; this.#fillChunkLightGrids(baked, activeLights, lightOcclusion); const simple = this.lightingMode === "simple"; for (let localY = 0; localY < CHUNK_SIZE; localY++) { for (let localX = 0; localX < CHUNK_SIZE; localX++) { const baseX = localX * SPRITE_SIZE_PX; const baseY = localY * SPRITE_SIZE_PX; if (simple) { const gridW = CHUNK_SIZE + 2; const intensity = baked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? 0; const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255); for (let py = 0; py < SPRITE_SIZE_PX; py++) { for (let px = 0; px < SPRITE_SIZE_PX; px++) { const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4; pixels[offset] = value; pixels[offset + 1] = value; pixels[offset + 2] = value; pixels[offset + 3] = 255; } } continue; } const corners = this.#tileLitCorners(baked, localX, localY); const nw = corners.nw; const ne = corners.ne; const sw = corners.sw; const se = corners.se; for (let py = 0; py < SPRITE_SIZE_PX; py++) { const v = (py + 0.5) / SPRITE_SIZE_PX; const left = nw + (sw - nw) * v; const right = ne + (se - ne) * v; for (let px = 0; px < SPRITE_SIZE_PX; px++) { const u = (px + 0.5) / SPRITE_SIZE_PX; const intensity = left + (right - left) * u; const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255); const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4; pixels[offset] = value; pixels[offset + 1] = value; pixels[offset + 2] = value; pixels[offset + 3] = 255; } } } } const ctx = baked.lightmapCanvas.getContext("2d"); ctx.putImageData(new ImageData(pixels, atlasPx, atlasPx), 0, 0); invalidateCanvasTexture(this.scene, baked.lightmapCanvas); } #updateSwipes (now) { this.swipes = this.swipes.filter((swipe) => { if (swipe.lerp && swipe.started != null) { const durationMs = swipe.durationMs ?? 400; const t = Math.min(1, (now - swipe.started) / durationMs); const fromPivot = tilePivot(swipe.fromTileX, swipe.fromTileY, this.tileSize()); const toPivot = tilePivot(swipe.tileX, swipe.tileY, this.tileSize()); const x = fromPivot.x + (toPivot.x - fromPivot.x) * t; const y = fromPivot.y + (toPivot.y - fromPivot.y) * t; const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02; if (swipe.object?.transform) { swipe.object.transform.rotation = Math.atan2( toPivot.y - fromPivot.y, toPivot.x - fromPivot.x ) * (180 / Math.PI); } this.#placePivoted(swipe.object, x, y, sortY, SORT_FX); this.#applyPhysicalCombatFxDarkness( swipe.object, swipe.fromTileX, swipe.fromTileY, swipe.tileX, swipe.tileY, swipe.dualTint ?? null ); } else if (swipe.fromTileX != null) { this.#applyPhysicalCombatFxDarkness( swipe.object, swipe.fromTileX, swipe.fromTileY, swipe.tileX, swipe.tileY, swipe.dualTint ?? null ); } if (swipe.until > now) { return true; } swipe.object?.destroy(); return false; }); } #updateDamageNumbers (now) { const layer = this.damageNumbersEl; if (!layer) { return; } this.damageFloats = this.damageFloats.filter((entry) => { const elapsed = now - entry.started; if (elapsed >= DAMAGE_FLOAT_MS) { entry.element?.remove(); return false; } const entity = this.entities.get(entry.entityId); if (!entity) { entry.element?.remove(); return false; } if (!entry.element) { entry.element = document.createElement("span"); entry.element.className = "damage-number"; entry.element.textContent = String(entry.damage); layer.append(entry.element); } const anchor = this.nametagAnchor(entity); if (!anchor) { return true; } const t = elapsed / DAMAGE_FLOAT_MS; entry.element.style.left = `${anchor.x}px`; entry.element.style.top = `${anchor.y - 6 - t * 28}px`; entry.element.style.opacity = String(1 - t); return true; }); } #updateSkillLevelFloats (now) { const layer = this.skillLevelFloatsEl; if (!layer) { return; } this.skillLevelFloats = this.skillLevelFloats.filter((entry) => { const elapsed = now - entry.started; if (elapsed >= SKILL_LEVEL_FLOAT_MS) { entry.element?.remove(); return false; } const entity = this.entities.get(entry.entityId); if (!entity) { entry.element?.remove(); return false; } if (!entry.element) { const root = document.createElement("div"); root.className = "skill-level-float"; const levelEl = document.createElement("div"); levelEl.className = "skill-level-float-level"; levelEl.textContent = `↑${entry.level}↑`; const icon = document.createElement("img"); icon.className = "skill-level-float-icon"; icon.src = entry.icon; icon.alt = entry.displayName || ""; root.append(levelEl, icon); entry.element = root; layer.append(entry.element); } const anchor = this.nametagAnchor(entity); if (!anchor) { return true; } const t = elapsed / SKILL_LEVEL_FLOAT_MS; entry.element.style.left = `${anchor.x}px`; entry.element.style.top = `${anchor.y - 10 - t * 18}px`; entry.element.style.opacity = String(Math.max(0, 1 - t * 0.85)); return true; }); } #syncBloomLayer () { if (!this.bloomEnabled) { this.scene.setLayers([{ name: "default" }]); return; } const settings = this.settings ?? DEFAULT_WORLD_SETTINGS; this.scene.setLayers([ { name: "default" }, { name: RENDER_LAYER_BLOOM, composite: "add", postShaders: Shader.getBloomPostChain({ threshold: settings.bloomThreshold, softKnee: settings.bloomSoftKnee, intensity: settings.bloomIntensity, blurSize: settings.bloomBlurSize, saturation: settings.bloomSaturation, colorPreserve: settings.bloomColorPreserve, dilate: settings.bloomDilate, scales: Math.max(1, Math.round(settings.bloomScales ?? 1)), halfRes: (settings.bloomHalfRes ?? 1) >= 0.5 }) } ]); } } export function nightFactor (hour, nightDarkness = 0.72) { const peak = Math.min(1, Math.max(0, nightDarkness)); if (hour >= 8 && hour <= 16) { return 0; } if (hour >= 22 || hour <= 5) { return peak; } if (hour < 8) { return lerp(peak, 0, (hour - 5) / 3); } return lerp(0, peak, (hour - 16) / 6); } function bodySpriteName (sex) { const key = sex === "female" ? "player-body-female" : "player-body-male"; return spriteImageName("character", key, key); } function lerp (a, b, t) { return a + (b - a) * Math.min(1, Math.max(0, t)); } function makeLightmapCanvas (size) { const canvas = document.createElement("canvas"); canvas.width = size; canvas.height = size; return canvas; } function copyCanvas (source, dest) { const ctx = dest.getContext("2d"); ctx.imageSmoothingEnabled = false; ctx.clearRect(0, 0, dest.width, dest.height); ctx.drawImage(source, 0, 0); } function drawHpBar (canvas, current, max) { const ctx = canvas.getContext("2d"); ctx.clearRect(0, 0, HP_BAR_W, HP_BAR_H); ctx.fillStyle = "#000000"; ctx.fillRect(0, 0, HP_BAR_W, HP_BAR_H); const ratio = max > 0 ? Math.max(0, Math.min(1, current / max)) : 0; const fillW = Math.round(12 * ratio); if (fillW > 0) { ctx.fillStyle = "#ff0000"; ctx.fillRect(1, 1, fillW, 2); } }