SPB Git

Repository Public License

Fixtures.swift 17.1 KB 333 lines swift

1// ORIX Convert — Packages/EngineVector/Tests/EngineVectorTests/Fixtures.swift2// Description: Test fixtures drawn in code with Core Graphics / Core Text, and pixel helpers shared by the tests.3// Author: Simon-Pierre Boucher — contact@spboucher.ai4import CoreGraphics5import CoreText6import Foundation7import ImageIO8@testable import EngineVector910enum Fixture {11    static let sRGB = CGColorSpace(name: CGColorSpace.sRGB)!1213    static func color(_ r: Int, _ g: Int, _ b: Int, _ a: Double = 1) -> CGColor {14        CGColor(srgbRed: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a))15    }1617    /// Draws with a top-left origin, y down, one unit per pixel. `background: nil` leaves the canvas transparent.18    static func render(_ width: Int, _ height: Int, background: CGColor? = color(255, 255, 255), antialias: Bool = true,19                       _ draw: (CGContext) -> Void) -> CGImage {20        let ctx = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: sRGB,21                            bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!22        ctx.translateBy(x: 0, y: CGFloat(height))23        ctx.scaleBy(x: 1, y: -1)24        ctx.setShouldAntialias(antialias)25        ctx.setAllowsAntialiasing(antialias)26        if let background {27            ctx.setFillColor(background)28            ctx.fill(CGRect(x: 0, y: 0, width: width, height: height))29        }30        draw(ctx)31        return ctx.makeImage()!32    }3334    static func disc(_ size: Int = 256, radius: Double = 80, center: (Double, Double)? = nil, antialias: Bool = true) -> CGImage {35        let c = center ?? (Double(size) / 2, Double(size) / 2)36        return render(size, size, antialias: antialias) { ctx in37            ctx.setFillColor(color(0, 0, 0))38            ctx.fillEllipse(in: CGRect(x: c.0 - radius, y: c.1 - radius, width: 2 * radius, height: 2 * radius))39        }40    }4142    static func ring(_ size: Int = 256, outer: Double = 96, inner: Double = 56) -> CGImage {43        render(size, size) { ctx in44            let c = Double(size) / 245            ctx.setFillColor(color(20, 60, 200))46            ctx.addEllipse(in: CGRect(x: c - outer, y: c - outer, width: 2 * outer, height: 2 * outer))47            ctx.addEllipse(in: CGRect(x: c - inner, y: c - inner, width: 2 * inner, height: 2 * inner))48            ctx.fillPath(using: .evenOdd)49        }50    }5152    /// The picture `orix-convert dev seed images` draws (the benchmark and sweep input): a diagonal gradient, 2453    /// translucent rectangles and ellipses, and 40 thin white lines running from the top edge to the bottom edge.54    /// Many colour regions end on the border of the image, which is what the tracer got wrong (2026-11-21).55    static func seeded(width: Int, height: Int, seed: Int) -> CGImage {56        let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: sRGB,57                                bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)!58        let w = CGFloat(width), h = CGFloat(height)59        let hue = CGFloat((seed * 37) % 360) / 36060        let colors = [CGColor(red: 0.05 + 0.4 * hue, green: 0.15, blue: 0.45, alpha: 1), CGColor(red: 0.95, green: 0.75 - 0.3 * hue, blue: 0.35, alpha: 1)] as CFArray61        if let gradient = CGGradient(colorsSpace: sRGB, colors: colors, locations: [0, 1]) {62            context.drawLinearGradient(gradient, start: .zero, end: CGPoint(x: w, y: h), options: [])63        }64        var state = UInt64(truncatingIfNeeded: seed &* 2654435761 &+ 12345)65        func next() -> CGFloat {66            state = state &* 6364136223846793005 &+ 144269504088896340767            return CGFloat((state >> 33) % 10_000) / 10_00068        }69        for _ in 0..<24 {70            context.setFillColor(CGColor(red: next(), green: next(), blue: next(), alpha: 0.85))71            let rect = CGRect(x: next() * w * 0.9, y: next() * h * 0.9, width: next() * w * 0.3 + 4, height: next() * h * 0.3 + 4)72            if next() > 0.5 { context.fillEllipse(in: rect) } else { context.fill(rect) }73        }74        context.setStrokeColor(CGColor(red: 1, green: 1, blue: 1, alpha: 0.9))75        context.setLineWidth(max(1, w / 400))76        for index in 0..<40 {77            context.move(to: CGPoint(x: CGFloat(index) * w / 40, y: 0))78            context.addLine(to: CGPoint(x: w - CGFloat(index) * w / 40, y: h))79        }80        context.strokePath()81        return context.makeImage()!82    }8384    /// Largest distance by which a contour of `document` leaves its canvas, measured on the true extent of every85    /// curve (its extrema), not on its control points. 0 when the whole drawing is inside.86    static func excursion(_ document: VectorDocument) -> Double {87        var worst = 0.088        let vw = Double(document.width), vh = Double(document.height)89        for layer in document.layers { for sub in layer.subpaths {90            var current = sub.start91            worst = max(worst, -current.x, -current.y, current.x - vw, current.y - vh)92            for s in sub.segments {93                var points = [s.end]94                if case .cubic(let a, let b, let p) = s { points += TracedSVGReader.cubicExtrema(current, a, b, p) }95                for p in points { worst = max(worst, -p.x, -p.y, p.x - vw, p.y - vh) }96                current = s.end97            }98        } }99        return worst100    }101102    /// Black axis-aligned rectangle with fractional edges plus a triangle.103    static func polygons(_ size: Int = 256, antialias: Bool = true) -> CGImage {104        render(size, size, antialias: antialias) { ctx in105            ctx.setFillColor(color(0, 0, 0))106            ctx.fill(CGRect(x: 40.25, y: 30.5, width: 100.5, height: 60.25))107            ctx.move(to: CGPoint(x: 60, y: 230)); ctx.addLine(to: CGPoint(x: 200, y: 215)); ctx.addLine(to: CGPoint(x: 120, y: 120))108            ctx.closePath(); ctx.fillPath()109        }110    }111112    /// Draws a line of bold text with its baseline starting at (x, baseline), in a y-down context.113    static func drawText(_ string: String, in ctx: CGContext, x: CGFloat, baseline: CGFloat, fontSize: CGFloat, color foreground: CGColor) {114        let font = CTFontCreateWithName("Helvetica-Bold" as CFString, fontSize, nil)115        let attributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key(kCTFontAttributeName as String): font,116                                                         NSAttributedString.Key(kCTForegroundColorAttributeName as String): foreground]117        let line = CTLineCreateWithAttributedString(NSAttributedString(string: string, attributes: attributes))118        // Core Text draws with y up: flip locally around the baseline.119        ctx.saveGState()120        ctx.translateBy(x: x, y: baseline)121        ctx.scaleBy(x: 1, y: -1)122        ctx.textPosition = .zero123        CTLineDraw(line, ctx)124        ctx.restoreGState()125    }126127    static func text(_ string: String = "ORIX", width: Int = 512, height: Int = 200, fontSize: CGFloat = 130,128                     foreground: CGColor = color(15, 15, 20), background: CGColor? = color(255, 255, 255)) -> CGImage {129        render(width, height, background: background) { ctx in130            drawText(string, in: ctx, x: 24, baseline: CGFloat(height) * 0.72, fontSize: fontSize, color: foreground)131        }132    }133134    static func thinLines(_ size: Int = 256) -> CGImage {135        render(size, size) { ctx in136            ctx.setStrokeColor(color(0, 0, 0))137            ctx.setLineWidth(3)138            ctx.move(to: CGPoint(x: 20, y: 30)); ctx.addLine(to: CGPoint(x: 236, y: 60)); ctx.strokePath()139            ctx.setLineWidth(2)140            ctx.addEllipse(in: CGRect(x: 60, y: 90, width: 130, height: 110)); ctx.strokePath()141            ctx.setLineWidth(4)142            ctx.move(to: CGPoint(x: 30, y: 230)); ctx.addCurve(to: CGPoint(x: 230, y: 225), control1: CGPoint(x: 90, y: 150), control2: CGPoint(x: 160, y: 300)); ctx.strokePath()143        }144    }145146    /// Flat illustration with five well-separated colours (background included), regions touching each other.147    static func illustration(_ size: Int = 320) -> CGImage {148        let s = CGFloat(size) / 320149        return render(size, size, background: color(245, 240, 225)) { ctx in150            ctx.scaleBy(x: s, y: s)151            ctx.setFillColor(color(40, 120, 200)); ctx.fill(CGRect(x: 0, y: 190, width: 320, height: 130))152            ctx.setFillColor(color(230, 70, 50)); ctx.fillEllipse(in: CGRect(x: 60, y: 50, width: 150, height: 150))153            ctx.setFillColor(color(250, 200, 40))154            ctx.move(to: CGPoint(x: 180, y: 250)); ctx.addLine(to: CGPoint(x: 300, y: 250)); ctx.addLine(to: CGPoint(x: 240, y: 110)); ctx.closePath(); ctx.fillPath()155            ctx.setFillColor(color(30, 30, 40)); ctx.fill(CGRect(x: 30, y: 230, width: 110, height: 50))156            ctx.fillEllipse(in: CGRect(x: 110, y: 100, width: 40, height: 40))157        }158    }159160    /// Icon on a transparent background: rounded square with a white glyph.161    static func transparentIcon(_ size: Int = 128) -> CGImage {162        let s = CGFloat(size) / 128163        return render(size, size, background: nil) { ctx in164            ctx.scaleBy(x: s, y: s)165            ctx.setFillColor(color(10, 132, 255))166            ctx.addPath(CGPath(roundedRect: CGRect(x: 12, y: 12, width: 104, height: 104), cornerWidth: 24, cornerHeight: 24, transform: nil)); ctx.fillPath()167            ctx.setFillColor(color(255, 255, 255))168            ctx.move(to: CGPoint(x: 64, y: 30)); ctx.addLine(to: CGPoint(x: 96, y: 92)); ctx.addLine(to: CGPoint(x: 32, y: 92)); ctx.closePath(); ctx.fillPath()169        }170    }171172    /// Hard-edged (no anti-aliasing) black shape on white: a pixel is ink when its centre satisfies `inside`.173    static func hardEdged(_ width: Int, _ height: Int, inside: (Double, Double) -> Bool) -> CGImage {174        var data = [UInt8](repeating: 255, count: width * height * 4)175        for y in 0..<height { for x in 0..<width where inside(Double(x) + 0.5, Double(y) + 0.5) {176            let i = (y * width + x) * 4177            data[i] = 0; data[i + 1] = 0; data[i + 2] = 0178        } }179        return image(fromRGBA: data, width: width, height: height)180    }181182    /// Deterministic pseudo-random numbers (xorshift) for noise fixtures.183    struct Random {184        var state: UInt64185        mutating func next() -> UInt64 {186            state ^= state << 13; state ^= state >> 7; state ^= state << 17187            return state188        }189        mutating func unit() -> Double { Double(next() % 1_000_000) / 1_000_000 }190    }191192    static func image(fromRGBA data: [UInt8], width: Int, height: Int) -> CGImage {193        let provider = CGDataProvider(data: Data(data) as CFData)!194        return CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4, space: sRGB,195                       bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue), provider: provider, decode: nil,196                       shouldInterpolate: false, intent: .defaultIntent)!197    }198199    static func pixels(_ image: CGImage) -> [UInt8] {200        (try! Raster(image: image, width: image.width, height: image.height)).data201    }202203    /// A scan-like page: grey paper, dark disc and bar, salt-and-pepper specks and Gaussian-ish noise.204    static func noisyScan(_ size: Int = 256) -> CGImage {205        let base = render(size, size, background: color(232, 230, 224)) { ctx in206            ctx.setFillColor(color(35, 35, 40))207            ctx.fillEllipse(in: CGRect(x: 50, y: 40, width: 120, height: 120))208            ctx.fill(CGRect(x: 40, y: 190, width: 180, height: 30))209        }210        var data = pixels(base)211        var random = Random(state: 0x9E3779B97F4A7C15)212        for i in 0..<(size * size) {213            let noise = Int((random.unit() + random.unit() + random.unit() - 1.5) * 28)214            let speck = random.next() % 400215            for c in 0..<3 {216                var v = Int(data[i * 4 + c]) + noise217                if speck == 0 { v = 20 } else if speck == 1 { v = 245 }218                data[i * 4 + c] = UInt8(max(0, min(255, v)))219            }220        }221        return image(fromRGBA: data, width: size, height: size)222    }223224    /// Photo-like content: smooth two-dimensional gradients plus fine texture.225    static func photoLike(_ size: Int = 256) -> CGImage {226        var data = [UInt8](repeating: 255, count: size * size * 4)227        var random = Random(state: 42)228        for y in 0..<size {229            for x in 0..<size {230                let u = Double(x) / Double(size), v = Double(y) / Double(size)231                let r = 128 + 100 * sin(u * 5.1 + v * 2.2) + (random.unit() - 0.5) * 30232                let g = 128 + 100 * sin(v * 6.3 - u * 1.7 + 1) + (random.unit() - 0.5) * 30233                let b = 128 + 100 * cos((u + v) * 4.4) + (random.unit() - 0.5) * 30234                let i = (y * size + x) * 4235                data[i] = UInt8(max(0, min(255, r))); data[i + 1] = UInt8(max(0, min(255, g))); data[i + 2] = UInt8(max(0, min(255, b)))236            }237        }238        return image(fromRGBA: data, width: size, height: size)239    }240241    /// Black shapes with a field of isolated 2 × 2 specks.242    static func speckled(_ size: Int = 200) -> (image: CGImage, speckCount: Int) {243        var count = 0244        let image = render(size, size, antialias: false) { ctx in245            ctx.setFillColor(color(0, 0, 0))246            ctx.fill(CGRect(x: 60, y: 60, width: 80, height: 80))247            for k in 0..<12 {248                ctx.fill(CGRect(x: 8 + k * 15, y: 12 + (k % 3) * 9, width: 2, height: 2)); count += 1249            }250        }251        return (image, count)252    }253254    static func write(_ image: CGImage, type: String, to url: URL, properties: [CFString: Any] = [:]) -> Bool {255        guard let destination = CGImageDestinationCreateWithURL(url as CFURL, type as CFString, 1, nil) else { return false }256        CGImageDestinationAddImage(destination, image, properties as CFDictionary)257        return CGImageDestinationFinalize(destination)258    }259260    static func temporaryDirectory(_ name: String = "vector") -> URL {261        let url = FileManager.default.temporaryDirectory.appendingPathComponent("orix-\(name)-\(UUID().uuidString)", isDirectory: true)262        try! FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)263        return url264    }265266    /// Mean absolute difference (0–255) between two images composited over white, at the size of `a`.267    static func meanAbsoluteError(_ a: CGImage, _ b: CGImage) -> Double {268        let ra = try! Raster(image: a, width: a.width, height: a.height).flattened(over: .white)269        let rb = try! Raster(image: b, width: a.width, height: a.height).flattened(over: .white)270        var sum = 0.0271        for i in stride(from: 0, to: ra.data.count, by: 4) {272            sum += Double(abs(Int(ra.data[i]) - Int(rb.data[i])) + abs(Int(ra.data[i + 1]) - Int(rb.data[i + 1])) + abs(Int(ra.data[i + 2]) - Int(rb.data[i + 2]))) / 3273        }274        return sum / Double(a.width * a.height)275    }276}277278// MARK: - Geometry and pixel helpers279280enum Probe {281    /// Points sampled along every segment of a layer.282    static func samples(_ layer: VectorLayer, perSegment: Int = 24) -> [VectorPoint] {283        var out: [VectorPoint] = []284        for sub in layer.subpaths {285            var cur = sub.start286            for s in sub.segments {287                for k in 0...perSegment {288                    let t = Double(k) / Double(perSegment), u = 1 - t289                    switch s {290                    case .line(let p): out.append(VectorPoint(x: cur.x * u + p.x * t, y: cur.y * u + p.y * t))291                    case .cubic(let a, let b, let p):292                        out.append(VectorPoint(x: cur.x * u * u * u + 3 * a.x * u * u * t + 3 * b.x * u * t * t + p.x * t * t * t,293                                               y: cur.y * u * u * u + 3 * a.y * u * u * t + 3 * b.y * u * t * t + p.y * t * t * t))294                    }295                }296                cur = s.end297            }298        }299        return out300    }301302    /// Signed area of a contour (curves flattened).303    static func signedArea(_ sub: VectorSubpath) -> Double {304        let pts = samples(VectorLayer(color: .black, subpaths: [sub]), perSegment: 16)305        var area = 0.0306        for i in 0..<pts.count {307            let a = pts[i], b = pts[(i + 1) % pts.count]308            area += a.x * b.y - b.x * a.y309        }310        return area / 2311    }312313    /// Every vertex (segment end point) of a layer.314    static func vertices(_ layer: VectorLayer) -> [VectorPoint] {315        layer.subpaths.flatMap { sub in sub.segments.map(\.end) }316    }317318    static func nearest(_ points: [VectorPoint], to x: Double, _ y: Double) -> Double {319        points.map { (($0.x - x) * ($0.x - x) + ($0.y - y) * ($0.y - y)).squareRoot() }.min() ?? .infinity320    }321322    /// Premultiplied RGBA of pixel (x, y).323    static func pixel(_ image: CGImage, _ x: Int, _ y: Int) -> [Int] {324        let data = Fixture.pixels(image)325        let i = (y * image.width + x) * 4326        return [Int(data[i]), Int(data[i + 1]), Int(data[i + 2]), Int(data[i + 3])]327    }328329    static func layer(_ document: VectorDocument, near color: VectorColor, tolerance: Int = 24) -> VectorLayer? {330        document.layers.first { abs(Int($0.color.red) - Int(color.red)) <= tolerance && abs(Int($0.color.green) - Int(color.green)) <= tolerance && abs(Int($0.color.blue) - Int(color.blue)) <= tolerance }331    }332}333
Files main
Menu

Theme