WarpGrid
A checkerboard of rects warped under the mouse (drawRect)
- Run
swift run --package-path Examples Example-Patterns-WarpGrid- Source
- Examples/Patterns/WarpGrid/Sketch.swift
// Ported from the p5.js sketch week-4/pattern-2 (MIT) in
// https://github.com/eaviles/rtp-sfpc-f21-p5 — itself a p5 port of Zach
// Lieberman's openFrameworks sample for the RTP class at SFPC, Fall 2021
// (https://github.com/ofZach/RTP_SFPC_F21). Reworked for Ollin's API.
import Foundation
import Ollin
/// A 30×30 checkerboard of rectangles whose columns warp toward one edge. Each
/// column's left/right edge is a 0...1 fraction raised to a `mouseX`-driven
/// power (`pow`), so moving the cursor squeezes the columns to one side and
/// stretches the rest — the checkerboard breathes horizontally under the mouse.
///
/// Demonstrates `drawRect`: every cell is one `drawRect(x, y, width, height)`, filled
/// black or white by an `(i + j)` parity rule. Until the mouse first moves the
/// grid breathes by itself, on a slow sweep that stands in for the cursor, so
/// a window nobody has touched and an export both show it at work.
@main
final class WarpGrid: Sketch {
override func setup() {
noStroke()
}
override func draw() {
background(.black)
let cellHeight = width / 30
// What drives the power: the cursor once it has moved (`mouseX` starts
// at 0, which would leave every column at zero width), and a sweep of
// its own before that.
let drive = mouseX > 0 ? mouseX : map(sin(time * 0.6), -1, 1, 0.12, 0.88) * width
for i in 0..<30 {
// Column edges, warped by that power curve. `i`-only, so hoisted out
// of the inner loop.
let leftPct = pow(map(Double(i), 0, 30, 0, 1), drive * 0.01)
let rightPct = pow(map(Double(i + 1), 0, 30, 0, 1), drive * 0.01)
let left = map(leftPct, 0, 1, 0, width)
let right = map(rightPct, 0, 1, 0, width)
for j in 0..<30 {
let y = map(Double(j), 0, 30, 0, width)
fill((i + j) % 2 == 0 ? .white : .black)
drawRect(left, y, right - left, cellHeight)
}
}
}
}