# CodigoDeBarras

upright bars of yarn, each a whole number of units long, over fields of close tones.

Run it with `swift run --package-path Examples Example-Recreations-EduardoTerrazas-CodigoDeBarras`.

```swift
//  Recreation after Eduardo Terrazas - Posibilidades de una estructura,
//  subserie Código de barras (Barcode). The tablas pictured on his page are
//  yarn on board, and one picture there is filed as 1.5.6. A homage, not a
//  reproduction of any one tabla, and not affiliated with or endorsed by the
//  artist or his galleries.
//  https://eduardoterrazas.com/index.php/barcode/
//  https://eduardoterrazas.com/index.php/possibilities-of-a-structure/
//
//  An original Ollin interpretation, written from the two sentences his site
//  gives the subseries and from the four tablas pictured on his page. One of
//  them was measured on a grid. The rule that deals the bars is this
//  sketch's own. Nothing was ported: the work is yarn pressed into wax.

import Foundation
import Ollin

/// Código de barras (Eduardo Terrazas). One of the five subseries of
/// *Posibilidades de una estructura*. His site ties it to the talk of its
/// time about programming and cybernetics. "Through a play of parallel
/// lines, these works by Terrazas refer to bar codes, commercially
/// introduced in the late 1960s."
///
/// The parallel lines are upright bars of yarn. Read on a grid, the tabla
/// his site files as 1.5.6 is 40 units a side. Every bar is one unit wide
/// and a whole number of units long. A level line crosses the board 30
/// units down. A bar stands on the bottom edge, stands on that line, or
/// hangs from the top edge, and no two need be the same length. Bars come
/// in a dark wool and a light one. Behind them, wider upright fields in a
/// few close tones fill the board above the line and below it.
///
/// This sketch deals such a tabla from a number. `units` is how many bar
/// widths the side holds, and `horizon` how far down the level line lies.
/// `bars` is the share of the columns that hold a bar. A bar beside another
/// takes the other wool, and most bars after a gap do too. Now and then a
/// bar's column is finished in the other wool, which makes one line of two
/// wools from top to bottom. `wools` picks the set: the blues of the tabla
/// measured, the grays with a pale green, or the bright set with yellow
/// bars.
///
/// Every piece is laid the way he describes the yarn: one strand, then
/// another and another in parallel lines that follow its outline. A bar's
/// strands run its length and turn at its two ends, which leaves the small
/// arrowheads the photographs show.
///
/// Try it: `firstTabla` is the number the cycle starts from, and a click
/// takes the next one. `tablas` is how many the cycle shows. Over one cycle
/// of `seconds` each tabla is held and then laid over by the next. The new
/// one comes in from the left, each column from the bottom up. So the bars
/// rise in turn, the way a code is read. That cycle is also the export loop.
///
/// `--export-svg` writes every piece of yarn as a closed rectangle in its
/// color.
@main
final class CodigoDeBarras: Sketch {
    enum Wools: String, CaseIterable, ParamOption { case blue, gray, bright }

    /// How many bar widths the side of the board holds.
    @Param(24 ... 80, icon: "ruler") var units = 40
    /// How far down the board the level line lies, as a part of its side.
    @Param(0.5 ... 0.9, icon: "minus") var horizon = 0.75
    /// The share of the columns that hold a bar.
    @Param(0.1 ... 0.9, icon: "barcode") var bars = 0.6
    /// The set of wools the tabla is laid in.
    @Param(icon: "swatchpalette") var wools = Wools.blue
    /// How round the strands read: 0 is flat color.
    @Param(0 ... 1, icon: "sun.max") var relief = 0.7
    /// The number of the first tabla of the cycle, counted on from the seed.
    @Param(0 ... 9999, icon: "dice") var firstTabla = 0
    /// How many tablas one cycle shows, one after another.
    @Param(1 ... 6, icon: "square.stack") var tablas = 3
    /// One cycle: each tabla held, then laid over by the next.
    @Param(6 ... 120, icon: "clock") var seconds = 24.0

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

    /// Where the tabla's middle sits, and half its side, in pixels.
    nonisolated static let center = Vector2(540, 540)
    nonisolated static let half = 420.0

    // MARK: - One tabla

    /// One piece of yarn: a rectangle of whole units, and its wool.
    struct Field: Equatable {
        var column: Int, row: Int, columns: Int, rows: Int
        var wool: Int
    }

    /// One possibility: the wool in every unit square of the board, and the
    /// rectangles those squares make up. The ground tones are numbered from
    /// 0, and the two bar wools follow them, the dark one first.
    struct Tabla {
        var units: Int
        var line: Int
        var cells: [Int]
        var fields: [Field]
    }

    /// Deals a tabla from its number. The fields above the level line come
    /// first, side by side from the left. Most take the first tone for
    /// their whole height. The others take another tone for all of it, for
    /// a part hung from the top, or for a part standing on the line. Then
    /// the fields below the line, no two neighbors alike. Then the bars, a
    /// column at a time from the left. Every draw is made for every column,
    /// bar or no bar. So one bar more or less leaves the rest of the tabla
    /// as it was dealt.
    nonisolated static func deal(number: Int, units n: Int, horizon: Double, bars: Double,
                                 tones: Int, calm: Double, lightTone: Int?) -> Tabla {
        var rng = SplitMix64(seed: UInt64(bitPattern: Int64(number &* 1_000_003 &+ 156)))
        func unit() -> Double { Double(rng.next() >> 11) / Double(1 << 53) }
        func pick(_ count: Int) -> Int { min(count - 1, Int(unit() * Double(count))) }
        func between(_ low: Int, _ high: Int) -> Int { low + pick(max(1, high - low + 1)) }

        let line = min(n - 2, max(2, Int((horizon * Double(n)).rounded())))
        var cells = [Int](repeating: 0, count: n * n)
        func lay(_ column: Int, _ rows: Range<Int>, _ wool: Int) {
            for row in rows where row >= 0 && row < n { cells[row * n + column] = wool }
        }
        let narrow = max(2, n / 20), wide = max(narrow + 1, n / 5)

        // Above the line.
        var column = 0, last = -1
        while column < n {
            let width = min(n - column, between(narrow, wide))
            let quiet = unit() < calm
            var tone = 1 + pick(tones - 1)
            let how = pick(3)
            let tall = between(max(2, line / 4), max(3, line * 3 / 4))
            if quiet || tone == last { tone = 0 }
            for at in column ..< column + width {
                lay(at, 0 ..< line, 0)
                switch how {
                case 0: lay(at, 0 ..< line, tone)
                case 1: lay(at, 0 ..< tall, tone)
                default: lay(at, line - tall ..< line, tone)
                }
            }
            last = tone
            column += width
        }

        // Below the line.
        column = 0
        last = -1
        while column < n {
            let width = min(n - column, between(narrow, wide + narrow))
            var tone = pick(tones)
            if tone == last { tone = (tone + 1) % tones }
            for at in column ..< column + width { lay(at, line ..< n, tone) }
            last = tone
            column += width
        }

        // The bars.
        let dark = tones, light = tones + 1
        let low = n - line
        var wool = unit() < 0.5 ? dark : light
        var beside = false
        var halves: [(Int, Range<Int>, Int)] = []
        for at in 0 ..< n {
            let has = unit() < bars
            let stand = unit(), length = unit(), partner = unit(), same = unit()
            guard has else {
                beside = false
                continue
            }
            // A bar right beside another always takes the other wool, so
            // the two stay two bars. After a gap most bars change wool too.
            if beside || same >= 0.25 { wool = wool == dark ? light : dark }
            beside = true
            let rows: Range<Int>
            if stand < 0.4 {
                // Standing on the bottom edge: short, up to the line, or on
                // through it.
                let long: Int
                if length < 0.4 {
                    long = 1 + Int(length / 0.4 * Double(max(1, low - 1)))
                } else if length < 0.5 {
                    long = low
                } else {
                    long = low + 1 + Int((length - 0.5) / 0.5 * Double(line - 1))
                }
                rows = n - long ..< n
            } else if stand < 0.7 {
                // Standing on the line.
                rows = line - (2 + Int(length * Double(line - 2))) ..< line
            } else {
                // Hanging from the top edge.
                rows = 0 ..< 1 + Int(length * Double(line - 1))
            }
            // A light bar on a ground of its own color would not show, so
            // it is left out, and the column counts as empty.
            if wool == light, let twin = lightTone, rows.contains(where: { cells[$0 * n + at] == twin }) {
                beside = false
                continue
            }
            lay(at, rows, wool)
            // Now and then the rest of the column is to be laid in the
            // other wool: one line of two wools, top to bottom.
            if partner < 0.2, stand < 0.4 || stand >= 0.7 {
                let rest = stand < 0.4 ? 0 ..< rows.lowerBound : rows.upperBound ..< n
                halves.append((at, rest, wool == dark ? light : dark))
            }
        }
        // Those other halves go down last. One is laid only where it would
        // touch no bar of its own wool beside it and would show against its
        // ground. So a bar always stays one unit wide.
        for (at, rows, wool) in halves {
            let touches = rows.contains { row in
                (at > 0 && cells[row * n + at - 1] == wool) || (at + 1 < n && cells[row * n + at + 1] == wool)
            }
            var hidden = false
            if wool == light, let twin = lightTone { hidden = rows.contains { cells[$0 * n + at] == twin } }
            if !touches && !hidden { lay(at, rows, wool) }
        }

        let pieces = fields(of: cells, units: n, line: line, tones: tones)
        return Tabla(units: n, line: line, cells: cells, fields: pieces)
    }

    /// The rectangles a board of unit squares is laid in. A piece is an
    /// upright run of one wool, joined to the runs beside it that begin and
    /// end on the same rows. A ground tone stops at the level line, so the
    /// fields above it and below it are laid apart; a bar runs through.
    nonisolated static func fields(of cells: [Int], units n: Int, line: Int, tones: Int) -> [Field] {
        var taken = [Bool](repeating: false, count: n * n)
        var found: [Field] = []
        for column in 0 ..< n {
            for row in 0 ..< n where !taken[row * n + column] {
                let wool = cells[row * n + column]
                /// Whether the wool runs on from one row into the next.
                func joins(_ above: Int, _ at: Int) -> Bool {
                    guard above >= 0, above + 1 < n else { return false }
                    if wool < tones, above + 1 == line { return false }
                    return cells[above * n + at] == wool && cells[(above + 1) * n + at] == wool
                }
                var bottom = row + 1
                while bottom < n, joins(bottom - 1, column), !taken[bottom * n + column] { bottom += 1 }
                var right = column + 1
                while right < n {
                    let whole = (row ..< bottom).allSatisfy {
                        cells[$0 * n + right] == wool && !taken[$0 * n + right]
                    }
                    if !whole || joins(row - 1, right) || joins(bottom - 1, right) { break }
                    right += 1
                }
                for r in row ..< bottom { for c in column ..< right { taken[r * n + c] = true } }
                found.append(Field(column: column, row: row, columns: right - column, rows: bottom - row,
                                   wool: wool))
            }
        }
        return found
    }

    // MARK: - The yarn

    /// The four parts a rectangle of yarn is laid in. Its strands run
    /// beside its own edges and work inward. That makes two long parts
    /// whose strands run its length, and two ends where they turn. Each
    /// part comes with the way its strands lie: 0 level, 1 upright.
    nonisolated static func parts(_ box: Rectangle) -> [(outline: [Vector2], lay: Int)] {
        let x0 = box.x, y0 = box.y, x1 = box.x + box.width, y1 = box.y + box.height
        let inset = min(box.width, box.height) / 2
        let a = Vector2(x0 + inset, y0 + inset), b = Vector2(x1 - inset, y0 + inset)
        let c = Vector2(x1 - inset, y1 - inset), d = Vector2(x0 + inset, y1 - inset)
        return [
            ([Vector2(x0, y0), Vector2(x1, y0), b, a], 0),
            ([Vector2(x1, y0), Vector2(x1, y1), c, b], 1),
            ([Vector2(x1, y1), Vector2(x0, y1), d, c], 0),
            ([Vector2(x0, y1), Vector2(x0, y0), a, d], 1),
        ]
    }

    /// A convex outline cut to an upright box.
    nonisolated static func cut(_ outline: [Vector2], to box: Rectangle) -> [Vector2] {
        var result = outline
        let planes: [(Double, Double, Double)] = [
            (-1, 0, -box.x), (1, 0, box.x + box.width), (0, -1, -box.y), (0, 1, box.y + box.height),
        ]
        for (a, b, c) in planes where result.count >= 3 {
            var kept: [Vector2] = []
            for index in result.indices {
                let p = result[index], q = result[(index + 1) % result.count]
                let dp = a * p.x + b * p.y - c, dq = a * q.x + b * q.y - c
                if dp <= 0 { kept.append(p) }
                if (dp < 0 && dq > 0) || (dp > 0 && dq < 0) { kept.append(p + (q - p) * (dp / (dp - dq))) }
            }
            result = kept
        }
        // Drop a corner that the cut or a narrow piece has doubled.
        var clean: [Vector2] = []
        for point in result where clean.last.map({ ($0 - point).length > 1e-9 }) ?? true { clean.append(point) }
        if let first = clean.first, let end = clean.last, clean.count > 1, (first - end).length <= 1e-9 {
            clean.removeLast()
        }
        return clean.count >= 3 ? clean : []
    }

    /// One strand of yarn, run at every pixel of a piece. Strands are
    /// counted from the board's upper left corner, level or upright. So the
    /// pieces share their rows, and a bar is a whole number of strands wide.
    private static let yarn = """
    static float3 barrasWool(float v) {
        float r = floor(v / 65536.0);
        float g = floor((v - r * 65536.0) / 256.0);
        float b = v - r * 65536.0 - g * 256.0;
        return float3(r, g, b) / 255.0;
    }

    float4 shade(float2 uv, ShaderInfo info) {
        float2 p = info.position - float2(param(info, 0), param(info, 1));
        float pitch = param(info, 2);
        float relief = param(info, 3);
        float lay = param(info, 4);
        float3 wool = srgbToLinear(barrasWool(param(info, 5)));

        // `across` is the way the strands are counted and `run` the way
        // they lie.
        float2 across = lay < 0.5 ? float2(0.0, 1.0) : float2(1.0, 0.0);
        float2 run = float2(across.y, across.x);
        float x = dot(p, across) / pitch;
        float along = dot(p, run) / pitch;

        float strand = floor(x);
        float f = fract(x) * 2.0 - 1.0;
        float lot = hash12(float2(strand, 23.0 + lay * 29.0));
        float rise = sqrt(max(0.0, 1.0 - f * f));
        float3 normal = normalize(float3(across * f, rise + 0.35));
        float ply = sin((along / 3.0 + f * 0.5 + lot) * 6.2831853);
        normal = normalize(normal + float3(run * ply * 0.35, 0.0));
        float lit = max(dot(normal, normalize(float3(-0.45, -0.6, 0.66))), 0.0);
        float groove = smoothstep(1.0, 0.72, abs(f));
        float fiber = valueNoise(float2(along * 0.9 + lot * 40.0, x * 7.0)) - 0.5;
        float tone = mix(1.0, (0.50 + 0.58 * lit) * mix(0.66, 1.0, groove), relief);
        tone *= 1.0 + relief * (0.10 * fiber + 0.07 * (lot - 0.5));
        return float4(linearToSrgb(wool * tone), 1.0);
    }
    """

    // MARK: - Drawing

    private let wall = Color(hex: 0xE9E6DF)
    private let oak = Color(hex: 0xB89A72)
    private let recess = Color(hex: 0x2B2622)

    /// A set of wools: the ground tones and the two bar wools. `calm` is
    /// how often a field above the line keeps the first tone. `lightTone`
    /// is the ground tone, if any, that is the light bar's own color.
    private struct WoolSet {
        var grounds: [Color]
        var dark: Color, light: Color
        var calm: Double
        var lightTone: Int?
    }

    private var woolSet: WoolSet {
        switch wools {
        case .blue:
            // Sampled from the picture filed as 1.5.6, a little lighter.
            return WoolSet(grounds: [Color(hex: 0x8FB0DB), Color(hex: 0x4670BF), Color(hex: 0xE9E7E0)],
                       dark: Color(hex: 0x17171A), light: Color(hex: 0xE9E7E0), calm: 0.7, lightTone: 2)
        case .gray:
            return WoolSet(grounds: [Color(hex: 0x8E8E8C), Color(hex: 0xB4B4B0), Color(hex: 0x4A4A4C),
                                     Color(hex: 0xA7BC8A)],
                           dark: Color(hex: 0x141416), light: Color(hex: 0xE6E4DC), calm: 0.35, lightTone: nil)
        case .bright:
            return WoolSet(grounds: [Color(hex: 0xB8122E), Color(hex: 0x5A8FD6), Color(hex: 0x8FA651),
                                 Color(hex: 0x1C4C7C), Color(hex: 0xB84A1E), Color(hex: 0xC2468E)],
                       dark: Color(hex: 0x1658B8), light: Color(hex: 0xE6CC52), calm: 0.15, lightTone: nil)
        }
    }

    private var kept: [String: Tabla] = [:]

    /// The tabla at a place in the cycle, dealt once and kept.
    private func tabla(at index: Int, in set: WoolSet) -> Tabla {
        let number = variation &+ firstTabla &+ index
        let name = "\(number)/\(units)/\(horizon)/\(bars)/\(wools.rawValue)"
        if let found = kept[name] { return found }
        if kept.count > 60 { kept.removeAll() }
        let made = CodigoDeBarras.deal(number: number, units: units, horizon: horizon, bars: bars,
                                       tones: set.grounds.count, calm: set.calm, lightTone: set.lightTone)
        kept[name] = made
        return made
    }

    override func mousePressed() {
        firstTabla = firstTabla >= 9999 ? 0 : firstTabla + 1
    }

    override func draw() {
        let set = woolSet
        let c = CodigoDeBarras.center, h = CodigoDeBarras.half
        let n = Double(units), unit = 2 * h / n
        let left = c.x - h, top = c.y - h

        background(wall)
        noStroke()
        fill(oak)
        drawRect(center: c, width: 2 * h + 64, height: 2 * h + 64)
        fill(recess)
        drawRect(center: c, width: 2 * h + 36, height: 2 * h + 36)

        // Where the cycle is: a tabla held, or the next one being laid
        // over it. `swept` counts columns from the left, and a column takes
        // `front` columns' time to be laid from the bottom up.
        let count = max(1, tablas)
        let place = loopProgress(over: seconds) * Double(count)
        let slot = min(count - 1, Int(place)), within = place - Double(slot)
        let front = max(4, n / 4)
        let swept = within < 0.42 ? 0 : (within - 0.42) / 0.58 * (n + front)
        let old = tabla(at: slot, in: set), new = tabla(at: (slot + 1) % count, in: set)

        // The boxes each tabla shows through. The new one shows in the
        // columns already laid, the old one in the columns not yet reached.
        // Each column in between is cut at the height the yarn has come to.
        var boxes: [(tabla: Tabla, box: Rectangle)] = []
        let done = min(n, max(0, (swept - front).rounded(.down) + (swept >= front ? 1 : 0)))
        let untouched = min(n, max(done, swept.rounded(.up)))
        if done > 0 { boxes.append((new, Rectangle(x: left, y: top, width: done * unit, height: 2 * h))) }
        if untouched < n {
            let rest = Rectangle(x: left + untouched * unit, y: top, width: (n - untouched) * unit, height: 2 * h)
            boxes.append((old, rest))
        }
        var column = done
        while column < untouched {
            let risen = min(1, max(0, (swept - column) / front)) * 2 * h
            let x = left + column * unit
            if risen < 2 * h { boxes.append((old, Rectangle(x: x, y: top, width: unit, height: 2 * h - risen))) }
            if risen > 0 { boxes.append((new, Rectangle(x: x, y: top + 2 * h - risen, width: unit, height: risen))) }
            column += 1
        }

        func color(of wool: Int) -> Color {
            wool < set.grounds.count ? set.grounds[wool] : (wool == set.grounds.count ? set.dark : set.light)
        }
        func pixels(_ field: Field) -> Rectangle {
            Rectangle(x: left + Double(field.column) * unit, y: top + Double(field.row) * unit,
                      width: Double(field.columns) * unit, height: Double(field.rows) * unit)
        }

        if isVectorExporting {
            for (tabla, box) in boxes {
                for field in tabla.fields {
                    let whole = pixels(field)
                    let outline = CodigoDeBarras.cut(whole.contour.points, to: box)
                    guard !outline.isEmpty else { continue }
                    fill(color(of: field.wool))
                    drawPolygon(outline)
                }
            }
            return
        }

        // Pieces are put down a wool and a lay at a time, so that every
        // piece sharing a paint is drawn in one go. No two pieces overlap,
        // so the order does not change the picture.
        let woolCount = set.grounds.count + 2
        var groups = [[[Vector2]]](repeating: [], count: 2 * woolCount)
        for (tabla, box) in boxes {
            for field in tabla.fields {
                let whole = pixels(field)
                guard whole.x < box.x + box.width, whole.x + whole.width > box.x,
                      whole.y < box.y + box.height, whole.y + whole.height > box.y else { continue }
                for part in CodigoDeBarras.parts(whole) {
                    let outline = CodigoDeBarras.cut(part.outline, to: box)
                    if !outline.isEmpty { groups[part.lay * woolCount + field.wool].append(outline) }
                }
            }
        }
        // A bar is a whole number of strands wide, three pixels or so each.
        let pitch = unit / max(3, (unit / 3).rounded())
        func packed(_ color: Color) -> Float {
            let r = (color.red * 255).rounded(), g = (color.green * 255).rounded()
            let b = (color.blue * 255).rounded()
            return Float(r * 65536 + g * 256 + b)
        }
        for (key, outlines) in groups.enumerated() where !outlines.isEmpty {
            fill(Shader(CodigoDeBarras.yarn, params: [
                Float(left), Float(top), Float(pitch), Float(relief), Float(key / woolCount),
                packed(color(of: key % woolCount)),
            ]))
            for outline in outlines { drawPolygon(outline) }
        }
    }
}
```
