Ollin

RedAzaleas

Three canvases of red marks that dance in place, after Thomas's Red Azaleas Singing and Dancing Rock and Roll Music (1976).

Run
swift run --package-path Examples Example-Recreations-AlmaThomas-RedAzaleas
Source
Examples/Recreations/AlmaThomas/RedAzaleas/Sketch.swift
//  Recreation after Alma Thomas - "Red Azaleas Singing and Dancing Rock and
//  Roll Music" (1976; acrylic on three canvases, 73 3/4 x 158 1/2 in. across
//  all three, Smithsonian American Art Museum, bequest of the artist,
//  1980.36.2A-C), the largest painting of her career. A homage, not a
//  reproduction, and not affiliated with or endorsed by the artist or her
//  estate.
//  https://americanart.si.edu/artwork/red-azaleas-singing-and-dancing-rock-and-roll-music-24017
//  https://americanart.si.edu/blog/alma-thomas-conservation
//  https://americanart.si.edu/blog/alma-thomas-composing-colors
//
//  An original Ollin interpretation, written from the museum's picture of the
//  painting and from its accounts of the late work. Nothing was ported: the
//  work is acrylic on canvas. The size of a mark, the white between marks,
//  and the share of red from left to right were measured on the picture. How
//  the marks are placed and how they move is this sketch's own reading.

import Foundation
import Ollin

/// "Red Azaleas Singing and Dancing Rock and Roll Music" (Alma Thomas,
/// Washington, 1976). Her late paintings have no ruled rows. The museum's
/// conservators write that after health problems in 1974 the columns of
/// strokes gave way to a free play of wedges and curves. This is the largest
/// of those paintings: three canvases side by side, one red, on white. At the
/// left the red marks are packed so tight that the white is a net of thin
/// channels. Toward the right they come apart, and at the far right single
/// marks stand in open white.
///
/// The picture was measured before anything was written. Red covers about
/// 0.62 of the left edge, 0.50 of the middle, and 0.27 of the right edge. A
/// mark stays about the same size all the way across, so it is the white
/// that grows. The long marks mostly stand upright.
///
/// This sketch keeps those numbers and deals the rest. Marks are scattered
/// with a spacing that grows toward the right, and the canvas is divided so
/// each mark owns the ground nearest to it. A mark is a block, a bar, a wedge,
/// or a curved comma of one brush, `size` across. It is cut where it would
/// leave its own ground, less `channel` of white. So packed marks press into
/// the shape of their ground, and loose marks keep the shape the brush gave
/// them. `loosen` says how far the marks come apart toward the right, and
/// `ragged` is the brush's edge.
///
/// She said of this painting: "Look at it move." Here every mark dances in
/// place, on the beat, at `tempo`. A mark may step and turn only inside its
/// own ground, along the way it has the most room, by `swing` of that room.
/// So the packed marks at the left can only tremble, the loose marks at the
/// right step and turn, and no two marks ever touch or cross from one canvas
/// to the next. Eight bars make one lap, which is the export loop.
///
/// Try it: `loosen` at 0 packs all three canvases, and `swing` at 0 is the
/// still painting. A click deals the next painting.
@main
final class RedAzaleas: Sketch {
    /// The side of one mark, as a share of the canvas height.
    @Param(0.022 ... 0.06, icon: "ruler") var size = 0.036
    /// The white between two packed marks, as a share of a mark.
    @Param(0.08 ... 0.6, icon: "arrow.left.and.right") var channel = 0.17
    /// How far the marks come apart toward the right: 0 packs all three
    /// canvases, 1 is the painting.
    @Param(0 ... 1.5, icon: "arrow.right.to.line") var loosen = 1.0
    /// How ragged the brush leaves an edge, in canvas points.
    @Param(0 ... 3, icon: "scribble") var ragged = 0.8
    /// How far a mark moves on the beat, as a share of the room it has.
    @Param(0 ... 1, icon: "figure.dance") var swing = 0.8
    /// Beats a minute.
    @Param(90 ... 180, icon: "metronome") var tempo: Tempo = 144

