// The fog and marker layer (T7, #70; DESIGN 7.1 layer 4, 7.3). Three states from the server's facts: // never-seen floor is opaque black, explored floor is black at ~0.6 alpha, currently visible floor // is cut out of the fog so the map shows through. // // Mechanism (spec #63 decision 9 leaves the Pixi object to the build): // - one RGBA canvas at cell resolution (`ceil(w/cell) x ceil(h/cell)`) holds the *explored* state: // never-seen cells alpha 255, explored cells alpha ~0.6. It is repainted from an `ImageData` // buffer; a cell diff mutates only the new bytes and uploads only the dirty rectangle, so "only // changed cells" is the normal path (DESIGN 7.2); // - a second canvas of the same size is the texture the sprite displays: the explored canvas is // copied into it and the union of this player's `vision` polygons is cut out with // `destination-out`, which is the polygon cut-out itself, not a separate stencil pass. It is // recomposed only when an explored or vision frame arrives; there is no per-frame work here; // - player markers are small sprites in the same layer, drawn above the fog sprite from the // `marker` set/del frames, never inferred from tiles or walls (decision 17). // // Why no stencil mask: a Graphics stencil mask forces a depth-stencil attachment plus a full-frame // stencil pass on every frame. Measured on the e2e's software renderer it cost ~350 ms of the // phone-class viewport-fill budget (test 412x869 dpr 2.625); the baked cut-out keeps the same // pixels and leaves the fill at the pre-fog baseline. The cut-out is rasterized at cell resolution, // the same resolution as the explored grid the server sends. // // The GM has no fog (story 26): the layer hides and the GM never receives `explored`/`vision`/ // `marker` frames anyway. The counts, timings and ids are published on the canvas dataset; the e2e // reads them and probes the pixels, so the test never touches renderer internals. import { Container, Graphics, GraphicsContext, Sprite, Texture } from 'pixi.js' import type { RenderContext, RenderModule } from '../stage.ts' import type { RootState } from '../../reducer.ts' import { fogOf } from '../../slices/fog.ts' import type { FogState, VisionPoly } from '../../slices/fog.ts' /** Explored-but-not-visible: black at 0.6 alpha, so the map reads dimmed, never hidden. */ export const EXPLORED_ALPHA = 0.6 /** One shared icon context for every marker: a lit window pane with a dark frame. */ const MARKER_ICON = new GraphicsContext() .roundRect(-7, -7, 14, 14, 2) .fill(0xffcc33) .stroke({ width: 2, color: 0x2b1d00 }) export const renderModule: RenderModule = { name: 'fog', mount({ app, layers, store }: RenderContext) { const canvas = app.canvas // Markers live in their own layer above the fog sprite. const markerLayer = new Container() layers.fog.addChild(markerLayer) let sprite: Sprite | null = null let texture: Texture | null = null /** Explored state (`alpha 255` never seen, `alpha 153` explored), at cell resolution. */ let base: HTMLCanvasElement | null = null let baseContext: CanvasRenderingContext2D | null = null let baseImage: ImageData | null = null /** What the sprite shows: `base` with the vision polygons cut out. */ let shown: HTMLCanvasElement | null = null let shownContext: CanvasRenderingContext2D | null = null let grid = { cols: 0, rows: 0 } let cell = 0 let sceneId: number | null = null /** The union of this player's polygons, kept for every recompose after a cell diff. */ let currentPolys: readonly VisionPoly[] = [] let renderedExplored = -1 let renderedVision = -1 let renderedMarkers = -1 const markerNodes = new Map() // Instrumentation. `cellsPainted` is the cumulative number of cell pixels touched, so a diff // is visibly cheaper than the snapshot; `fullRedraws` stays at 1 after a connect. const stats = { cellsPainted: 0, fullRedraws: 0, visionBuilds: 0, markerUpdates: 0, lastFresh: 0, exploredMs: 0, fullMs: 0, visionMs: 0, } function destroySurface(): void { sprite?.destroy() sprite = null texture?.destroy(true) texture = null base = null baseContext = null baseImage = null shown = null shownContext = null grid = { cols: 0, rows: 0 } cell = 0 sceneId = null renderedExplored = -1 renderedVision = -1 } function build(fog: FogState, width: number, height: number): void { const cols = fog.cols const rows = fog.rows if (cols <= 0 || rows <= 0) return base = document.createElement('canvas') base.width = cols base.height = rows const exploredContext = base.getContext('2d') if (!exploredContext) return baseContext = exploredContext baseImage = exploredContext.createImageData(cols, rows) // Before the first `explored` frame everything is never-seen: opaque black. exploredContext.fillStyle = '#000' exploredContext.fillRect(0, 0, cols, rows) shown = document.createElement('canvas') shown.width = cols shown.height = rows const fogContext = shown.getContext('2d') if (!fogContext) return shownContext = fogContext fogContext.fillStyle = '#000' fogContext.fillRect(0, 0, cols, rows) grid = { cols, rows } cell = fog.cell texture = Texture.from(shown) // The cell texture is displayed scaled: smooth beats a pixelated haze at any zoom. texture.source.scaleMode = 'linear' sprite = new Sprite(texture) sprite.width = width sprite.height = height sprite.label = 'fog' layers.fog.addChildAt(sprite, 0) sceneId = fog.sceneId renderedExplored = -1 renderedVision = -1 } /** * Rebuild the displayed texture from the explored base and the current vision polygons. The * canvas 2D `destination-out` fill is the polygon cut-out: antialiased at cell resolution and * one cheap draw, with no mask/stencil state on the render target. */ function compose(): number { if (!shownContext || !base || !shown) return 0 const started = performance.now() shownContext.globalCompositeOperation = 'copy' shownContext.drawImage(base, 0, 0) const polys = currentPolys if (polys.length > 0 && cell > 0) { shownContext.globalCompositeOperation = 'destination-out' shownContext.save() shownContext.scale(1 / cell, 1 / cell) // One fill per polygon: overlapping polygons punch the same hole whether their winding // orders agree or not (a single nonzero fill could cancel an opposite-winding overlap). for (const poly of polys) { const [first, ...rest] = poly.pts if (!first) continue shownContext.beginPath() shownContext.moveTo(first[0], first[1]) for (const [x, y] of rest) shownContext.lineTo(x, y) shownContext.closePath() shownContext.fill() } shownContext.restore() } shownContext.globalCompositeOperation = 'source-over' texture?.source.update() return performance.now() - started } /** Paint the explored state into `base`. Full repaint only for a snapshot or missed revision. */ function paintExplored(fog: FogState): void { if (!baseContext || !baseImage || !texture || fog.cols !== grid.cols || fog.rows !== grid.rows) { return } const started = performance.now() const data = baseImage.data const full = fog.snapshot || fog.exploredVersion !== renderedExplored + 1 const alpha = Math.round(EXPLORED_ALPHA * 255) if (full) { for (let i = 3; i < data.length; i += 4) data[i] = 255 for (const index of fog.cells) data[index * 4 + 3] = alpha baseContext.putImageData(baseImage, 0, 0) stats.cellsPainted += grid.cols * grid.rows stats.fullRedraws += 1 } else if (fog.fresh.length > 0) { let minX = grid.cols let minY = grid.rows let maxX = -1 let maxY = -1 for (const index of fog.fresh) { data[index * 4 + 3] = alpha const x = index % grid.cols const y = (index / grid.cols) | 0 if (x < minX) minX = x if (y < minY) minY = y if (x > maxX) maxX = x if (y > maxY) maxY = y } stats.cellsPainted += fog.fresh.length // One write of the dirtied rectangle, not the whole map. baseContext.putImageData(baseImage, 0, 0, minX, minY, maxX - minX + 1, maxY - minY + 1) } else { renderedExplored = fog.exploredVersion stats.exploredMs = performance.now() - started return } currentPolys = fog.polys const composeMs = compose() renderedExplored = fog.exploredVersion renderedVision = fog.visionVersion stats.lastFresh = fog.fresh.length stats.exploredMs = performance.now() - started + composeMs if (full) stats.fullMs = stats.exploredMs } /** Recompose the cut-out; nothing per frame. */ function paintVision(fog: FogState): void { if (!base) return currentPolys = fog.polys stats.visionMs = compose() renderedVision = fog.visionVersion stats.visionBuilds += 1 } /** Apply one `marker` change: only added, removed or moved ids are touched. */ function paintMarkers(fog: FogState): void { for (const [id, node] of markerNodes) { if (fog.markers[id] !== undefined) continue markerLayer.removeChild(node) node.destroy() markerNodes.delete(id) } for (const [id, pos] of Object.entries(fog.markers)) { let node = markerNodes.get(id) if (!node) { node = new Graphics(MARKER_ICON) node.label = `marker-${id}` markerLayer.addChild(node) markerNodes.set(id, node) } if (node.x !== pos[0] || node.y !== pos[1]) node.position.set(pos[0], pos[1]) } renderedMarkers = fog.markerVersion stats.markerUpdates += 1 } function publish(fog: FogState): void { const datasets = canvas.dataset const role = store.state.session.role datasets['fog'] = role === 'gm' ? 'gm' : sceneId === null ? 'idle' : 'player' datasets['fogCells'] = String(fog.cells.size) datasets['fogPolys'] = String(fog.polys.length) datasets['fogMarkers'] = Object.keys(fog.markers).join(' ') datasets['fogCellsPainted'] = String(stats.cellsPainted) datasets['fogFullRedraws'] = String(stats.fullRedraws) datasets['fogVisionBuilds'] = String(stats.visionBuilds) datasets['fogMarkerUpdates'] = String(stats.markerUpdates) datasets['fogLastFresh'] = String(stats.lastFresh) datasets['fogExploredMs'] = stats.exploredMs.toFixed(3) datasets['fogFullMs'] = stats.fullMs.toFixed(3) datasets['fogVisionMs'] = stats.visionMs.toFixed(3) } function sync(state: RootState): void { const fog = fogOf(state) const role = state.session.role const gm = role === 'gm' // The GM sees everything: no fog and no marker-only memory (stories 24-26). if (sprite) sprite.visible = !gm markerLayer.visible = !gm if (gm || fog.cols <= 0 || !state.session.scene) { publish(fog) return } const width = state.session.scene.w const height = state.session.scene.h if (sceneId !== fog.sceneId || !sprite) { destroySurface() build(fog, width, height) for (const node of markerNodes.values()) node.destroy() markerNodes.clear() } else if (sprite.width !== width || sprite.height !== height) { sprite.width = width sprite.height = height } if (!sprite) { publish(fog) return } if (fog.exploredVersion !== renderedExplored) paintExplored(fog) // A vision frame can arrive before the first explored frame; compose still needs the base. else if (fog.visionVersion !== renderedVision) paintVision(fog) if (fog.markerVersion !== renderedMarkers) paintMarkers(fog) publish(fog) } // The stage is created once the session is live, but a resync can beat `app.init`: start from // whatever the reducer already holds, then follow the event stream. sync(store.state) const unsubscribe = store.subscribe(sync) return () => { unsubscribe() for (const node of markerNodes.values()) node.destroy() markerNodes.clear() destroySurface() layers.fog.removeChild(markerLayer) markerLayer.destroy({ children: true }) } }, }