Ollin

GreenModule

Upright and level bars of color that lock together with half circles, after Saloua Raouda Choucair's Composition with Green Module (1950).

Run
swift run --package-path Examples Example-Recreations-SalouaRaoudaChoucair-GreenModule
Source
Examples/Recreations/SalouaRaoudaChoucair/GreenModule/Sketch.swift
//  Recreation after Saloua Raouda Choucair - Composition with Green Module
//  (1950; oil on canvas, 58 x 67 cm; Sharjah Art Foundation Collection). It
//  is one of the module paintings of her Paris years: upright and level bars
//  of flat color that lock together with half circles. A homage, not a
//  reproduction, and not affiliated with or endorsed by the artist or her
//  estate.
//  https://www.sharjahart.org/en/resources/collections/details/composition-with-green-module
//  https://mathaf.org.qa/en/encyclopedia/artists-biographies/saloua-raouda-choucair/
//
//  An original Ollin interpretation, read off pictures of the painting. The
//  Sharjah Art Foundation's note on it says that "Semi-circular cut-ins
//  soften the geometry". It calls a module "an independent unit that can be
//  combined with others to form a larger system". How the canvas is ruled,
//  where the half circles sit and how large they are is measured from its
//  picture of the work. Each composition here is dealt inside those
//  measures. Nothing was ported: the work is oil paint.

import Foundation
import Ollin

/// *Composition with Green Module* (Saloua Raouda Choucair, 1950): bars of
/// flat color that lock together with half circles. **Press** to deal
/// another composition.
///
/// The canvas is ruled into upright bars from edge to edge. Most are narrow
/// and two or three are wide, as in the painting. A few level bars lie
/// across a run of them, and some uprights are cut once more, so the bars
/// end at different heights. Each piece is one flat color. All of it sits
/// on a grid of sixty steps by fifty-two, the painting's own proportion,
/// with the narrowest bars two steps wide.
///
/// That much is plain rectangles. The module is what happens on a side
/// between two bars: a half circle, standing on the side, pushed into the
/// bar beyond. It takes the color of the bar it stands on. So a bulge on
/// one bar is a bite out of the next. The two still fill the canvas between
/// them with nothing left over.
///
/// A half circle may stand across the place where two bars meet a third.
/// Then the line between the two runs on through it, and each bar colors its
/// own part. The painting has one of these: a dome pushed up into a dark
/// bar, ochre on its left and pale yellow on its right.
///
/// The colors are the painting's, sampled from the Sharjah Art Foundation's
/// picture: black, navy, three greens, two blues, ochre and two pale tones.
/// Narrow bars take the dark ones more often, and wide fields the ochre and
/// the greens. The light tones gather low on the canvas, as they do there.
///
/// During a lap each half circle slides along its side and back. It keeps
/// clear of the corners and of every other half circle, so the bars stay
/// locked the whole way round.
///
/// Try it: `bars` is how many uprights cross the canvas and `levels` how
/// many level bars lie over them. `lobes` is the share of sides that carry
/// a half circle, and `swell` caps how large one can be. `joined` lets
/// touching bars share a color, which makes the L and T shapes of the
/// painting.
@main
final class GreenModule: Sketch {
    /// How many upright bars cross the canvas.
    @Param(6 ... 18, icon: "rectangle.split.3x1") var bars = 12
    /// How many level bars lie across a run of uprights.
    @Param(0 ... 4, icon: "rectangle.split.1x2") var levels = 2
    /// The share of sides between bars that carry a half circle.
    @Param(0 ... 1, icon: "circle.lefthalf.filled") var lobes = 0.42
    /// The largest radius a half circle may have, in grid steps. The
    /// painting's run from about three steps to six.
    @Param(2.5 ... 7, icon: "circle.dashed") var swell = 5.6
    /// The chance that a bar takes the color of a bar it touches, so that the
    /// two read as one L or T.
    @Param(0 ... 0.5, icon: "square.on.square") var joined = 0.16
    /// How far each half circle travels along its side during a lap, as a
    /// share of the room it has.
    @Param(0 ... 1, icon: "arrow.left.and.right") var slide = 1.0
    /// Seconds for one lap: every half circle out along its side and back.
    @Param(12 ... 30, icon: "timer") var seconds = 24.0

