Ollin

CajaGenerativa

A box of violet acrylic and bent aluminum, after Vidal's Caja generativa en violeta (given to the museum in 1970).

Run
swift run --package-path Examples Example-Recreations-MacEntyreVidal-CajaGenerativa
Source
Examples/Recreations/MacEntyreVidal/CajaGenerativa/Sketch.swift
//  Recreation after Miguel Ángel Vidal - the boxes of acrylic and bent
//  aluminum, read from Caja generativa en violeta (undated, acrylic and
//  aluminum, 47 x 51 x 10.6 cm) in the Museo Nacional de Bellas Artes, Buenos
//  Aires, which records it as given by the artist in 1970, and from the
//  published accounts of his Cajas topológicas reversibles (1973, acrylic
//  and aluminum). A homage, not a reproduction, and not affiliated with or
//  endorsed by the artist or his estate.
//  https://www.bellasartes.gob.ar/coleccion/obra/7787/
//  https://elojodelarte.com/biografias/coleccion-mnba-desplazamiento-luminoso-de-miguel-angel-vidal
//  http://miguelangelvidal.com.ar/obras.html
//
//  An original Ollin interpretation, written from the museum's picture of
//  the box and from published accounts of how the boxes are built: plates of
//  aluminum set concave and convex inside boxes of acrylic, which change
//  with where the viewer stands and how the light falls. The box's size is
//  the museum's. The number of plates, their uneven widths, and the colors
//  are read off its picture. How deep each plate is bent is not published
//  and is dealt here. The room the box mirrors is this sketch's own, since a
//  mirror shows whatever room it hangs in. Nothing was ported: the work is
//  sheet metal and acrylic, cut and bent by hand.

import Foundation
import Ollin

/// Caja generativa (Miguel Ángel Vidal, Buenos Aires, by 1970). Vidal took
/// his line off the canvas. He built boxes of colored acrylic and stood
/// plates of polished aluminum inside them, each plate bent a little, one
/// hollow and the next bulging. Nothing in the box is painted. Each band of
/// color is the room, thrown back by a bent mirror and seen through the
/// acrylic: a lit wall, a window, a lamp, the dark shape of whoever is
/// looking. A plate that bulges gathers a wide sweep of the room into narrow
/// bands. A flat one shows one wall and nothing else. Take a step and every
/// band slides, at its own speed and in its own direction.
///
/// This sketch deals a box and a room from the seed. The box holds `plates`
/// plates of uneven widths, each one flat, hollow, or bulging. The room has
/// a warm wall, a window or two of sky, a few dark doorways, and a few lamps.
/// The picture is the front of the box, seen by an eye 160 centimeters away.
/// For every point of a plate the sketch follows the ray from the eye and
/// turns it about the plate's own slope, so that it leaves at the angle it
/// arrived. Then it paints what the room holds in that direction. Over one
/// cycle of `seconds` the eye walks `walk` centimeters to one side, back
/// past the middle to the other, and home. The plates stand a few
/// centimeters behind the front, so their edges shift against the box as
/// the eye moves.
///
/// Try it: drag across the canvas to stand where the pointer is, and click
/// to deal the next box and room. `bend` at its lowest leaves near-flat
/// mirrors with wide calm bands. `look` picks the acrylic: violet, blue, or
/// orange. `--export-svg` gives the box in plan, seen from above: the
/// plates, the eye, and nine rays to each plate with the way each leaves.
@main
final class CajaGenerativa: Sketch {
    /// The box and where the eye stands, in centimeters. The width, the
    /// height, and the depth are the museum's.
    enum Box {
        static let width = 47.0
        static let height = 51.0
        static let depth = 10.6
        /// The thickness of the acrylic walls.
        static let wall = 0.8
        /// How far the eye stands from the front of the box.
        static let eyeDistance = 160.0
        /// How far above the middle of the box the eye is.
        static let eyeHeight = 6.0
        /// How deep in the box the plates stand when they are flat.
        static let plateDepth = 5.4
    }

    /// The color of the acrylic, after three of the boxes.
    enum Look: String, CaseIterable, ParamOption {
        /// The box in the Museo Nacional de Bellas Artes.
        case violeta
        /// The blue of one of the Cajas topológicas reversibles (1973).
        case azul
        /// The orange of his Torre generativa (1967).
        case naranja
    }

