import { BACKGROUND, FOREGROUND, Matrix, Shape } from './dxf-geometry'; /** * Painting shapes onto a canvas. Shapes are grouped by colour, dash, width * and kind into one Path2D each, built in world coordinates once per drawing. * Painting is then a handful of stroke() calls whatever the zoom, which is * what keeps a floor plan with tens of thousands of lines responsive while * panning. * * Groups are kept per layer, so a layer switched off - or frozen in one * viewport of a layout - is skipped without rebuilding anything; and they are * split into segments at each mask (a WIPEOUT, an MTEXT background), which * must cover what was drawn before it and nothing drawn after. */ /** As drawn; every colour as its grey; or everything black on white (white on a dark background). */ export type ColorMode = 'color' | 'grey' | 'mono'; /** AutoCAD text height is the height of a capital; a font's em box is taller by about this much. */ export const CAP_TO_EM = 1 / 0.716; export interface Batch { color: number; kind: 'line' | 'fill'; tint: boolean; dash: number[] | null; /** A polyline's own width, in world units; 0 for none. */ width: number; /** Lineweight in millimetres. */ lw: number; path: Path2D; } export interface LayerPaint { batches: Batch[]; texts: Shape[]; points: Shape[]; } export interface Segment { /** Painted first, over everything in the segments before. */ mask: Path2D | null; maskColor: number; /** The mask's layer: switched off, or frozen in the viewport, it hides nothing. */ maskLayer: string; layers: Map; } export function prepare(shapes: Shape[]): Segment[] { const segments: Segment[] = []; let seg: Segment = { mask: null, maskColor: BACKGROUND, maskLayer: '', layers: new Map() }; let keys = new Map(); segments.push(seg); for (const s of shapes) { if (s.ghost) continue; if (s.mask) { seg = { mask: new Path2D(), maskColor: s.color, maskLayer: s.layer, layers: new Map() }; keys = new Map(); addRings(seg.mask!, s, true); segments.push(seg); continue; } let lp = seg.layers.get(s.layer); if (!lp) { lp = { batches: [], texts: [], points: [] }; seg.layers.set(s.layer, lp); } if (s.kind === 'text') { lp.texts.push(s); continue; } if (s.kind === 'point') { lp.points.push(s); continue; } const key = `${s.layer}\u0000${s.kind}|${s.color}|${s.tint ? 1 : 0}|${s.dash?.join(',') ?? ''}|${s.width ?? 0}|${s.lw ?? 0}`; let b = keys.get(key); if (!b) { b = { color: s.color, kind: s.kind, tint: !!s.tint, dash: s.dash ?? null, width: s.width ?? 0, lw: s.lw ?? 0, path: new Path2D() }; keys.set(key, b); lp.batches.push(b); } addRings(b.path, s, s.kind === 'fill'); } return segments; } function addRings(path: Path2D, s: Shape, close: boolean): void { for (const r of s.rings ?? []) { if (s.segs) { for (let i = 0; i + 3 < r.length; i += 4) { path.moveTo(r[i], r[i + 1]); path.lineTo(r[i + 2], r[i + 3]); } continue; } path.moveTo(r[0], r[1]); for (let i = 2; i < r.length; i += 2) path.lineTo(r[i], r[i + 1]); if (s.closed || close) path.closePath(); } } export interface PaintOptions { /** World to CSS pixels on the canvas (y down). */ m: Matrix; dpr: number; dark: boolean; mode: ColorMode; /** Layers not to paint: those switched off, and those frozen in this viewport. */ hidden: Set; /** A lineweight in millimetres as a stroke width in CSS pixels. */ lwPx: (mm: number) => number; /** Outline(s) to paint inside, in CSS pixels: a viewport's boundary. */ clip?: number[][]; /** Canvas size in CSS pixels, to skip text far off screen. */ w: number; h: number; } /** Paints prepared segments through a view. */ export function paintSegments(ctx: CanvasRenderingContext2D, segments: Segment[], o: PaintOptions): void { const { m, dpr, dark, mode } = o; const s = Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2])) || 1; ctx.save(); if (o.clip) { ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.beginPath(); for (const r of o.clip) { ctx.moveTo(r[0], r[1]); for (let i = 2; i < r.length; i += 2) ctx.lineTo(r[i], r[i + 1]); ctx.closePath(); } ctx.clip('evenodd'); } const world = () => ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]); ctx.lineJoin = 'round'; ctx.lineCap = 'round'; for (const seg of segments) { world(); if (seg.mask && !o.hidden.has(seg.maskLayer)) { ctx.fillStyle = cssColor(mode === 'mono' ? BACKGROUND : seg.maskColor, dark, mode); ctx.fill(seg.mask, 'nonzero'); } const shown = [...seg.layers].filter(([name]) => !o.hidden.has(name)).map(([, lp]) => lp); // Fills first, so lines and text sit on top of hatching. for (const lp of shown) { for (const b of lp.batches) { if (b.kind !== 'fill') continue; ctx.globalAlpha = b.tint ? 0.28 : 1; ctx.fillStyle = cssColor(b.color, dark, mode); ctx.fill(b.path, 'evenodd'); } } ctx.globalAlpha = 1; for (const lp of shown) { for (const b of lp.batches) { if (b.kind === 'fill') continue; // A dash pattern that would be under two pixels on screen is drawn solid: // it would only read as a grey smudge, and is slow to rasterise. const dashLen = b.dash?.reduce((a, v) => a + v, 0) ?? 0; ctx.setLineDash(b.dash && dashLen * s > 4 ? b.dash : []); ctx.strokeStyle = cssColor(b.color, dark, mode); ctx.lineWidth = Math.max(o.lwPx(b.lw) / s, b.width); ctx.stroke(b.path); } } ctx.setLineDash([]); // Points and text in screen space: canvas text at a sub-pixel font size // does not render reliably, so world sizes are converted here. ctx.setTransform(dpr, 0, 0, dpr, 0, 0); for (const lp of shown) { for (const p of lp.points) { const r = p.rings![0]; const x = m[0] * r[0] + m[2] * r[1] + m[4]; const y = m[1] * r[0] + m[3] * r[1] + m[5]; ctx.fillStyle = cssColor(p.color, dark, mode); ctx.fillRect(x - 1.5, y - 1.5, 3, 3); } for (const t of lp.texts) paintText(ctx, t, m, s, o.w, o.h, cssColor(t.color, dark, mode)); } } ctx.restore(); } function paintText(ctx: CanvasRenderingContext2D, t: Shape, m: Matrix, s: number, w: number, h: number, css: string): void { const tx = t.text!; const size = tx.height * s * CAP_TO_EM; if (size < 2.5) return; const x = m[0] * tx.x + m[2] * tx.y + m[4]; const y = m[1] * tx.x + m[3] * tx.y + m[5]; if (x < -w || x > 2 * w || y < -h || y > 2 * h) return; // The text's direction carried through the view, which turns y down. const c = Math.cos(tx.rotation), sn = Math.sin(tx.rotation); const angle = Math.atan2(m[1] * c + m[3] * sn, m[0] * c + m[2] * sn); ctx.save(); ctx.translate(x, y); ctx.rotate(angle); ctx.scale(tx.widthFactor * (tx.mirrored ? -1 : 1), 1); ctx.font = `${size}px Arial, Helvetica, sans-serif`; ctx.fillStyle = css; ctx.textAlign = tx.align; ctx.textBaseline = tx.lines.length > 1 && tx.baseline === 'alphabetic' ? 'bottom' : tx.baseline; const step = tx.height * s * tx.lineSpacing; const n = tx.lines.length; // Multi-line blocks are anchored by their top, middle or bottom edge as a whole. const first = tx.baseline === 'middle' ? -((n - 1) * step) / 2 : tx.baseline === 'bottom' ? -(n - 1) * step : 0; tx.lines.forEach((line, i) => ctx.fillText(line, 0, first + i * step)); ctx.restore(); } /** The screen background behind a drawing. */ export function backgroundCss(dark: boolean): string { return dark ? '#1d1f27' : '#ffffff'; } /** * A shape colour as CSS. ACI 7 (FOREGROUND) follows the background; pure * white on a light background, or pure black on a dark one, would vanish and * is swapped. Grey turns each colour into its luminance; mono makes every * line the foreground colour. */ export function cssColor(c: number, dark: boolean, mode: ColorMode = 'color'): string { if (c === BACKGROUND) return backgroundCss(dark); let rgb: number; if (c === FOREGROUND || mode === 'mono') rgb = dark ? 0xf2f2f2 : 0x111111; else if (!dark && c === 0xffffff) rgb = 0x111111; else if (dark && c === 0x000000) rgb = 0xf2f2f2; else rgb = c; if (mode === 'grey') { const r = (rgb >> 16) & 255, g = (rgb >> 8) & 255, b = rgb & 255; let y = Math.round(0.299 * r + 0.587 * g + 0.114 * b); // Light colours on white paper would fade out; keep every grey at least as dark as mid-grey. if (!dark) y = Math.min(y, 0x80); rgb = (y << 16) | (y << 8) | y; } return `#${rgb.toString(16).padStart(6, '0')}`; }