    // 67 by 58 centimeters is very nearly 60 by 52, so a grid step is square.
    override var canvasSize: CanvasSize { .size(1260, 1092) }
    override var loopDuration: Double? { seconds }

    /// The grid the painting is ruled on.
    enum Grid {
        static let columns = 60
        static let rows = 52
        /// The rim a half circle keeps clear of along the other three sides
        /// of the bar it enters, in steps.
        static let rim = 0.75
    }

    /// A bar: a rectangle on the grid, and which paint it takes.
    struct Bar {
        var x0: Int, y0: Int, x1: Int, y1: Int
        var color = 0
        var wide: Int { x1 - x0 }
        var tall: Int { y1 - y0 }
    }

    /// The four sides of a bar a half circle can enter through.
    enum Side: CaseIterable { case top, right, bottom, left }

    /// A half circle: the bar it is pushed into, the side it stands on, and
    /// how it travels along that side. All in grid steps.
    struct Lobe {
        var bar: Int
        var side: Side
        var radius: Double
        /// The middle of its travel along the side.
        var middle: Double
        /// How far it goes to each side of the middle.
        var reach: Double
        /// Where in the lap its travel starts, from 0 to 1.
        var phase: Double
    }

    /// The painting's colors, sampled from the Sharjah Art Foundation's
    /// picture and lifted a little, since that picture is dim.
    private let paints: [Color] = [
        Color(hex: 0x1B1C1F),  // black
        Color(hex: 0x1B2638),  // navy
        Color(hex: 0x1F4245),  // deep green
        Color(hex: 0x2F4E48),  // dark green
        Color(hex: 0x6C7769),  // gray green
        Color(hex: 0x17325A),  // blue
        Color(hex: 0x93AFD0),  // light blue
        Color(hex: 0x8D7632),  // ochre
        Color(hex: 0xA9B487),  // pale green
        Color(hex: 0xBDBB88),  // pale yellow
    ]

    /// Where the dealing starts. The first composition dealt then has the
    /// painting's ochre field and a dome pushed up into a dark bar.
    private let firstDeal = 12

    private var plan: [Bar] = []
    private var halves: [Lobe] = []
    private var built = ""
    private var dealt = 0

    override func mousePressed() {
        dealt += 1
    }

    // MARK: - The frame

    override func draw() {
        let key = "\(variation)/\(dealt)/\(bars)/\(levels)/\(lobes)/\(swell)/\(joined)"
        if key != built {
            (plan, halves) = GreenModule.deal(seed: variation &+ firstDeal &+ dealt &* 7919, bars: bars, levels: levels,
                                              lobes: lobes, swell: swell, joined: joined)
            built = key
        }

        let step = width / Double(Grid.columns)
        background(paints[0])
        noStroke()
        for bar in plan {
            fill(paints[bar.color])
            drawRect(Double(bar.x0) * step, Double(bar.y0) * step,
                     Double(bar.wide) * step, Double(bar.tall) * step)
        }

        let progress = loopProgress(over: seconds)
        for lobe in halves {
            let at = lobe.middle + lobe.reach * slide * sin((progress + lobe.phase) * .tau)
            for part in GreenModule.parts(of: lobe, at: at, in: plan) {
                fill(paints[part.color])
                drawPolygon(part.outline.map { $0 * step })
            }
        }
    }

    // MARK: - A half circle on a side

    /// The line a side lies on, the stretch of it the bar covers, and which
    /// way is into the bar.
    static func line(of side: Side, on bar: Bar) -> (at: Int, from: Int, to: Int, inward: Double) {
        switch side {
        case .top: return (bar.y0, bar.x0, bar.x1, 1)
        case .bottom: return (bar.y1, bar.x0, bar.x1, -1)
        case .left: return (bar.x0, bar.y0, bar.y1, 1)
        case .right: return (bar.x1, bar.y0, bar.y1, -1)
        }
    }

