Ollin

Tteia

Thirteen columns of gold thread in a dark room, seen by someone walking round them, after Lygia Pape's Ttéia 1, C (2002).

Run
swift run --package-path Examples Example-Recreations-LygiaPape-Tteia
Source
Examples/Recreations/LygiaPape/Tteia/Sketch.swift
//  Recreation after Lygia Pape - Ttéia 1, C: gold thread, nails, wood, and
//  light. Thirteen square columns of thread stand between a low platform and
//  the ceiling of a black room. Inhotim, in Brumadinho, dates it 2002 and has
//  shown it since 2012 in a gallery built for it. It was at the 53rd Venice
//  Biennale in 2009. A homage, not a reproduction, and not affiliated with
//  or endorsed by the artist's estate or the museums.
//  https://www.inhotim.org.br/en/item-do-acervo/galeria-lygia-pape/
//  https://www.metmuseum.org/art/collection/search/693920
//  https://21-22.anozero-bienaldecoimbra.pt/en/artists/lygia-pape
//
//  An original Ollin interpretation, written from published descriptions and
//  from pictures of the work. On record are thirteen columns, 1,848 brass
//  nails, 5,542 meters of thread, about fourteen lamps, and one printed size:
//  550 by 900 by 800 centimeters, from the Metropolitan Museum's showing. No
//  measured plan is published. So where each column stands, how wide it is,
//  and which way it leans are this sketch's own, dealt from the seed and then
//  held to those totals. The 2.5 centimeters between nails is read off
//  photographs. Nothing was ported: the work is thread and nails.
//
//  The light on a thread follows the model James Kajiya and Timothy Kay
//  published for thin fibers, with the shine read from the halfway direction:
//  "Rendering fur with three dimensional textures", SIGGRAPH 1989.
//  https://doi.org/10.1145/74334.74361

import Foundation
import Ollin

/// *Ttéia 1, C* (Lygia Pape, 2002): columns of gold thread in a dark room,
/// seen by someone walking round them. **Press** to deal another plan and
/// watch it strung.
///
/// A column is a square of nails on the platform and an equal square on the
/// ceiling, with one row of nails round each and nothing inside. A thread
/// runs from each nail to the one above it, so the column is a hollow square
/// tube, and all its threads are parallel. By a curator's account, one
/// thread makes the whole column. Here it starts at a corner and goes down,
/// along to the next nail, up, and along again, all the way round.
///
/// Here thirteen columns stand on a platform nine meters by eight under a
/// ceiling five and a half meters up. The nails are 2.5 centimeters apart
/// and the squares are between 20 and 65 centimeters across. Five columns
/// stand plumb and eight lean, each its own way. The leaning ones meet in
/// twos and threes and pass through one another, the threads of one going
/// between the threads of the other. Once the plan is dealt, the leans are
/// scaled until the thread comes to 5,542 meters. With 1,848 nails that
/// makes each run six meters long on average.
///
/// Fourteen small lamps hang at the ceiling, each aimed at one column. A
/// thread is a thin shiny cylinder. It mirrors a lamp into a cone of
/// directions about its own length, so the eye sees it shine only where the
/// halfway direction between lamp and eye stands square to the thread. All
/// the threads of a column are parallel, so a whole face lights up together
/// and goes out together as the eye moves. That is worked out here for every
/// point of every thread, from where the lamp, the thread, and the eye are.
///
/// Nothing in the room moves but the viewer. One lap of the loop is one walk
/// round the platform, `distance` meters from its middle with the eye `eye`
/// meters up. `strung` is how much of the thread is up, column by column.
/// `glow` is how bright the lamps are, and `spill` is the faint light that
/// reaches the rest of each thread. `thread` is its thickness in
/// millimeters, drawn much thicker than the real one so it can be seen.
///
/// Try it: `--export-svg` gives every thread as one straight line, with the
/// platform's outline, as the eye sees them at that moment.
@main
final class Tteia: Sketch {
    /// How much of the thread has been strung, column by column.
    @Param(0 ... 1, icon: "arrow.up.and.down") var strung = 1.0
    /// How far the viewer walks from the middle of the platform, in meters.
    @Param(8 ... 15, icon: "figure.walk") var distance = 10.8
    /// How high the viewer's eye is, in meters.
    @Param(0.6 ... 2.4, icon: "eye") var eye = 1.6
    /// How bright the lamps are.
    @Param(0.2 ... 2.5, icon: "light.max") var glow = 1.0
    /// The faint light that reaches the whole length of every thread.
    @Param(0 ... 0.3, icon: "moon") var spill = 0.035
    /// The thickness of the thread as drawn, in millimeters.
    @Param(1 ... 10, icon: "lineweight") var thread = 4.0
    /// Seconds for one walk round the platform.
    @Param(12 ... 30, icon: "timer") var seconds = 30.0

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

