# LaSerpiente

one line of black steel broken at sharp angles, walked through in the patio it was made for, after Goeritz's La serpiente de El Eco (1953).

Run it with `swift run --package-path Examples Example-Recreations-MathiasGoeritz-LaSerpiente`.

```swift
//  Recreation after Mathias Goeritz - La serpiente de El Eco (1953), the
//  black serpent of welded sheet metal he made for the patio of the Museo
//  Experimental El Eco, Sullivan 43, Mexico City. It was first known as
//  Ataque, the attack. The Museo de Arte Moderno, Mexico City, holds La
//  serpiente de El Eco (1953, enameled iron) in its sculpture garden. A
//  homage, not a reproduction, and not affiliated with or endorsed by the
//  artist's estate or the museums.
//  https://mam.inba.gob.mx/descargas/Fichas-interactivas-ENG_2023.pdf
//  https://eleco.unam.mx/storage/2021/03/Manifiesto-Emocional-El-sentido-de-un-museo-experimental-David-Miranda-2021.pdf
//  https://eleco.unam.mx/storage/2021/06/2017_PUBLICACION_La-disonancia-de-El-eco.pdf
//  https://eleco.unam.mx/storage/2021/09/2021_09_Re_vista04_PARPADEOS_RebecaBarquera.pdf
//  https://polired.upm.es/index.php/proyectos_arquitectonicos/article/download/3225/3335/12056
//
//  An original Ollin interpretation, written from published descriptions and
//  from pictures of the work. The line is read off three photographs of
//  1953, by Armando Salas Portugal and Marianne Gast, and one of the copy
//  made for the 2014 retrospective. It is approximate, and simpler than the
//  piece where the body meets its last rise. The museum gives the one it
//  holds as 8 meters long by 3 high. In a photograph of 1953 the neck stands
//  more than twice as tall as the dancer beside it. So the serpent here is
//  8 meters long and taller than the museum's figure, tall enough to walk
//  under, and `neck` sets how tall. The patio is drawn plainer than it is.
//  The heights of its walls, about 7 meters and 11 for the yellow one, are
//  from Fernando Quesada's study of the building. Its other sizes, its
//  bearing, and the gray of its floor are this sketch's guesses.

import Foundation
import Ollin

/// *La serpiente de El Eco* (Mathias Goeritz, Mexico City, 1953): one line
/// of black steel, broken at sharp angles, in the patio it was made for.
/// The eye walks through it.
///
/// El Eco was the building Goeritz planned as a sculpture to be lived in.
/// For its patio he made a serpent of welded sheet metal. In his notes for
/// the opening, the great iron cross of the window onto the patio is
/// "atacada", attacked, by it. The museum that holds a serpent today
/// describes how it is made: he starts from a basic element, the line, and
/// with it forms pronounced angles. El Eco's own account likens the shape
/// to the crests of an electrocardiogram.
///
/// So the sketch is one line of eight points. It starts at the jaws, which
/// lie open on the floor. It climbs the neck, the tallest run. Then it drops
/// to the floor, rises to a small crest, touches down again, rises to a
/// last peak, and ends at the tail. Each run is a hollow box of plate that
/// swells and thins along its length. The runs do not lie in one plane, so
/// the zigzag reads differently from every side.
///
/// Goeritz wrote that the serpent had to become almost a piece of
/// architecture, "con aperturas para el ballet", with openings for the
/// ballet danced there on opening night. The walk takes two of them. It
/// passes between the neck and the body, where a dancer stands in a
/// photograph of 1953, and under the last arch.
///
/// Try it: `view` is where you are. **walk** goes through the openings, one
/// lap every `seconds`. **patio** circles the serpent from near the walls.
/// **chart** unrolls the line flat, height against length, the way a chart
/// of temperatures is drawn, and exports as a drawing (`--export-svg`).
/// `neck` is how tall the serpent stands, in meters, and `girth` swells or
/// thins every run. `hour` moves the sun. In the afternoon the shadow of the
/// tall west wall crosses the patio and takes the serpent's own shadow.
@main
final class LaSerpiente: Sketch {
    enum View: String, CaseIterable, ParamOption { case walk, patio, chart }

    /// Where you are: walking through it, circling it, or reading its chart.
    @Param(icon: "eye") var view = View.walk
    /// One lap of the walk, in seconds.
    @Param(12 ... 30, icon: "timer") var seconds = 30.0
    /// The hour of the day, which places the sun.
    @Param(7 ... 17, icon: "sun.max") var hour = 10.5
    /// How tall the serpent stands at the top of its neck, in meters.
    @Param(4.6 ... 6, icon: "arrow.up.and.down") var neck = 5.3
    /// How thick every run is, against the thickness read off the pictures.
    @Param(0.5 ... 1.4, icon: "square.resize") var girth = 1.0

    override var canvasSize: CanvasSize { .square(1080) }
    override var loopDuration: Double? { seconds }

    // MARK: - The line

    /// One corner of the line: where it is, in meters, and how thick the
    /// box of plate is there. `x` runs east, `y` up, and `z` south. `across`
    /// is the box's size square to the bend, and `deep` its size in the
    /// plane the line bends in. A run swells or thins from one corner to
    /// the next.
    struct Corner {
        var at: Vector3
        var across = 0.34
        var deep = 0.34
    }

    /// The height of the neck's top corner in the table below, which the
    /// other heights follow.
    static let readHeight = 4.6

    /// From the jaws to the tail. The first run is the head, flat on the
    /// floor, and is built on its own.
    static let corners: [Corner] = [
        Corner(at: Vector3(-4.1, 0.42, 0.67)),
        Corner(at: Vector3(-1.9, 0.42, 0.19), across: 0.5, deep: 0.5),
        Corner(at: Vector3(-1.52, 4.6, 0.0), across: 0.5, deep: 0.6),
        Corner(at: Vector3(0.1, 0.05, 1.43), across: 0.34, deep: 0.2),
        Corner(at: Vector3(1.05, 1.95, 0.38), across: 0.42, deep: 0.42),
        Corner(at: Vector3(2.19, 0.05, -1.24), across: 0.5, deep: 0.4),
        Corner(at: Vector3(2.86, 3.2, 0.1), across: 0.8, deep: 0.5),
        Corner(at: Vector3(3.9, 0.05, 2.19), across: 0.6, deep: 0.36),
    ]

    /// How far a cut may run past its corner, as a multiple of the plate's
    /// own thickness. It blunts the sharpest corners a little.
    static let longestCut = 2.4

    /// The line for a serpent that stands `neck` meters tall: the plan
    /// stays, and everything above the head stretches. The steel's highest
    /// point is the outside of the cut at the top of the neck, which stands
    /// a little above the line's own corner there.
    private func line() -> [Vector3] {
        let head = LaSerpiente.corners[0].at.y
        let above = LaSerpiente.corners[2].deep * girth / 2 * LaSerpiente.longestCut
        let stretch = (neck - above - head) / (LaSerpiente.readHeight - head)
        return LaSerpiente.corners.map { corner in
            let y = corner.at.y <= head ? corner.at.y : head + (corner.at.y - head) * stretch
            return Vector3(corner.at.x, y, corner.at.z)
        }
    }

    // The patio, in meters. No wall meets another square, as in the
    // building, where he avoided right angles.
    static let west = -8.0
    static let east = 8.0
    static let north = -6.0
    static let south = 7.4
    static let tile = 0.4

    private var serpent: Mesh?
    private var builtFor = ""
    private let floor = LaSerpiente.tiles()
    private let ground = Mesh.plane(width: 60, depth: 60)
    private let walls = LaSerpiente.patioWalls()

    // MARK: - The frame

    override func draw() {
        if view == .chart {
            drawChart()
            return
        }
        let key = "\(neck)/\(girth)"
        if key != builtFor {
            serpent = LaSerpiente.build(line(), girth: girth)
            builtFor = key
        }

        let sun = sunDirection()
        let low = max(0, min(1, (0.6 - sun.y) / 0.6))
        background(Color(hex: 0xBFD3E2).mixed(with: Color(hex: 0xE6D8C2), low * 0.7))
        placeCamera()

        // The sky lights every plate a little and the sun lights the ones
        // that face it. Two weak lights stand for what a sunlit patio sends
        // back: one across from the sun, for the walls and plates in shade,
        // and one up from the pale tiles, for the underside of every run.
        ambientLight(Color(red: 0.56, green: 0.58, blue: 0.63))
        directionalLight(Color(red: 1.0, green: 0.96, blue: 0.88).mixed(with: Color(hex: 0xFFC890), low * 0.6),
                         direction: sun * -1, intensity: 1.05)
        directionalLight(Color(red: 1.0, green: 0.97, blue: 0.92), direction: Vector3(sun.x, -0.1, sun.z).normalized,
                         intensity: 0.28, castsShadow: false)
        directionalLight(Color(red: 1.0, green: 0.95, blue: 0.88), direction: Vector3(0, 1, 0),
                         intensity: 0.2, castsShadow: false)
        castShadows()
        shadowSoftness(0.2)

        noStroke()
        fill(Color(hex: 0x6F6C68))
        withState {
            translate(0, -0.02, 0)
            drawMesh(ground)
        }
        fill(.white)
        drawMesh(floor)
        for wall in walls {
            fill(wall.color)
            drawMesh(wall.mesh)
        }
        if let serpent {
            // Black enamel: dark, with a soft shine where a plate faces the
            // sun.
            withState {
                material(Material(specular: 0.2, specularSharpness: 10))
                fill(Color(hex: 0x2D2B28))
                drawMesh(serpent)
            }
        }
    }

    /// The sun for `hour` on a day late in October at 19.4 degrees north,
    /// when it stands lower in the south and the shadows are longer. It is
    /// the direction from the ground toward the sun (x east, y up, z south),
    /// with the patio's back wall taken as north.
    private func sunDirection() -> Vector3 {
        let latitude = 19.4 * Double.pi / 180
        let tilt = -12.0 * Double.pi / 180
        let angle = (hour - 12) * 15 * Double.pi / 180
        return Vector3(-cos(tilt) * sin(angle),
                       sin(latitude) * sin(tilt) + cos(latitude) * cos(tilt) * cos(angle),
                       sin(latitude) * cos(tilt) * cos(angle) - cos(latitude) * sin(tilt)).normalized
    }

    // MARK: - Where the eye is

    /// How far round the lap the clock is, 0 to 1.
    private var lap: Double {
        let t = time / seconds
        return t - t.rounded(.down)
    }

    /// The walk, as points on the floor (x east, z south). It goes north
    /// between the neck and the body, east behind the serpent, round the
    /// tail, back west under the last arch, and along the front.
    static let walk: [Vector2] = [
        Vector2(-2.57, 3.52), Vector2(-2.19, 2.24), Vector2(-1.13, 0.53), Vector2(-0.43, -0.76),
        Vector2(0.57, -2.0), Vector2(2.19, -2.67), Vector2(4.0, -2.0), Vector2(4.76, -0.9),
        Vector2(4.05, -0.26), Vector2(2.95, 0.29), Vector2(2.0, 0.93), Vector2(1.43, 2.19),
        Vector2(0.38, 3.43), Vector2(-1.24, 4.1),
    ]

    /// The walk as a smooth closed path, cut into short equal steps so the
    /// walker keeps one pace.
    static let steps: [Vector2] = {
        let count = walk.count
        var fine: [Vector2] = []
        for k in 0 ..< count {
            let p0 = walk[(k + count - 1) % count], p1 = walk[k], p2 = walk[(k + 1) % count], p3 = walk[(k + 2) % count]
            for j in 0 ..< 40 {
                let t = Double(j) / 40, t2 = t * t, t3 = t2 * t
                // A curve through the four points that passes each one.
                let a = p1 * 2
                let b = (p2 - p0) * t
                let c = (p0 * 2 - p1 * 5 + p2 * 4 - p3) * t2
                let d = (p1 * 3 - p0 - p2 * 3 + p3) * t3
                fine.append((a + b + c + d) * 0.5)
            }
        }
        var along: [Double] = [0]
        for k in 1 ... fine.count { along.append(along[k - 1] + (fine[k % fine.count] - fine[k - 1]).length) }
        let total = along[fine.count]
        var even: [Vector2] = []
        var k = 0
        for j in 0 ..< 720 {
            let want = total * Double(j) / 720
            while along[k + 1] < want { k += 1 }
            let t = (want - along[k]) / max(along[k + 1] - along[k], 1e-9)
            even.append(fine[k] + (fine[(k + 1) % fine.count] - fine[k]) * t)
        }
        return even
    }()

    /// A place on the walk for a lap from 0 to 1.
    static func walker(_ lap: Double) -> Vector2 {
        let count = Double(steps.count)
        let at = (lap - lap.rounded(.down)) * count
        let k = Int(at) % steps.count
        return steps[k] + (steps[(k + 1) % steps.count] - steps[k]) * (at - at.rounded(.down))
    }

    private func placeCamera() {
        if view == .patio {
            // Once round the serpent, keeping near the walls.
            let a = lap * 2 * Double.pi
            let eye = Vector3(6.9 * sin(a), 1.6, 0.6 + 5.9 * cos(a))
            perspective(eye: eye, target: Vector3(0, 0.38 * neck, 0.3),
                        fieldOfView: .degrees(72), near: 0.1, far: 200)
            return
        }
        // The walker looks where the path goes, a few steps ahead, and a
        // little toward the middle of the serpent and up at it.
        let here = LaSerpiente.walker(lap), ahead = LaSerpiente.walker(lap + 0.035)
        let toward = (ahead - here).normalized
        let middle = (Vector2(0.38, 0.29) - here)
        let pull = middle.length > 0.5 ? middle.normalized : toward
        let look = (toward * 0.6 + pull).normalized
        let eye = Vector3(here.x, 1.6, here.y)
        perspective(eye: eye, target: eye + Vector3(look.x, 0.22, look.y) * 4,
                    fieldOfView: .degrees(72), near: 0.05, far: 200)
    }

    // MARK: - Building the serpent

    /// The plates of a mesh as they are added: flat faces, each with its own
    /// normal, so every plate takes the light as one plane.
    struct Plates {
        var positions: [Vector3] = []
        var normals: [Vector3] = []
        var indices: [UInt32] = []

        /// One flat plate. `inside` is any point within the solid, which
        /// tells the plate which way is out.
        mutating func plate(_ p0: Vector3, _ p1: Vector3, _ p2: Vector3, _ p3: Vector3, inside: Vector3) {
            var corners = [p0, p1, p2, p3]
            var normal = (p2 - p0).cross(p3 - p1)
            guard normal.length > 1e-12 else { return }
            normal = normal.normalized
            let middle = (p0 + p1 + p2 + p3) / 4
            if normal.dot(middle - inside) < 0 {
                corners.reverse()
                normal = normal * -1
            }
            let base = UInt32(positions.count)
            positions += corners
            normals += [normal, normal, normal, normal]
            indices += [base, base + 1, base + 2, base, base + 2, base + 3]
        }

        /// A box from its four corners at one end and its four at the other,
        /// each set in order round the box. `capped` closes the two ends.
        mutating func box(_ a: [Vector3], _ b: [Vector3], capped: Bool = true) {
            let inside = (a[0] + a[1] + a[2] + a[3] + b[0] + b[1] + b[2] + b[3]) / 8
            for j in 0 ..< 4 { plate(a[j], a[(j + 1) % 4], b[(j + 1) % 4], b[j], inside: inside) }
            guard capped else { return }
            plate(a[0], a[1], a[2], a[3], inside: inside)
            plate(b[0], b[1], b[2], b[3], inside: inside)
        }

        var mesh: Mesh { Mesh(positions: positions, normals: normals, indices: indices) }
    }

    /// The whole serpent as one mesh: the head, and a box of plate for every
    /// run after it.
    static func build(_ line: [Vector3], girth: Double) -> Mesh {
        var plates = Plates()
        buildHead(&plates, from: line[0], to: line[1], girth: girth)
        let rings = sections(line, girth: girth)
        for k in 1 ..< line.count - 1 { plates.box(rings[k], rings[k + 1], capped: false) }
        let first = rings[1], last = rings[line.count - 1]
        plates.plate(first[0], first[1], first[2], first[3], inside: line[2])
        plates.plate(last[0], last[1], last[2], last[3], inside: line[line.count - 2])
        return plates.mesh
    }

    /// The four corners of the box at every corner of the line. Where two
    /// runs meet, both are cut on the plane that halves the angle between
    /// them, so the plates of one close on the plates of the next. That is
    /// how a welder joins two lengths of box at an angle.
    static func sections(_ line: [Vector3], girth: Double) -> [[Vector3]] {
        let count = line.count
        func heading(_ k: Int) -> Vector3 { (line[k + 1] - line[k]).normalized }

        // `across` at a corner is square to the plane the line bends in.
        // Each one is turned to agree with the one before it, so a run's
        // four edges join the same four corners at both ends.
        var across = [Vector3](repeating: Vector3(0, 0, 1), count: count)
        var kept = Vector3(0, 0, 1)
        for k in 2 ..< count - 1 {
            var square = heading(k - 1).cross(heading(k))
            square = square.length > 1e-6 ? square.normalized : kept
            if square.dot(kept) < 0 { square = square * -1 }
            kept = square
            across[k] = square
        }
        across[1] = across[2]
        across[count - 1] = across[count - 2]

        var rings = [[Vector3]](repeating: [], count: count)
        for k in 1 ..< count {
            let arriving = k > 1 ? heading(k - 1) : heading(k)
            let leaving = k < count - 1 ? heading(k) : arriving
            var side = across[k] - arriving * across[k].dot(arriving)
            side = side.length > 1e-6 ? side.normalized : across[k]
            // `inward` lies in the cut and in the plane of the bend.
            var inward = leaving - arriving
            let guide = side.cross(arriving)
            inward = inward.length > 1e-6 ? inward.normalized : guide
            if inward.dot(guide) < 0 { inward = inward * -1 }
            // A cut at an angle is longer than the box is thick.
            let slant = (arriving + leaving).length / 2
            let longer = min(1 / max(slant, 1e-3), longestCut)
            let u = side * (corners[k].across * girth / 2)
            let v = inward * (corners[k].deep * girth / 2 * longer)
            rings[k] = [line[k] + u + v, line[k] - u + v, line[k] - u - v, line[k] + u - v]
        }
        return rings
    }

    /// The head lies on the floor: a block under the neck and two jaws in
    /// front of it, the lower one a little longer, with the mouth between.
    static func buildHead(_ plates: inout Plates, from tip: Vector3, to neck: Vector3, girth: Double) {
        let flat = Vector3(neck.x - tip.x, 0, neck.z - tip.z)
        let length = flat.length
        let along = flat.normalized
        let side = Vector3(-along.z, 0, along.x) * (0.36 * girth)
        let origin = Vector3(tip.x, 0, tip.z)
        // A block between two distances along the head, with a floor height
        // and a top height at each end.
        func block(_ s0: Double, _ s1: Double, _ low: (Double, Double), _ high: (Double, Double)) {
            let p = origin + along * s0, q = origin + along * s1
            let up = Vector3(0, 1, 0)
            plates.box([p + side + up * low.0, p - side + up * low.0, p - side + up * high.0, p + side + up * high.0],
                       [q + side + up * low.1, q - side + up * low.1, q - side + up * high.1, q + side + up * high.1])
        }
        let throat = 0.4 * length
        block(throat, length + 0.3 * girth, (-0.02, -0.02), (0.78, 0.86))
        block(-0.22, throat + 0.02, (-0.02, -0.02), (0.3, 0.3))
        block(0.02, throat + 0.02, (0.5, 0.5), (0.64, 0.78))
    }

    // MARK: - Building the patio

    /// The floor: square tiles, each a touch lighter or darker than the
    /// next, with a dark joint between them.
    static func tiles() -> Mesh {
        var positions: [Vector3] = []
        var normals: [Vector3] = []
        var colors: [Color] = []
        var indices: [UInt32] = []
        let joint = 0.012
        var row = 0
        var z = north
        while z < south {
            var column = 0
            var x = west
            while x < east {
                let shade = 0.62 + 0.07 * jitter(row * 977 + column)
                let base = UInt32(positions.count)
                let x1 = min(x + tile, east) - joint, z1 = min(z + tile, south) - joint
                positions += [Vector3(x + joint, 0, z + joint), Vector3(x + joint, 0, z1),
                              Vector3(x1, 0, z1), Vector3(x1, 0, z + joint)]
                normals += [Vector3](repeating: Vector3(0, 1, 0), count: 4)
                colors += [Color](repeating: Color(red: shade, green: shade * 0.985, blue: shade * 0.955), count: 4)
                indices += [base, base + 1, base + 2, base, base + 2, base + 3]
                x += tile
                column += 1
            }
            z += tile
            row += 1
        }
        return Mesh(positions: positions, normals: normals, indices: indices, colors: colors)
    }

    /// A wall as it is drawn: its mesh and its coat.
    struct Wall {
        var mesh: Mesh
        var color: Color
    }

    /// The patio's walls, each as its footprint on the floor (x east, z
    /// south), how tall it stands, and its coat. The dark back wall and the
    /// gray west wall are the building. The low white wall is the street
    /// side. The tall yellow wall that holds nothing up stands where the
    /// dark wall meets it.
    static let footprints: [(outline: [Vector2], tall: Double, color: Color)] = [
        ([Vector2(west - 0.6, north - 0.2), Vector2(east + 0.9, north + 0.25),
          Vector2(east + 0.9, north - 0.5), Vector2(west - 0.6, north - 0.9)], 7.0, Color(hex: 0x4F4E4C)),
        ([Vector2(west + 0.15, north - 0.5), Vector2(west - 0.25, south + 0.6),
          Vector2(west - 0.9, south + 0.6), Vector2(west - 0.5, north - 0.5)], 7.0, Color(hex: 0xB9B6AF)),
        ([Vector2(east - 0.1, north), Vector2(east + 0.35, south + 0.6),
          Vector2(east + 0.75, south + 0.6), Vector2(east + 0.3, north)], 2.5, Color(hex: 0xE4E1D8)),
        ([Vector2(west - 0.6, south + 0.1), Vector2(east + 0.8, south + 0.45),
          Vector2(east + 0.8, south + 0.85), Vector2(west - 0.6, south + 0.5)], 2.5, Color(hex: 0xE4E1D8)),
        ([Vector2(east - 2.9, north + 0.05), Vector2(east - 0.55, north + 0.55),
          Vector2(east - 0.62, north + 1.0), Vector2(east - 2.97, north + 0.5)], 11, Color(hex: 0xF0CD1E)),
    ]

    static func patioWalls() -> [Wall] {
        footprints.map { wall in
            var plates = Plates()
            plates.box(wall.outline.map { Vector3($0.x, -0.02, $0.y) }, wall.outline.map { Vector3($0.x, wall.tall, $0.y) })
            return Wall(mesh: plates.mesh, color: wall.color)
        }
    }

    /// A number in 0...1 fixed for each whole number.
    static func jitter(_ i: Int) -> Double {
        var h = UInt64(truncatingIfNeeded: i &+ 1) &* 0x9E37_79B9_7F4A_7C15
        h ^= h >> 31
        h = h &* 0xBF58_476D_1CE4_E5B9
        h ^= h >> 29
        return Double(h & 0xFFFF) / 65535
    }

    // MARK: - The chart

    private static let ink = Color(hex: 0x1C1B1A)
    private static let paper = Color(hex: 0xF2EEE4)

    /// Two drawings of the one line. Above, the line unrolled: how far along
    /// the floor it has gone, left to right, against how high it stands.
    /// Each run keeps its true rise, and the runs that turn in the patio are
    /// laid out straight. Below, the plan: the same line from above, in its
    /// patio, with the walk dotted round it.
    private func drawChart() {
        background(LaSerpiente.paper)
        let points = line()
        var along: [Double] = [0]
        for k in 1 ..< points.count {
            let step = Vector2(points[k].x - points[k - 1].x, points[k].z - points[k - 1].z)
            along.append(along[k - 1] + step.length)
        }
        let total = along[points.count - 1]
        let unit = width * 0.86 / total
        let left = (width - total * unit) / 2
        let floorY = 70 + 5.5 * unit
        func place(_ s: Double, _ y: Double) -> Vector2 { Vector2(left + s * unit, floorY - y * unit) }
        let flat = (0 ..< points.count).map { place(along[$0], points[$0].y) }

        // A rule at every meter of height, and the floor.
        stroke(Color(hex: 0x1C1B1A, alpha: 0.18))
        strokeWeight(0.6)
        noFill()
        for meter in 1 ... 5 {
            drawLine(place(-0.4, Double(meter)), place(total + 0.4, Double(meter)))
        }
        stroke(LaSerpiente.ink)
        strokeWeight(1.2)
        drawLine(place(-0.4, 0), place(total + 0.4, 0))

        // The body: the head as its block and jaws, then each run as the
        // slab its plates make when seen from the side.
        fill(LaSerpiente.ink)
        noStroke()
        let throat = 0.4 * along[1]
        drawPolygon([place(throat, 0), place(along[1] + 0.3 * girth, 0), place(along[1] + 0.3 * girth, 0.86), place(throat, 0.78)])
        drawPolygon([place(-0.22, 0), place(throat, 0), place(throat, 0.3), place(-0.22, 0.3)])
        drawPolygon([place(0.02, 0.5), place(throat, 0.5), place(throat, 0.78), place(0.02, 0.64)])
        // Each corner is cut the way the steel is, on the line that halves
        // the angle, and a run is the slab between two cuts.
        var upper: [Vector2] = [], lower: [Vector2] = []
        for k in 1 ..< flat.count {
            let leaving = k < flat.count - 1 ? (flat[k + 1] - flat[k]).normalized : (flat[k] - flat[k - 1]).normalized
            let arriving = k > 1 ? (flat[k] - flat[k - 1]).normalized : leaving
            var cut = leaving - arriving
            cut = cut.length > 1e-6 ? cut.normalized : arriving.perpendicular
            if cut.dot(arriving.perpendicular) < 0 { cut = cut * -1 }
            let longer = min(1 / max((arriving + leaving).length / 2, 1e-3), LaSerpiente.longestCut)
            let half = cut * (LaSerpiente.corners[k].deep * girth * unit / 2 * longer)
            upper.append(flat[k] + half)
            lower.append(flat[k] - half)
        }
        for k in 0 ..< upper.count - 1 {
            drawPolygon([upper[k], upper[k + 1], lower[k + 1], lower[k]])
        }

        // The plan, north up: the walls, the yellow wall, and the serpent
        // as the floor would see it.
        let scale = 36.0
        let middle = Vector2(width / 2, floorY + 58 + (LaSerpiente.south - LaSerpiente.north) * scale / 2)
        let patioMiddle = Vector2((LaSerpiente.west + LaSerpiente.east) / 2, (LaSerpiente.north + LaSerpiente.south) / 2)
        func plan(_ p: Vector2) -> Vector2 { middle + (p - patioMiddle) * scale }
        for wall in LaSerpiente.footprints {
            fill(wall.tall > 10 ? Color(hex: 0xF0CD1E) : Color(hex: 0x1C1B1A, alpha: wall.tall > 5 ? 0.55 : 0.2))
            drawPolygon(wall.outline.map(plan))
        }
        fill(LaSerpiente.ink)
        let rings = LaSerpiente.sections(points, girth: girth)
        for k in 1 ..< points.count - 1 {
            drawPolygon(LaSerpiente.hull((rings[k] + rings[k + 1]).map { Vector2($0.x, $0.z) }).map(plan))
        }
        let tip = Vector2(points[0].x, points[0].z), foot = Vector2(points[1].x, points[1].z)
        let headway = (foot - tip).normalized, side = headway.perpendicular * (0.36 * girth)
        drawPolygon([tip - headway * 0.22 + side, foot + headway * (0.3 * girth) + side,
                     foot + headway * (0.3 * girth) - side, tip - headway * 0.22 - side].map(plan))

        // The walk, as a row of dots.
        noStroke()
        fill(Color(hex: 0x1C1B1A, alpha: 0.5))
        for k in stride(from: 0, to: LaSerpiente.steps.count, by: 8) {
            let at = plan(LaSerpiente.steps[k])
            drawCircle(at.x, at.y, 1.3)
        }

        // The line itself, the one element everything is made from, drawn
        // through both. A bead runs it from the jaws to the tail once a lap.
        let level = points.map { plan(Vector2($0.x, $0.z)) }
        noFill()
        stroke(LaSerpiente.paper)
        strokeWeight(1.4)
        drawPolyline(flat)
        drawPolyline(level)
        var gone = lap * total
        var beads = [flat[0], level[0]]
        for k in 1 ..< flat.count {
            let span = along[k] - along[k - 1]
            if gone <= span || k == flat.count - 1 {
                let t = min(1, gone / max(span, 1e-9))
                beads = [flat[k - 1] + (flat[k] - flat[k - 1]) * t, level[k - 1] + (level[k] - level[k - 1]) * t]
                break
            }
            gone -= span
        }
        if !isVectorExporting {
            fill(Color(hex: 0xF0CD1E))
            stroke(LaSerpiente.ink)
            strokeWeight(1.2)
            for bead in beads { drawCircle(bead.x, bead.y, 6.5) }
        }
    }

    /// The smallest convex outline round a handful of points.
    static func hull(_ points: [Vector2]) -> [Vector2] {
        let sorted = points.sorted { $0.x != $1.x ? $0.x < $1.x : $0.y < $1.y }
        func turn(_ o: Vector2, _ a: Vector2, _ b: Vector2) -> Double {
            (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x)
        }
        var lower: [Vector2] = [], upper: [Vector2] = []
        for p in sorted {
            while lower.count >= 2 && turn(lower[lower.count - 2], lower[lower.count - 1], p) <= 0 { lower.removeLast() }
            lower.append(p)
        }
        for p in sorted.reversed() {
            while upper.count >= 2 && turn(upper[upper.count - 2], upper[upper.count - 1], p) <= 0 { upper.removeLast() }
            upper.append(p)
        }
        return Array(lower.dropLast() + upper.dropLast())
    }
}
```
