// The grid layer (story 18, DESIGN 7.1 layer 2): one TilingSprite over a tiny cell texture, not a // per-frame redraw. The texture is `grid_size` world pixels square with a one-pixel line along its // top/left edge; tiling it across the scene puts a line on every cell boundary. // // The toggle is owned by the camera module (`#grid-toggle`); this module only follows // `viewport.grid` and writes `data-grid` on the canvas so the e2e can prove the state change. import { Texture, TilingSprite } from 'pixi.js' import type { RenderModule } from '../stage.ts' import type { SceneInfo } from '../../protocol.ts' import { viewport } from '../../viewport.ts' function gridTexture(cell: number): Texture { const canvas = document.createElement('canvas') canvas.width = cell canvas.height = cell const context = canvas.getContext('2d') if (context) { context.strokeStyle = 'rgba(230, 240, 255, 0.30)' context.lineWidth = 1 context.beginPath() context.moveTo(0.5, 0) context.lineTo(0.5, cell) context.moveTo(0, 0.5) context.lineTo(cell, 0.5) context.stroke() } const texture = Texture.from(canvas) texture.source.label = `grid-${cell}` return texture } export const renderModule: RenderModule = { name: 'grid', mount({ app, layers }) { let sprite: TilingSprite | null = null let texture: Texture | null = null let sceneId: number | null = null function build(scene: SceneInfo): void { const cell = Math.max(4, Math.round(scene.grid_size || scene.tile_size || 32)) texture = gridTexture(cell) sprite = new TilingSprite({ texture, width: scene.w, height: scene.h }) sprite.label = 'grid' layers.grid.addChild(sprite) sceneId = scene.id } function sync(): void { const { scene, grid } = viewport.state if (!scene) { if (sprite) sprite.visible = false return } if (scene.id !== sceneId) { destroy() build(scene) } if (sprite) sprite.visible = grid app.canvas.dataset['grid'] = grid ? 'on' : 'off' } function destroy(): void { sprite?.destroy() sprite = null texture?.destroy(true) texture = null sceneId = null } const unsubscribe = viewport.subscribe(sync) sync() return () => { unsubscribe() destroy() } }, }