    /// The room, in meters, and the counts on record. The size is the one
    /// a museum has printed.
    enum Room {
        static let ceiling = 5.5
        static let platform = Vector2(9, 8)
        /// The distance from one nail to the next.
        static let gap = 0.025
        static let columns = 13
        /// Nail gaps along one side of a square, summed over the thirteen.
        /// Four sides and two ends of each thread make the 1,848 nails.
        static let gapsInAll = 231
        /// Meters of thread in the whole work.
        static let thread = 5542.0
    }

    /// One column: where its square stands on the platform, where the equal
    /// square sits on the ceiling, and how many nail gaps make a side.
    struct Column {
        var foot: Vector2
        var head: Vector2
        var gaps: Int

        var side: Double { Double(gaps) * Room.gap }
        var threads: Int { gaps * 4 }
        /// One run of thread, from a nail to the nail above it.
        var run: Double { (Room.ceiling * Room.ceiling + (head - foot).lengthSquared).squareRoot() }

        /// Where nail `index` stands on its square, from the square's middle.
        /// The nails go round from one corner, and each corner is counted once.
        func nail(_ index: Int) -> Vector2 {
            let half = side / 2
            let along = Double(index % gaps) * Room.gap
            switch index / gaps {
            case 0: return Vector2(-half + along, -half)
            case 1: return Vector2(half, -half + along)
            case 2: return Vector2(half - along, half)
            default: return Vector2(-half, half - along)
            }
        }

        func floorPoint(_ index: Int) -> Vector3 {
            let at = foot + nail(index)
            return Vector3(at.x, 0, at.y)
        }

        func ceilingPoint(_ index: Int) -> Vector3 {
            let at = head + nail(index)
            return Vector3(at.x, Room.ceiling, at.y)
        }
    }

    /// A lamp at the ceiling: where it hangs, the point of a column it is
    /// aimed at, and half the angle of its cone.
    struct Lamp {
        var at: Vector3
        var aim: Vector3
        var cone: Double
        var column: Int
    }

    private var columns: [Column] = []
    private var lamps: [Lamp] = []
    private var built = ""
    private var dealt = 0
    /// When the last plan was dealt by a press, so it can be seen strung.
    private var pressedAt: Double?

    private let gold = Color(hex: 0xE6AE45)
    private let bright = Color(hex: 0xFFEFC4)
    private let lampLight = Color(hex: 0xFFE2B0)

    override func mousePressed() {
        dealt += 1
        pressedAt = time
    }

    // MARK: - The frame

    override func draw() {
        let key = "\(variation)/\(dealt)"
        if key != built {
            (columns, lamps) = Tteia.deal(seed: variation &+ dealt &* 7919)
            built = key
        }

        let turn = loopProgress(over: seconds) * .tau
        let from = Vector3(sin(turn) * distance, eye, cos(turn) * distance)
        perspective(eye: from, target: Vector3(0, 3.05, 0), fieldOfView: .degrees(54))

        // After a press the thread goes up over twelve seconds.
        var up = strung
        if let pressedAt, !isExporting { up *= min(1, (time - pressedAt) / 12) }

        if isVectorExporting {
            drawThePlan(up: up)
            return
        }

        background(Color(hex: 0x020202))
        toneMap(.neutral)
        drawThePlatform()
        drawTheNails(up: up)
        drawTheThreads(from: from, up: up)
        drawTheLamps(from: from)
    }

    // MARK: - Dealing a plan