    /// The color of the acrylic.
    @Param(icon: "paintpalette") var look = Look.violeta
    /// How many plates of aluminum stand in the box.
    @Param(3 ... 8, icon: "rectangle.split.3x1") var plates = 6
    /// How deeply the plates are bent, from nearly flat to as deep as the box allows.
    @Param(0.1 ... 1, icon: "wave.3.right") var bend = 0.4
    /// How far the eye walks to either side of the box, in centimeters.
    @Param(0 ... 140, icon: "figure.walk") var walk = 70.0
    /// Seconds for the eye to walk to both sides and come home.
    @Param(6 ... 30, icon: "clock") var seconds = 16.0

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

    /// One plate of aluminum, standing upright in the box.
    struct Plate {
        /// Its left and right edges, in centimeters from the box's middle.
        var left: Double
        var right: Double
        /// How far its middle bulges toward the viewer. Negative is hollow.
        var sag: Double
        /// A hand-bent plate is not the same top and bottom: the share by
        /// which the bend grows from top to bottom.
        var taper: Double
        /// And it is turned a little: radians of turn from top to bottom.
        var twist: Double

        var width: Double { right - left }

        /// The bulge at height `v`, 0 at the top of the plate and 1 at the bottom.
        func sag(at v: Double) -> Double { sag * (1 + taper * (v - 0.5)) }

        /// How deep in the box the plate is at `u`, -1 at its left edge and
        /// 1 at its right, and how steeply it runs there.
        func section(_ u: Double, _ v: Double) -> (depth: Double, slope: Double) {
            let turn = tan(twist * (v - 0.5))
            let s = sag(at: v)
            return (Box.plateDepth - s * (1 - u * u) + turn * u * width / 2,
                    4 * s * u / width + turn)
        }
    }

    /// Something in the room that takes the place of the wall behind it.
    struct Patch {
        /// Where it is, in radians to the right of straight out from the box.
        var center: Double
        var half: Double
        var soft: Double
        var light: SIMD3<Double>
    }

    /// A lamp: a narrow source much brighter than the wall.
    struct Lamp {
        var center: Double
        var width: Double
        var light: SIMD3<Double>
    }

    private struct Dealt: Equatable { var plates: Int; var bend: Double; var seed: Int }
    private var dealtFor: Dealt?
    private var standing: [Plate] = []
    private var patches: [Patch] = []
    private var lamps: [Lamp] = []
    private var wash = 0.0

    // The pointer: a drag moves the eye, a click deals the next box.
    private var pressedAt = Vector2(0, 0)
    private var dealNext = false
    private var releasedAt = -100.0
    private var releasedEye = 0.0

    /// Where the eye is, in centimeters right of the box's middle.
    private var eye = 0.0

    private static let warm = SIMD3(1.0, 0.85, 0.70)
    private static let sky = SIMD3(0.12, 0.60, 1.0)

    /// Canvas pixels to a centimeter, and the middle of the box's front.
    private var perCentimeter: Double { 0.74 * height / Box.height }
    private var boxMiddle: Vector2 { Vector2(width / 2, height / 2 - 6) }

    override func mousePressed() {
        pressedAt = mouse
    }

    override func mouseReleased() {
        // A press that did not travel is a click.
        if (mouse - pressedAt).length < 6 { dealNext = true }
        releasedAt = time
        releasedEye = eye
    }

