SPB Git

Repository Public

StrokeRenderer.swift 8.3 KB 159 lines swift

1// SP Lecture Studio — LecturePDF2// File: Packages/LecturePDF/Sources/StrokeRenderer.swift3// Description: Deterministic Core Graphics vector renderer for ink strokes, shapes and the laser pointer (live canvas, PDF export, video).4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import CoreGraphics9import LectureCore1011public extension RGBAColor {12    var cgColor: CGColor { CGColor(colorSpace: Bitmap.sRGB, components: [r, g, b, a]) ?? CGColor(red: r, green: g, blue: b, alpha: a) }13}1415/// Maps page-normalized coordinates (origin top-left, y down) to a rect of a Core Graphics context.16public struct PageMapping: Sendable {17    public var rect: CGRect18    /// True when the context has its origin at the top-left (UIKit / flipped NSView); false for bitmap and PDF contexts.19    public var flipped: Bool20    public init(rect: CGRect, flipped: Bool) { self.rect = rect; self.flipped = flipped }21    public func point(_ x: Double, _ y: Double) -> CGPoint {22        CGPoint(x: rect.minX + x * rect.width, y: flipped ? rect.minY + y * rect.height : rect.maxY - y * rect.height)23    }24    /// Inverse mapping: context point → page-normalized point.25    public func normalized(_ p: CGPoint) -> (x: Double, y: Double) {26        guard rect.width > 0, rect.height > 0 else { return (0, 0) }27        let x = (p.x - rect.minX) / rect.width28        let y = flipped ? (p.y - rect.minY) / rect.height : (rect.maxY - p.y) / rect.height29        return (x, y)30    }31}3233public enum StrokeRenderer {34    /// Draws the first `count` points of a stroke (all of them when nil).35    public static func draw(_ stroke: Stroke, count: Int? = nil, in ctx: CGContext, mapping: PageMapping) {36        let n = min(count ?? stroke.points.count, stroke.points.count)37        guard n > 0 else { return }38        let base = max(0.5, stroke.width * mapping.rect.width)39        ctx.saveGState()40        ctx.setLineCap(.round); ctx.setLineJoin(.round)41        ctx.setStrokeColor(stroke.color.cgColor); ctx.setFillColor(stroke.color.cgColor)42        if stroke.tool.isTranslucent { ctx.setBlendMode(.multiply) }4344        if stroke.tool.isShape {45            drawShape(stroke, count: n, in: ctx, mapping: mapping, width: base)46        } else if n == 1 {47            let p = mapping.point(stroke.points[0].x, stroke.points[0].y), w = base * stroke.points[0].w48            ctx.fillEllipse(in: CGRect(x: p.x - w / 2, y: p.y - w / 2, width: w, height: w))49        } else {50            let pts = stroke.points[0..<n]51            let uniform = stroke.tool.isTranslucent || !pts.contains { abs($0.w - pts[pts.startIndex].w) > 0.02 }52            if uniform {53                // One path, stroked once: a translucent marker does not darken where its own segments overlap.54                ctx.setLineWidth(base * pts[pts.startIndex].w)55                ctx.addPath(smoothPath(Array(pts), mapping: mapping)); ctx.strokePath()56            } else {57                // Pressure-sensitive ink: each smoothed span is stroked with its own width.58                let a = Array(pts)59                var prevMid = mapping.point(a[0].x, a[0].y)60                for i in 1..<a.count {61                    let p0 = mapping.point(a[i - 1].x, a[i - 1].y), p1 = mapping.point(a[i].x, a[i].y)62                    let mid = i == a.count - 1 ? p1 : CGPoint(x: (p0.x + p1.x) / 2, y: (p0.y + p1.y) / 2)63                    ctx.setLineWidth(base * (a[i - 1].w + a[i].w) / 2)64                    ctx.move(to: prevMid)65                    if i == 1 { ctx.addLine(to: mid) } else { ctx.addQuadCurve(to: mid, control: p0) }66                    ctx.strokePath()67                    prevMid = mid68                }69            }70        }71        ctx.restoreGState()72    }7374    /// Quadratic smoothing through the midpoints of the samples.75    static func smoothPath(_ a: [StrokePoint], mapping: PageMapping) -> CGPath {76        let path = CGMutablePath()77        let first = mapping.point(a[0].x, a[0].y)78        path.move(to: first)79        guard a.count > 2 else { path.addLine(to: mapping.point(a[a.count - 1].x, a[a.count - 1].y)); return path }80        for i in 1..<(a.count - 1) {81            let c = mapping.point(a[i].x, a[i].y), nx = mapping.point(a[i + 1].x, a[i + 1].y)82            path.addQuadCurve(to: CGPoint(x: (c.x + nx.x) / 2, y: (c.y + nx.y) / 2), control: c)83        }84        path.addLine(to: mapping.point(a[a.count - 1].x, a[a.count - 1].y))85        return path86    }8788    /// Shapes are defined by their first point (anchor) and the latest point (current corner while dragging).89    static func drawShape(_ stroke: Stroke, count n: Int, in ctx: CGContext, mapping: PageMapping, width: CGFloat) {90        let a = mapping.point(stroke.points[0].x, stroke.points[0].y)91        let b = mapping.point(stroke.points[n - 1].x, stroke.points[n - 1].y)92        ctx.setLineWidth(width)93        switch stroke.tool {94        case .rectangle:95            ctx.setLineJoin(.miter)96            ctx.stroke(CGRect(x: min(a.x, b.x), y: min(a.y, b.y), width: abs(b.x - a.x), height: abs(b.y - a.y)))97        case .ellipse:98            ctx.strokeEllipse(in: CGRect(x: min(a.x, b.x), y: min(a.y, b.y), width: abs(b.x - a.x), height: abs(b.y - a.y)))99        case .arrow:100            let len = hypot(b.x - a.x, b.y - a.y)101            ctx.move(to: a); ctx.addLine(to: b); ctx.strokePath()102            guard len > 0.5 else { return }103            let head = min(len * 0.45, max(width * 4.5, 8)), angle = atan2(b.y - a.y, b.x - a.x)104            for side in [-1.0, 1.0] {105                let t = angle + .pi - side * 0.45106                ctx.move(to: b); ctx.addLine(to: CGPoint(x: b.x + head * cos(t), y: b.y + head * sin(t)))107            }108            ctx.strokePath()109        default:110            ctx.move(to: a); ctx.addLine(to: b); ctx.strokePath()111        }112    }113114    public static func draw(_ strokes: [VisibleStroke], in ctx: CGContext, mapping: PageMapping) {115        for v in strokes { draw(v.stroke, count: v.pointCount, in: ctx, mapping: mapping) }116    }117118    /// Laser pointer: red dot with a soft halo.119    public static func drawPointer(x: Double, y: Double, in ctx: CGContext, mapping: PageMapping) {120        let p = mapping.point(x, y)121        let r = max(4, mapping.rect.width * 0.009)122        ctx.saveGState()123        ctx.setFillColor(CGColor(colorSpace: Bitmap.sRGB, components: [1, 0.1, 0.1, 0.22])!)124        ctx.fillEllipse(in: CGRect(x: p.x - r * 2.2, y: p.y - r * 2.2, width: r * 4.4, height: r * 4.4))125        ctx.setFillColor(CGColor(colorSpace: Bitmap.sRGB, components: [1, 0.08, 0.08, 0.95])!)126        ctx.fillEllipse(in: CGRect(x: p.x - r, y: p.y - r, width: r * 2, height: r * 2))127        ctx.setFillColor(CGColor(colorSpace: Bitmap.sRGB, components: [1, 0.85, 0.85, 0.9])!)128        ctx.fillEllipse(in: CGRect(x: p.x - r * 0.35, y: p.y - r * 0.35, width: r * 0.7, height: r * 0.7))129        ctx.restoreGState()130    }131132    /// Distance test used by the stroke eraser (page-normalized units; `aspect` = page width / height).133    public static func hit(_ stroke: Stroke, x: Double, y: Double, radius: Double, aspect: Double) -> Bool {134        let r = radius + stroke.width / 2135        if stroke.tool.isShape, let a = stroke.points.first, let b = stroke.points.last {136            let minX = min(a.x, b.x), maxX = max(a.x, b.x), minY = min(a.y, b.y), maxY = max(a.y, b.y)137            let ry = r * aspect138            switch stroke.tool {139            case .rectangle, .ellipse:140                let inOuter = x >= minX - r && x <= maxX + r && y >= minY - ry && y <= maxY + ry141                let inInner = x > minX + r && x < maxX - r && y > minY + ry && y < maxY - ry142                return inOuter && !inInner143            default:144                return segmentDistance(px: x, py: y / aspect, ax: a.x, ay: a.y / aspect, bx: b.x, by: b.y / aspect) <= r145            }146        }147        let pts = stroke.points148        if pts.count == 1 { return hypot(pts[0].x - x, (pts[0].y - y) / aspect) <= r }149        for i in 1..<max(1, pts.count) where segmentDistance(px: x, py: y / aspect, ax: pts[i - 1].x, ay: pts[i - 1].y / aspect, bx: pts[i].x, by: pts[i].y / aspect) <= r { return true }150        return false151    }152153    static func segmentDistance(px: Double, py: Double, ax: Double, ay: Double, bx: Double, by: Double) -> Double {154        let dx = bx - ax, dy = by - ay, len2 = dx * dx + dy * dy155        let t = len2 > 0 ? max(0, min(1, ((px - ax) * dx + (py - ay) * dy) / len2)) : 0156        return hypot(px - (ax + t * dx), py - (ay + t * dy))157    }158}159
Files main
Menu

Theme