    /// Deals thirteen columns and their lamps. Everything comes from the
    /// seed, so a seed is a plan.
    static func deal(seed: Int) -> ([Column], [Lamp]) {
        var rng = SplitMix64(seed: UInt64(bitPattern: Int64(seed &* 1_000_003 &+ 2002)))
        func roll() -> Double { Double(rng.next() >> 11) / Double(1 << 53) }
        func roll(_ low: Double, _ high: Double) -> Double { low + (high - low) * roll() }

        // The widths: between 8 and 26 gaps a side, 231 in all.
        var gaps = (0 ..< Room.columns).map { _ in 8 + Int(roll() * 19) }
        var sum = gaps.reduce(0, +)
        while sum != Room.gapsInAll {
            let i = Int(roll() * Double(Room.columns))
            if sum < Room.gapsInAll, gaps[i] < 26 {
                gaps[i] += 1
                sum += 1
            } else if sum > Room.gapsInAll, gaps[i] > 8 {
                gaps[i] -= 1
                sum -= 1
            }
        }

        // Eight columns lean and meet in a three, two twos, and one alone.
        // Five stand plumb.
        let meetings = [3, 2, 2, 1]
        let leaners = meetings.reduce(0, +)
        var best: [Column] = []
        for _ in 0 ..< 900 {
            // How steeply each leaner leans, then one scale on all of them
            // so that the thread comes to the length on record.
            let slopes = (0 ..< leaners).map { _ in tan(.degrees(roll(24, 38))) }
            func thread(_ scale: Double) -> Double {
                var total = 0.0
                for i in 0 ..< Room.columns {
                    let slope = i < leaners ? slopes[i] * scale : 0
                    total += Double(gaps[i] * 4) * Room.ceiling * (1 + slope * slope).squareRoot()
                }
                return total
            }
            var low = 0.3, high = 3.0
            guard thread(low) < Room.thread, thread(high) > Room.thread else { continue }
            for _ in 0 ..< 60 {
                let middle = (low + high) / 2
                if thread(middle) < Room.thread { low = middle } else { high = middle }
            }
            let scale = (low + high) / 2
            let steepest = slopes.max()! * scale, gentlest = slopes.min()! * scale
            guard steepest < tan(.degrees(42)), gentlest > tan(.degrees(18)) else { continue }

            var dealt: [Column] = []
            var places: [Vector2] = []
            var fits = true
            var index = 0
            for count in meetings where fits {
                // Where this group meets, and how high up.
                var meeting = Vector2.zero
                var found = false
                for _ in 0 ..< 60 where !found {
                    meeting = Vector2(roll(-2.7, 2.7), roll(-2.3, 2.3))
                    found = places.allSatisfy { ($0 - meeting).length > 2.3 }
                }
                guard found else {
                    fits = false
                    break
                }
                places.append(meeting)
                let height = roll(0.38, 0.62) * Room.ceiling
                let first = roll(0, .tau)
                let apart = count == 2 ? roll(1.3, 3.1) : .tau / Double(count)
                for j in 0 ..< count {
                    let side = Double(gaps[index]) * Room.gap
                    let way = first + Double(j) * apart + (count == 2 ? 0 : roll(-0.45, 0.45))
                    let toward = Vector2(cos(way), sin(way))
                    // Each passes a little off the meeting point, so they
                    // thread through one another and are not stacked on it.
                    let through = meeting + Vector2(roll(-0.3, 0.3), roll(-0.3, 0.3)) * side
                    let slope = slopes[index] * scale
                    let column = Column(foot: through - toward * (slope * height),
                                        head: through + toward * (slope * (Room.ceiling - height)),
                                        gaps: gaps[index])
                    guard stands(column, among: dealt) else {
                        fits = false
                        break
                    }
                    dealt.append(column)
                    index += 1
                }
            }
            guard fits else { continue }

            // The plumb ones, wherever there is room.
            for i in leaners ..< Room.columns where fits {
                var placed = false
                for _ in 0 ..< 200 where !placed {
                    let at = Vector2(roll(-1, 1) * Room.platform.x / 2, roll(-1, 1) * Room.platform.y / 2)
                    let column = Column(foot: at, head: at, gaps: gaps[i])
                    if stands(column, among: dealt) {
                        dealt.append(column)
                        placed = true
                    }
                }
                fits = placed
            }
            guard fits else { continue }
            best = dealt
            break
        }

        return (best, hang(over: best, roll: roll))
    }

    /// Whether a column fits: both squares on the platform's footprint, and
    /// clear of the squares already there.
    private static func stands(_ column: Column, among others: [Column]) -> Bool {
        let half = column.side / 2 + 0.2
        for at in [column.foot, column.head] {
            if abs(at.x) + half > Room.platform.x / 2 || abs(at.y) + half > Room.platform.y / 2 { return false }
        }
        for other in others {
            let reach = (column.side + other.side) / 2
            let feet = column.foot - other.foot, heads = column.head - other.head
            if max(abs(feet.x), abs(feet.y)) < reach + 0.25 { return false }
            if max(abs(heads.x), abs(heads.y)) < reach + 0.15 { return false }
        }
        return true
    }

