import type { ImageDocument } from "@core/document"; import type { EditorState } from "@editor/state"; export type RenderFrame = { document: ImageDocument; editor: EditorState; }; export type ImageRenderer = { render(frame: RenderFrame): void; dispose(): void; }; export type RendererBackend = "webgl"; export function createRenderer(canvas: HTMLCanvasElement, backend: RendererBackend = "webgl"): ImageRenderer { if (backend !== "webgl") { throw new Error(`Unsupported renderer backend: ${backend}`); } const context = canvas.getContext("webgl2"); if (!context) { throw new Error("WebGL2 is not available"); } const clearRect = (x: number, y: number, w: number, h: number, color: [number, number, number, number]) => { context.scissor(x, canvas.height - y - h, w, h); context.clearColor(...color); context.clear(context.COLOR_BUFFER_BIT); }; return { render(frame) { const { w, h } = frame.editor.viewport.size; const { center, zoom } = frame.editor.viewport; if (canvas.width !== w) canvas.width = w; if (canvas.height !== h) canvas.height = h; context.viewport(0, 0, w, h); context.disable(context.SCISSOR_TEST); context.clearColor(0.18, 0.18, 0.2, 1); context.clear(context.COLOR_BUFFER_BIT); context.enable(context.SCISSOR_TEST); for (const artboard of frame.document.artboards) { const x = Math.round(w / 2 + (artboard.bounds.x - center.x) * zoom); const y = Math.round(h / 2 + (artboard.bounds.y - center.y) * zoom); const width = Math.max(0, Math.round(artboard.bounds.w * zoom)); const height = Math.max(0, Math.round(artboard.bounds.h * zoom)); if (artboard.backgroundColor === "transparent") { const squareSize = Math.max(4, Math.round(12 * zoom)); for (let py = y; py < y + height; py += squareSize) { for (let px = x; px < x + width; px += squareSize) { const sx = Math.max(0, px); const sy = Math.max(0, py); const sw = Math.min(px + squareSize, x + width, w) - sx; const sh = Math.min(py + squareSize, y + height, h) - sy; if (sw <= 0 || sh <= 0) continue; const checker = (Math.floor((px - x) / squareSize) + Math.floor((py - y) / squareSize)) % 2 === 0; clearRect(sx, sy, sw, sh, checker ? [0.82, 0.82, 0.86, 1] : [0.94, 0.94, 0.97, 1]); } } } } context.disable(context.SCISSOR_TEST); }, dispose() {}, }; }