    /// Three canvases side by side, in the proportion of the painting.
    override var canvasSize: CanvasSize { .size(1935, 900) }

    /// Eight bars: every figure below repeats in one, two, or four beats, so
    /// the lap closes on itself.
    override var loopDuration: Double? { tempo.seconds(bars: Self.bars) }

    static let bars = 8.0
    static let panels = 3

    /// One mark: its two coats as outlines around its own center, where that
    /// center rests, and the room it has inside its own ground: the way it
    /// steps, how far it can go forward and back along it, and how far it
    /// can turn.
    private struct Shard {
        var shape: Shape
        var second: Shape
        var center: Vector2
        var color: Color
        var deeper: Color
        var along: Vector2
        var forth: Double
        var back: Double
        var turn: Double
        var figure: Int
        var entry: Double
    }

    /// A dance figure: the places a mark steps to and the turns it makes, one
    /// to a count, and how many counts go to a beat.
    private struct Figure {
        var counts: Double
        var steps: [Double]
        var turns: [Double]
    }

    private static let figures = [
        Figure(counts: 1, steps: [-1, 1], turns: [0.4, -0.4]),              // side to side
        Figure(counts: 1, steps: [-0.3, 0.3], turns: [-1, 1]),              // the twist
        Figure(counts: 1, steps: [-1, 0, 1, 0], turns: [-0.6, 0, 0.6, 0]),  // step and touch
        Figure(counts: 2, steps: [-0.5, -0.5, 0.5, 0.5], turns: [-1, 1]),   // the shimmy
        Figure(counts: 1, steps: [0, 1, 0, -1], turns: [1, 0, -1, 0]),      // rock back, rock forward
    ]

    private struct Dealt: Equatable {
        var size, channel, loosen, ragged: Double
        var seed: Int
    }

    private let ground = Color(hex: 0xFBF8F2)
    private let seam = Color(hex: 0x2B2622)
    private var dealtFor: Dealt?
    private var shards: [Shard] = []
    private var pressed = false

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

    override func draw() {
        if pressed {
            pressed = false
            seed(variation + 1)
        }
        let wanted = Dealt(size: size, channel: channel, loosen: loosen, ragged: ragged, seed: variation)
        if dealtFor != wanted {
            dealtFor = wanted
            deal()
        }

        background(ground)
        noStroke()
        let beat = tempo.beats(at: time)
        for shard in shards {
            let figure = Self.figures[shard.figure]
            let count = (beat + shard.entry) * figure.counts
            let pose = Self.pose(figure.steps, at: count)
            let step = swing * pose * (pose >= 0 ? shard.forth : shard.back)
            let turn = swing * Self.pose(figure.turns, at: count) * shard.turn
            // Two coats: a thin one to the mark's edge, and a heavier one
            // that stops a little short of it.
            withState(at: shard.center + shard.along * step, rotation: turn) {
                fill(shard.color)
                drawShape(shard.shape)
                fill(shard.deeper)
                drawShape(shard.second)
            }
        }

        // The edges where one canvas meets the next.
        stroke(seam)
        strokeWeight(2)
        for panel in 1 ..< Self.panels {
            let x = width * Double(panel) / Double(Self.panels)
            drawLine(x, 0, x, height)
        }
    }

    /// Where a dancer is at `count`: it snaps to each pose in the first part
    /// of a count and holds it for the rest, which is what makes a beat.
    static func pose(_ poses: [Double], at count: Double) -> Double {
        let whole = count.rounded(.down)
        let index = Int(whole)
        let n = poses.count
        let from = poses[((index % n) + n) % n], to = poses[(((index + 1) % n) + n) % n]
        let x = min(1, (count - whole) / 0.42)
        return from + (to - from) * (1 - pow(1 - x, 3))
    }

    // MARK: The deal

