import QuartzCore
import Foundation

private typealias PlugVec = SIMD3<Double>
private typealias PlugPoint = SIMD2<Double>

private struct PlugFrame {
    let plate: CGPath
    let plateFront: CGPath
    let sockets: CGPath
    let slots: CGPath
    let prongs: CGPath
    let body: CGPath
    let cable: CGPath
    let cap: CGPath
    let sparks: CGPath
    let facing: Bool
}

private enum PlugModel {
    static let duration = 4.0
    static let count = 120
    static let t0 = 0.12, th = 0.85, tr = 1.22, tk = 1.42, tc = 1.52, tu = 3.05, to = 3.2, te = 3.95
    static let yaw = 18.0 * Double.pi / 180, pitch = 12.0 * Double.pi / 180
    static let cx = 38.0, cy = 56.0
    static let seat = PlugVec(0, -17, 3.6)
    static let pw = 31.0, ph = 20.0, pl = 7.0, pr = 8.0
    static let into: [PlugVec] = [PlugVec(28, 150, 26), PlugVec(40, 100, 26), PlugVec(18, 68, 26), PlugVec(40, 38, 26), PlugVec(26, 12, 24), PlugVec(36, -10, 22)]
    static let hover = PlugVec(36, -10, 22)
    static let bay = PlugVec(44, -2, 26)
    static let quit = PlugVec(30, -14, 30)
    static let outPath: [PlugVec] = [quit, PlugVec(44, 12, 28), PlugVec(22, 48, 26), PlugVec(42, 92, 26), PlugVec(28, 150, 26)]
    static let sp1 = lerp(bay, seat, 0.35)
    static let sp2 = seat + PlugVec(0, 0, 18)
    static let nodes = 36
    static let seg = 3.0
    static let anchor = PlugVec(22, 80, 10)
    static let gravity = PlugVec(0, 70, 0)

    static func clamp(_ u: Double) -> Double { max(0, min(1, u)) }
    static func ease(_ u: Double) -> Double { let c = clamp(u); return c * c * (3 - 2 * c) }
    static func eout(_ u: Double) -> Double { 1 - pow(1 - clamp(u), 3) }
    static func ein3(_ u: Double) -> Double { pow(clamp(u), 3) }
    static func dot(_ a: PlugVec, _ b: PlugVec) -> Double { (a * b).sum() }
    static func cross(_ a: PlugVec, _ b: PlugVec) -> PlugVec { PlugVec(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x) }
    static func norm(_ a: PlugVec) -> PlugVec { let d = dot(a, a).squareRoot(); return a / (d == 0 ? 1 : d) }
    static func lerp(_ a: PlugVec, _ b: PlugVec, _ u: Double) -> PlugVec { a + (b - a) * u }

    static func project(_ p: PlugVec) -> PlugPoint {
        let x1 = p.x * cos(yaw) + p.z * sin(yaw)
        let z1 = -p.x * sin(yaw) + p.z * cos(yaw)
        let y2 = p.y * cos(pitch) + z1 * sin(pitch)
        return PlugPoint(cx + x1, cy + y2)
    }

    static func projectVector(_ v: PlugVec) -> PlugPoint { project(v) - project(PlugVec(0, 0, 0)) }
    static let camera = norm(PlugVec(sin(yaw) * cos(pitch), -sin(pitch), cos(yaw) * cos(pitch)))

    static func cg(_ p: PlugPoint) -> CGPoint { CGPoint(x: p.x, y: p.y) }

    static func matrix(_ o: PlugVec, _ e1: PlugVec, _ e2: PlugVec) -> CGAffineTransform {
        let a = projectVector(e1), b = projectVector(e2), c = project(o)
        return CGAffineTransform(a: a.x, b: a.y, c: b.x, d: b.y, tx: c.x, ty: c.y)
    }

    static func roundRect(_ w: Double, _ h: Double, _ r: Double, _ n: Int = 6) -> [PlugPoint] {
        var out: [PlugPoint] = []
        let corners: [(Double, Double, Double)] = [(w / 2 - r, h / 2 - r, 0), (-w / 2 + r, h / 2 - r, 90), (-w / 2 + r, -h / 2 + r, 180), (w / 2 - r, -h / 2 + r, 270)]
        for (ccx, ccy, a0) in corners {
            for j in 0...n {
                let a = (a0 + 90 * Double(j) / Double(n)) * Double.pi / 180
                out.append(PlugPoint(ccx + r * cos(a), ccy + r * sin(a)))
            }
        }
        return out
    }