    /// Hangs the lamps: one for each column, aimed at its upper half from
    /// a little way off, and one more on the widest column.
    private static func hang(over columns: [Column], roll: (Double, Double) -> Double) -> [Lamp] {
        var lamps: [Lamp] = []
        func lamp(on index: Int, at share: Double) {
            let column = columns[index]
            let on = column.foot + (column.head - column.foot) * share
            let aim = Vector3(on.x, share * Room.ceiling, on.y)
            // The lamp hangs outward of the point it lights, so its beam
            // comes in at a slant.
            let outward = on.length > 0.3 ? atan2(on.y, on.x) : roll(0, .tau)
            let way = outward + roll(-1.3, 1.3)
            let off = roll(1.5, 2.9)
            let at = Vector3(on.x + cos(way) * off, Room.ceiling - 0.05, on.y + sin(way) * off)
            lamps.append(Lamp(at: at, aim: aim, cone: roll(0.105, 0.15), column: index))
        }
        for index in columns.indices { lamp(on: index, at: roll(0.5, 0.78)) }
        if let widest = columns.indices.max(by: { columns[$0].gaps < columns[$1].gaps }) {
            lamp(on: widest, at: roll(0.26, 0.4))
        }
        return lamps
    }

    // MARK: - Light on a thread

    /// How much of a lamp's light a point gets: all of it inside the cone,
    /// none outside, soft at the rim, and weaker with distance.
    private func reach(of lamp: Lamp, at point: Vector3) -> (amount: Double, toLamp: Vector3) {
        let offset = lamp.at - point
        let far = offset.length
        let toLamp = offset / far
        let axis = (lamp.aim - lamp.at).normalized
        let off = acos(clamp(-toLamp.dot(axis), -1, 1))
        let inside = 1 - smoothstep(lamp.cone * 0.55, lamp.cone, off)
        return (inside * 9 / (far * far), toLamp)
    }

    /// The light a point of a thread sends to the eye. `along` is the
    /// thread's own direction.
    private func shine(at point: Vector3, along: Vector3, from: Vector3, lamps lit: [Lamp]) -> Double {
        let toEye = (from - point).normalized
        var sum = 0.0
        for lamp in lit {
            let (amount, toLamp) = reach(of: lamp, at: point)
            guard amount > 0 else { continue }
            // The matte part: brightest when the light crosses the thread.
            let slant = along.dot(toLamp)
            let matte = max(0, 1 - slant * slant).squareRoot()
            // The mirror part: only where the halfway direction between the
            // lamp and the eye stands square to the thread.
            let halfway = (toLamp + toEye).normalized
            let square = along.dot(halfway)
            let mirror = pow(max(0, 1 - square * square), 45)
            sum += amount * (0.3 * matte + 2.2 * mirror)
        }
        return sum * glow
    }

    // MARK: - Drawing

    /// How many whole threads are up, and how far along the next one is.
    private func threadsUp(_ up: Double) -> (whole: Int, part: Double) {
        let lengths = columns.flatMap { column in Array(repeating: column.run, count: column.threads) }
        if up >= 1 { return (lengths.count, 0) }
        var left = up * lengths.reduce(0, +)
        var whole = 0
        for length in lengths {
            if left >= length {
                left -= length
                whole += 1
            } else {
                return (whole, left / length)
            }
        }
        return (whole, 0)
    }

