# GrassyMelodicChant

a green pavement with eight whorls, laid stone by stone, after Thomas's Grassy Melodic Chant (1976).

Run it with `swift run --package-path Examples Example-Recreations-AlmaThomas-GrassyMelodicChant`.

```swift
//  Recreation after Alma Thomas - "Grassy Melodic Chant" (1976; acrylic on
//  canvas, 46 x 36 in., Smithsonian American Art Museum, bequest of the
//  artist, 1980.36.5). A homage, not a reproduction, and not affiliated with
//  or endorsed by the artist or her estate.
//  https://americanart.si.edu/artwork/grassy-melodic-chant-24010
//  https://americanart.si.edu/blog/alma-thomas-composing-colors
//  https://www.denverartmuseum.org/en/composing-color-exhibition-guide-music-nature
//
//  An original Ollin interpretation, written from the museum's picture of the
//  painting. Nothing was ported: the work is acrylic on canvas. No statement
//  of a rule for this painting was found, so the structure here was read off
//  the picture: the size of a stone, the width of a joint, the eight whorls
//  and the side each one's blades stand on were measured there.

import Foundation
import Ollin

/// "Grassy Melodic Chant" (Alma Thomas, Washington, 1976) is one green laid
/// in pieces like a pavement, with the white of the canvas left as the joints
/// between them. A curator at the museum that holds it describes these late
/// paintings as mosaics, as if tiny pieces of tile were being placed
/// together. In eight places the pavement turns into a whorl: a small web of
/// spokes and rings, and beside it two or three long curved blades.
///
/// The picture was measured before anything was written. Green covers about
/// 0.79 of the canvas. A stone is about 0.044 of the width across and a joint
/// about 0.005. The whorls sit about a third of the width apart. Going down
/// the canvas their blades stand on the left, then the right, then the left.
/// A first reading had the stones lying in rows bent around each whorl. The
/// count said otherwise: away from a web and its blades, as many stones lie
/// across a whorl's circles as along them. So the pavement here has no rows.
///
/// This sketch keeps those numbers and deals the rest. `whorls` centers are
/// spread over the canvas. Around each one the ground is cut into a web, with
/// `blades` curved blades on one side. The rest of the canvas is divided into
/// patches a few stones across. Each patch is cut in two across its longer
/// way, and each part again, until a part is the size of a `stone`. `drift`
/// is how far the edges of the patches and the rings of a web wander. Every
/// piece is drawn in from its cut by half of `joint`, a little more or less
/// from stone to stone. `ragged` is the brush's edge.
///
/// The pavement is laid stone by stone over the first part of `seconds`. The
/// whorls come in one after another from the top, like the voices of a round.
/// Each one's stones go down from its web outward. Then the pavement holds,
/// and is taken up the way it came, which is also the export loop.
///
/// Try it: `whorls` at 3 or at 12, `blades` at 0, `drift` at 0 for straight
/// patches. A click deals the next pavement.
@main
final class GrassyMelodicChant: Sketch {
    /// How many whorls the pavement turns around.
    @Param(2 ... 14, icon: "hurricane") var whorls = 8
    /// The size of a stone, as a share of the canvas width.
    @Param(0.035 ... 0.09, icon: "ruler") var stone = 0.05
    /// The white joint between two stones, as a share of a stone.
    @Param(0.04 ... 0.4, icon: "arrow.left.and.right") var joint = 0.11
    /// The long curved blades beside each whorl.
    @Param(0 ... 5, icon: "leaf") var blades = 3
    /// How far the edges of the patches and the rings of the webs wander.
    @Param(0 ... 1, icon: "water.waves") var drift = 0.6
    /// How ragged the brush leaves an edge, in canvas points.
    @Param(0 ... 3, icon: "scribble") var ragged = 0.8
    /// Seconds for one lap: laying, a hold, and taking up.
    @Param(12 ... 30, icon: "clock") var seconds = 24.0

    /// The proportion of the painting, 36 wide by 46 high.
    override var canvasSize: CanvasSize { .size(1080, 1380) }

    override var loopDuration: Double? { seconds }

    /// One stone: its outline in a thin first coat, a second coat that stops
    /// short of the edge, and when it is laid.
    private struct Stone {
        var shape: Shape
        var color: Color
        var second: Shape
        var deeper: Color
        var turn: Double
    }

    private struct Dealt: Equatable {
        var whorls, blades: Int
        var stone, joint, drift, ragged: Double
        var seed: Int
    }

    private let ground = Color(hex: 0xEFF1EA)
    private var dealtFor: Dealt?
    private var stones: [Stone] = []
    private var pressed = false

    /// A click deals the next pavement.
    override func mousePressed() {
        pressed = true
    }

    override func draw() {
        if pressed {
            pressed = false
            seed(variation + 1)
        }
        let wanted = Dealt(whorls: whorls, blades: blades, stone: stone, joint: joint, drift: drift,
                           ragged: ragged, seed: variation)
        if dealtFor != wanted {
            dealtFor = wanted
            deal()
        }

        background(ground)
        noStroke()
        for stone in stones.prefix(stonesLaid()) {
            fill(stone.color)
            drawShape(stone.shape)
            fill(stone.deeper)
            drawShape(stone.second)
        }
    }

    /// How many stones are down now: laid over the first part of the lap, all
    /// of them through the hold, then taken up in the reverse order.
    private func stonesLaid() -> Int {
        let phase = (time / seconds).truncatingRemainder(dividingBy: 1)
        let laid = 0.64, held = 0.88
        let share: Double
        if phase < laid {
            share = phase / laid
        } else if phase < held {
            share = 1
        } else {
            share = 1 - (phase - held) / (1 - held)
        }
        return Int((Double(stones.count) * share).rounded(.down))
    }

    // MARK: The deal

    private func deal() {
        var generator = SplitMix64(seed: UInt64(truncatingIfNeeded: variation) &* 0x9E37_79B9_7F4A_7C15 &+ 0x1976)
        func roll() -> Double { Double(generator.next() >> 11) * 0x1p-53 }
        func roll(_ low: Double, _ high: Double) -> Double { low + (high - low) * roll() }

        let side = stone * width
        let white = joint * side
        let margin = 1.5 * side
        let field = Rectangle(x: -margin, y: -margin, width: width + 2 * margin, height: height + 2 * margin)

        // The whorls: each new center is the candidate farthest from the ones
        // already there, which spreads them evenly without a grid. They are
        // then read from the top down, and the blades change sides at each.
        let inset = 0.13 * width
        var centers: [Vector2] = []
        for _ in 0 ..< whorls {
            var best = Vector2.zero, bestApart = -1.0
            for _ in 0 ..< 40 {
                let candidate = Vector2(roll(inset, width - inset), roll(inset, height - inset))
                let apart = centers.map { $0.distance(to: candidate) }.min() ?? .infinity
                if apart > bestApart { best = candidate; bestApart = apart }
            }
            centers.append(best)
        }
        centers.sort { $0.y != $1.y ? $0.y < $1.y : $0.x < $1.x }
        let firstSide = roll() < 0.5

        // A ground is the part of the canvas nearer to one center than to any
        // other. The edge between two grounds is bent by a slow noise read at
        // the place itself, so both neighbors bend it the same way and still
        // meet along it.
        func bent(_ p: Vector2) -> Vector2 {
            let f = 1 / (2.2 * side)
            return p + Vector2(noise(p.x * f + 3, p.y * f + 17) - 0.5, noise(p.x * f + 29, p.y * f + 7) - 0.5)
                * (1.1 * side * drift)
        }
        func grounds(of sites: [Vector2]) -> [[Vector2]] {
            Voronoi(sites: sites, bounds: field).cells.map { cell -> [Vector2] in
                let corners = cell.contours.first?.points ?? []
                var outline: [Vector2] = []
                for (i, a) in corners.enumerated() {
                    let b = corners[(i + 1) % corners.count]
                    // Walk each edge from its lower end, so the two grounds
                    // that share it place the same points on it.
                    let forward = a.x != b.x ? a.x < b.x : a.y < b.y
                    let from = forward ? a : b, to = forward ? b : a
                    let pieces = max(1, Int((from.distance(to: to) / (0.5 * side)).rounded()))
                    var along = (0 ..< pieces).map { bent(from + (to - from) * (Double($0) / Double(pieces))) }
                    if !forward { along = [bent(to)] + along.dropFirst().reversed() }
                    outline += along
                }
                return outline
            }
        }

        /// A piece of the pavement as it is cut, before its joint is taken
        /// off: its outline, the whorl it belongs to, how far out from that
        /// whorl it lies, and whether it is part of a whorl (the web's joints
        /// are finer than the rest).
        struct Cut {
            var points: [Vector2]
            var whorl: Int
            var out: Double
            var ofWhorl: Bool
            var fine: Bool
        }
        var cuts: [Cut] = []

        /// A corner on the edge of a ring: its angle around the whorl and how
        /// far out it is.
        struct Node {
            var angle: Double
            var radius: Double
        }
        /// How far out an edge is at `angle`: where the ray at that angle
        /// meets the straight side between the two corners it falls between.
        func reach(of edge: [Node], at angle: Double) -> Double {
            guard let first = edge.first, let last = edge.last else { return 0 }
            if angle <= first.angle { return first.radius }
            if angle >= last.angle { return last.radius }
            var i = 0
            while i + 2 < edge.count, edge[i + 1].angle <= angle { i += 1 }
            let a = edge[i], b = edge[i + 1]
            let between = b.angle - a.angle
            guard between > 1e-9 else { return a.radius }
            return a.radius * b.radius * sin(between)
                / (a.radius * sin(angle - a.angle) + b.radius * sin(b.angle - angle))
        }
        /// A closed edge written out for two turns either way, so a ring that
        /// starts at any angle can read it straight through.
        func turns(_ edge: [Node]) -> [Node] {
            (-2 ... 2).flatMap { turn in edge.map { Node(angle: $0.angle + Double(turn) * 2 * .pi, radius: $0.radius) } }
        }

        // The whorls. Each is a web, a small disc cut into wedges with two
        // rings of small pieces around it, and beside the web its blades.
        let whorlGrounds = grounds(of: centers)
        let web = [0.6, 1.2, 1.8].map { $0 * side }
        let pitch = 0.62 * side
        var footprints: [Shape] = []
        for (whorl, center) in centers.enumerated() {
            func place(_ angle: Double, _ radius: Double) -> Vector2 { center + Vector2(angle: angle, length: radius) }

            /// Lays one ring outside the edge `inner` (the whorl's own center
            /// when there is none), cut at `angles`. Every cut ends at a new
            /// corner about `out` from the center, off by up to `wander` and
            /// leaning by up to `lean`. A piece lies between two cuts: its
            /// outer side is the straight line between two new corners, and
            /// its inner side follows the edge it was laid against. Returns
            /// the new corners, which are the edge for the next ring.
            func lay(outside inner: [Node]?, cutAt angles: [Double], out: Double, wander: Double, lean: Double,
                     depth: Double) -> [Node] {
                let count = angles.count
                let outer = angles.map { Node(angle: $0 + roll(-lean, lean), radius: out + roll(-wander, wander) * drift) }
                for m in 0 ..< count {
                    let a0 = angles[m], n0 = outer[m]
                    let a1 = m + 1 < count ? angles[m + 1] : angles[0] + 2 * .pi
                    var n1 = outer[(m + 1) % count]
                    if m + 1 == count { n1.angle += 2 * .pi }
                    var points: [Vector2] = []
                    if let inner {
                        points.append(place(a0, reach(of: inner, at: a0)))
                        for node in inner where node.angle > a0 + 1e-6 && node.angle < a1 - 1e-6 {
                            points.append(place(node.angle, node.radius))
                        }
                        points.append(place(a1, reach(of: inner, at: a1)))
                    } else {
                        points.append(center)
                    }
                    points.append(place(n1.angle, n1.radius))
                    points.append(place(n0.angle, n0.radius))
                    cuts.append(Cut(points: points, whorl: whorl, out: depth, ofWhorl: true, fine: true))
                }
                return outer
            }
            /// The cuts of the next ring: one where each corner of `edge` is,
            /// so a spoke carries on, and one more between every `every`th
            /// pair of them.
            func carriedOn(from edge: [Node], extraEvery every: Int) -> [Double] {
                var angles: [Double] = []
                for (m, node) in edge.enumerated() {
                    let next = m + 1 < edge.count ? edge[m + 1].angle : edge[0].angle + 2 * .pi
                    let between = roll(0.4, 0.6)
                    angles.append(node.angle)
                    if m % every == 0 { angles.append(node.angle + (next - node.angle) * between) }
                }
                return angles
            }
            /// A curved band between two radii, from one angle to another.
            func band(_ inner: Double, _ outer: Double, from: Double, to: Double) -> [Vector2] {
                let steps = max(1, Int(((to - from) / 0.12).rounded(.up)))
                let angles = (0 ... steps).map { from + (to - from) * Double($0) / Double(steps) }
                return angles.map { place($0, outer) } + angles.reversed().map { place($0, inner) }
            }

            let spokes = Int(roll(4, 6)), start = roll(0, 2 * .pi)
            let hubCuts = (0 ..< spokes).map { start + (Double($0) + roll(-0.12, 0.12)) * 2 * .pi / Double(spokes) }
            let hub = lay(outside: nil, cutAt: hubCuts, out: web[0], wander: 0.12 * side, lean: 0, depth: web[0] / 2)
            let second = lay(outside: turns(hub), cutAt: carriedOn(from: hub, extraEvery: 2), out: web[1],
                             wander: 0.14 * side, lean: 0.07, depth: (web[0] + web[1]) / 2)
            let rim = lay(outside: turns(second), cutAt: carriedOn(from: second, extraEvery: 2), out: web[2],
                          wander: 0.12 * side, lean: 0.06, depth: (web[1] + web[2]) / 2)

            // The blades: long curved bands on one side of the web. The outer
            // ones are the longer ones, and where a blade stops short of the
            // sweep a small piece takes the rest.
            var outline = rim.map { place($0.angle, $0.radius) }
            if blades > 0 {
                let onLeft = (whorl % 2 == 0) == firstSide
                let facing = (onLeft ? Double.pi : 0) + roll(-0.3, 0.3)
                let half = roll(0.62, 0.8)
                let s0 = facing - half - 0.08, s1 = facing + half + 0.08
                let near = web[2] + 0.05 * side
                let far = near + Double(blades) * pitch
                for blade in 0 ..< blades {
                    let inner = near + Double(blade) * pitch, outer = inner + pitch
                    let sweep = half * (0.78 + 0.22 * Double(blade + 1) / Double(blades))
                    let shift = roll(-0.1, 0.1)
                    var from = max(s0, facing + shift - sweep), to = min(s1, facing + shift + sweep)
                    if (from - s0) * inner < 0.5 * side { from = s0 }
                    if (s1 - to) * inner < 0.5 * side { to = s1 }
                    let depth = (inner + outer) / 2
                    cuts.append(Cut(points: band(inner + 0.04 * pitch, outer - 0.04 * pitch, from: from, to: to),
                                    whorl: whorl, out: depth, ofWhorl: true, fine: false))
                    if from > s0 {
                        cuts.append(Cut(points: band(inner, outer, from: s0, to: from), whorl: whorl, out: depth,
                                        ofWhorl: true, fine: false))
                    }
                    if to < s1 {
                        cuts.append(Cut(points: band(inner, outer, from: to, to: s1), whorl: whorl, out: depth,
                                        ofWhorl: true, fine: false))
                    }
                }
                // The whorl's outline: around the blades' sweep, and around
                // the rim of the web for the rest of the turn.
                let turned = turns(rim)
                let sweepSteps = max(2, Int(((s1 - s0) / 0.12).rounded(.up)))
                outline = (0 ... sweepSteps).map { place(s0 + (s1 - s0) * Double($0) / Double(sweepSteps), far) }
                outline.append(place(s1, reach(of: turned, at: s1)))
                outline += turned.filter { $0.angle > s1 + 1e-6 && $0.angle < s0 + 2 * .pi - 1e-6 }
                    .map { place($0.angle, $0.radius) }
                outline.append(place(s0, reach(of: turned, at: s0 + 2 * .pi)))
            }
            footprints.append(Shape(outline, closed: true).intersection(Shape(whorlGrounds[whorl], closed: true)))
        }

        // The pavement between the whorls. The canvas is first divided into
        // patches a few stones across, less the whorls. Each patch is then
        // cut in two across its longer way, and each part again, until a part
        // is the size of a stone. Parts wait their turn on a list.
        var patchRolls = SplitMix64(seed: generator.next())
        let patches = grounds(of: Ollin.poissonDisk(in: field, radius: 2.3 * side, using: &patchRolls))
        var waiting: [[Vector2]] = []
        for patch in patches {
            var rest = Shape(patch, closed: true)
            for footprint in footprints { rest = rest.subtracting(footprint) }
            waiting += rest.contours.map(\.points).filter { Self.area($0) > 0.08 * side * side }
        }
        while let part = waiting.popLast() {
            let enough = pow(1.36 * side, 2) * roll(0.7, 1.3)
            let slant = roll(-0.3, 0.3), off = roll(-0.12, 0.12)
            let middle = Self.centroid(part)
            if Self.area(part) > enough {
                let (way, length) = Self.longerWay(of: part)
                let line = Ray2(origin: middle + way * (off * length), direction: way.perpendicular.rotated(by: slant))
                let (left, right) = Shape(part, closed: true).split(along: line)
                let halves = (left.contours + right.contours).map(\.points).filter { Self.area($0) > 0.04 * side * side }
                if halves.count >= 2 {
                    waiting += halves
                    continue
                }
            }
            // A stone belongs to the nearest whorl, which is the voice that
            // lays it.
            let whorl = centers.indices.min { centers[$0].distance(to: middle) < centers[$1].distance(to: middle) } ?? 0
            cuts.append(Cut(points: part, whorl: whorl, out: centers[whorl].distance(to: middle), ofWhorl: false, fine: false))
        }

        // Draw every piece in from its cut by half a joint, and give it the
        // brush's edge. A whorl's own pieces are kept to its outline first.
        let longest = cuts.map(\.out).max() ?? 1
        var laid: [Stone] = []
        for cut in cuts {
            let tone = roll(-1, 1), wash = roll(), hand = roll(0.45, 1.45), coat = roll(1, 3), lean = roll(0, 2 * .pi)
            var edgeRolls = SplitMix64(seed: generator.next())
            let whole = Shape(cut.points, closed: true)
            let own = cut.ofWhorl ? whole.intersection(footprints[cut.whorl]) : whole
            // The hand: one stone keeps a little more of its joint, the next a
            // little less, so the white between them is never one width.
            let drawIn = (cut.fine ? 0.3 : 0.5) * white * hand
            // The brush's edge is never rougher than the stone was drawn in
            // by, so a stone stays inside its own cut.
            let rough = min(ragged, 0.8 * drawIn)
            for piece in own.offset(by: -drawIn).contours where Self.area(piece.points) > 0.05 * side * side {
                // A piece that lies wholly off the canvas is never laid.
                let xs = piece.points.map(\.x), ys = piece.points.map(\.y)
                guard (xs.max() ?? 0) > 0, (xs.min() ?? 0) < width, (ys.max() ?? 0) > 0, (ys.min() ?? 0) < height else { continue }
                let points = Self.roughened(piece.points, by: rough, every: 9) { Double(edgeRolls.next() >> 11) * 0x1p-53 }
                // One green, a little deeper or paler from stone to stone, and
                // now and then as thin as a wash.
                var color = Color(hex: 0x0E9C88)
                color = tone >= 0 ? color.mixed(with: .white, 0.07 * tone) : color.mixed(with: .black, -0.07 * tone)
                if wash > 0.82 { color = color.mixed(with: Color(hex: 0x55C2AC), (wash - 0.82) * 3) }
                // The voices of the round: each whorl starts a little after
                // the one above it and grows outward at the same pace.
                let turn = Double(cut.whorl) * 0.3 * longest + cut.out
                // The second coat: the same green, heavier, a brush's width
                // in from the edge and pulled a little to one side.
                let pull = 0.02 * side
                let within = Shape(points, closed: true).offset(by: -(coat * 0.03 * side + pull + rough), join: .round)
                    .contours.max { Self.area($0.points) < Self.area($1.points) }?.points ?? []
                let second = Self.roughened(within, by: rough, every: 6) { Double(edgeRolls.next() >> 11) * 0x1p-53 }
                    .map { $0 + Vector2(angle: lean, length: pull) }
                laid.append(Stone(shape: Shape(points, closed: true), color: color.mixed(with: Color(hex: 0x4FC2AB), 0.2),
                                  second: Shape(second, closed: true), deeper: color.withAlpha(0.9), turn: turn))
            }
        }
        stones = laid.enumerated().sorted { $0.element.turn != $1.element.turn ? $0.element.turn < $1.element.turn : $0.offset < $1.offset }
            .map(\.element)
    }

    // MARK: Plane geometry

    /// An outline with the brush's edge: a point every `step` or so along each
    /// side, each pushed in or out by up to `amount`.
    static func roughened(_ points: [Vector2], by amount: Double, every step: Double,
                          roll: () -> Double) -> [Vector2] {
        guard amount > 0 else { return points }
        var out: [Vector2] = []
        for (i, a) in points.enumerated() {
            let b = points[(i + 1) % points.count]
            let length = a.distance(to: b)
            guard length > 1e-6 else { continue }
            let across = (b - a).perpendicular / length
            let pieces = max(1, Int((length / step).rounded()))
            for k in 0 ..< pieces {
                let push = (2 * roll() - 1) * amount * (k == 0 ? 0.5 : 1)
                out.append(a + (b - a) * (Double(k) / Double(pieces)) + across * push)
            }
        }
        return out
    }

    /// The area of an outline.
    static func area(_ points: [Vector2]) -> Double {
        var sum = 0.0
        for (i, a) in points.enumerated() { sum += a.cross(points[(i + 1) % points.count]) }
        return abs(sum) / 2
    }

    /// The center of an outline's area.
    static func centroid(_ points: [Vector2]) -> Vector2 {
        var sum = Vector2.zero, total = 0.0
        for (i, a) in points.enumerated() {
            let b = points[(i + 1) % points.count]
            let weight = a.cross(b)
            sum = sum + (a + b) * weight
            total += weight
        }
        guard abs(total) > 1e-9 else { return points.first ?? .zero }
        return sum / (3 * total)
    }

    /// The direction an outline is longest in, and how long it is that way,
    /// from the spread of its corners.
    static func longerWay(of points: [Vector2]) -> (way: Vector2, length: Double) {
        let count = Double(max(points.count, 1))
        let mean = points.reduce(Vector2.zero, +) / count
        var xx = 0.0, yy = 0.0, xy = 0.0
        for p in points {
            let d = p - mean
            xx += d.x * d.x
            yy += d.y * d.y
            xy += d.x * d.y
        }
        let way = Vector2(angle: 0.5 * atan2(2 * xy, xx - yy))
        let along = points.map { ($0 - mean).dot(way) }
        return (way, (along.max() ?? 0) - (along.min() ?? 0))
    }
}
```