    /// How loose the marks are at a place: 0 where they are packed into a net
    /// of thin channels, 1 where each keeps the shape the brush gave it, and 2
    /// where they stand apart in open white. The steps are the ones measured
    /// on the painting: packed for the first eighth of the width, themselves
    /// through the middle, and apart in the last eighth. A slow noise bends
    /// where each step falls.
    private func looseness(at p: Vector2) -> Double {
        let wander = 2 * noise(p.x / (0.55 * height) + 11, p.y / (0.55 * height) + 5) - 1
        let x = p.x / width + 0.06 * wander
        return loosen * (smoothstep(0.12, 0.32, x) + smoothstep(0.74, 0.90, x))
    }

    /// The way the brush was going at a place: mostly up and down, as
    /// measured, leaning one way or the other from one part of the canvas to
    /// the next.
    private func grain(at p: Vector2) -> Double {
        let lean = 2 * noise(p.x / (0.22 * height) + 71, p.y / (0.22 * height) + 31) - 1
        return .pi / 2 + 1.2 * lean
    }

    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 = size * height
        let white = channel * side
        // The centers reach past the canvas, so the edges cut marks the way
        // the canvas does.
        let margin = 2.5 * side
        let field = Rectangle(x: -margin, y: -margin, width: width + 2 * margin, height: height + 2 * margin)

        // Scatter the centers: a new one is kept when it is far enough from
        // every center already there, and "far enough" grows with looseness.
        func spacing(at p: Vector2) -> Double {
            let apart = min(max(looseness(at: p) - 1, 0), 1.5)
            let hollow = 2 * noise(p.x / (0.3 * height) + 40, p.y / (0.3 * height) + 23) - 1
            return side * (1.0 + 0.7 * apart) * (1 + 0.3 * min(apart, 1) * hollow)
        }
        // Centers sit farther apart along the brush's way than across it, so
        // a mark's ground is longer than it is wide.
        let stretch = 1.4.squareRoot()
        let cell = side / 2
        let columns = Int(field.width / cell) + 1, rows = Int(field.height / cell) + 1
        var grid = [[Int]](repeating: [], count: columns * rows)
        var centers: [Vector2] = []
        var apart: [Double] = []
        var misses = 0
        while misses < 3000, centers.count < 6000 {
            let p = Vector2(field.x + roll() * field.width, field.y + roll() * field.height)
            let r = spacing(at: p)
            let way = Vector2(angle: grain(at: p))
            let gx = Int((p.x - field.x) / cell), gy = Int((p.y - field.y) / cell)
            let span = Int(side * 3.2 / cell) + 1
            var free = true
            search: for y in max(0, gy - span) ... min(rows - 1, gy + span) {
                for x in max(0, gx - span) ... min(columns - 1, gx + span) {
                    for other in grid[y * columns + x] {
                        let offset = centers[other] - p
                        let far = Vector2(offset.dot(way) / stretch, offset.cross(way) * stretch).length
                        if far < (r + apart[other]) / 2 {
                            free = false
                            break search
                        }
                    }
                }
            }
            if free {
                grid[gy * columns + gx].append(centers.count)
                centers.append(p)
                apart.append(r)
                misses = 0
            } else {
                misses += 1
            }
        }

        // Each center owns the ground nearer to it than to any other.
        let grounds = Voronoi(sites: centers, bounds: field).cells
        let panelWidth = width / Double(Self.panels)