    static func hull(_ input: [PlugPoint]) -> [PlugPoint] {
        var pts = input.map { PlugPoint(($0.x * 1000).rounded() / 1000, ($0.y * 1000).rounded() / 1000) }
        pts.sort { $0.x != $1.x ? $0.x < $1.x : $0.y < $1.y }
        var unique: [PlugPoint] = []
        for p in pts where unique.last != p { unique.append(p) }
        guard unique.count >= 3 else { return unique }
        func crossing(_ o: PlugPoint, _ a: PlugPoint, _ b: PlugPoint) -> Double { (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x) }
        var lower: [PlugPoint] = []
        var upper: [PlugPoint] = []
        for p in unique {
            while lower.count >= 2 && crossing(lower[lower.count - 2], lower[lower.count - 1], p) <= 0 { lower.removeLast() }
            lower.append(p)
        }
        for p in unique.reversed() {
            while upper.count >= 2 && crossing(upper[upper.count - 2], upper[upper.count - 1], p) <= 0 { upper.removeLast() }
            upper.append(p)
        }
        return Array(lower.dropLast()) + Array(upper.dropLast())
    }

    static func poly(_ pts: [PlugPoint]) -> CGPath {
        let path = CGMutablePath()
        path.addLines(between: pts.map(cg))
        path.closeSubpath()
        return path
    }

    static func roundedPoly(_ pts: [PlugPoint], _ r: Double) -> CGPath {
        let n = pts.count
        let path = CGMutablePath()
        for i in 0..<n {
            let a = pts[(i + n - 1) % n], b = pts[i], c = pts[(i + 1) % n]
            let d1 = max(hypot(b.x - a.x, b.y - a.y), 1e-6)
            let d2 = max(hypot(c.x - b.x, c.y - b.y), 1e-6)
            let k1 = min(r, d1 * 0.5) / d1
            let k2 = min(r, d2 * 0.5) / d2
            let p1 = b + (a - b) * k1
            let p2 = b + (c - b) * k2
            if i == 0 { path.move(to: cg(p1)) } else { path.addLine(to: cg(p1)) }
            path.addQuadCurve(to: cg(p2), control: cg(b))
        }
        path.closeSubpath()
        return path
    }

    static func catmull(_ pts: [PlugVec], _ u: Double) -> PlugVec {
        let n = pts.count - 1
        let x = clamp(u) * Double(n)
        let i = min(Int(x), n - 1)
        let f = x - Double(i)
        let p0 = pts[max(i - 1, 0)], p1 = pts[i], p2 = pts[i + 1], p3 = pts[min(i + 2, n)]
        let a = p1 * 2
        let b = (p2 - p0) * f
        let c = (p0 * 2 - p1 * 5 + p2 * 4 - p3) * (f * f)
        let d = (p3 - p0 + (p1 - p2) * 3) * (f * f * f)
        return (a + b + c + d) * 0.5
    }

    static func bezier(_ p0: PlugVec, _ p1: PlugVec, _ p2: PlugVec, _ p3: PlugVec, _ u: Double) -> PlugVec {
        let a = pow(1 - u, 3), b = 3 * u * pow(1 - u, 2), c = 3 * u * u * (1 - u), d = u * u * u
        return p0 * a + p1 * b + p2 * c + p3 * d
    }

    static func head(_ t: Double) -> (PlugVec, Double) {
        if t < t0 { return (into[0], 1) }
        if t < th {
            let u = (t - t0) / (th - t0)
            return (catmull(into, eout(u) * 0.55 + ease(u) * 0.45), 1)
        }
        if t < tr {
            let b = t - th
            let a = ease(b / 0.12)
            let s = 2 * Double.pi * 2.6 * b
            return (hover + PlugVec(7 * a * sin(s), -2.5 * a * abs(sin(s)), 2 * a * cos(s)), 1)
        }
        if t < tk {
            let u = ease((t - tr) / (tk - tr))
            return (lerp(hover, bay, u), 1 - 0.16 * u)
        }
        if t < tc {
            let u = ein3((t - tk) / (tc - tk))
            return (bezier(bay, sp1, sp2, seat, u), 0.84 + 0.6 * u)
        }
        if t < tu {
            let b = t - tc
            return (seat, 1 - 0.32 * exp(-11 * b) * cos(2 * Double.pi * 3.4 * b))
        }
        if t < to {
            let u = ease((t - tu) / (to - tu))
            return (seat + PlugVec(0, 0, 0.6 * u), 1 + 0.32 * u)
        }
        let u = (t - to) / (te - to)
        if u < 0.2 {
            let v = eout(u / 0.2)
            return (lerp(seat, quit, v), 1.32 - 0.5 * v + 0.18 * sin(Double.pi * v))
        }
        return (catmull(outPath, ease((u - 0.2) / 0.8) * 0.7 + (u - 0.2) / 0.8 * 0.3), 1)
    }

