# LocationOfATrapezoid

Wall Drawing 237 (1974), a trapezoid found by following one long sentence, with the sentence written on the wall beside it.

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

```swift
//  Recreation after Sol LeWitt - "Wall Drawing 237: The location of a
//  trapezoid" (June 1974). One long sentence places a trapezoid on a wall. It
//  names only the wall's corners, the midpoints of its sides, its center, and
//  points halfway between them. The sentence is written on the wall beside
//  the figure. First drawn by LeWitt at Galleria Sperone, Turin, and on view
//  in the wall drawing retrospective at MASS MoCA. A homage, not a
//  reproduction, and not affiliated with or endorsed by the artist or his
//  estate.
//  https://massmoca.org/event/walldrawing237/
//  https://www.tate.org.uk/art/artworks/lewitt-the-location-of-six-geometric-figures-65206
//
//  An original Ollin interpretation written from the sentence itself. Nothing
//  was ported: the work is an instruction a drafter carries out by hand. The
//  wording is the note Sotheby's printed with the work in its catalog of May
//  2013. It was checked word for word against the paragraph under LeWitt's
//  1975 etching of the same title. The etching says "square" where the wall
//  drawing says "wall". The corners this sketch finds on a square wall were
//  measured against that etching.

import Ollin

/// "Wall Drawing 237: The location of a trapezoid" (Sol LeWitt, June 1974).
/// The instruction is one sentence:
///
/// "A trapezoid whose top side is half as long as its bottom side and whose
/// left side is one and a half times as long as the top side and is located
/// where a line drawn from a point halfway between a point halfway between
/// the center of the wall and the upper left corner and a point halfway
/// between the midpoint of the top side and the upper left corner to a point
/// halfway between the midpoint of the right side and the upper right corner
/// is crossed by two lines, the first of which is drawn from a point halfway
/// between the midpoint of the top side and a point halfway between the
/// midpoint of the top side and the upper left corner to a point halfway
/// between a point halfway between the center of the wall and the midpoint of
/// the bottom side and a point halfway between the midpoint of the bottom
/// side and the lower left corner, the second line is drawn from a point
/// halfway between the midpoint of the top side and the upper right corner to
/// the center of the wall, the left side is drawn to a point halfway between
/// a point halfway between the center of the wall and the lower left corner
/// and a point halfway between the midpoint of the left side and the lower
/// left corner."
///
/// The sentence is long, but it is a list of steps. Every place in it is
/// found from nine places any wall has: four corners, the midpoints of four
/// sides, and the center. One line is drawn, two more cross it, and the piece
/// of the first line between the two crossings is the top of the trapezoid.
/// The left side leaves the top's left end toward one more found point and
/// stops at one and a half times the top's length. The bottom is twice the
/// top and parallel to it, as a trapezoid's two bases are, and the right side
/// closes the figure.
///
/// LeWitt had the sentence written on the wall beside the figure, in pencil,
/// and the drafters write it in capital letters. So the sketch writes it too,
/// in single pencil strokes, and each point and line appears when the words
/// that name it have been written. The faint lines are the measuring: the
/// two places a point lies halfway between. Then the trapezoid goes on in
/// black crayon, the wall is held, and it is painted over.
///
/// Nothing here is left to chance, and the drafter has no choice to make.
/// What changes the drawing is the wall. Every measure comes from the wall's
/// own corners and sides, so the same sentence gives a different trapezoid on
/// a wall of another shape.
///
/// Try it: `proportion` is the wall's width over its height, and a press
/// walks on to the next of a few other walls. `lettering` is the most the
/// capitals may stand, and they shrink when the wall leaves them less room.
/// `lap` is the seconds for one wall and the length of one exact loop.
/// Everything is strokes, the lettering too, so `--export-svg` with `--at 25`
/// gives the finished wall to a pen.
@main
final class LocationOfATrapezoid: Sketch {
    /// The wall's width over its height. At 1 the wall is a square, the shape
    /// the 1975 etching gives it.
    @Param(0.6 ... 2, icon: "rectangle") var proportion = 1.0
    /// The most the capital letters may stand, in points. They are drawn
    /// smaller when the wall has no room for the sentence at this size.
    @Param(4.5 ... 9, icon: "textformat") var lettering = 7.5
    /// Seconds for one wall, which is one lap of the loop.
    @Param(12 ... 30, icon: "clock") var lap = 28.0

    override var loopDuration: Double? { lap }

    // MARK: The instruction

    /// A mark the drafter makes on the wall.
    private enum Mark {
        /// A short tick where a side of the wall has its midpoint.
        case tick(Vector2, Vector2)
        /// The faint line between two places, measured to find its middle.
        case measure(Vector2, Vector2)
        /// A small cross on a found point.
        case point(Vector2)
        /// A line of the construction.
        case rule(Vector2, Vector2)

        /// How long the mark takes to make, counted in letters written.
        var letters: Double {
            switch self {
            case .tick: 3
            case .measure: 10
            case .point: 5
            case .rule: 30
            }
        }
    }

    /// A run of the sentence and the marks made once it has been written.
    private struct Part {
        var words: String
        var marks: [Mark]
    }

    /// The places the sentence finds on one wall, and the trapezoid.
    private struct Location {
        var parts: [Part]
        /// The trapezoid's corners: the top side's two ends, then the bottom
        /// side's right and left ends.
        var topLeft: Vector2, topRight: Vector2, bottomRight: Vector2, bottomLeft: Vector2
    }

    /// Carries the sentence out on `wall`. The words are kept with the marks
    /// they call for, in the sentence's own order.
    private func locate(on wall: Rectangle) -> Location {
        func halfway(_ a: Vector2, _ b: Vector2) -> Vector2 { Vector2.lerp(a, b, 0.5) }

        // The nine places any wall has.
        let upperLeft = wall.topLeft, upperRight = wall.topRight
        let lowerLeft = wall.bottomLeft, lowerRight = wall.bottomRight
        let top = halfway(upperLeft, upperRight), bottom = halfway(lowerLeft, lowerRight)
        let left = halfway(upperLeft, lowerLeft), right = halfway(upperRight, lowerRight)
        let middle = wall.center

        // "a line drawn from ... to ..."
        let centerToUpperLeft = halfway(middle, upperLeft)
        let topToUpperLeft = halfway(top, upperLeft)
        let lineStart = halfway(centerToUpperLeft, topToUpperLeft)
        let lineEnd = halfway(right, upperRight)
        // "... is crossed by two lines, the first of which ..."
        let firstStart = halfway(top, topToUpperLeft)
        let centerToBottom = halfway(middle, bottom)
        let bottomToLowerLeft = halfway(bottom, lowerLeft)
        let firstEnd = halfway(centerToBottom, bottomToLowerLeft)
        // "the second line ..."
        let secondStart = halfway(top, upperRight)
        // "the left side is drawn to ..."
        let centerToLowerLeft = halfway(middle, lowerLeft)
        let leftToLowerLeft = halfway(left, lowerLeft)
        let leftAim = halfway(centerToLowerLeft, leftToLowerLeft)

        // The top side is the piece of the line between the two crossings.
        let topLeft = Self.crossing(lineStart, lineEnd, firstStart, firstEnd)
        let topRight = Self.crossing(lineStart, lineEnd, secondStart, middle)
        let topLength = topLeft.distance(to: topRight)
        let along = (topRight - topLeft) * (1 / topLength)
        // The left side: toward the found point, one and a half tops long.
        let down = (leftAim - topLeft) * (1 / topLeft.distance(to: leftAim))
        let bottomLeft = topLeft + down * (1.5 * topLength)
        // The bottom side: twice the top, and parallel to it.
        let bottomRight = bottomLeft + along * (2 * topLength)

        // Ticks a little way into the wall at the midpoints of its sides.
        let reach = 9.0
        let ticks: [Mark] = [
            .tick(top, top + Vector2(0, reach)), .tick(right, right - Vector2(reach, 0)),
            .tick(bottom, bottom - Vector2(0, reach)), .tick(left, left + Vector2(reach, 0)),
            .point(middle),
        ]

        let parts = [
            Part(words: "The location of a trapezoid.", marks: ticks),
            Part(words: "A trapezoid whose top side is half as long as its bottom side and whose "
                + "left side is one and a half times as long as the top side and is located where "
                + "a line drawn from ", marks: []),
            Part(words: "a point halfway between a point halfway between the center of the wall "
                + "and the upper left corner ",
                 marks: [.measure(middle, upperLeft), .point(centerToUpperLeft)]),
            Part(words: "and a point halfway between the midpoint of the top side and the upper "
                + "left corner ",
                 marks: [.measure(top, upperLeft), .point(topToUpperLeft),
                         .measure(centerToUpperLeft, topToUpperLeft), .point(lineStart)]),
            Part(words: "to a point halfway between the midpoint of the right side and the upper "
                + "right corner ",
                 marks: [.measure(right, upperRight), .point(lineEnd), .rule(lineStart, lineEnd)]),
            Part(words: "is crossed by two lines, the first of which is drawn from a point halfway "
                + "between the midpoint of the top side and a point halfway between the midpoint "
                + "of the top side and the upper left corner ",
                 marks: [.measure(top, topToUpperLeft), .point(firstStart)]),
            Part(words: "to a point halfway between a point halfway between the center of the wall "
                + "and the midpoint of the bottom side ",
                 marks: [.measure(middle, bottom), .point(centerToBottom)]),
            Part(words: "and a point halfway between the midpoint of the bottom side and the lower "
                + "left corner, ",
                 marks: [.measure(bottom, lowerLeft), .point(bottomToLowerLeft),
                         .measure(centerToBottom, bottomToLowerLeft), .point(firstEnd),
                         .rule(firstStart, firstEnd)]),
            Part(words: "the second line is drawn from a point halfway between the midpoint of the "
                + "top side and the upper right corner ",
                 marks: [.measure(top, upperRight), .point(secondStart)]),
            Part(words: "to the center of the wall, ",
                 marks: [.rule(secondStart, middle)]),
            Part(words: "the left side is drawn to a point halfway between a point halfway between "
                + "the center of the wall and the lower left corner ",
                 marks: [.measure(middle, lowerLeft), .point(centerToLowerLeft)]),
            Part(words: "and a point halfway between the midpoint of the left side and the lower "
                + "left corner.",
                 marks: [.measure(left, lowerLeft), .point(leftToLowerLeft),
                         .measure(centerToLowerLeft, leftToLowerLeft), .point(leftAim),
                         .rule(topLeft, leftAim)]),
        ]
        return Location(parts: parts, topLeft: topLeft, topRight: topRight,
                        bottomRight: bottomRight, bottomLeft: bottomLeft)
    }

    /// Where the line through `a` and `b` meets the line through `c` and `d`.
    private static func crossing(_ a: Vector2, _ b: Vector2,
                                 _ c: Vector2, _ d: Vector2) -> Vector2 {
        let r = b - a, s = d - c
        let denominator = r.x * s.y - r.y * s.x
        guard abs(denominator) > 1e-12 else { return a }
        let t = ((c.x - a.x) * s.y - (c.y - a.y) * s.x) / denominator
        return a + r * t
    }

    // MARK: The lettering

    /// The sentence set in single-stroke capitals: the pen strokes of every
    /// letter, in the order they are written, one entry for each character.
    private struct Lettering {
        var strokes: [[[Vector2]]] = []
        var height = 0.0
    }

    /// Sets `parts` in capitals `capHeight` tall inside a block `measure`
    /// wide whose top left corner is `origin`. The title takes the first line
    /// and the sentence wraps under it, word by word.
    private func letter(_ parts: [Part], at origin: Vector2, measure: Double,
                        capHeight: Double) -> Lettering {
        let font = StrokeFont.builtIn
        // The font's ascent is the height of its capitals.
        let scale = capHeight / font.ascentUnits
        let lineHeight = capHeight * 1.62
        let space = font.advanceUnits(for: " ") * scale
        var set = Lettering()
        var pen = Vector2(origin.x, origin.y + capHeight)

        func write(_ word: Substring) {
            for character in word {
                var strokes: [[Vector2]] = []
                if let glyph = font.glyph(for: character) {
                    strokes = glyph.polylines.map { line in line.map { pen + $0 * scale } }
                }
                set.strokes.append(strokes)
                pen = Vector2(pen.x + font.advanceUnits(for: character) * scale, pen.y)
            }
        }

        for (index, part) in parts.enumerated() {
            let capitals = part.words.uppercased()
            var rest = Substring(capitals)
            while !rest.isEmpty {
                // Take the next space, or the next word.
                if rest.first == " " {
                    rest.removeFirst()
                    set.strokes.append([])
                    pen = Vector2(pen.x + space, pen.y)
                    continue
                }
                let end = rest.firstIndex(of: " ") ?? rest.endIndex
                let word = rest[..<end]
                rest = rest[end...]
                let wordWidth = word.reduce(0) { $0 + font.advanceUnits(for: $1) * scale }
                if pen.x + wordWidth > origin.x + measure, pen.x > origin.x {
                    pen = Vector2(origin.x, pen.y + lineHeight)
                }
                write(word)
            }
            // The title stands on a line of its own.
            if index == 0 {
                pen = Vector2(origin.x, pen.y + lineHeight)
            }
        }
        set.height = pen.y - origin.y + capHeight * 0.3
        return set
    }

    // MARK: The wall

    private let wallColor = Color(hex: 0xF3F1EC)
    private let pencil = Color(white: 0.24)
    private let crayon = Color(white: 0.07)

    /// A few other walls a press walks on to, as width over height. The first
    /// is whatever `proportion` says.
    private let otherWalls: [Double] = [4.0 / 3, 3.0 / 4, 16.0 / 9, 5.0 / 8, 2]
    private var walked = 0

    /// What was worked out for the current wall, kept until the wall or the
    /// lettering changes.
    private var location: Location?
    private var lettered = Lettering()
    private var partEnds: [Double] = []
    private var workedFrom: [Double] = []

    override func mousePressed() {
        walked += 1
    }

    /// Works the wall out again when its shape or the lettering has changed.
    private func prepare() -> (wall: Rectangle, location: Location) {
        let step = walked % (otherWalls.count + 1)
        let shape = step == 0 ? proportion : otherWalls[step - 1]
        let room = min(width, height) * 0.9
        let wall = Rectangle(center: center,
                             width: shape >= 1 ? room : room * shape,
                             height: shape >= 1 ? room / shape : room)
        let settings = [wall.width, wall.height, lettering]
        if settings == workedFrom, let location { return (wall, location) }
        workedFrom = settings

        let found = locate(on: wall)
        location = found

        // Two places on the wall are clear of the figure: under its bottom
        // side on the right, and beside its right side under the first line.
        // The sentence goes where it can be written larger.
        let gap = room * 0.035
        let inset = room * 0.045
        let below = Rectangle(x: wall.x + wall.width * 0.53, y: found.bottomRight.y + gap,
                              width: wall.width * 0.47 - inset,
                              height: wall.y + wall.height - inset - found.bottomRight.y - gap)
        let besideLeft = max(found.topRight.x, found.bottomRight.x) + gap
        let besideTop = wall.y + wall.height * 0.25 + gap
        let beside = Rectangle(x: besideLeft, y: besideTop,
                               width: wall.x + wall.width - inset - besideLeft,
                               height: wall.y + wall.height - inset - besideTop)
        var best = Lettering()
        var bestSize = 0.0
        for block in [below, beside] where block.width > 60 && block.height > 20 {
            var size = lettering
            var set = letter(found.parts, at: block.topLeft, measure: block.width, capHeight: size)
            while set.height > block.height, size > 4 {
                size -= 0.25
                set = letter(found.parts, at: block.topLeft, measure: block.width, capHeight: size)
            }
            if size > bestSize {
                bestSize = size
                best = set
            }
        }
        lettered = best

        // How many characters have been written when each part ends.
        var written = 0.0
        partEnds = found.parts.map { part in
            written += Double(part.words.count)
            return written
        }
        return (wall, found)
    }

    override func draw() {
        background(wallColor)
        let (wall, found) = prepare()
        let letterCount = partEnds.last ?? 1

        // The lap: write and construct, draw the figure, hold, paint over.
        let turn = (time / lap).truncatingRemainder(dividingBy: 1)
        let writing = 0.66, figureStart = 0.72, figureEnd = 0.86, held = 0.955
        let fade = turn < held ? 0 : (turn - held) / (1 - held)
        let ink = 1 - fade * fade * (3 - 2 * fade)
        // The pencil keeps counting after the last letter, so the marks the
        // last words call for have time to be made.
        let cursor = turn / writing * letterCount

        noFill()
        strokeCap(.round)
        strokeJoin(.round)

        // The wall's own edges.
        strokeWeight(1)
        stroke(pencil.withAlpha(0.5))
        drawPolyline([wall.topLeft, wall.topRight, wall.bottomRight, wall.bottomLeft], closed: true)
        guard ink > 0.002 else { return }

        // The marks, each begun when the words before it have been written.
        for (index, part) in found.parts.enumerated() {
            var begins = partEnds[index]
            for mark in part.marks {
                let done = min(1, (cursor - begins) / mark.letters)
                begins += mark.letters
                guard done > 0 else { break }
                switch mark {
                case let .tick(from, to):
                    stroke(pencil.withAlpha(0.6 * ink))
                    drawLine(from, Vector2.lerp(from, to, done))
                case let .measure(from, to):
                    // A line along the wall's edge would only retrace it.
                    if Self.liesOnEdge(from, to, of: wall) { continue }
                    stroke(pencil.withAlpha(0.2 * ink))
                    drawLine(from, Vector2.lerp(from, to, done))
                case let .point(place):
                    stroke(pencil.withAlpha(0.75 * ink))
                    let arm = 4.5
                    drawLine(place - Vector2(arm, 0), place + Vector2(arm, 0))
                    if done > 0.5 { drawLine(place - Vector2(0, arm), place + Vector2(0, arm)) }
                case let .rule(from, to):
                    stroke(pencil.withAlpha(0.6 * ink))
                    drawLine(from, Vector2.lerp(from, to, done))
                }
            }
        }

        // The sentence, as far as it has been written.
        stroke(pencil.withAlpha(0.78 * ink))
        strokeWeight(0.9)
        let shown = min(lettered.strokes.count, Int(cursor))
        for strokes in lettered.strokes.prefix(shown) {
            for line in strokes where line.count > 1 { drawPolyline(line) }
        }

        // The trapezoid, in crayon: the top, the left side, the bottom, and
        // the side that closes it.
        let sides = [
            (found.topLeft, found.topRight), (found.topLeft, found.bottomLeft),
            (found.bottomLeft, found.bottomRight), (found.topRight, found.bottomRight),
        ]
        let drawn = (turn - figureStart) / (figureEnd - figureStart) * Double(sides.count)
        guard drawn > 0 else { return }
        stroke(crayon.withAlpha(0.94 * ink))
        strokeWeight(3)
        for (index, side) in sides.enumerated() {
            let done = min(1, drawn - Double(index))
            guard done > 0 else { break }
            drawLine(side.0, Vector2.lerp(side.0, side.1, done))
        }
    }

    /// Whether both points sit on one and the same edge of the wall.
    private static func liesOnEdge(_ a: Vector2, _ b: Vector2, of wall: Rectangle) -> Bool {
        let near = 0.01
        let right = wall.x + wall.width, bottom = wall.y + wall.height
        let onLeft = abs(a.x - wall.x) < near && abs(b.x - wall.x) < near
        let onRight = abs(a.x - right) < near && abs(b.x - right) < near
        let onTop = abs(a.y - wall.y) < near && abs(b.y - wall.y) < near
        let onBottom = abs(a.y - bottom) < near && abs(b.y - bottom) < near
        return onLeft || onRight || onTop || onBottom
    }
}
```
