# Asendorf Grids Screensaver: Agent Build Guide

Nov 17, 2026 · @Anthony

## Goal

Build an offline macOS screensaver, "Asendorf Grids.saver", that plays Kim Asendorf's generative pieces natively in Metal and switches to a random one every 60 seconds. It took about a day with dead ends. Following this guide should take 1–2 hours.

| Collection | Source | Variants | Year |
| --- | --- | --- | --- |
| Rainbow Grid | [rainbowgrid.xyz](https://rainbowgrid.xyz) | 54 ("P16-2F" … "L64-2B") | 2021 |
| monogrid | [monogrid.xyz](https://monogrid.xyz) | 256 (ids "00" … "ff") | 2021 |
| Sabotage | [sabotage.kim](https://sabotage.kim) | 263 minted tokens (#1–256, #1001–1005, #1007, #1008) | 2022 |

Rotation picks a collection uniformly, then a variant within it. The current scene's name and ID (e.g. "Sabotage #35") is shown bottom-left in the 24 pt system font, white with a soft black shadow. It stays for 10 s after each scene starts, then fades out over 1.5 s (opacity computed per frame from the scene start time, implicit animations disabled). The finished bundle is about 1.1 MB, runs at 60 fps at full screen, and needs no network.

Do not ship the original HTML/WebGL in a WKWebView. On current macOS it renders black inside the screensaver host (see the next section). Port each piece to Swift + Metal instead: every piece is a small GLSL feedback simulation plus a JS grid generator, so the port is mechanical.

## macOS pitfalls (read first)

Each of these produced a black screen and cost hours. Tested on macOS 26/27 (Darwin 27), Apple Silicon.

| Symptom | Cause | Fix |
| --- | --- | --- |
| WKWebView / WebGL saver is black, in preview and full screen | Legacy .saver bundles run inside sandboxed `legacyScreenSaver` and are shown remotely by WallpaperAgent; WebKit's GPU output never arrives | Native Metal only |
| Intermittent black runs, frames stop after a few seconds | `MTKView`'s display link pauses because the hosting window reports itself occluded | No MTKView. Drive frames with your own `Timer` at 1/60 s added to `RunLoop.main` in `.common` mode |
| Some runs fully black although frames are drawn | macOS reuses the same `ScreenSaverView` across runs (plus creates a new one each run). Adding/removing a Metal subview on the reused, remotely displayed view sometimes never reaches the screen | Make the `ScreenSaverView` itself layer-backed by a `CAMetalLayer` for its whole life: override `makeBackingLayer()`, `wantsUpdateLayer = true`, empty `updateLayer()`, `layerContentsRedrawPolicy = .never`. Never add subviews. Overlays (the scene label) go in a CATextLayer added to that backing layer once in makeBackingLayer(); afterwards change only its string and frame, with implicit actions disabled |
| Rendering keeps going after the user dismisses the saver | `stopAnimation` is not always called | Also observe the distributed notification `com.apple.screensaver.willstop`; 2 s later, stop if `window?.isVisible` is false |
| System Settings preview tile shows black | Same remote-display limitation; unsolved | Accept it. Start rendering from `viewDidMoveToWindow` too, since the preview often never gets `startAnimation` |
| No `metal` compiler on the machine | Command Line Tools lack the Metal toolchain | Ship `.metal` source in Resources and compile at runtime with `device.makeLibrary(source:options:)`; set `mathMode = .safe` on macOS 15+, else `fastMathEnabled = false` |

Other facts:

- Screenshots (`screencapture`) do not capture the running screensaver, and its sandbox container can't be read. Verify by logging (see Testing).
- `killall ScreenSaverEngine` and `caffeinate -u` do not reliably dismiss it on this OS. Warn the user before you launch the real saver with `open -a ScreenSaverEngine`; they will have to move the mouse.
- After installing a new build, `killall legacyScreenSaver` so the old binary is unloaded.
- Keep the Objective-C principal class name unique (`@objc(RainbowGridView)` here). Two installed bundles with the same class name clash.

## Project layout and build

No Xcode project is needed: one shell script compiles all Swift files with `swiftc`, assembles the bundle and ad-hoc signs it.

| File | Role |
| --- | --- |
| `RainbowGridView.swift` | The `ScreenSaverView` (principal class). CAMetalLayer backing, 60 Hz timer, lifecycle, rotation every 60 s, logging, one-time health check |
| `Artwork.swift` | `ArtworkRenderer` protocol, `ArtworkContext`, `ArtworkVariant`, runtime shader cache, `ArtworkCatalog` (random pick) |
| `RainbowGridEngine.swift` + `RainbowGrid.metal` | Rainbow Grid port |
| `Monogrid.swift` + `Monogrid.metal` | monogrid port |
| `Sabotage.swift` + `Sabotage.metal` + `resources/sabotage-params.json` | Sabotage port (params \~234 KB) |
| `build.sh` | Build, sign, `./build.sh install` |
| `thumbnail.png`, `thumbnail@2x.png` | Tile in System Settings |

The renderer interface every collection implements:

```swift
protocol ArtworkRenderer: AnyObject {
    // Advance the simulation one step and draw into the screen drawable's pass.
    func draw(into pass: MTLRenderPassDescriptor, commandBuffer: MTLCommandBuffer, now: CFTimeInterval)
    var currentTexture: MTLTexture { get }   // .shared storage, read back once for the health check
}
struct ArtworkContext { let device: MTLDevice; let pixelFormat: MTLPixelFormat
    let widthPoints: Int; let heightPoints: Int; let scale: Double }
struct ArtworkVariant { let collection: String; let name: String
    let make: (ArtworkContext) -> ArtworkRenderer? }
```

Build script essentials:

1. For `arm64` and `x86_64`: `swiftc -O -target <arch>-apple-macos13.0 -module-name RainbowGrid -emit-library -Xlinker -bundle -framework ScreenSaver -framework Metal -framework QuartzCore -framework AppKit *.swift`, then `lipo -create`.
2. Bundle `Asendorf Grids.saver/Contents/{MacOS,Resources,Info.plist}`. Copy all `.metal` files, `resources/`, and thumbnails into Resources.
3. Info.plist: `CFBundleIdentifier` (e.g. `local.rainbowgrid.saver`), `CFBundleName`/`CFBundleDisplayName` "Asendorf Grids", `CFBundlePackageType` BNDL, `NSPrincipalClass` = the view class, `LSMinimumSystemVersion` 13.0.
4. `codesign --force --deep --sign - <bundle>`.
5. Install: copy to `~/Library/Screen Savers/`, then `killall legacyScreenSaver`. The user selects it in System Settings → Screen Saver.

View-side render loop, per frame: match `drawableSize` to bounds × `backingScaleFactor`; create the renderer at the view size in points (floor); `nextDrawable()`; `renderer.draw`; present and commit. If the renderer fails to build, log it and pick another variant. An env var (`RG_VARIANT="monogrid 4a"`) that forces a variant makes testing much easier.

## Porting the three collections

All three share one architecture: a JS generator fills an RGBA8 image at CSS-pixel (point) resolution, then a GLSL fragment shader runs a feedback step between two ping-pong textures every frame, with the untouched initial image as a third "original" texture. Port the generator line by line into Swift and the shaders into Metal. Fetch the originals with `curl` and read their unminified `lib/*.js` modules inside `bundle.js` (browserify).

### Shared GLSL → Metal rules

- Textures: `rgba8Unorm`, `.shared` storage, nearest filtering, clamp-to-edge, matching WebGL.
- One full-screen triangle as vertex shader; uniforms passed with `setFragmentBytes` (dims, time, 16 × float4 rects).
- GLSL `mod` is floored: define `mod(x, y) = x - y * floor(x / y)` helpers; Metal's `fmod` truncates and breaks the noise.
- `mat2(a,b,c,d)` → `float2x2(float2(a,b), float2(c,d))`; drop precision qualifiers; `#define vec2 float2` etc. saves time.
- Coordinates: texture row 0 = GL y = 0. The step pass uses `uv = position.xy / dims`. The present pass uses `uv = 0.5 * (p + 1)` so row 0 lands at the bottom of the screen, like WebGL.
- Present = nearest-neighbour upscale from points to the drawable's pixels.
- Effect slots: 16 slots each point at a random rectangle from the generator; re-roll each slot on a timer as the JS does.

### Rainbow Grid

- Token metadata: `https://gateway.pinata.cloud/ipfs/QmSGvRD4QpgYtzc9EzgXyCf6Ky89b3CfbE6m3UXyj9EYF3/<0–53>.json`. Each `animation_url` is its own IPFS HTML with the variant baked in (e.g. P16-2F = `QmYS2Uo4qvpqZ7W8k4rPwzaNNTQeHQWQ5u9KcCYfoeNwLR`). `ipfs.io` and Pinata refuse HTML; `ipfs.filebase.io` or `ipfs2.seadn.io` work.
- 54 variants = size `s` 0–8 × style `u` 0–5. Name: P (u<3) or L, min rect, colours, F/FB/B.
- minRect = 16·ceil((s+1)/3) + 16·floor(s/6) (16/32/64). numColors = \[2,4,7,7,4,2\]\[u\]. colorMode = s % 3 (0 F: bg black, fg random; 1 FB: both non-black; 2 B: bg random, fg black).
- Pixel size \[0,1) for P, \[2,8) for L; gap \[2,10) for P, \[2,3) for L; split probability 0.98 both ways.
- Palette index 0–6: black, red, green, blue, yellow, cyan, magenta. Effect slots re-roll every 0–5 s. Step shader ends with a small hue shift (0.05).
- Many "F" variants are mostly black; that is faithful to the original, not a bug.

### monogrid

- Source: `https://monogrid.xyz/bundle.js` (`lib/grid-generator.js`, `lib/app-default.js`). Each work is `/id/<row><col>` with two hex digits.
- From d = row, p = col: balance = d < 8 ? 1 − p/15 : p/15; r = floor(max(1, d−6)/2); pixelSize \[max(0,d−8)−r, max(1,d−7)+r); a = floor(max(1, 9−d)/2); gap \[max(2,9−d)−a, max(3,10−d)+a); splitH = 1 − 0.064·(|p−7.5|−0.5); splitV same with d; min rect 32.
- Grid starts all white (1); each rect is black-on-white or inverted by `random < balance`. The very first split always keeps both halves. A zero period means "not lit" (JS NaN).
- Only framebuffer 0 gets the grid; framebuffer 1 starts black. Slots re-roll after floor(8000·rand) ms.

### Sabotage

- Engine: `https://sabotage.kim/scripts/single.js` (`lib/app-instance.js`, `pattern-generator.js`, `symbol-pattern.js`, `utils.js`, plus the `simplex-noise` package's `noise2D`).
- Params: each `https://sabotage.kim/id/<N>` embeds `const data = JSON.parse('{…}')`. Scrape 1–256 and 1001–1008 into one JSON array; drop `cover`/thumbnail fields. #257–1000 were never minted; #1006 is null.
- Canvas = CSS pixels / `canvasScale`, tiled with square cells (`numberRows` rows). Each cell gets a symbol from 8 groups (Grids, Lines, Pixels, Colors, Dots, Gradients, RadialGradients, Compositions) chosen by noise or random with `symbol*Weight`.
- Feedback: even frames shift some rows left/right (entering pixels come from the reference pattern); odd frames shift the "saboteur" columns down. A final pass applies RGB offsets, hue rotation/animation and the gradient.
- Route every `Math.random()` through one swappable function so you can seed it and diff against the JS pixel for pixel. Emulate `Uint8Array` stores (NaN → 0, truncate, mod 256) and `Math.round`.
- Black strips at top/right edges are expected: the cell grid doesn't divide the screen evenly, same as the site.

## Testing and verification

Test in a window first, and touch the real screensaver only at the end, with the user's OK.

- **Harness app:** a \~60-line Swift app that `Bundle(path:).load()`s the .saver, instantiates `principalClass` as a `ScreenSaverView` in a 900×560 window, calls `startAnimation`, waits \~8 s and runs `screencapture -l <windowID>`. Pass `RG_VARIANT` to force a variant. This catches nearly every rendering bug.
- **Reference images:** render the original HTML in headless Chrome (`--headless --screenshot --window-size=900,560 --virtual-time-budget=8000`) and compare side by side. The patterns are random, so compare style, density and colour, not pixels, except Sabotage with seeded randomness.
- **Generator statistics:** run the JS generator and the Swift port \~300 times each (node vs a Swift test) and compare rect counts and black/white ratio.
- **Logging:** use `os.Logger(subsystem: "local.rainbowgrid.saver")`. Log "started \<variant> at WxH", fps every 30 s, stop reasons, shader compile errors. Read with `log show --last 5m --predicate 'subsystem == "local.rainbowgrid.saver"'`.
- **Health check:** at frame 120, read back `currentTexture` in the command buffer's completion handler and log how many sampled pixels are non-black. This is the only way to confirm the real (unscreenshottable) screensaver is drawing.
- **Real run:** `open -a ScreenSaverEngine`, then check the log for each new view instance. Expect two instances per run (the reused one and a new one); both should log started + healthy.

Results from the reference build: all three collections at 59.8–60 fps full screen on Apple Silicon; Sabotage pixel-identical to the JS for 17 seeded tokens (two gradient tokens differ by at most one level in a few dozen pixels).

## Checklist for the agent

1. Confirm the Mac has Swift (`swiftc --version`). No Xcode or Metal toolchain needed.
2. Write `RainbowGridView.swift` and `Artwork.swift` with the CAMetalLayer-backed view, own 60 Hz timer, willstop observer and runtime shader compile. Get a solid-colour test renderer showing in the harness.
3. Download Rainbow Grid's `bundle.js`; port the grid generator and the step/present shaders. Verify P16-7FB and L64-4B in the harness against headless Chrome.
4. Port monogrid (generator + shaders); verify "4a" and "87".
5. Scrape Sabotage params to `resources/sabotage-params.json`; port the pattern generator, symbols, simplex noise and shaders; verify a seeded token pixel for pixel.
6. Wire all three into `ArtworkCatalog`; set rotation to 60 s.
7. Write `build.sh` (universal binary, Info.plist named "Asendorf Grids", ad-hoc sign, install).
8. Install, then ask the user before starting the real saver; check the log for started + health lines; have the user select it in System Settings.

The three ports are independent; run steps 3–5 in parallel subagents once step 2 works. The original source of this build exists as a folder of Swift/Metal files; ask its owner for a copy if you'd rather start from it.