    override func draw() {
        if dealNext {
            dealNext = false
            seed(variation + 1)
        }
        let wanted = Dealt(plates: plates, bend: bend, seed: variation)
        if dealtFor != wanted {
            dealtFor = wanted
            deal()
        }

        // The eye walks to one side, back past the middle to the other, and
        // home, so the cycle closes. A drag puts it under the pointer, and
        // for a moment after the drag it eases back to its walk.
        let walking = walk * sin(2 * .pi * loopProgress(over: max(1, seconds)))
        if mouseIsPressed, (mouse - pressedAt).length >= 6 {
            eye = (mouse.x / width * 2 - 1) * max(walk, 60)
        } else {
            let back = min(1, max(0, (time - releasedAt) / 0.8))
            eye = releasedEye + (walking - releasedEye) * back * back * (3 - 2 * back)
        }

        if isVectorExporting {
            drawThePlan()
            return
        }

        background(Color(hex: 0xECECEE))
        noStroke()
        let w = Box.width / 2, h = Box.height / 2, d = Box.depth

        // The box's shadow on the wall: light from above and in front.
        for i in 0 ..< 14 {
            let grow = Double(i) * 2.2
            fill(Color(hex: 0x3A3040, alpha: 0.022))
            let a = screen(-w, -h, 0), b = screen(w, h, 0)
            drawRect(a.x - grow + 4, a.y - grow * 0.4 + 10, b.x - a.x + 2 * grow, b.y - a.y + grow * 1.4,
                     cornerRadius: 6 + grow)
        }

        // A side of the box shows outside its front when the eye is past
        // that side, lit from the room.
        for side in [-1.0, 1.0] where eye * side > w {
            fill(tone(Self.warm * 0.55).mixed(with: .white, 0.3))
            drawPolygon([screen(side * w, -h, 0), screen(side * w, -h, d), screen(side * w, h, d), screen(side * w, h, 0)])
        }

        // The front of the box is the picture. Everything inside it is seen
        // through it, so everything inside is cut to it.
        let front = Rectangle(corner: screen(-w, -h, 0), width: Box.width * perCentimeter, height: Box.height * perCentimeter)
        withClip(front) {
            // The back of the box, then its inner walls, ceiling, and floor.
            fill(tone(Self.warm * 0.03))
            drawRect(front)
            let inner = d - Box.wall
            fill(tone(Self.warm * 0.10))
            for side in [-1.0, 1.0] {
                drawPolygon([screen(side * w, -h, 0), screen(side * w, -h, inner), screen(side * w, h, inner), screen(side * w, h, 0)])
            }
            fill(tone(Self.warm * 0.05))
            drawPolygon([screen(-w, -h, 0), screen(w, -h, 0), screen(w, -h, inner), screen(-w, -h, inner)])
            fill(tone(Self.warm * 0.20))
            drawPolygon([screen(-w, h, 0), screen(w, h, 0), screen(w, h, inner), screen(-w, h, inner)])

            // The plates. Each is cut into small cells, and a cell is painted
            // with what its middle reflects.
            let top = -h + 1.3, bottom = h - 1.3
            for plate in standing {
                let columns = Self.columns(of: plate, scale: perCentimeter)
                for row in 0 ..< Self.rows {
                    let v0 = Double(row) / Double(Self.rows), v1 = Double(row + 1) / Double(Self.rows)
                    for column in 0 ..< columns {
                        let u0 = -1 + 2 * Double(column) / Double(columns)
                        let u1 = -1 + 2 * Double(column + 1) / Double(columns)
                        fill(tone(reflection(off: plate, (u0 + u1) / 2, (v0 + v1) / 2).light))
                        drawPolygon([
                            corner(of: plate, u0, v0, top, bottom), corner(of: plate, u1, v0, top, bottom),
                            corner(of: plate, u1, v1, top, bottom), corner(of: plate, u0, v1, top, bottom),
                        ])
                    }
                }
            }
        }

        // The acrylic walls seen edge on, a darker frame around the front.
        noFill()
        stroke(tone(Self.warm * 0.07).withAlpha(0.55))
        strokeWeight(Box.wall * perCentimeter)
        let inset = Box.wall * perCentimeter / 2
        drawRect(front.x + inset, front.y + inset, front.width - 2 * inset, front.height - 2 * inset)
        stroke(tone(Self.warm * 1.2).mixed(with: .white, 0.4).withAlpha(0.7))
        strokeWeight(1.2)
        drawRect(front)
    }

    // MARK: - The mirror

    /// How many cells across a plate is cut into: one about every two pixels.
    static func columns(of plate: Plate, scale: Double) -> Int { max(8, Int(plate.width * scale / 2)) }
    /// How many cells down.
    static let rows = 24