        shards = []
        for (index, at) in centers.enumerated() {
            // Every roll a mark needs is made before anything can drop it, so
            // one dropped mark never changes the marks after it.
            let kind = roll()
            let lean = roll(-1, 1), wide = roll(), long = roll(), bend = roll(), sweep = roll()
            let corners = (0 ..< 8).map { _ in roll(-1, 1) }
            let tone = roll(-1, 1), thin = roll(), heading = roll(0, 2 * .pi)
            let figure = Int(roll() * Double(Self.figures.count)), late = roll()
            let coat = roll(0.03, 0.09), drag = roll(0, 2 * .pi)
            var edge = SplitMix64(seed: generator.next())

            // The mark's own ground: its cell, kept to its own canvas.
            guard var home = grounds[index].contours.first?.points, home.count >= 3 else { continue }
            let panel = min(Self.panels - 1, max(0, Int(at.x / panelWidth)))
            let left = Double(panel) * panelWidth, right = left + panelWidth
            if panel > 0 { home = Self.cut(home, keeping: Vector2(-1, 0), upTo: -left) }
            if panel < Self.panels - 1 { home = Self.cut(home, keeping: Vector2(1, 0), upTo: right) }
            guard home.count >= 3 else { continue }
            let bed = Shape(home, closed: true).offset(by: -white / 2)

            // The brush mark, laid the way the brush was going there.
            let loose = looseness(at: at)
            var outline: [Vector2]
            var angle = grain(at: at) + 0.9 * lean * abs(lean)
            if kind < 0.60 {            // a block
                let w = side * (0.72 + 0.36 * wide), l = w * (1.2 + 1.0 * long)
                outline = Self.block(length: l, width: w, taper: 1, corners: corners)
            } else if kind < 0.78 {     // a bar
                let w = side * (0.32 + 0.16 * wide), l = side * (1.4 + 1.2 * long)
                outline = Self.block(length: l, width: w, taper: 1, corners: corners.map { $0 * 0.5 })
            } else if kind < 0.93 {     // a wedge
                let w = side * (0.8 + 0.35 * wide), l = w * (1.2 + 0.8 * long)
                outline = Self.block(length: l, width: w, taper: 0.08 + 0.4 * bend, corners: corners)
                angle += lean < 0 ? .pi : 0
            } else {                    // a comma
                outline = Self.comma(radius: side * (0.9 + 0.9 * long), sweep: 0.9 + 1.1 * sweep,
                                     width: side * (0.32 + 0.14 * wide))
                angle = heading
            }
            // Where the marks are packed the brush runs past its ground and is
            // cut by it, which is what packs them.
            let fill = 1.6 - 0.48 * min(max(loose, 0), 1)
            let placed = Shape(outline.map { at + ($0 * fill).rotated(by: angle) }, closed: true)
            guard let cutOut = placed.intersection(bed).contours.max(by: { Self.area($0.points) < Self.area($1.points) }),
                  Self.area(cutOut.points) > 0.12 * side * side else { continue }

            // The brush's edge. It is never rougher than the white the mark
            // was drawn in by, so the mark stays on its own ground.
            let rough = min(ragged, 0.45 * white)
            let points = Self.roughened(cutOut.points, by: rough, every: 7) { Double(edge.next() >> 11) * 0x1p-53 }
            let middle = Self.centroid(points)
            let reach = max(points.map { $0.distance(to: middle) }.max() ?? 1, 1)

            // The mark's room. For each side of its ground, how far the
            // nearest corner of the mark is from it. Two fifths of the least
            // of those are kept for turning. The rest is for stepping, along
            // the way that allows the longest step forward and back together.
            let sides = Self.sides(of: home)
            let depths = sides.map { wall in points.map { wall.inward.dot($0 - wall.from) }.min() ?? 0 }
            let least = max(0, depths.min() ?? 0)
            let turning = 0.4 * least
            var along = Vector2.unitX, forth = 0.0, back = 0.0
            for k in 0 ..< 12 {
                let way = Vector2(angle: Double(k) * .pi / 12)
                var ahead = 0.8 * side, behind = 0.8 * side
                for (wall, depth) in zip(sides, depths) {
                    let closing = -wall.inward.dot(way)
                    if closing > 1e-9 { ahead = min(ahead, (depth - turning) / closing) }
                    if closing < -1e-9 { behind = min(behind, (depth - turning) / -closing) }
                }
                if max(ahead, 0) + max(behind, 0) > forth + back {
                    along = way
                    forth = max(ahead, 0)
                    back = max(behind, 0)
                }
            }

            // One red, a little lighter or darker from mark to mark, and now
            // and then thin enough to go toward orange.
            var color = Color(hex: 0xC02A1C)
            color = tone >= 0 ? color.mixed(with: .white, 0.05 * tone) : color.mixed(with: .black, -0.08 * tone)
            if thin > 0.85 { color = color.mixed(with: Color(hex: 0xD9502C), (thin - 0.85) * 2) }

            // The heavier coat lies inside the first, so it never adds to
            // the mark's outline.
            let within = Shape(points, closed: true).offset(by: -coat * side - rough, join: .round)
                .contours.max { Self.area($0.points) < Self.area($1.points) }?.points ?? []
            let second = Self.roughened(within, by: rough, every: 6) { Double(edge.next() >> 11) * 0x1p-53 }
                .map { $0 + Vector2(angle: drag, length: 0.5 * coat * side) }

            // The whole move is kept a little short of the room, so a mark
            // never quite reaches the edge of its ground.
            shards.append(Shard(shape: Shape(points.map { $0 - middle }, closed: true),
                                second: Shape(second.map { $0 - middle }, closed: true), center: middle,
                                color: color.mixed(with: Color(hex: 0xE2603A), 0.22), deeper: color.withAlpha(0.88),
                                along: along, forth: 0.95 * forth, back: 0.95 * back,
                                turn: min(0.95 * turning / reach, 0.5),
                                figure: figure, entry: late < 0.4 ? 0 : (late < 0.8 ? 1 : 0.5)))
        }
    }

    // MARK: The shapes a brush leaves

    /// A four-cornered mark `length` long and `width` across, its far end
    /// `taper` times as wide as its near end, each corner pushed a little by
    /// the hand.
    static func block(length: Double, width: Double, taper: Double, corners: [Double]) -> [Vector2] {
        let a = length / 2, near = width / 2, far = width / 2 * taper
        let push = 0.12 * width
        return [
            Vector2(-a + corners[0] * push, -near + corners[1] * push),
            Vector2(a + corners[2] * push, -far + corners[3] * push * taper),
            Vector2(a + corners[4] * push, far + corners[5] * push * taper),
            Vector2(-a + corners[6] * push, near + corners[7] * push),
        ]
    }

    /// A curved mark: a band `width` across bent along an arc of `radius`
    /// through `sweep` radians, centered on its own middle.
    static func comma(radius: Double, sweep: Double, width: Double) -> [Vector2] {
        let steps = 7
        var outer: [Vector2] = [], inner: [Vector2] = []
        for k in 0 ... steps {
            let angle = -sweep / 2 + sweep * Double(k) / Double(steps)
            outer.append(Vector2(angle: angle, length: radius + width / 2) - Vector2(radius, 0))
            inner.append(Vector2(angle: angle, length: radius - width / 2) - Vector2(radius, 0))
        }
        return outer + inner.reversed()
    }

    /// 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
    }

    // MARK: Plane geometry

    /// The part of a convex outline where `normal` dotted with a point is at
    /// most `limit`.
    static func cut(_ points: [Vector2], keeping normal: Vector2, upTo limit: Double) -> [Vector2] {
        var out: [Vector2] = []
        for (i, a) in points.enumerated() {
            let b = points[(i + 1) % points.count]
            let da = normal.dot(a) - limit, db = normal.dot(b) - limit
            if da <= 0 { out.append(a) }
            if (da < 0 && db > 0) || (da > 0 && db < 0) { out.append(a + (b - a) * (da / (da - db))) }
        }
        return out
    }

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

    static func area(_ points: [Vector2]) -> Double { abs(signedArea(points)) }

    /// 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 sides of a convex outline, each with a point on it and the
    /// direction that points into the outline from it.
    static func sides(of convex: [Vector2]) -> [(from: Vector2, inward: Vector2)] {
        let turn = signedArea(convex) >= 0 ? 1.0 : -1.0
        var out: [(from: Vector2, inward: Vector2)] = []
        for (i, a) in convex.enumerated() {
            let b = convex[(i + 1) % convex.count]
            let length = a.distance(to: b)
            guard length > 1e-9 else { continue }
            out.append((a, (b - a).perpendicular * (turn / length)))
        }
        return out
    }
}

↑↓ move ↩ open