# TorresDeSatelite

five wedges of painted concrete on a traffic island, seen from a passing car, after Goeritz and Barragán's Torres de Satélite (1957 to 1958).

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

```swift
//  Recreation after Mathias Goeritz - the Torres de Satélite (1957 to 1958).
//  Five prisms of painted concrete stand on a traffic island at the south
//  entrance of Ciudad Satélite, Naucalpan de Juárez, State of Mexico. The
//  work is his and the architect Luis Barragán's. The two disputed the
//  credit from 1968 and signed a document of shared authorship in 1987. The
//  painter Jesús Reyes Ferreira is credited with advice on the color. A
//  homage, not a reproduction, and not affiliated with or endorsed by the
//  artist's estate or the Barragan Foundation.
//  https://www.barragan-foundation.org/works/list/torres-de-satelite
//  https://www.museoreinasofia.es/en/collections/artwork/torres-de-ciudad-satelite-towers-satellite-city
//
//  An original Ollin interpretation, written from published descriptions and
//  from pictures of the work. The plan is read off the open map's outlines of
//  the five towers (openstreetmap.org). It is checked against the sizes of
//  the model the Museo Reina Sofía holds. Sources differ on the heights. The
//  tallest and the shortest here are 52 and 30 meters, as the Mexico City
//  government's visitor page gives them. The three between are read off
//  photographs. The Barragan Foundation gives the design as about 37 to 57
//  meters. Which tower took which orange in 1967 is this sketch's guess. The
//  plaza is drawn level, and the real one slopes a little.

import Foundation
import Ollin

/// The *Torres de Satélite* (Mathias Goeritz and Luis Barragán, 1957 to
/// 1958), seen from a car on the highway. They were made to be seen from
/// there.
///
/// Five hollow prisms of concrete stand on a long traffic island in the
/// middle of the road north out of Mexico City. Each one is a wedge in plan:
/// a narrow triangle with its short side to the north and its point to the
/// south. Everything the towers do comes from that. Driving up from the city
/// you meet five blades, edge on. Alongside the island the blades open into
/// flat walls of color. Looking back from the north they are five slender
/// towers. Nothing moves except the person looking.
///
/// The sketch stands the five wedges on the island and drives a circuit
/// round them. The car goes north along the east side, round, and south
/// along the west side, one lap every `seconds`. The eye stays on the
/// towers, as a passenger's would. The concrete was cast a band at a time,
/// the way factory chimneys were. So every wall is ruled with a line about
/// each meter, and `grooves` is how dark those lines read.
///
/// Try it: `paint` is the coat. **first** is early 1958, three white towers
/// with one orange and one yellow. **blue** is the coat that soon followed,
/// when one white tower was painted blue. It is the scheme that stands there
/// now. **orange** is 1967, oranges and yellow only, the coat the towers
/// wore through the 1968 Olympics. `hour` moves the sun through a day at
/// this latitude. `view` is where you are: **highway** in the car, **plaza**
/// on foot at the south end of the island, or **plan** above it. The plan is
/// drawn north up with each tower's shadow, and it exports as a drawing
/// (`--export-svg`).
@main
final class TorresDeSatelite: Sketch {
    enum View: String, CaseIterable, ParamOption { case highway, plaza, plan }
    enum Paint: String, CaseIterable, ParamOption { case first, blue, orange }

    /// Where you are: in the car, on foot on the plaza, or above the plan.
    @Param(icon: "eye") var view = View.highway
    /// The coat of paint: early 1958, the one with the blue tower, or 1967's
    /// oranges.
    @Param(icon: "paintpalette") var paint = Paint.blue
    /// One lap of the circuit, 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 = 9.5
    /// How dark the lines between the bands of concrete read.
    @Param(0 ... 1, icon: "line.3.horizontal") var grooves = 0.55

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

    // MARK: - The five towers

    /// One tower: a wedge in plan and a height. `east` and `north` place the
    /// middle of its short side, in meters from the middle of the island.
    struct Tower {
        var east: Double
        var north: Double
        /// The short side, which faces north.
        var width: Double
        /// From the short side to the point, which faces south.
        var depth: Double
        var height: Double
        /// The coat in each scheme: first, blue, orange.
        var coats: [Color]

        /// The three corners in plan as (east, north): the two ends of the
        /// short side, west then east, and the point.
        var corners: [Vector2] {
            [Vector2(east - width / 2, north), Vector2(east + width / 2, north), Vector2(east, north - depth)]
        }
    }

    private static let white = Color(hex: 0xEFEADC)
    private static let orange = Color(hex: 0xD2502A)
    private static let yellow = Color(hex: 0xE2A531)
    private static let blue = Color(hex: 0x2F5FA8)

    /// West to east, as a driver coming from the south reads them. They are
    /// the blue one, the tallest, the widest, the red one in front, and the
    /// smallest.
    static let towers: [Tower] = [
        Tower(east: -13.0, north: 23.9, width: 4.6, depth: 12.0, height: 35,
              coats: [white, blue, Color(hex: 0xE4702C)]),
        Tower(east: -6.8, north: 50.7, width: 6.2, depth: 11.8, height: 52,
              coats: [white, white, Color(hex: 0xD9562B)]),
        Tower(east: 0.0, north: 44.5, width: 6.7, depth: 24.0, height: 30,
              coats: [yellow, yellow, Color(hex: 0xE9A63A)]),
        Tower(east: 6.6, north: -15.7, width: 5.4, depth: 14.5, height: 43,
              coats: [orange, orange, Color(hex: 0xC8442A)]),
        Tower(east: 12.4, north: 13.8, width: 4.6, depth: 5.8, height: 37,
              coats: [white, white, Color(hex: 0xDD6230)]),
    ]

    // The island and the road, in meters.
    static let islandHalfWidth = 15.5
    static let islandHalfLength = 73.0
    static let curb = 0.18
    /// How far from the middle of the island the car keeps.
    static let lane = 22.0
    /// Half the straight of the circuit, north to south.
    static let run = 140.0
    static let roadHalfWidth = 40.0

    private var meshes: [Mesh] = []
    private var meshedFor = -1.0
    private let island = TorresDeSatelite.slab(TorresDeSatelite.islandOutline(), from: 0, to: TorresDeSatelite.curb)
    private let earth = Mesh.plane(width: 6000, depth: 6000)
    private let road = Mesh.plane(width: 2 * TorresDeSatelite.roadHalfWidth, depth: 6000)
    private let dash = Mesh.box(size: 1)

    // MARK: - The frame

    override func draw() {
        if view == .plan {
            drawPlan()
            return
        }
        if meshedFor != grooves {
            meshes = TorresDeSatelite.towers.enumerated().map { TorresDeSatelite.mesh(of: $1, index: $0, grooves: grooves) }
            meshedFor = grooves
        }

        let sun = sunDirection()
        let low = max(0, min(1, (0.5 - sun.y) / 0.5))
        let zenith = Color(hex: 0x2E6FB3).mixed(with: Color(hex: 0x3B62A0), low)
        let horizon = Color(hex: 0xC9DCE6).mixed(with: Color(hex: 0xEBD9BE), low)
        background(zenith)
        placeCamera()

        // Haze that thins with height: the sky pales toward the horizon and
        // the far road sinks into it.
        fog(horizon, density: 0.0008, heightFalloff: 0.012)
        // The sky lights every wall a little, and the sun lights the walls
        // that face it. The bright ground and far sky send some light back
        // onto the other walls, so a shaded wall keeps its color.
        ambientLight(Color(red: 0.40, green: 0.43, blue: 0.50))
        directionalLight(Color(red: 1.0, green: 0.95, blue: 0.86).mixed(with: Color(hex: 0xFFC48A), low * 0.6),
                         direction: sun * -1, intensity: 0.80)
        directionalLight(Color(red: 1.0, green: 0.96, blue: 0.90), direction: Vector3(sun.x, -0.25, sun.z).normalized,
                         intensity: 0.22, castsShadow: false)
        castShadows()
        shadowSoftness(0.15)
        temporalAntialiasing()

        noStroke()
        fill(Color(hex: 0xC9B48F))
        withState {
            translate(0, -0.08, 0)
            drawMesh(earth)
        }
        fill(Color(hex: 0x4A4A4D))
        withState {
            translate(0, -0.04, 0)
            drawMesh(road)
        }
        drawLaneLines()
        fill(Color(hex: 0xD8D4C8))
        drawMesh(island)

        let scheme = TorresDeSatelite.Paint.allCases.firstIndex(of: paint) ?? 1
        for (i, tower) in TorresDeSatelite.towers.enumerated() {
            fill(tower.coats[scheme])
            drawMesh(meshes[i])
        }
    }

    /// The sun for `hour` on a day of equal light and dark at 19.5 degrees
    /// north. It is the direction from the ground toward the sun (x east, y
    /// up, z south).
    private func sunDirection() -> Vector3 {
        let latitude = 19.5 * Double.pi / 180
        let angle = (hour - 12) * 15 * Double.pi / 180
        return Vector3(-sin(angle), cos(latitude) * cos(angle), sin(latitude) * cos(angle)).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)
    }

    private func placeCamera() {
        if view == .plaza {
            // A few steps round a small circle on the plaza, south of the
            // nearest tower, looking up at the group.
            let a = lap * 2 * Double.pi
            let eye = Vector3(-5 + 6 * cos(a), 1.6, 44 + 4 * sin(a))
            perspective(eye: eye, target: Vector3(0, 19, -16), fieldOfView: .degrees(66), near: 0.3, far: 5000)
            return
        }
        // The passenger keeps the towers in view. The eye turns toward the
        // middle of the group and looks up more as the car comes close. So
        // the road stays in the picture and the walls climb out of it.
        let at = TorresDeSatelite.carPosition(lap)
        let toward = TorresDeSatelite.middle - at
        let distance = max(toward.length, 1)
        let near = 1 - TorresDeSatelite.smooth((distance - 35) / 115)
        let pitch = (12 + 11 * near) * Double.pi / 180
        let eye = Vector3(at.x, 1.25, at.y)
        let look = Vector3(toward.x / distance * cos(pitch), sin(pitch), toward.y / distance * cos(pitch))
        perspective(eye: eye, target: eye + look * 50, fieldOfView: .degrees(58), near: 0.3, far: 5000)
    }

    /// The middle of the group as (x east, z south), where the eye turns.
    static let middle = Vector2(0, -16)

    /// A smooth step from 0 to 1 over 0...1.
    static func smooth(_ t: Double) -> Double {
        let x = max(0, min(1, t))
        return x * x * (3 - 2 * x)
    }

    /// The car on its circuit, as (x east, z south). It goes north up the
    /// east side, round the north end, south down the west side, and round
    /// again.
    static func carPosition(_ lap: Double) -> Vector2 {
        let straight = 2 * run
        let turn = Double.pi * lane
        let total = 2 * straight + 2 * turn
        var s = lap * total
        if s < straight { return Vector2(lane, run - s) }
        s -= straight
        if s < turn {
            let a = s / lane
            return Vector2(lane * cos(a), -run - lane * sin(a))
        }
        s -= turn
        if s < straight { return Vector2(-lane, -run + s) }
        s -= straight
        let a = s / lane
        return Vector2(-lane * cos(a), run + lane * sin(a))
    }

    // MARK: - Building

    /// One tower as a mesh: three walls ruled into bands a meter high, and a
    /// lid. The colors on the vertices are grays near white that multiply
    /// the coat. Each band is a touch lighter or darker than its neighbors,
    /// with a dark line where one pour met the next.
    static func mesh(of tower: Tower, index: Int, grooves: Double) -> Mesh {
        var positions: [Vector3] = []
        var normals: [Vector3] = []
        var colors: [Color] = []
        var indices: [UInt32] = []
        let plan = tower.corners.map { Vector2($0.x, -$0.y) }
        let middle = (plan[0] + plan[1] + plan[2]) / 3

        func quad(_ a: Vector2, _ b: Vector2, _ y0: Double, _ y1: Double, _ normal: Vector3, _ shade: Double) {
            let base = UInt32(positions.count)
            positions += [Vector3(a.x, y0, a.y), Vector3(b.x, y0, b.y), Vector3(b.x, y1, b.y), Vector3(a.x, y1, a.y)]
            normals += [normal, normal, normal, normal]
            colors += [Color](repeating: Color(white: shade), count: 4)
            indices += [base, base + 1, base + 2, base, base + 2, base + 3]
        }

        let line = 0.07
        for side in 0 ..< 3 {
            var a = plan[side], b = plan[(side + 1) % 3]
            let along = (b - a).normalized
            var out = Vector2(along.y, -along.x)
            if out.dot((a + b) / 2 - middle) < 0 { out = out * -1 }
            // Wound so the wall faces outward.
            if Vector3(along.x, 0, along.y).cross(Vector3(0, 1, 0)).dot(Vector3(out.x, 0, out.y)) < 0 { swap(&a, &b) }
            let normal = Vector3(out.x, 0, out.y)
            var y = 0.0
            var band = 0
            while y < tower.height - 1e-9 {
                let top = min(y + 1, tower.height)
                let tint = 1 - 0.07 * jitter(index * 7919 + side * 131 + band)
                quad(a, b, y, min(y + line, top), normal, tint * (1 - 0.6 * grooves))
                if top > y + line { quad(a, b, y + line, top, normal, tint) }
                y = top
                band += 1
            }
        }
        let base = UInt32(positions.count)
        positions += plan.map { Vector3($0.x, tower.height, $0.y) }
        normals += [Vector3(0, 1, 0), Vector3(0, 1, 0), Vector3(0, 1, 0)]
        colors += [Color](repeating: .white, count: 3)
        let up = (plan[1] - plan[0]).x * (plan[2] - plan[0]).y - (plan[1] - plan[0]).y * (plan[2] - plan[0]).x
        indices += up < 0 ? [base, base + 1, base + 2] : [base, base + 2, base + 1]
        return Mesh(positions: positions, normals: normals, indices: indices, colors: colors)
    }

    /// The island's outline as (x east, z south): a long strip with round
    /// ends.
    static func islandOutline() -> [Vector2] {
        let r = islandHalfWidth, straight = islandHalfLength - islandHalfWidth
        var points: [Vector2] = []
        for k in 0 ... 24 {
            let a = Double.pi * Double(k) / 24
            points.append(Vector2(r * cos(a), straight + r * sin(a)))
        }
        for k in 0 ... 24 {
            let a = Double.pi + Double.pi * Double(k) / 24
            points.append(Vector2(r * cos(a), -straight + r * sin(a)))
        }
        return points
    }

    /// A flat slab under a convex outline, from one height to another.
    static func slab(_ outline: [Vector2], from y0: Double, to y1: Double) -> Mesh {
        var positions: [Vector3] = []
        var normals: [Vector3] = []
        var indices: [UInt32] = []
        let count = outline.count
        for p in outline {
            positions.append(Vector3(p.x, y1, p.y))
            normals.append(Vector3(0, 1, 0))
        }
        for k in 1 ..< count - 1 { indices += [0, UInt32(k + 1), UInt32(k)] }
        for k in 0 ..< count {
            let a = outline[k], b = outline[(k + 1) % count]
            let along = (b - a).normalized
            let normal = Vector3(along.y, 0, -along.x)
            let base = UInt32(positions.count)
            positions += [Vector3(a.x, y0, a.y), Vector3(b.x, y0, b.y), Vector3(b.x, y1, b.y), Vector3(a.x, y1, a.y)]
            normals += [normal, normal, normal, normal]
            indices += [base, base + 2, base + 1, base, base + 3, base + 2]
        }
        return Mesh(positions: positions, normals: normals, indices: indices)
    }

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

    /// The painted lines of the road: dashes between the lanes and a solid
    /// line along each edge, on both sides of the island.
    private func drawLaneLines() {
        var marks: [MeshInstance] = []
        let y = -0.03
        for side in [-1.0, 1.0] {
            for lane in 0 ... 4 {
                let x = side * (TorresDeSatelite.islandHalfWidth + 2.5 + 3.5 * Double(lane))
                if lane == 0 || lane == 4 {
                    marks.append(MeshInstance(position: Vector3(x, y, 0), scale: Vector3(0.15, 0.02, 3000)))
                    continue
                }
                var z = -1494.0
                while z < 1500 {
                    marks.append(MeshInstance(position: Vector3(x, y, z), scale: Vector3(0.15, 0.02, 3)))
                    z += 12
                }
            }
        }
        fill(Color(hex: 0xE9E6DA))
        drawMesh(dash, instances: marks)
    }

    // MARK: - The plan

    /// The island from above, north up. It shows the five wedges in their
    /// coats, the shadow each throws at this hour, and the lanes. The car is
    /// drawn with the line its passenger looks along.
    private func drawPlan() {
        background(Color(hex: 0x4A4A4D))
        let unit = height * 0.9 / (2 * TorresDeSatelite.islandHalfLength)
        func place(_ p: Vector2) -> Vector2 { center + p * unit }

        // A tower's shadow on level ground spans two outlines: its own, and
        // the same one carried away from the sun. The distance is the
        // tower's height over the tangent of the sun's height. The shadows
        // are laid in one flat color on the road, and again in another
        // inside the island's outline. So two shadows that cross are no
        // darker than one.
        let sun = sunDirection()
        let reach = Vector2(-sun.x, -sun.z) / max(sun.y, 0.05)
        let shadows = TorresDeSatelite.towers.map { tower -> [Vector2] in
            let foot = tower.corners.map { Vector2($0.x, -$0.y) }
            return TorresDeSatelite.hull(foot + foot.map { $0 + reach * tower.height }).map(place)
        }
        noStroke()
        fill(Color(hex: 0x2E2E33))
        for shadow in shadows { drawPolygon(shadow) }

        noFill()
        stroke(Color(hex: 0xE9E6DA, alpha: 0.55))
        strokeWeight(1)
        for side in [-1.0, 1.0] {
            for lane in 0 ... 4 {
                let x = side * (TorresDeSatelite.islandHalfWidth + 2.5 + 3.5 * Double(lane))
                drawLine(place(Vector2(x, -90)), place(Vector2(x, 90)))
            }
        }

        noStroke()
        let plaza = TorresDeSatelite.islandOutline().map(place)
        fill(Color(hex: 0xD8D4C8))
        drawPolygon(plaza)
        withClip(Shape(plaza, closed: true)) {
            fill(Color(hex: 0x9E9B93))
            for shadow in shadows { drawPolygon(shadow) }
        }

        let scheme = TorresDeSatelite.Paint.allCases.firstIndex(of: paint) ?? 1
        stroke(Color(hex: 0x2A2A2C))
        strokeWeight(1)
        for tower in TorresDeSatelite.towers {
            fill(tower.coats[scheme])
            drawPolygon(tower.corners.map { place(Vector2($0.x, -$0.y)) })
        }

        let car = TorresDeSatelite.carPosition(lap)
        let ahead = (TorresDeSatelite.carPosition(lap + 0.002) - car).normalized
        let across = Vector2(-ahead.y, ahead.x)
        stroke(Color(hex: 0xE9E6DA, alpha: 0.5))
        strokeWeight(0.8)
        drawLine(place(car), place(TorresDeSatelite.middle))
        noStroke()
        fill(Color(hex: 0xE9E6DA))
        drawPolygon([car + ahead * 2.3 + across, car + ahead * 2.3 - across,
                     car - ahead * 2.3 - across, car - ahead * 2.3 + across].map(place))
    }

    /// 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())
    }
}
```