    /// What the eye sees at one point of a plate. The ray from the eye meets
    /// the plate and leaves at the angle it arrived, turned about the plate's
    /// own slope there. `angle` is where it leaves, in radians to the right
    /// of straight out from the box, and `light` is what the room holds
    /// there. Rays that would go on to a second plate are not followed.
    func reflection(off plate: Plate, _ u: Double, _ v: Double)
        -> (point: Vector2, direction: Vector2, angle: Double, light: SIMD3<Double>) {
        let (depth, slope) = plate.section(u, v)
        // Seen from above: x to the right, y into the box.
        let point = Vector2((plate.left + plate.right) / 2 + u * plate.width / 2, depth)
        let arriving = (point - Vector2(eye, -Box.eyeDistance)).normalized
        let normal = Vector2(slope, -1).normalized
        let leaving = arriving - normal * (2 * arriving.dot(normal))
        let angle = atan2(leaving.x, -leaving.y)
        // A ray that leaves into the box meets metal, not the room.
        guard leaving.y < -0.02 else { return (point, leaving, angle, Self.warm * 0.02) }
        // The room is lit from above, so a plate is a little brighter at its top.
        var light = room(at: angle) * (1.12 - 0.24 * v)
        // The viewer stands in the room too. Where the ray comes back to
        // within a body's half width of the eye, it finds the viewer.
        let back = point.x + leaving.x / -leaving.y * (depth + Box.eyeDistance)
        let body = 1 - Self.smooth(18, 26, abs(back - eye))
        light = light + (Self.warm * 0.035 - light) * body
        return (point, leaving, angle, light)
    }

    /// The light the room sends from one direction.
    func room(at angle: Double) -> SIMD3<Double> {
        // A warm wall, a little brighter to one side, and never quite even.
        let uneven = 1 + 0.07 * sin(9 * angle + 5 * wash) + 0.04 * sin(23 * angle - 11 * wash)
        var light = Self.warm * ((0.30 + 0.10 * cos(angle - wash)) * uneven)
        for patch in patches {
            let cover = 1 - Self.smooth(patch.half - patch.soft, patch.half + patch.soft, abs(angle - patch.center))
            light = light + (patch.light - light) * cover
        }
        for lamp in lamps {
            // A bright core and a wide faint glow around it.
            let away = (angle - lamp.center) / lamp.width
            light = light + lamp.light * (exp(-away * away) + 0.02 * exp(-away * away / 16))
        }
        // Near a right angle the ray grazes the wall the box hangs on.
        let grazing = Self.smooth(1.30, 1.50, abs(angle))
        return light + (Self.warm * 0.03 - light) * grazing
    }

    static func smooth(_ a: Double, _ b: Double, _ x: Double) -> Double {
        let t = min(1, max(0, (x - a) / (b - a)))
        return t * t * (3 - 2 * t)
    }

    /// Light seen through the acrylic twice, on the way in and on the way
    /// out, as a color. The curve keeps a lamp from clipping flat.
    func tone(_ light: SIMD3<Double>) -> Color {
        let tint: SIMD3<Double>
        switch look {
        case .violeta: tint = SIMD3(0.80, 0.06, 0.72)
        case .azul:    tint = SIMD3(0.06, 0.34, 0.92)
        case .naranja: tint = SIMD3(1.00, 0.30, 0.03)
        }
        let through = light * tint * 1.5
        return Color(linear: SIMD3(1 - exp(-through.x), 1 - exp(-through.y), 1 - exp(-through.z)))
    }

    // MARK: - The view

    /// Where a point of the box falls on the canvas. The front of the box is
    /// the picture plane. A point `z` centimeters behind it is seen along the
    /// line to the eye, so it shifts toward the eye and shrinks a little.
    func screen(_ x: Double, _ y: Double, _ z: Double) -> Vector2 {
        let k = Box.eyeDistance / (Box.eyeDistance + z)
        let eyeY = -Box.eyeHeight
        return Vector2(boxMiddle.x + perCentimeter * (eye + (x - eye) * k),
                       boxMiddle.y + perCentimeter * (eyeY + (y - eyeY) * k))
    }

    private func corner(of plate: Plate, _ u: Double, _ v: Double, _ top: Double, _ bottom: Double) -> Vector2 {
        let x = (plate.left + plate.right) / 2 + u * plate.width / 2
        return screen(x, top + (bottom - top) * v, plate.section(u, v).depth)
    }