    private func drawTheThreads(from: Vector3, up: Double) {
        let (whole, part) = threadsUp(up)
        struct Run { var points: [Vector3]; var colors: [Color]; var far: Double }
        var runs: [Run] = []
        var count = 0

        for (index, column) in columns.enumerated() {
            let lit = lamps.filter { $0.column == index }
            let low = Vector3(column.foot.x, 0, column.foot.y)
            let high = Vector3(column.head.x, Room.ceiling, column.head.y)
            let along = (high - low).normalized
            // Where along the column its lamps land. Points are set close
            // together there and nowhere else, since elsewhere the thread
            // only carries the spill.
            var stations: [Double] = [0, 1]
            for lamp in lit {
                let middle = clamp((lamp.aim - low).dot(along) / column.run, 0, 1)
                let half = 0.95 / column.run
                var at = max(0, middle - half)
                while at <= min(1, middle + half) {
                    stations.append(at)
                    at += 0.22 / column.run
                }
            }
            stations.sort()

            for nail in 0 ..< column.threads {
                defer { count += 1 }
                if count > whole || (count == whole && part <= 0) { break }
                // The thread goes down one run and up the next.
                let down = nail % 2 == 0
                let start = down ? column.ceilingPoint(nail) : column.floorPoint(nail)
                let end = down ? column.floorPoint(nail) : column.ceilingPoint(nail)
                let limit = count == whole ? part : 1
                // Stations are measured from the floor, and the thread from
                // where it starts.
                var shares = stations.map { down ? 1 - $0 : $0 }.filter { $0 <= limit }
                if limit < 1 { shares.append(limit) }
                shares.sort()
                var points: [Vector3] = [], colors: [Color] = []
                for share in shares {
                    let point = start + (end - start) * share
                    points.append(point)
                    colors.append(tint(spill + shine(at: point, along: along, from: from, lamps: lit)))
                }
                guard points.count > 1 else { continue }
                runs.append(Run(points: points, colors: colors,
                                far: ((start + end) / 2 - from).lengthSquared))
            }
        }

        // Light adds up where threads cross. The farthest go down first, so
        // that no thread hides another.
        blendMode(.add)
        strokeCap(.butt)
        strokeWeight(thread / 1000, in: .world)
        for run in runs.sorted(by: { $0.far > $1.far }) {
            drawPolyline(run.points, colors: run.colors)
        }
        blendMode(.normal)
    }

    /// Gold for ordinary light, turning pale where the shine is strongest.
    private func tint(_ light: Double) -> Color {
        if light <= 1 { return gold.withAlpha(light) }
        return gold.mixed(with: bright, min(1, (light - 1) / 2.5))
    }

    /// The nails on the platform: a short gold tick each, lit by whatever
    /// lamp reaches it.
    private func drawTheNails(up: Double) {
        let (whole, part) = threadsUp(up)
        blendMode(.add)
        strokeCap(.butt)
        strokeWeight(1.3)
        var count = 0
        for (index, column) in columns.enumerated() {
            let lit = lamps.filter { $0.column == index }
            for nail in 0 ..< column.threads {
                defer { count += 1 }
                if count > whole || (count == whole && part <= 0) { break }
                let at = column.floorPoint(nail)
                let light = spill * 2 + lit.reduce(0) { $0 + reach(of: $1, at: at).amount } * 0.5 * glow
                stroke(gold.withAlpha(min(1, light)))
                drawLine(at, at + Vector3(0, 0.012, 0))
            }
        }
        blendMode(.normal)
    }

    /// The platform, a low dark slab lit by the same lamps.
    private func drawThePlatform() {
        ambientLight(Color(white: 0.03))
        for lamp in lamps {
            spotLight(lampLight, at: lamp.at, direction: (lamp.aim - lamp.at).normalized,
                      coneAngle: lamp.cone * 2, penumbra: 0.6, intensity: 8 * glow, reach: 14)
        }
        noStroke()
        fill(Color(hex: 0x2A2724))
        material(.matte)
        withState {
            translate(0, -0.03, 0)
            drawBox(width: Room.platform.x, height: 0.06, depth: Room.platform.y)
        }
    }

    /// The lamps themselves, as the small points of light they are from
    /// the floor.
    private func drawTheLamps(from: Vector3) {
        noStroke()
        blendMode(.add)
        for lamp in lamps {
            guard let at = project(lamp.at) else { continue }
            // A lamp looks brightest to an eye inside its beam.
            let toEye = (from - lamp.at).normalized
            let facing = max(0, toEye.dot((lamp.aim - lamp.at).normalized))
            let level = (0.35 + 0.65 * pow(facing, 6)) * min(1, glow)
            fill(lampLight.withAlpha(0.14 * level))
            drawCircle(center: at, radius: 4.5)
            fill(bright.withAlpha(level))
            drawCircle(center: at, radius: 1.5)
        }
        blendMode(.normal)
    }

    /// Every thread as one straight line, and the platform's outline, as
    /// the eye sees them.
    private func drawThePlan(up: Double) {
        background(.white)
        noFill()
        stroke(.black)
        strokeWeight(0.6)
        let half = Room.platform / 2
        drawPolyline([Vector3(-half.x, 0, -half.y), Vector3(half.x, 0, -half.y),
                      Vector3(half.x, 0, half.y), Vector3(-half.x, 0, half.y)], closed: true)
        let (whole, _) = threadsUp(up)
        var count = 0
        for column in columns {
            for nail in 0 ..< column.threads where count < whole {
                drawLine(column.floorPoint(nail), column.ceilingPoint(nail))
                count += 1
            }
        }
    }
}

↑↓ move ↩ open