    /// The bars on the far side of `side`, each with the stretch of the side
    /// it shares.
    static func across(_ side: Side, of index: Int, in plan: [Bar]) -> [(bar: Int, from: Int, to: Int)] {
        let own = line(of: side, on: plan[index])
        var found: [(bar: Int, from: Int, to: Int)] = []
        for (other, bar) in plan.enumerated() where other != index {
            let facing: (at: Int, from: Int, to: Int)
            switch side {
            case .top: facing = (bar.y1, bar.x0, bar.x1)
            case .bottom: facing = (bar.y0, bar.x0, bar.x1)
            case .left: facing = (bar.x1, bar.y0, bar.y1)
            case .right: facing = (bar.x0, bar.y0, bar.y1)
            }
            let from = max(own.from, facing.from), to = min(own.to, facing.to)
            if facing.at == own.at, from < to { found.append((other, from, to)) }
        }
        return found.sorted { $0.from < $1.from }
    }

    /// The pieces of a half circle standing at `at` along its side: one for
    /// each bar it stands on, in that bar's color, cut where those bars meet.
    static func parts(of lobe: Lobe, at: Double, in plan: [Bar]) -> [(color: Int, outline: [Vector2])] {
        let side = line(of: lobe.side, on: plan[lobe.bar])
        var pieces: [(color: Int, outline: [Vector2])] = []
        for neighbor in across(lobe.side, of: lobe.bar, in: plan) {
            let from = max(at - lobe.radius, Double(neighbor.from))
            let to = min(at + lobe.radius, Double(neighbor.to))
            guard from < to else { continue }
            // The piece starts a hair inside the bar it stands on, so no
            // seam can open along the side.
            var along: [(Double, Double)] = [(from, -0.06), (to, -0.06)]
            let first = acos(clamp((to - at) / lobe.radius, -1, 1))
            let last = acos(clamp((from - at) / lobe.radius, -1, 1))
            let steps = max(2, Int((last - first) / 0.04))
            for i in 0 ... steps {
                let angle = lerp(first, last, Double(i) / Double(steps))
                along.append((at + lobe.radius * cos(angle), lobe.radius * sin(angle)))
            }
            let outline = along.map { place -> Vector2 in
                let depth = Double(side.at) + place.1 * side.inward
                return lobe.side == .top || lobe.side == .bottom ? Vector2(place.0, depth) : Vector2(depth, place.0)
            }
            pieces.append((plan[neighbor.bar].color, outline))
        }
        return pieces
    }

    // MARK: - Dealing a composition