    static func tangent(_ t: Double) -> PlugVec? {
        let a = head(max(t - 0.012, 0)).0
        let b = head(t + 0.012).0
        let d = b - a
        return dot(d, d) > 1e-4 ? norm(d) : nil
    }

    static func aim(_ t: Double) -> PlugVec {
        let look = norm(seat + PlugVec(0, 0, 4) - head(t).0)
        if t < th {
            let tg = tangent(t) ?? PlugVec(0, -1, 0)
            return norm(lerp(tg, look, ease((t - th + 0.25) / 0.25)))
        }
        if t < tk {
            let sw = sin(2 * Double.pi * 2.6 * (t - th) - 0.6) * ease((t - th) / 0.15) * (1 - ease((t - tr) / 0.2))
            return norm(look + PlugVec(0, 0.25 * sw, 0.35 * sw))
        }
        if t < tc {
            let u = ein3((t - tk) / (tc - tk))
            let tg = tangent(t) ?? PlugVec(0, 0, -1)
            return norm(lerp(look, tg, ease(u / 0.5)))
        }
        if t < to { return PlugVec(0, 0, -1) }
        let u = (t - to) / (te - to)
        guard let tg = tangent(t) else { return PlugVec(0, 0, -1) }
        return norm(lerp(PlugVec(0, 0, -1), tg, ease((u - 0.08) / 0.3)))
    }

    static func axes(_ u: PlugVec, _ roll: Double) -> (PlugVec, PlugVec) {
        var up = PlugVec(0, 1, 0)
        if abs(dot(up, u)) > 0.95 { up = PlugVec(1, 0, 0) }
        let v = norm(cross(up, u))
        let w = cross(u, v)
        return (v * cos(roll) + w * sin(roll), w * cos(roll) - v * sin(roll))
    }

    static func simulate() -> [([PlugVec], PlugVec)] {
        let subs = 10
        let dt = duration / Double(count) / Double(subs)
        var (f0, st0) = head(0)
        var us = aim(0)
        var be = f0 - us * (pl * st0 + 4)
        var pts = (0..<nodes).map { lerp(be, anchor, Double($0) / Double(nodes - 1)) }
        var prev = pts
        var frames: [([PlugVec], PlugVec)] = []
        for pass in 0..<2 {
            for fi in 0..<count {
                for s in 0..<subs {
                    var t = (Double(fi - 1) + Double(s + 1) / Double(subs)) * duration / Double(count)
                    t = t - (t / duration).rounded(.down) * duration
                    let (f, st) = head(t)
                    us = norm(lerp(us, aim(t), 0.5))
                    be = f - us * (pl * st + 4)
                    var lat = 0.0
                    if t0 < t && t < th + 0.05 { lat = 3500 * (1 - ease((t - th + 0.1) / 0.3)) }
                    if th <= t && t < tk { lat = 1500 * (1 - ease((t - tr) / 0.2)) }
                    if to + 0.1 < t && t < te { lat = 3000 * ease((t - to - 0.1) / 0.15) }
                    var next: [PlugVec] = []
                    next.reserveCapacity(nodes)
                    for i in 0..<nodes {
                        let p = pts[i], q = prev[i]
                        var acc = gravity
                        if i > 0 && i < nodes - 1 && lat != 0 {
                            let tg = norm(pts[i - 1] - pts[i + 1])
                            let sideways = norm(cross(tg, PlugVec(0, 0, 1)))
                            let f = lat * sin(2 * Double.pi * 2.6 * t - Double(i) * 0.42) * clamp(Double(i) / 4) * clamp(Double(nodes - 6 - i) / 10)
                            acc += sideways * f
                        }
                        let vel = (p - q) * 0.975
                        next.append(p + vel + acc * (dt * dt))
                    }
                    prev = pts
                    pts = next
                    for _ in 0..<24 {
                        pts[0] = be
                        pts[1] = be + us * (-seg * 0.9)
                        pts[nodes - 1] = anchor
                        for i in 0..<(nodes - 1) {
                            let a = pts[i], b = pts[i + 1]
                            let d = b - a
                            let len = max(dot(d, d).squareRoot(), 1e-6)
                            let k = (len - seg) / len * 0.5
                            let wa = i < 2 ? 0.0 : 1.0
                            let wb = (i + 1 == nodes - 1 || i + 1 < 2) ? 0.0 : 1.0
                            let tot = (wa + wb) == 0 ? 1.0 : wa + wb
                            if wa != 0 { pts[i] = a + d * (k * 2 * wa / tot) }
                            if wb != 0 { pts[i + 1] = b - d * (k * 2 * wb / tot) }
                        }
                        for i in 0..<(nodes - 2) {
                            let a = pts[i], b = pts[i + 2]
                            let d = b - a
                            let len = max(dot(d, d).squareRoot(), 1e-6)
                            if len < seg * 1.7 {
                                let k = (len - seg * 1.7) / len * 0.12
                                if i >= 2 { pts[i] = a + d * k }
                                if i + 2 < nodes - 1 { pts[i + 2] = b - d * k }
                            }
                        }
                        for i in 0..<nodes { pts[i].z = max(pts[i].z, 6) }
                    }
                }
                if pass == 1 { frames.append((pts, us)) }
            }
        }
        _ = (f0, st0)
        f0 = PlugVec(0, 0, 0)
        st0 = 0
        return frames
    }