    /// The vector file is the box in plan, seen from above: its outline, the
    /// plates as they stand just below half height, the eye, and nine rays to
    /// each plate. Each ray is drawn in, and then out for 40 centimeters the
    /// way it leaves, in the color of what it finds. The rays go to the
    /// middles of cells the picture paints, so each one's color is on the
    /// canvas too, where its plate shows that point.
    private func drawThePlan() {
        background(Color(hex: 0xFAFAF8))
        let unit = 5.4
        let base = Vector2(width / 2, 170)
        func plan(_ p: Vector2) -> Vector2 { Vector2(base.x + p.x * unit, base.y - p.y * unit) }
        noFill()
        strokeCap(.butt)
        stroke(Color(hex: 0x222222))
        strokeWeight(1)
        let w = Box.width / 2
        drawPolygon([plan(Vector2(-w, 0)), plan(Vector2(w, 0)), plan(Vector2(w, Box.depth)), plan(Vector2(-w, Box.depth))])
        let eyePoint = Vector2(eye, -Box.eyeDistance)
        drawCircle(center: plan(eyePoint), radius: 5)
        let v = (Double(Self.rows / 2) + 0.5) / Double(Self.rows)
        for plate in standing {
            stroke(Color(hex: 0x222222))
            strokeWeight(1.4)
            drawPolyline((0 ... 48).map { i in
                let u = -1 + Double(i) / 24
                return plan(Vector2((plate.left + plate.right) / 2 + u * plate.width / 2, plate.section(u, v).depth))
            })
            strokeWeight(0.6)
            let columns = Self.columns(of: plate, scale: perCentimeter)
            for i in 0 ..< 9 {
                let column = Int((0.06 + 0.11 * Double(i)) * Double(columns))
                let seen = reflection(off: plate, -1 + (2 * Double(column) + 1) / Double(columns), v)
                stroke(Color(hex: 0x999999))
                drawLine(plan(eyePoint), plan(seen.point))
                stroke(tone(seen.light))
                drawLine(plan(seen.point), plan(seen.point + seen.direction * 40))
            }
        }
    }

    // MARK: - The deal

    /// Deals the room and the plates from the seed. The room comes first, so
    /// that changing `plates` or `bend` stands other plates in the same room.
    private func deal() {
        randomSeed(variation)

        // The room: two or three dark doorways, a window or two of sky, and
        // two or three lamps, each somewhere in the half turn the box faces.
        wash = random(-0.7, 0.7)
        patches = []
        for _ in 0 ..< Int(random(2, 4)) {
            patches.append(Patch(center: random(-1.25, 1.25), half: random(0.07, 0.20), soft: 0.02,
                                 light: Self.warm * 0.025))
        }
        for _ in 0 ..< Int(random(1, 3)) {
            patches.append(Patch(center: random(-1.1, 1.1), half: random(0.10, 0.24), soft: 0.015,
                                 light: Self.sky * random(0.4, 0.6)))
        }
        lamps = []
        for _ in 0 ..< Int(random(2, 4)) {
            lamps.append(Lamp(center: random(-1.2, 1.2), width: random(0.012, 0.035),
                              light: SIMD3(1.0, 0.9, 0.75) * random(14, 34)))
        }

        // The plates fill the box side to side, in uneven widths, as the
        // museum's box has them. About one in four is left flat. The rest
        // are bent, hollow and bulging mostly in turn.
        let inside = Box.width - 2 * Box.wall - 0.6
        let shares = (0 ..< plates).map { _ in random(0.55, 1.6) }
        let total = shares.reduce(0, +)
        standing = []
        var left = -inside / 2
        var sign = random(1) < 0.5 ? -1.0 : 1.0
        for share in shares {
            let width = inside * share / total
            // No deeper than the box has room for, and no steeper than a
            // plate that still faces the front.
            let deepest = min(3.2, width * 0.22)
            let flat = random(1) < 0.25
            let sag = flat ? random(-0.03, 0.03) : sign * deepest * bend * random(0.35, 1)
            standing.append(Plate(left: left, right: left + width, sag: sag,
                                  taper: random(-0.16, 0.16), twist: random(-0.012, 0.012)))
            left += width
            if random(1) < 0.75 { sign = -sign }
        }
    }
}

↑↓ move ↩ open