    /// Deals the bars, their colors and the half circles. Everything comes
    /// from the seed, so a seed is a composition.
    static func deal(seed: Int, bars count: Int, levels: Int, lobes: Double, swell: Double,
                     joined: Double) -> ([Bar], [Lobe]) {
        var rng = SplitMix64(seed: UInt64(bitPattern: Int64(seed &* 1_000_003 &+ 1950)))
        func roll() -> Double { Double(rng.next() >> 11) / Double(1 << 53) }
        func roll(_ low: Int, _ high: Int) -> Int { low + Int(roll() * Double(high - low + 1)) }

        // The uprights. In the painting about a dozen cross the canvas. All
        // but two are five steps wide or less, and the two wide fields are
        // about nine and seventeen. Here about one in five is wide, and the
        // wide ones share what the narrow ones leave.
        var wideOnes = max(1, count / 5)
        var widths = (0 ..< count - wideOnes).map { _ in roll(2, 5) }
        while Grid.columns - widths.reduce(0, +) < wideOnes * 7, let most = widths.indices.max(by: { widths[$0] < widths[$1] }),
              widths[most] > 2 {
            widths[most] -= 1
        }
        // With few bars the wide ones would be too wide: make more of them.
        while (Grid.columns - widths.reduce(0, +)) / wideOnes > 20, widths.count > 1 {
            widths.removeLast()
            wideOnes += 1
        }
        var left = Grid.columns - widths.reduce(0, +)
        for remaining in stride(from: wideOnes, to: 0, by: -1) {
            let share = remaining == 1 ? left : clamp(Int(Double(left) / Double(remaining) * (0.6 + 0.8 * roll())),
                                                      7, left - 7 * (remaining - 1))
            // A wide bar goes in at a dealt place among the others.
            widths.insert(share, at: roll(0, widths.count))
            left -= share
        }
        var edges = [0]
        for width in widths { edges.append(edges[edges.count - 1] + width) }

        // The level bars: each lies across a run of uprights, two to five
        // steps thick, clear of the others.
        var plan: [Bar] = []
        var crossings: [Bar] = []
        for _ in 0 ..< levels {
            for _ in 0 ..< 40 {
                let first = roll(0, widths.count - 1), last = roll(first, widths.count - 1)
                let thick = roll(2, 5)
                let top = roll(8, Grid.rows - 8 - thick)
                let bar = Bar(x0: edges[first], y0: top, x1: edges[last + 1], y1: top + thick)
                guard bar.wide >= 12, bar.wide <= 46 else { continue }
                // Level bars over the same uprights keep six steps apart, so
                // a piece of upright is left between them.
                let clear = crossings.allSatisfy { $0.x1 <= bar.x0 || bar.x1 <= $0.x0 || $0.y1 + 6 <= bar.y0 || bar.y1 + 6 <= $0.y0 }
                guard clear else { continue }
                crossings.append(bar)
                break
            }
        }
        plan.append(contentsOf: crossings)

        // Each upright is what the level bars leave of it, top to bottom. A
        // long piece may be cut once more at a level of its own.
        for column in widths.indices {
            let x0 = edges[column], x1 = edges[column + 1]
            let over = crossings.filter { $0.x0 <= x0 && $0.x1 >= x1 }.sorted { $0.y0 < $1.y0 }
            var top = 0
            for stop in over.map({ ($0.y0, $0.y1) }) + [(Grid.rows, Grid.rows)] {
                if stop.0 > top {
                    let tall = stop.0 - top
                    if tall >= 16, roll() < (x1 - x0 > 5 ? 0.55 : 0.2) {
                        let cut = top + roll(6, tall - 6)
                        plan.append(Bar(x0: x0, y0: top, x1: x1, y1: cut))
                        plan.append(Bar(x0: x0, y0: cut, x1: x1, y1: stop.0))
                    } else {
                        plan.append(Bar(x0: x0, y0: top, x1: x1, y1: stop.0))
                    }
                }
                top = stop.1
            }
        }

        // Painting: a bar takes a color none of its painted neighbors has,
        // or now and then the color of one of them. The shares follow the
        // painting: narrow bars mostly dark, fields mostly ochre and green.
        //                       black navy deep  dark  gray  blue light ochre pale  pale
        //                                  green green green      blue        green yellow
        let narrowTaste: [Double] = [4.5, 3.5, 1, 2.5, 1, 2.5, 1.6, 0.3, 0.5, 0.5]
        let fieldTaste: [Double] = [1.2, 1.2, 4, 2.5, 2, 1.5, 0.8, 6.5, 2, 2]
        // The ochre and the pale tones gather low on the canvas, the dark
        // ones high.
        let lowTones = [7, 8, 9]
        var painted = Array(repeating: false, count: plan.count)
        let order = plan.indices.map { ($0, roll()) }.sorted { $0.1 < $1.1 }.map(\.0)
        for index in order {
            let bar = plan[index]
            let neighbors = Side.allCases.flatMap { across($0, of: index, in: plan) }.map(\.bar).filter { painted[$0] }
            if !neighbors.isEmpty, roll() < joined {
                plan[index].color = plan[neighbors[roll(0, neighbors.count - 1)]].color
            } else {
                var taste = min(bar.wide, bar.tall) <= 5 ? narrowTaste : fieldTaste
                let low = Double(bar.y0 + bar.y1) / 2 / Double(Grid.rows)
                for tone in lowTones { taste[tone] *= 0.3 + 1.7 * low }
                for neighbor in neighbors { taste[plan[neighbor].color] = 0 }
                var pick = roll() * taste.reduce(0, +)
                var color = 0
                for (i, weight) in taste.enumerated() where weight > 0 {
                    color = i
                    pick -= weight
                    if pick < 0 { break }
                }
                plan[index].color = color
            }
            painted[index] = true
        }

        // The half circles. Every side between bars is a candidate. Each is
        // dealt its numbers first, so that changing `lobes` keeps the ones
        // already there, and then they are taken in a dealt order.
        struct Candidate { var bar: Int; var side: Side; var chance: Double; var size: Double; var place: Double; var phase: Double; var order: Double }
        var candidates: [Candidate] = []
        for index in plan.indices {
            for side in Side.allCases where !across(side, of: index, in: plan).isEmpty {
                candidates.append(Candidate(bar: index, side: side, chance: roll(), size: roll(), place: roll(),
                                            phase: roll(), order: roll()))
            }
        }
        candidates.sort { $0.order < $1.order }

        var taken: [Swept] = []
        var halves: [Lobe] = []
        for candidate in candidates {
            let bar = plan[candidate.bar]
            let side = line(of: candidate.side, on: bar)
            let level = candidate.side == .top || candidate.side == .bottom
            // In the painting about eight of eleven stand on upright lines,
            // so a level line is half as likely to carry one.
            guard candidate.chance < (level ? lobes / 2 : lobes) else { continue }
            let depth = Double(level ? bar.tall : bar.wide)
            let length = Double(side.to - side.from)
            // As large as its dealt size, the side and the bar allow.
            let radius = min(lerp(2.6, swell, candidate.size), (length - 2 * Grid.rim) / 2, depth - Grid.rim)
            guard radius >= 2.4 else { continue }
            // Its travel keeps the whole half circle a rim clear of the
            // corners, and is at most seven steps each way.
            let low = Double(side.from) + radius + Grid.rim, high = Double(side.to) - radius - Grid.rim
            let reach = min((high - low) / 2, 7)
            let middle = lerp(low + reach, high - reach, candidate.place)
            let swept = Swept(bar: candidate.bar, upright: !level, at: side.at,
                              from: middle - reach - radius - Grid.rim / 2, to: middle + reach + radius + Grid.rim / 2,
                              deep: radius + Grid.rim / 2, inward: side.inward)

            // It must show whole wherever it travels: every bar it can stand
            // on has another color than the bar it enters.
            let stoodOn = across(candidate.side, of: candidate.bar, in: plan)
                .filter { Double($0.from) < swept.to && Double($0.to) > swept.from }
            guard stoodOn.allSatisfy({ plan[$0.bar].color != bar.color }) else { continue }

            // It must not meet another half circle: not on the same line,
            // from either side of it, and not inside the same bar.
            let clear = taken.allSatisfy { other in
                if other.upright == swept.upright, other.at == swept.at, other.from < swept.to, other.to > swept.from {
                    return false
                }
                return other.bar != swept.bar || !swept.meets(other)
            }
            guard clear else { continue }
            taken.append(swept)
            halves.append(Lobe(bar: candidate.bar, side: candidate.side, radius: radius,
                               middle: middle, reach: reach, phase: candidate.phase))
        }
        return (plan, halves)
    }

    /// The room a half circle sweeps as it travels: the stretch of the line
    /// it stands on, and a strip that deep into the bar it enters.
    private struct Swept {
        var bar: Int
        /// Whether the line it stands on is upright.
        var upright: Bool
        var at: Int
        var from: Double
        var to: Double
        var deep: Double
        var inward: Double

        /// The strip as a box: its two corners.
        var box: (low: Vector2, high: Vector2) {
            let near = Double(at), far = Double(at) + deep * inward
            return upright ? (Vector2(min(near, far), from), Vector2(max(near, far), to))
                           : (Vector2(from, min(near, far)), Vector2(to, max(near, far)))
        }

        func meets(_ other: Swept) -> Bool {
            let a = box, b = other.box
            return a.low.x < b.high.x && b.low.x < a.high.x && a.low.y < b.high.y && b.low.y < a.high.y
        }
    }
}

↑↓ move ↩ open