# PhonePoster

A new picture over a poster on a real wall. A layer the sketch draws is laid on the poster's four pinned corners and stays on them as the camera moves, and three balls circle out of it and back through the wall, which hides the half behind it (occluding). Hold with space and click four corners to pin your own, the first one choosing the surface under it; R forgets them. Needs import OllinPhone.

Run it with `swift run --package-path Examples Example-3D-Phone-PhonePoster`.

```swift
import Foundation
import Ollin
import OllinPhone

/// A new picture over a poster on a real wall.
///
/// A recording the phone made plays back, and the poster on its wall is
/// replaced: a layer the sketch draws every frame is laid on the poster's four
/// corners and stays on them as the camera moves. The shapes of the new
/// poster then leave it. Three balls circle out into the room and back in
/// through the wall, and the wall hides the half of each that is behind it.
///
/// A corner is a point of the room kept in the sketch. It comes from a click:
/// the line of sight through the click (`view.ray(through:covering:)`) is met
/// with the wall the phone found, and the place they meet is on the wall for
/// good. `drawImage(_:topLeft:topRight:bottomRight:bottomLeft:)` lays the
/// layer on four of them exactly, however the wall is turned to the camera.
/// And `occluding { }` draws the wall's surface as depth alone, which is what
/// lets a real wall hide a drawn ball.
///
/// The recording bundled here is a stand-in: a small room drawn on the Mac
/// and written with the writer the phone runs, with its poster's corners
/// already pinned below. To play a recording of your own, set
/// `OLLIN_PHONE_RECORDING` to its path, hold it with **space**, and click the
/// poster's four corners, top left first and round to the right.
///
/// The first corner chooses the surface: the one under that click. In a
/// **Room** recording it is the surface the phone found there, whichever
/// that is. In a **World** recording, which carries depth and no surfaces,
/// it is fitted from the depth under the click. The other three corners land
/// on the same surface. The four are parameters, points of the room in
/// meters, so they can be nudged by number, saved into the sketch, and passed
/// to an export.
///
/// Keys: **space** holds the recording and carries on, **R** forgets the
/// corners.
@main
final class PhonePoster: Sketch {

    override var canvasSize: CanvasSize { .size(1080, 1440) }

    /// One lap of the recording, so an export of this sketch loops.
    override var loopDuration: Double? {
        guard let recording = device.recording, recording.frameRate > 0 else { return nil }
        return recording.duration + 1 / recording.frameRate
    }

    let device = PhoneDevice(playing: PhonePoster.open())

    /// The poster's corners in the room, in meters. The defaults are the
    /// bundled room's.
    @Param(x: -30...30, y: -30...30, z: -30...30) var topLeft = Vector3(0.2, 2.225, -1.54)
    @Param(x: -30...30, y: -30...30, z: -30...30) var topRight = Vector3(0.9, 2.225, -1.54)
    @Param(x: -30...30, y: -30...30, z: -30...30) var bottomRight = Vector3(0.9, 1.275, -1.54)
    @Param(x: -30...30, y: -30...30, z: -30...30) var bottomLeft = Vector3(0.2, 1.275, -1.54)

    /// The bundled room's corners, to tell a recording of your own that has
    /// not been pinned yet from one that has.
    static let roomCorners = [
        Vector3(0.2, 2.225, -1.54), Vector3(0.9, 2.225, -1.54),
        Vector3(0.9, 1.275, -1.54), Vector3(0.2, 1.275, -1.54),
    ]

    /// How many of the four corners are pinned, in order from the top left.
    private var pinned = 4
    /// The corners pinned so far, top left first and round to the right.
    private var corners: [Vector3] {
        Array([topLeft, topRight, bottomRight, bottomLeft].prefix(pinned))
    }

    /// The surface the poster is on: the one under the first corner. A found
    /// surface is read fresh each frame, since it grows; a fitted one is one
    /// frame's reading, and is kept.
    private var fitted: PhonePlane?

    /// The new poster, drawn flat every frame.
    var layer: RenderTarget!
    static let sheet = (width: 700.0, height: 950.0)

    /// The three colors of the new poster, and of the balls that leave it.
    static let inks = [Color(hex: 0xF25C3B), Color(hex: 0x2F7DD1), Color(hex: 0xF2B63B)]

    static func open() -> PhoneRecording {
        if let path = ProcessInfo.processInfo.environment["OLLIN_PHONE_RECORDING"],
           let own = try? PhoneRecording(path: path) {
            return own
        }
        return try! PhoneRecording(resource: "Wall", withExtension: "ollinrecording", in: .module)
    }

    override func setup() {
        textFont(OutlineFont.system)
        layer = makeRenderTarget(width: Int(Self.sheet.width), height: Int(Self.sheet.height))
        device.start()
        // Another recording has another wall, and its poster is yours to pin,
        // unless the corners already say where it is: saved into the sketch,
        // or passed with `--param`.
        if let path = ProcessInfo.processInfo.environment["OLLIN_PHONE_RECORDING"],
           device.recording?.path == (path as NSString).expandingTildeInPath,
           [topLeft, topRight, bottomRight, bottomLeft] == Self.roomCorners {
            pinned = 0
        }
    }

    /// The surface the poster is on, or `nil` before there is one. With a
    /// corner pinned it is the surface through that corner; before that, the
    /// largest wall the phone found, so the picture is not bare while the
    /// first click is awaited.
    private func surface() -> PhonePlane? {
        guard let first = corners.first else {
            return device.planes.largest(of: .wall) ?? device.planes.largest
        }
        // The corners sit a centimeter proud of the wall, as paper does.
        if let found = device.planes.nearest(to: first), found.distance(to: first) <= 0.06 { return found }
        if fitted == nil { fitted = device.surface(at: first) }
        return fitted
    }

    /// The lap's phase, 0 to 1, so everything that moves comes back round.
    private var lap: Double {
        let length = loopDuration ?? 6
        return (time / length).truncatingRemainder(dividingBy: 1)
    }

    override func draw() {
        background(.black)
        drawSheet()

        guard let view = device.latestCamera else {
            return drawStatus(device.waitingMessage, style: .info)
        }
        drawPhonePicture(view)
        camera(view)
        let wall = surface()

        // Lit the way the room was lit, for the balls.
        if let light = device.latestLight { ambientLight(light.ambient) }
        directionalLight(.white, direction: Vector3(-0.45, -1, -0.55))
        noStroke()

        guard corners.count == 4 else {
            // Mark what has been pinned so far.
            for corner in corners {
                withState {
                    noLights()
                    fill(Self.inks[0])
                    translate(corner)
                    drawSphere(radius: 0.02)
                }
            }
            return drawCaption("Hold with space, then click the poster's corners: \(corners.count) of 4")
        }

        // The layer, on the four corners.
        drawImage(layer.image, topLeft: corners[0], topRight: corners[1],
                  bottomRight: corners[2], bottomLeft: corners[3])
        // The balls need the surface itself, to pass through it and be
        // hidden by it. A fitted one arrives on the first frame that shows it.
        guard let wall else {
            return drawCaption("A new picture on the poster")
        }

        // The wall as depth alone: from here on it hides what goes behind it.
        occluding { drawMesh(wall.mesh) }

        // Three balls on a circle that stands square to the wall, half of it
        // in the room and half behind the plaster.
        let middle = (corners[0] + corners[2]) / 2
        let surface = wall.plane
        material(.dielectric(roughness: 0.3))
        for (index, ink) in Self.inks.enumerated() {
            let turn = .tau * (lap + Double(index) / 3)
            let along = [Vector2(0, 1), Vector2(0.87, -0.5), Vector2(-0.87, -0.5)][index]
            let reach = 0.42
            let onWall = surface.coordinates(of: middle) + along * (reach * cos(turn))
            withState {
                fill(ink)
                translate(surface.point(at: onWall, lift: reach * sin(turn)))
                drawSphere(radius: 0.09)
            }
        }
        drawCaption("A new picture on the poster, and its shapes passing through the wall")
    }

    /// The new poster: three discs that swell in turn over a dark sheet, in
    /// the layer's own pixels.
    private func drawSheet() {
        withTarget(layer) {
            let w = Self.sheet.width, h = Self.sheet.height
            background(Color(hex: 0x14161B))
            noStroke()
            for (index, ink) in Self.inks.enumerated() {
                let beat = 0.5 + 0.5 * sin(.tau * (lap * 3 + Double(index) / 3))
                let center = Vector2(w * (0.3 + 0.2 * Double(index)), h * (0.3 + 0.2 * Double(index)))
                fill(ink.withAlpha(0.3))
                drawCircle(center.x, center.y, w * (0.2 + 0.1 * beat))
                fill(ink)
                drawCircle(center.x, center.y, w * (0.09 + 0.07 * beat))
            }
            noFill()
            stroke(Color(hex: 0xECE7DC))
            strokeWeight(14)
            drawRect(7, 7, w - 14, h - 14)
        }
    }

    // MARK: Pinning

    override func mousePressed() {
        // A click is a corner while the recording is held and corners are owed.
        guard pinned < 4, let recording = device.recording, !recording.isPlaying,
              let view = device.latestCamera else { return }
        let canvas = Vector2(width, height)
        // The first corner takes the surface under the click, and the rest
        // land on the surface the first one chose.
        guard let wall = pinned == 0 ? device.surface(under: mouse, covering: canvas) : surface()
        else { return }
        let ray = view.ray(through: mouse, covering: canvas)
        // A centimeter proud of the wall, as a sheet of paper is.
        guard let spot = wall.plane.moved(by: .zero, lift: 0.01).intersection(with: ray) else { return }
        switch pinned {
        case 0: topLeft = spot
        case 1: topRight = spot
        case 2: bottomRight = spot
        default: bottomLeft = spot
        }
        if pinned == 0 { fitted = device.planes.isEmpty ? wall : nil }
        pinned += 1
    }

    override func keyPressed() {
        guard let recording = device.recording else { return }
        if key == " " {
            if recording.isPlaying { recording.pause() } else { recording.play() }
        } else if key == "r" {
            pinned = 0
            fitted = nil
        }
    }
}
```