    static func smooth(_ pts: [PlugPoint]) -> CGPath {
        let path = CGMutablePath()
        path.move(to: cg(pts[0]))
        for i in 0..<(pts.count - 1) {
            let p0 = i > 0 ? pts[i - 1] : pts[i]
            let p1 = pts[i], p2 = pts[i + 1]
            let p3 = i + 2 < pts.count ? pts[i + 2] : p2
            let c1 = p1 + (p2 - p0) / 6
            let c2 = p2 - (p3 - p1) / 6
            path.addCurve(to: cg(p2), control1: cg(c1), control2: cg(c2))
        }
        return path
    }

    static func plateS(_ t: Double) -> Double {
        var s = 0.0
        if t >= tc { let b = t - tc; s += 0.05 * exp(-9 * b) * cos(2 * Double.pi * 3 * b) }
        if tu <= t && t < to { s -= 0.025 * ease((t - tu) / (to - tu)) }
        if t >= to { let b = t - to; s -= 0.025 * exp(-12 * b) * cos(2 * Double.pi * 3 * b) }
        return s
    }

    static func frame(_ t: Double, _ rope: [PlugVec], _ u: PlugVec) -> PlugFrame {
        let s = plateS(t)
        let sx = 1 + 0.6 * s, sy = 1 - s
        let ex = PlugVec(sx, 0, 0), ey = PlugVec(0, sy, 0)
        let slab = roundRect(36, 78, 11)
        let front = slab.map { project(PlugVec($0.x * sx, $0.y * sy, 3)) }
        let backPts = slab.map { project(PlugVec($0.x * sx, $0.y * sy, 0)) }
        let plate = poly(hull(front + backPts))
        let plateFront = poly(front)
        let sockets = CGMutablePath()
        let slots = CGMutablePath()
        for yy in [-17.0, 17.0] {
            var m = matrix(PlugVec(0, yy * sy, 3), ex, ey)
            sockets.addPath(CGPath(roundedRect: CGRect(x: -12, y: -10, width: 24, height: 20), cornerWidth: 8, cornerHeight: 8, transform: nil), transform: m)
            slots.addPath(CGPath(roundedRect: CGRect(x: -7.2, y: -5, width: 3, height: 10), cornerWidth: 1.5, cornerHeight: 1.5, transform: nil), transform: m)
            slots.addPath(CGPath(roundedRect: CGRect(x: 4.2, y: -4, width: 3, height: 8), cornerWidth: 1.5, cornerHeight: 1.5, transform: nil), transform: m)
            m = .identity
        }

        let (f, st) = head(t)
        var roll = Double.pi / 2
        if th < t && t < tk { roll += 0.25 * sin(2 * Double.pi * 2.6 * (t - th)) * (1 - ease((t - tr) / 0.2)) }
        if tk <= t && t < to { roll = Double.pi / 2 * (1 - ease((t - tk) / (tc - tk) / 0.85)) }
        if t >= to { roll = Double.pi / 2 * ease((t - to - 0.08) / 0.25) }
        let (v, w) = axes(u, roll)
        let cs = 1 / st.squareRoot()
        let length = pl * st
        let face = roundRect(pw, ph, pr).map { f + v * ($0.x * cs) + w * ($0.y * cs) }
        let back = face.map { $0 - u * length }
        let tailCenter = f - u * length - u * 4
        let tail = roundRect(12, 12, 6).map { tailCenter + v * ($0.x * cs) + w * ($0.y * cs) }
        let body = roundedPoly(hull((face + back + tail).map(project)), 6)
        let facing = dot(u, camera) > 0

        let prongs = CGMutablePath()
        for vx in [-7.5, 7.5] {
            var plen = 12.0
            let base = f + v * (vx * cs)
            let tip = base + u * plen
            if tip.z < 3 && u.z < -0.3 {
                let k = (base.z - 3) / max(base.z - tip.z, 1e-6)
                plen *= clamp(k)
            }
            if plen < 0.4 { continue }
            var corners: [PlugPoint] = []
            for a in [0.0, plen] {
                for dv in [-0.7, 0.7] {
                    for dw in [-3.6, 3.6] {
                        corners.append(project(base + u * a + v * dv + w * (dw * cs)))
                    }
                }
            }
            prongs.addPath(roundedPoly(hull(corners), 1.2))
        }

        let tipPoint = project(f - u * (length + 4))
        let cap = CGMutablePath()
        cap.addEllipse(in: CGRect(x: tipPoint.x - 5.2, y: tipPoint.y - 5.2, width: 10.4, height: 10.4))
        cap.addEllipse(in: CGRect(x: tipPoint.x - 2.2, y: tipPoint.y - 2.2, width: 4.4, height: 4.4))

        let sparks = CGMutablePath()
        let b = t - tc
        if b >= 0 && b <= 0.42 {
            let q = b / 0.42
            for ang in stride(from: 0, to: 360, by: 45) {
                let a = (Double(ang) + 22) * Double.pi / 180
                let r = 17 + 12 * eout(q)
                let rad = 2.8 * (1 - ease((q - 0.35) / 0.65))
                if rad > 1 {
                    let p = project(PlugVec(seat.x + cos(a) * r * 1.1, seat.y + sin(a) * r * 0.85, 8))
                    sparks.addEllipse(in: CGRect(x: p.x - rad, y: p.y - rad, width: rad * 2, height: rad * 2))
                }
            }
        }

        return PlugFrame(plate: plate, plateFront: plateFront, sockets: sockets, slots: slots, prongs: prongs, body: body, cable: smooth(rope.map(project)), cap: facing ? CGMutablePath() : cap, sparks: sparks, facing: facing)
    }

