# InteraccionLineal

one red, a few planes and three frames of bar, seen on a walk past, after Felguérez's Interacción lineal (1976).

Run it with `swift run --package-path Examples Example-Recreations-ManuelFelguerez-InteraccionLineal`.

```swift
//  Recreation after Manuel Felguerez - "Interaccion lineal" (1976; polychromed
//  iron; 30.5 x 41 x 10.5 cm; Coleccion MUAC, UNAM, gift of the artist, 2018).
//  One of the small free-standing pieces he made in metal in the years of
//  "La maquina estetica"; shown in "Manuel Felguerez: Trayectorias" (MUAC,
//  Mexico City, 2019 to 2020). A homage, not a reproduction, and not
//  affiliated with or endorsed by the artist or his estate.
//  https://muac.unam.mx/assets/docs/folio_082_manuel_felguerez.pdf
//
//  An original Ollin interpretation, read off the one photograph of the piece
//  in that catalog (Francisco Kochen's, taken from the front) and written from
//  the artist's own essay "Origen y desarrollo del espacio multiple" (1974).
//  Nothing was ported: the work is welded and painted iron. The photograph
//  fixes what the piece looks like from the front, and the catalog gives its
//  size. How far back each part sits is a reading of that one view.

import Foundation
import Ollin

/// "Interaccion lineal" (Manuel Felguerez, 1976): one red, a few planes, and
/// three rectangles drawn in the air.
///
/// The piece is small, 41 centimeters wide, and every part of it is painted
/// the same red. A band of sheet iron is bent into an open box with two
/// rounded corners. A tall plate with one rounded corner stands inside it and
/// rises through its top. A square block hangs at the plate's edge, with a
/// triangle under it. Three frames of square bar run around all of that, two
/// behind the box and one in front: rectangles drawn as lines. The large
/// frame at the back carries two disks on its bottom bar. The square, the
/// triangle and the circle are all here, the three families of form he
/// built everything from.
///
/// Two passages of his 1974 essay are the rule. The first is about color.
/// When a form takes on volume it keeps its color, he writes, but the color
/// now answers to the laws of optics, and a red cube will show at least five
/// tones of red. So this sketch has one paint, and no second color anywhere
/// on the piece. Every tone you see is the light's doing, and `unlit` shows
/// it: with the lights off the piece is one flat red shape, the plane it came
/// from. The second is about sculpture. Part the relief wholly from its
/// ground, he writes, and it is born without supports; yet its own material
/// obliges it to make new ones and stand on the earth again, keeping its
/// geometry of the air. That is the box on its short legs, two centimeters
/// above the plinth.
///
/// The interaction of the title happens when you move. From the front the
/// frames are lines lying across the planes. Step to one side and the lines
/// slide over the planes, the back frames one way and the front frame the
/// other, because they stand at different depths. The default view takes
/// that walk, to one side, to the other, and back. Its middle is the place
/// the catalog's photographer stood.
///
/// What is read and what is chosen. The catalog has one photograph, taken
/// from the front. It shows the tops of the box, of its floor and of the
/// block as thin bands, and those bands place the camera: about 1.2 meters
/// away and ten degrees above. With the camera placed, each outline measured
/// in the picture is put back at its own depth. Depth is read where the
/// picture gives it: the plate stands six tenths of the way back on the
/// floor, the block is about as deep as the box, and the box's wall hides
/// part of one disk. Where it does not, depth is chosen: the box is taken
/// nearly as deep as the catalog's 10.5 centimeters, with two frames against
/// its back and one against its front. The plate hides the right side of the
/// tall frame, so that frame's width is a guess, and so is the leg at the
/// back.
///
/// Try it: `view` is `walk`, `front` (flat and straight on, with the light
/// moving instead of the eye) or `plan` (every outline as an ink line, which
/// `--export-svg` writes for a pen). `swing` is how far the walk goes to
/// each side and `seconds` how long it takes. `depth` chooses another volume
/// for the same plan, from nearly flat to twice as deep; every plane, he
/// wrote, holds infinitely many. The seed is the visit: where the walk
/// begins and where the light stands. A click starts another one.
@main
final class InteraccionLineal: Sketch {
    enum View: String, CaseIterable, ParamOption { case walk, front, plan }

    /// How the piece is seen: on a walk past it, from the front with the
    /// light moving, or as a plan in ink lines.
    @Param(icon: "eye") var view = View.walk
    /// Seconds for the walk to go to one side, to the other, and back.
    @Param(8 ... 30, icon: "clock") var seconds = 24.0
    /// How far to each side the walk goes, in degrees.
    @Param(0 ... 60, icon: "arrow.left.and.right") var swing = 34.0
    /// The piece's depth, as a multiple of the 10.5 centimeters it has.
    @Param(0.2 ... 2, icon: "arrow.up.and.down") var depth = 1.0
    /// Lights off: the piece as one flat red shape.
    @Param(icon: "lightbulb.slash") var unlit = false

    /// Four to three, close to the piece's own 41 by 30.5.
    override var canvasSize: CanvasSize { .size(1440, 1080) }
    /// One walk there and back is one lap. The plan holds still.
    override var loopDuration: Double? { view == .plan ? nil : max(4, seconds) }

    // MARK: The piece, in centimeters

    /// The piece's width and height as rebuilt, legs included. The catalog
    /// gives 41 by 30.5.
    private let size = Vector2(40.8, 30.15)
    /// Sheet iron for the planes, square bar for the frames.
    private let sheet = 0.3
    private let bar = 0.53
    /// The bent box, front to back, before `depth` scales it. With a frame
    /// against each side it makes the catalog's 10.5.
    private let boxDepth = 9.46

    /// The one paint.
    private let red = Color(red: 0.78, green: 0.23, blue: 0.16)
    private let plinth = Color(red: 0.93, green: 0.925, blue: 0.91)
    private let room = Color(red: 0.90, green: 0.90, blue: 0.89)
    private let paper = Color(red: 0.94, green: 0.93, blue: 0.90)
    private let ink = Color(red: 0.16, green: 0.10, blue: 0.10)

    /// One part: an outline in the piece's front plane (x from its left
    /// edge, y up from the plinth), where it sits front to back, and how
    /// thick it is that way. Holes are the insides of frames.
    private struct Part {
        var outline: [Vector2]
        var holes: [[Vector2]] = []
        /// The middle of the part, front to back; positive is toward the eye.
        var z: Double
        var thickness: Double
    }

    /// The legs under the right end of the box: where, and how thick.
    private let legAt = 30.64
    private let legRadius = 0.34
    private let floorUnder = 2.21

    private var pressed = false

    override func mousePressed() {
        pressed = true
    }

    // MARK: Drawing

    override func draw() {
        if pressed {
            pressed = false
            seed(variation + 1)
        }
        let parts = build()
        if view == .plan {
            drawThePlan(parts)
            return
        }

        background(room)
        let lap = max(4, seconds)
        // The seed sets where in its lap the visit begins.
        let phase = (time / lap + visit.start).truncatingRemainder(dividingBy: 1) * 2 * .pi
        placeCamera(phase)
        light(phase)

        // The plinth: a white block whose top is the ground the piece
        // found for itself, wide enough that its edges stay out of the walk.
        withState {
            translate(0, -30, 0)
            fill(plinth)
            material(.matte)
            drawBox(width: 110, height: 60, depth: 64)
        }

        // Every part in the same paint.
        fill(red)
        material(paint)
        for part in parts {
            withState {
                translate(-size.x / 2, 0, part.z)
                if part.holes.isEmpty {
                    drawExtrude(part.outline, depth: part.thickness)
                } else {
                    drawExtrude(Shape(outer: part.outline, holes: part.holes), depth: part.thickness)
                }
            }
        }
        // The two round legs under the right end of the box. The one at the
        // back is assumed.
        let reach = boxDepth * depth / 2
        for z in [reach - 0.8, -(reach - 0.8)] {
            withState {
                translate(legAt - size.x / 2, floorUnder / 2, z)
                drawCylinder(radius: legRadius, height: floorUnder, segments: 20)
            }
        }
    }

    /// Enamel on iron: a hard, even coat with a soft shine.
    private let paint = Material.physicallyBased(metallic: 0, roughness: 0.4)

    /// What the seed deals: where the walk starts, and where the key light
    /// stands, as an angle round the piece and a height.
    private var visit: (start: Double, lightTurn: Double, lightHeight: Double) {
        var rng = SplitMix64(seed: UInt64(bitPattern: Int64(variation &* 1_000_003 &+ 29)))
        let start = Double.random(in: 0 ..< 1, using: &rng)
        let turn = Double.random(in: -0.8 ... -0.25, using: &rng)
        let height = Double.random(in: 0.7 ... 1.0, using: &rng)
        return (start, turn, height)
    }

    /// Where the eye looks: the middle of the piece.
    private var target: Vector3 { Vector3(0, 14.6, 0) }

    private func placeCamera(_ phase: Double) {
        if view == .front {
            // Straight on and flat, the frame the plan uses.
            ortho(eye: target + Vector3(0, 0, 40), target: target, height: height / unit)
            return
        }
        // A walk past the plinth, on an arc to one side, to the other, and
        // back. Its middle is where the catalog's camera stood, as near as
        // the photograph tells: 1.2 meters away, a little left of center,
        // ten degrees above.
        let side = -0.036 + swing * .pi / 180 * sin(phase)
        let tilt = 0.18
        let eye = target + Vector3(sin(side) * cos(tilt), sin(tilt), cos(side) * cos(tilt)) * 122
        perspective(eye: eye, target: target, fieldOfView: 0.37)
    }

    private func light(_ phase: Double) {
        if unlit {
            noLights()
            return
        }
        // A studio to give the enamel something to shine with, kept out of
        // the picture; one key that throws the shadows; a dim fill so the
        // shaded sides keep their red. On the walk the key stands still.
        // From the front it sways from side to side, so the tones change.
        environment(.studio.intensified(to: 0.35).lightingOnly())
        toneMap(.aces)
        ambientLight(Color(white: 0.12))
        let visit = self.visit
        let turn = view == .front ? 0.9 * sin(phase) : visit.lightTurn
        let rise = visit.lightHeight
        let from = Vector3(sin(turn) * cos(rise), sin(rise), cos(turn) * cos(rise))
        directionalLight(Color(red: 1, green: 0.97, blue: 0.92), direction: -from, intensity: 1.3)
        directionalLight(Color(white: 0.8), direction: Vector3(from.x, -0.25, -from.z).normalized,
                         intensity: 0.25, castsShadow: false)
        castShadows()
        shadowSoftness(0.6)
    }

    // MARK: The plan

    /// Pixels to a centimeter, the piece filling most of the canvas.
    private var unit: Double { min(width * 0.8 / size.x, height * 0.8 / size.y) }

    /// Every outline as an ink line, seen from the front: the planes, the
    /// block as its square, and the frames as the double lines they are.
    private func drawThePlan(_ parts: [Part]) {
        background(paper)
        noFill()
        stroke(ink)
        strokeWeight(max(1.2, unit * 0.07))
        strokeJoin(.round)
        let unit = self.unit
        // The plan sits where the front view puts the piece.
        let origin = Vector2(width / 2 - size.x / 2 * unit, height / 2 + target.y * unit)
        func place(_ p: Vector2) -> Vector2 { origin + Vector2(p.x, -p.y) * unit }
        for part in parts {
            drawPolyline(part.outline.map(place), closed: true)
            for hole in part.holes {
                drawPolyline(hole.map(place), closed: true)
            }
        }
        // The round legs, one behind the other, seen as one.
        drawPolyline([Vector2(legAt - legRadius, floorUnder), Vector2(legAt - legRadius, 0),
                      Vector2(legAt + legRadius, 0), Vector2(legAt + legRadius, floorUnder)].map(place))
    }

    // MARK: Building the parts

    /// The parts, back to front. The numbers are centimeters: each outline
    /// measured in the photograph, then put back at its own depth through
    /// the camera the photograph implies.
    private func build() -> [Part] {
        let reach = boxDepth * depth / 2
        let back = -(reach + bar / 2), front = reach + bar / 2
        // Sheet set against the back frames, a hair in front of their face.
        let onTheFrames = -reach - sheet / 2 + 0.02
        var parts: [Part] = []

        // Two frames against the back of the box. The tall one on the left
        // is as high as the square one on the right, and here half as wide,
        // a guess: the plate hides its other side.
        parts.append(frame(3.42, 7.49, 14.57, 29.95, z: back))
        parts.append(frame(18.51, 4.91, 40.79, 27.31, z: back))

        // Two disks on the square frame's bottom bar. They just fill the
        // gap from the box's wall to the frame's far side.
        for x in [33.6, 38.04] {
            parts.append(Part(outline: circle(Vector2(x, 5.17), 2.22), z: onTheFrames, thickness: sheet))
        }

        // The box: a band of sheet bent round, its two left corners rounded,
        // open to the front and the back.
        let outer = rounded(5.84, floorUnder, 31.38, 20.7, topLeft: 1.9, bottomLeft: 1.9)
        let inner = rounded(5.84 + sheet, floorUnder + sheet, 31.38 - sheet, 20.7 - sheet,
                            topLeft: 1.9 - sheet, bottomLeft: 1.9 - sheet)
        parts.append(Part(outline: outer, holes: [Array(inner.reversed())], z: 0, thickness: 2 * reach))

        // The tall plate, six tenths of the way back, with its one rounded
        // corner and the tab at its foot that is the piece's third leg.
        let behindTheMiddle = -0.2 * reach
        var plate = rounded(6.14, floorUnder + sheet, 15.79, 30.15, topLeft: 1.7, bottomLeft: 0)
        plate.insert(contentsOf: [Vector2(15.49, floorUnder + sheet), Vector2(15.49, 0), Vector2(15.79, 0)], at: 1)
        parts.append(Part(outline: plate, z: behindTheMiddle, thickness: sheet))

        // The block at the plate's edge, square from the front and nearly
        // as deep as the box, and the triangle that hangs under it.
        let block = [Vector2(15.83, 9.65), Vector2(20.66, 9.65), Vector2(20.66, 14.53), Vector2(15.83, 14.53)]
        parts.append(Part(outline: block, z: 0, thickness: 1.84 * reach))
        parts.append(Part(outline: [Vector2(16.06, 5.33), Vector2(20.84, 5.33), Vector2(18.45, 9.65)],
                          z: 0.17 * reach, thickness: sheet))

        // The frame in front, out past the box's left side.
        parts.append(frame(0, 10.6, 10.01, 20.46, z: front))
        return parts
    }

    /// A rectangle drawn in square bar: its outside, and its inside as a hole.
    private func frame(_ x0: Double, _ y0: Double, _ x1: Double, _ y1: Double, z: Double) -> Part {
        let outside = [Vector2(x0, y0), Vector2(x1, y0), Vector2(x1, y1), Vector2(x0, y1)]
        let inside = [Vector2(x0 + bar, y0 + bar), Vector2(x0 + bar, y1 - bar),
                      Vector2(x1 - bar, y1 - bar), Vector2(x1 - bar, y0 + bar)]
        return Part(outline: outside, holes: [inside], z: z, thickness: bar)
    }

    /// A rectangle, counterclockwise from its bottom left, with its two left
    /// corners rounded by the radii given (zero leaves a corner square).
    private func rounded(_ x0: Double, _ y0: Double, _ x1: Double, _ y1: Double,
                         topLeft: Double, bottomLeft: Double) -> [Vector2] {
        var points: [Vector2] = []
        func arc(_ center: Vector2, _ radius: Double, from: Double) {
            for step in 0 ... 12 {
                let angle = from + .pi / 2 * Double(step) / 12
                points.append(center + Vector2(cos(angle), sin(angle)) * radius)
            }
        }
        if bottomLeft > 0 {
            arc(Vector2(x0 + bottomLeft, y0 + bottomLeft), bottomLeft, from: .pi)
        } else {
            points.append(Vector2(x0, y0))
        }
        points.append(Vector2(x1, y0))
        points.append(Vector2(x1, y1))
        if topLeft > 0 {
            arc(Vector2(x0 + topLeft, y1 - topLeft), topLeft, from: .pi / 2)
        } else {
            points.append(Vector2(x0, y1))
        }
        return points
    }

    private func circle(_ center: Vector2, _ radius: Double) -> [Vector2] {
        (0 ..< 48).map { center + Vector2(cos(Double($0) / 48 * 2 * .pi), sin(Double($0) / 48 * 2 * .pi)) * radius }
    }
}
```
