# LinesToPointsOnAGrid

the seven walls of Wall Drawing 273 (1975), drawn one after another.

Run it with `swift run --package-path Examples Example-Recreations-SolLeWitt-LinesToPointsOnAGrid`.

```swift
//  Recreation after Sol LeWitt - "Wall Drawing 273" (September 1975): seven
//  walls of crayon lines over a pencil grid. The lines run from the sides, the
//  corners, and the center of each wall to points on the grid, in red, blue,
//  and yellow. First drawn at the Israel Museum, Jerusalem, and now in the
//  Doris and Donald Fisher Collection at the San Francisco Museum of Modern
//  Art. A homage, not a reproduction, and not affiliated with or endorsed by
//  the artist or his estate.
//  https://www.sfmoma.org/artwork/FC.512
//  https://www.sfmoma.org/read/drawing-with-instructions/
//
//  An original Ollin interpretation written from the published instruction.
//  Nothing was ported: a LeWitt wall drawing is a written instruction that
//  drafters carry out, and this sketch is one more drafter. Where the
//  instruction leaves a choice, this drafter's habits are read off the
//  museum's photograph of the seventh wall. That wall has about a hundred
//  lines and is thirty grid squares wide. Twice as many lines leave its
//  center as leave any one corner or side, and the lines from one point are
//  spread evenly around it.

import Ollin

/// "Wall Drawing 273" (Sol LeWitt, September 1975). The instruction, whole:
///
/// > A 6" (15 cm) grid covering the walls. Lines from corners, sides, and
/// > center of the walls to random points on the grid.
/// > 1st wall: Red lines from the midpoints of four sides;
/// > 2nd wall: Blue lines from the four corners;
/// > 3rd wall: Yellow lines from the center;
/// > 4th wall: Red lines from the midpoints of four sides, blue lines from
/// > four corners;
/// > 5th wall: Red lines from the midpoints of four sides, yellow lines from
/// > the center;
/// > 6th wall: Blue lines from four corners, yellow lines from the center;
/// > 7th wall: Red lines from the midpoints of four sides, blue lines from
/// > four corners, yellow lines from the center.
/// > Each wall has an equal number of lines. (The number of lines and their
/// > length are determined by the draftsman.)
///
/// There are three kinds of starting point and three colors, one color to a
/// kind. The seven walls are every way to choose among three things: each one
/// alone, each pair, and all three together. Where a line starts is fixed.
/// Where it ends is a point on the grid that the drafter picks. The drafter
/// picks how many lines there are too, as long as every wall gets the same.
///
/// The sketch is the drafter, and it shows the room one wall at a time, in
/// the instruction's order. The pencil grid covers the wall. The lines go on
/// one after another, each from its starting point out to its grid point. The
/// finished wall is held for a moment, then cleared for the next one, and
/// after the seventh the lap starts again.
///
/// "Random points" leaves the drafter room, and this drafter's habits come
/// from counting the museum's photograph of the seventh wall. There, no two
/// lines from one point lie closer than about four degrees. So each line here
/// is the best of a handful of throws: the one that points farthest from the
/// lines already drawn from its point. A throw is a direction and a length,
/// moved to the nearest grid point, which gives short lines and long ones in
/// equal measure. No line runs along the edge of the wall or is shorter than
/// an eighth of it. And the center gets two shares of a wall's lines for
/// every one share a corner or a midpoint gets. On the photograph that is ten
/// lines from each corner, ten from each midpoint, and twenty from the center.
///
/// Try it: `lines` is the number on every wall, and `reach` is how far across
/// the wall a line may run. Those are the two things the instruction hands to
/// the drafter. `grid` is how many six-inch squares cross the wall, so 30 is
/// a wall fifteen feet wide. `room` picks the room, and a press moves to the
/// next one. `lap` is the seconds for all seven walls and the length of one
/// exact loop. The lines export as strokes: `--export-svg` with
/// `--frame 1620` gives the seventh wall back.
@main
final class LinesToPointsOnAGrid: Sketch {
    /// How many lines each wall gets. The instruction leaves the number to the
    /// drafter and asks only that all seven walls have the same.
    @Param(10 ... 240, icon: "line.diagonal") var lines = 100
    /// How far a line may run, as a share of the way from its starting point
    /// to the far edge of the wall. At 1 a line may cross the whole wall.
    @Param(0.25 ... 1, icon: "arrow.left.and.right") var reach = 1.0
    /// Six-inch grid squares across the wall, and down it.
    @Param(8 ... 60, icon: "square.grid.3x3") var grid = 30
    /// Seconds for the seven walls, which is one lap of the loop.
    @Param(14 ... 30, icon: "clock") var lap = 28.0
    /// Width of the crayon line.
    @Param(0.5 ... 4, icon: "pencil.tip") var lineWeight = 1.7
    /// Which room is drawn: the same instruction on seven other walls.
    @Param(1 ... 999, icon: "dice") var room = 1

    override var loopDuration: Double? { lap }

    /// The three kinds of starting point, in the order the instruction names
    /// their colors on the seventh wall.
    private enum Kind: Int, CaseIterable { case sides, corners, center }

    /// The seven walls: each kind alone, each pair, and all three.
    private let plan: [[Kind]] = [
        [.sides], [.corners], [.center],
        [.sides, .corners], [.sides, .center], [.corners, .center],
        [.sides, .corners, .center],
    ]

    /// One crayon line, from its starting point to its grid point.
    private struct Line {
        var from: Vector2
        var to: Vector2
        var kind: Kind
    }

    private let wallColor = Color(hex: 0xEEEEEA)
    private let pencil = Color(white: 0.45, alpha: 0.2)
    private let crayons: [Color] = [
        Color(hex: 0xC9515A), // red, from the midpoints of the sides
        Color(hex: 0x2F6CA6), // blue, from the corners
        Color(hex: 0xF0D62A), // yellow, from the center
    ]

    /// The seven walls of the current room, and the settings they were drawn
    /// up from, so a room is planned once and not on every frame.
    private var walls: [[Line]] = []
    private var plannedFrom: [Double] = []
    private var skipped = 0

    override func mousePressed() {
        skipped += 1
    }

    override func draw() {
        background(wallColor)

        let squares = max(2, grid)
        let side = min(width, height) * 0.94
        let wall = Rectangle(center: center, width: side, height: side)
        let pitch = side / Double(squares)
        planRoom(squares: squares)

        // The pencil grid that covers the wall. Its outer lines are the
        // wall's own edges.
        noFill()
        strokeCap(.butt)
        strokeWeight(1)
        stroke(pencil)
        for k in 0 ... squares {
            let offset = Double(k) * pitch
            drawLine(wall.x + offset, wall.y, wall.x + offset, wall.y + side)
            drawLine(wall.x, wall.y + offset, wall.x + side, wall.y + offset)
        }

        // Where in the lap we are: which wall, and how far through it.
        let turn = (time / lap).truncatingRemainder(dividingBy: 1) * Double(plan.count)
        let index = min(plan.count - 1, Int(turn))
        let phase = turn - Double(index)
        let drawing = 0.62, held = 0.92
        let current = walls[index]

        // The wall is cleared in the last moments of its turn.
        let fade = phase < held ? 0 : (phase - held) / (1 - held)
        let ink = 1 - fade * fade * (3 - 2 * fade)
        guard ink > 0.002 else { return }

        strokeCap(.round)
        strokeWeight(lineWeight)
        let progress = min(1, phase / drawing) * Double(current.count)
        let whole = min(current.count, Int(progress))
        for (k, line) in current.enumerated() where k <= whole {
            // The line under the crayon right now is drawn as far as it has
            // got, from its starting point outward.
            let done = k < whole ? 1 : progress - Double(whole)
            guard done > 0 else { continue }
            stroke(crayons[line.kind.rawValue].withAlpha(0.92 * ink))
            let from = wall.topLeft + line.from * pitch
            let to = wall.topLeft + line.to * pitch
            drawLine(from, Vector2.lerp(from, to, done))
        }
    }

    /// Plans the seven walls of a room when a setting they depend on changes.
    private func planRoom(squares: Int) {
        let count = max(10, lines)
        let settings = [Double(count), Double(squares), Double(room + skipped), reach]
        guard settings != plannedFrom else { return }
        plannedFrom = settings
        walls = plan.indices.map { index in
            // Each wall has its own run of chance, so one wall's choices do
            // not move another's.
            var generator = SplitMix64(seed: UInt64(room + skipped) &* 7_919 &+ UInt64(index))
            return planWall(plan[index], count: count, squares: squares, using: &generator)
        }
    }

    /// One wall: its starting points, how many lines each one gets, and a grid
    /// point for every line.
    private func planWall(_ kinds: [Kind], count: Int, squares: Int,
                          using generator: inout SplitMix64) -> [Line] {
        let far = Double(squares), half = far / 2
        // The starting points, in units of one grid square from the wall's
        // top left corner, with the shares of the lines each one takes.
        var starts: [(point: Vector2, kind: Kind, shares: Int)] = []
        for kind in kinds {
            switch kind {
            case .sides:
                let midpoints = [Vector2(half, 0), Vector2(far, half),
                                 Vector2(half, far), Vector2(0, half)]
                for point in midpoints { starts.append((point, kind, 1)) }
            case .corners:
                let corners = [Vector2(0, 0), Vector2(far, 0), Vector2(far, far), Vector2(0, far)]
                for point in corners { starts.append((point, kind, 1)) }
            case .center:
                starts.append((Vector2(half, half), kind, 2))
            }
        }

        // Share the wall's lines out, whole shares first. The lines left over
        // go one each to the starting points in order, so the wall holds
        // exactly `count` lines whatever the division leaves.
        let totalShares = starts.reduce(0) { $0 + $1.shares }
        var quotas = starts.map { count * $0.shares / totalShares }
        var left = count - quotas.reduce(0, +)
        var next = 0
        while left > 0 {
            quotas[next % quotas.count] += 1
            left -= 1
            next += 1
        }

        let shortest = far / 8
        var planned: [Line] = []
        planned.reserveCapacity(count)
        for (start, quota) in zip(starts, quotas) {
            // What this starting point has used so far: directions as
            // whole-number steps in lowest terms (so no line is drawn over
            // another), the same directions as angles, and the grid points.
            var takenSteps: Set<[Int]> = []
            var takenAngles: [Double] = []
            var takenPoints: Set<[Int]> = []
            for _ in 0 ..< quota {
                var best: (column: Int, row: Int, steps: [Int], angle: Double)?
                var bestGap = -1.0
                var throwsLeft = handful
                var tries = 0
                while throwsLeft > 0, tries < 800 {
                    tries += 1
                    // A throw: a direction, and a length along it.
                    let heading = Self.unit(&generator) * .tau
                    let along = Vector2(cos(heading), sin(heading))
                    let limit = Self.run(from: start.point, along: along, far: far) * reach
                    guard limit > shortest else { continue }
                    let length = shortest + Self.unit(&generator) * (limit - shortest)
                    let target = start.point + along * length
                    let column = min(squares, max(0, Int(target.x.rounded())))
                    let row = min(squares, max(0, Int(target.y.rounded())))
                    // Steps in half squares, since a midpoint can sit halfway
                    // between two grid lines.
                    let dx = 2 * column - Int((2 * start.point.x).rounded())
                    let dy = 2 * row - Int((2 * start.point.y).rounded())
                    if dx == 0, dy == 0 { continue }
                    let alongEdge = (dx == 0 && (start.point.x == 0 || start.point.x == far))
                        || (dy == 0 && (start.point.y == 0 || start.point.y == far))
                    if alongEdge { continue }
                    let divisor = Self.commonDivisor(abs(dx), abs(dy))
                    let steps = [dx / divisor, dy / divisor]
                    if takenSteps.contains(steps) { continue }
                    if (Vector2(Double(dx), Double(dy)) * 0.5).length < shortest { continue }
                    let angle = atan2(Double(dy), Double(dx))
                    let gap = takenAngles.map { Self.turn(between: angle, and: $0) }.min()
                        ?? .infinity
                    throwsLeft -= 1
                    if gap > bestGap {
                        bestGap = gap
                        best = (column, row, steps, angle)
                    }
                }
                if let best {
                    takenSteps.insert(best.steps)
                    takenAngles.append(best.angle)
                    takenPoints.insert([best.column, best.row])
                    planned.append(Line(from: start.point,
                                        to: Vector2(Double(best.column), Double(best.row)),
                                        kind: start.kind))
                    continue
                }
                // The grid has run out of fresh directions from this point (a
                // coarse grid asked for many lines). The wall still gets its
                // number: any grid point not used yet, then any at all.
                let atOrigin = start.point.x == 0 && start.point.y == 0
                var fallback = atOrigin ? Vector2(far, far) : Vector2(0, 0)
                for attempt in 0 ..< 800 {
                    let column = Int(generator.next() % UInt64(squares + 1))
                    let row = Int(generator.next() % UInt64(squares + 1))
                    let point = Vector2(Double(column), Double(row))
                    if point.distance(to: start.point) < 0.25 { continue }
                    if attempt < 400, takenPoints.contains([column, row]) { continue }
                    takenPoints.insert([column, row])
                    fallback = point
                    break
                }
                planned.append(Line(from: start.point, to: fallback, kind: start.kind))
            }
        }
        return planned
    }

    /// How many throws the drafter weighs for each line.
    private let handful = 6

    /// A number from 0 up to 1 from the run of chance.
    private static func unit(_ generator: inout SplitMix64) -> Double {
        Double(generator.next() >> 11) * 0x1p-53
    }

    /// How far a line from `point` can run along `direction` before it leaves
    /// a wall `far` squares wide and high. Zero when it points off the wall.
    private static func run(from point: Vector2, along direction: Vector2, far: Double) -> Double {
        var limit = Double.infinity
        if direction.x > 1e-9 { limit = min(limit, (far - point.x) / direction.x) }
        if direction.x < -1e-9 { limit = min(limit, -point.x / direction.x) }
        if direction.y > 1e-9 { limit = min(limit, (far - point.y) / direction.y) }
        if direction.y < -1e-9 { limit = min(limit, -point.y / direction.y) }
        return limit.isFinite ? max(0, limit) : 0
    }

    /// The angle between two directions, the short way around.
    private static func turn(between a: Double, and b: Double) -> Double {
        let difference = abs(a - b).truncatingRemainder(dividingBy: .tau)
        return min(difference, .tau - difference)
    }

    /// The greatest whole number that divides both.
    private static func commonDivisor(_ a: Int, _ b: Int) -> Int {
        var (a, b) = (a, b)
        while b != 0 { (a, b) = (b, a % b) }
        return max(a, 1)
    }
}
```