    nonisolated(unsafe) static let frames: [PlugFrame] = {
        let rope = simulate()
        return (0..<count).map { frame(Double($0) * duration / Double(count), rope[$0].0, rope[$0].1) }
    }()
}

extension FlairLayer {
    func buildPlug() {
        let unit = side
        let k = unit / 110
        let frames = PlugModel.frames
        let duration = PlugModel.duration
        let steps = PlugModel.count
        var map = CGAffineTransform(a: k, b: 0, c: 0, d: -k, tx: -5 * k, ty: unit + 5 * k)
        func placed(_ path: CGPath) -> CGPath { path.copy(using: &map) ?? path }
        let full = CGSize(width: unit, height: unit)
        let mid = CGPoint(x: unit / 2, y: unit / 2)
        let everything = CGRect(x: -unit, y: -unit, width: unit * 3, height: unit * 3)
        func paths(_ pick: (PlugFrame) -> CGPath) -> CAKeyframeAnimation {
            let values = (0..<steps).map { placed(pick(frames[$0])) }
            let times = (0..<steps).map { NSNumber(value: Double($0) / Double(steps)) }
            let animation = keyframes("path", values, times: times, timing: .linear)
            animation.calculationMode = .discrete
            return animation
        }
        func masked(_ hide: @escaping (PlugFrame) -> Bool) -> (CAShapeLayer, (PlugFrame) -> CGPath) {
            let mask = CAShapeLayer()
            mask.bounds = CGRect(origin: .zero, size: full)
            mask.position = mid
            mask.fillColor = CGColor(gray: 0, alpha: 1)
            mask.fillRule = .evenOdd
            let make: (PlugFrame) -> CGPath = { frame in
                let path = CGMutablePath()
                path.addRect(everything)
                if hide(frame) { path.addPath(self.placed(frame.body, map)) }
                return path
            }
            mask.path = make(frames[0])
            return (mask, make)
        }

        let clipper = container()
        let tile = CAShapeLayer()
        tile.bounds = CGRect(origin: .zero, size: full)
        tile.position = mid
        tile.path = CGPath(roundedRect: CGRect(origin: .zero, size: full), cornerWidth: 22 * k, cornerHeight: 22 * k, transform: nil)
        tile.fillColor = CGColor(gray: 0, alpha: 1)
        clipper.mask = tile

        let first = frames[0]
        let outlet = container()
        outlet.removeFromSuperlayer()
        clipper.addSublayer(outlet)
        let outletMask = masked { _ in true }
        outlet.mask = outletMask.0
        let plate = shape(placed(first.plate), size: full, at: mid, in: outlet)
        plate.opacity = 0.22
        let plateEdge = shape(placed(first.plate), size: full, at: mid, stroke: 4 * k, in: outlet)
        plateEdge.lineJoin = .round
        let plateFront = shape(placed(first.plateFront), size: full, at: mid, stroke: 2 * k, in: outlet)
        plateFront.lineJoin = .round
        plateFront.opacity = 0.55
        let sockets = shape(placed(first.sockets), size: full, at: mid, stroke: 2.6 * k, in: outlet)
        sockets.lineJoin = .round
        let slots = shape(placed(first.slots), size: full, at: mid, in: outlet)

        let prongHolder = container()
        prongHolder.removeFromSuperlayer()
        clipper.addSublayer(prongHolder)
        let prongMask = masked { !$0.facing }
        prongHolder.mask = prongMask.0
        let prongFill = shape(placed(first.prongs), size: full, at: mid, in: prongHolder)
        let prongEdge = shape(placed(first.prongs), size: full, at: mid, stroke: 1.6 * k, in: prongHolder)
        prongEdge.lineJoin = .round

        let bodyFill = shape(placed(first.body), size: full, at: mid, in: clipper)
        bodyFill.opacity = 0.22
        let bodyEdge = shape(placed(first.body), size: full, at: mid, stroke: 3.4 * k, in: clipper)
        bodyEdge.lineJoin = .round

        let cableHolder = container()
        cableHolder.removeFromSuperlayer()
        clipper.addSublayer(cableHolder)
        let cableMask = masked { $0.facing }
        cableHolder.mask = cableMask.0
        let cable = shape(placed(first.cable), size: full, at: mid, stroke: 5.4 * k, in: cableHolder)
        cable.lineCap = .round
        cable.lineJoin = .round

        let cap = shape(placed(first.cap), size: full, at: mid, in: clipper)
        cap.fillRule = .evenOdd
        let sparks = shape(placed(first.sparks), size: full, at: mid, in: clipper)

        guard animating else { return }
        let layers: [(CALayer, (PlugFrame) -> CGPath)] = [
            (plate, { $0.plate }), (plateEdge, { $0.plate }), (plateFront, { $0.plateFront }), (sockets, { $0.sockets }), (slots, { $0.slots }),
            (prongFill, { $0.prongs }), (prongEdge, { $0.prongs }), (bodyFill, { $0.body }), (bodyEdge, { $0.body }),
            (cable, { $0.cable }), (cap, { $0.cap }), (sparks, { $0.sparks }),
        ]
        for (layer, pick) in layers {
            run(group([paths(pick)], duration: duration), on: layer)
        }
        let times = (0..<steps).map { NSNumber(value: Double($0) / Double(steps)) }
        for (mask, make) in [outletMask, prongMask, cableMask] {
            let values = (0..<steps).map { make(frames[$0]) }
            let animation = keyframes("path", values, times: times, timing: .linear)
            animation.calculationMode = .discrete
            run(group([animation], duration: duration), on: mask)
        }
    }

    fileprivate func placed(_ path: CGPath, _ map: CGAffineTransform) -> CGPath {
        var m = map
        return path.copy(using: &m) ?? path
    }
}
