Ollin — the shipped-capability inventory
This is the per-feature inventory of everything Ollin ships today, split out of CLAUDE.md so the always-loaded guidance stays small. It is the authoritative answer to "does Ollin already do X, and what must not be broken about it?" — one bullet per capability, each a terse statement of the load-bearing invariants plus pointers to its example, snapshot, tests, and Docs/ page.
Where each kind of fact lives:
- Here — what exists, and the regression-preventing invariants of each shipped capability (terse; a rule whose violation is a bug).
CLAUDE.md— vision, scope, and the cross-cutting policy that spans features (the architecture rule, conventions, sourcing & attribution, the shader/Metal and rendering-performance rules, the ship checklist).ARCHITECTURE.md— engineering internals: the mechanism, the history, and the measurements behind a shipped system.Docs/— the user-facing API reference.ROADMAP.md/DESIGN-NOTES.md— what is ahead, and why it is shaped that way. Never a changelog.Guide/— the narrative book that teaches the capability.
When work ships it lands here, as step (1) of the ship checklist in CLAUDE.md § Roadmap & design notes. Keep bullets terse and route depth to its home: explanation and history to ARCHITECTURE.md, user-facing API to Docs/, forward plans to ROADMAP.md / DESIGN-NOTES.md.
A few load-bearing rules recur across the satellites; they are stated once in CLAUDE.md § Current state rather than repeated per bullet (non-isolated render-thread closures, no defaulted resource:in: bundle, never replacing a GPU texture in place, satellites not depending on each other, and the @unchecked Sendable producer + OSAllocatedUnfairLock handoff shape).
Today (the shipped surface)
Lifecycle & input.
Sketchbase class;setup()may throw (open func setup(; an override may leave) throws throwsoff, so every sketch compiles unchanged): a loader'sFileErrorgoes out with a baretry, the runner'sperformSetupturns it into one sentence on stderr andSketchRunner(readable afterwards, cleared by the next.setupError setup()that runs through, forwarded once throughonSetupError), the window is held with nothing drawn (draw(in:)returns while the sentence stands, as a compile error leaves the stage) until a reload or an asset rerun sets up clean, every headless drive goes throughrunSetup() throwsso an export fails with the sketch's own error, and the in-memory recorders (svg(of:),pdf(of:),gcode(of:),dxf(of:),drafting(of:),stitching(of:),embroidery(of:),spatialScene(of:)) throw with it;SketchSessionsits between the Swift compile error and the shader error in.setupError errorMessage, and both hosts' chips turn red on it (SetupThrowsTests); temporal state (frameCount/time/deltaTime/frameRate); A canvas rebuilds its frame timer when the screen under it can have changed (OllinMTKView: pause then resume on.restartFrameTimer NSWorkspace,.screensDidWakeNotification NSApplication, and the window's.didChangeScreenParametersNotification NSWindow/.didChangeScreenNotification NSWindow, never for a canvas whose loop is held, and asked of the runner, which alone writes the pause): a window opened while no display was awake got an MTKView timer that never fired and stayed blank for good (proven by hand on the lid-closed Studio Display: no frame before or after the wake, about 55 fps from the wake with the fix; a sketch already running when the display slept always recovered);.didChangeOcclusionStateNotification ScreenWakeTestspins the four triggers, the held case, the sleep's hold against aloop()and a night off arriving during it, and the teardown; mouse (mouseX/mouseY, the one-pointmouse: Vector2+previousMouse— snapshotted inadvancebecause the window writes the pointer only when it moves, somouse - previousMouseis a true per-frame delta; first frame's delta is zero, and in-draw remaps (view box,viewControl) never land in it —mouseIsPressed,mousePressed()/mouseReleased()) and keyboard (key/keyCode/keyIsPressed,keyPressed()/keyReleased(),isKeyDown(_:), typedKeyCode;moveAxisreads WASD + arrows as one-1...1Vector2in canvas orientation, up(0, -1), opposite keys canceling). Canvas edges read asshortSide/longSidebeside the per-millescale. The held-flag + release-hook pair makes drag-to-paint adraw()poll. Files dropped on the window arrive asStringpaths through the drainingdroppedFiles()(the house poll-and-clear read) withfilesDropped()fired once per drop after the pointer has moved to the drop point, so a sketch responds at the drop or polls indraw(); the canvas view (OllinMTKView) registers for file URLs and answersdraggingEntered/performDragOperation, mapping the drop through the samecanvasPointthe mouse uses (so a projected run reads the drop in its own canvas), and a drop is live input outside a take (neither recorded nor replayed, since a path is machine-bound). Every host takes it wherever the sketch runs; on the performance stage the editor takes a drop as text while the code shows.DropTests;Examples/. ExamplesImages/ Dropped Input/Drag(grab, per-framemouse - previousMouse, release, and a fling thrown at the hand's averaged speed) +Input/Keys(moveAxispolled indraw(),keyReleased()stamping a ring). What a sketch asks of its window goes through one internal seam,Sketch.host(SketchHost, answered bySketchRunner, nil in every export, so each ask is a no-op there by construction).redraw()wakes anoLoop()sketch for exactly one frame: it is one frame owed (SketchRunner,.drawsOneFrame LoopPass.oneFrame; see Holding the frame loop) and the frame that draws spends it; a refresh that draws nothing (the ring full, a held frame shown) leaves it set, so the frame is late rather than lost; asked insidesetup()/draw()it is spent by that frame, so aredraw()indraw()cannot loop; it passes the timeline's held clock with a zero step.isExportingforwards toOllinApp(.isExporting isRenderingHeadless && !isBenchmarking, the same predicateDrawernow reads), true through setup, warmup, and written frames of every headless drive (still, frames, vector, spatial, web, EXR, contact sheet, widget, each pinned) and false live and under.runsOnFixedClock --bench. The pointer over the canvas (pointerShape(_:),hidePointer()/showPointer(),PointerShapeover the system cursors) is a cursor rect onOllinMTKViewalone, neverNSCursor.hide(), so a host's sidebar keeps the arrow and installation mode's app-wide hide count is never touched; shape and hiding are separate state (a shape set while hidden is the one shown again), a call that changes nothing is one comparison, and the default arrow adds no rect at all.chooseFiles(showswithExtensions: allowsMultiple: ) NSOpenPanelas a sheet over the sketch's window (a free panel without one), so the run loop and the frames keep going; one panel at a time; the pick goes to the instance drawing when the panel closes through the drainingchosenFiles()and thefilesChosen()hook, live input outside a take like a drop; extensions are normalized (dot, case) toUTTypes and an unknown one still matches by name.launchFilesis the files the command line names, as typed and never checked against the disk (a mistyped name has to reach the loader that throws on it):OllinAppreads a word as a file unless it is a flag or the word a flag takes, by the shared flag table (.launchFiles( in: ) LaunchFlags, the.runand.internalUsescopes: a word after a value flag, a whole number after an optional-count flag, nothing after the rest), an unknown two-dash flag takes nothing, a one-dash name takes the next word (the system's launch arguments), and a bare--ends the flags; a host says which words are the sketch's (OllinApp, handed.declareSketchArguments SketchChoiceby OllinRun, OllinLive, and OllinLiveCoding, which leaves out the sketch file the host compiles), and.sketchArguments SketchLoaderclaims the command line for any process that loads a sketch file and declared nothing, so a gallery's or a figure renderer's own words never read as a sketch's files (.instantiate LaunchFilesTests, which walks every flag in the table;SketchTargetTests). A swap re-points the canvas at the new instance (wireLoopControlsetsOllinMTKView.sketchand its pointer): before, every click, key, pointer seed, and description after a live reload reached the first-mounted instance, since mouse input landed (the reload test verified red by sabotage).SketchConvenienceTests(redraw counted one frame per wake, sabotage red; isExporting through every drive and the bench exclusion, sabotage red).Docs/Core/Sketch.md,Docs/. A run's firstHelpers/ Input .md setup()is one function (SketchRunner), reached by the frame loop and by a replay's backward jump alike, and it answers a pending.performFirstSetup rerunSetup(): left pending across a fresh run, the rerun ransetup()again on the next frame.RunLifecycleTestsholds both orders against a restart, a reload, and a jump back.Holding the frame loop (
Sources/+Ollin/ Core/ LoopHold .swift SketchRunnerin.applyPause( ) Core/). Whether a window's frame timer runs is decided in one place, from two sets.SketchView .swift LoopHoldis every standing reason (stillfromnoLoop(),clockthe timeline's hold,replaya replay's pause or its end,hiddena schedule's night,asleep,stoppeda host's stop,closed).LoopPassis every frame owed (setup,reload,setupRerun,cameraSnap,settling,oneFrame,clockPass,scrub), andpassesThroughsays which reasons each goes through: a frame that was asked for passes the sketch's stillness and the timeline's hold (drawn at the held time), settling passes stillness only, a scrub passes a replay's pause, and nothing passes a night off, the sleep, a host's stop, or a canvas put away (work owed under those is late, never lost). Load-bearing:applyPause()is the only writer of a view'sisPausedunderSources/(LoopHoldTestsreads the sources and fails on another; the two excused files are listed there with their reasons), and a host or the canvas holds and releases through.onlyApplyPauseWritesTheFrameTimer holdLoop/releaseLoop, each reason let go only by the owner that took it; it writes only when the decision changes, which is what leaves a test's hand-stopped view as the test left it; the sketch's stillness is read from the instance drawing and never mirrored (a replaced instance'snoLoop()does not reach the window, and a sketch already still when its runner arrives still gets its first frame); the owed frames are read from the properties that carry the work, each of which decides the pause again when set, so there is no second copy; a replay dropsstillandclock(it draws every frame its take holds, the fix for a still sketch's take stalling on frame one); the pause is decided once per refresh and once per compound call (beginLoopChanges);refusingFrames(clock,replay,hidden,asleep,closed) also refuses a tick already queued when the hold lands, whilestillandstoppedleave a frame to whoever asks by hand (redrawOnce, every hand-turned test); work that runs at the top of a refresh (setup, a rerun, a swap) converts tooneFrame, which only a refresh that draws spends. A new reason is a case inLoopHoldplus its owner's hold and release; a new kind of owed frame is a case inLoopPass, its line inowedPasses, and adidSet { applyPause(on the property that carries it.) } LoopHoldTests(every pair of reasons, every kind of owed frame against every reason, the rule over all 32,768 sets, the sources; 17 of 26 pairs and 24 of 40 cells failed on the code before it),ScreenWakeTests,ScreenSaverHostTests. Mechanism and what the tables found:ARCHITECTURE.md§ The frame loop's holds.Rendering.
Drawer+ Metal renderer over several pipelines recorded into call-ordered batches (so SDF / triangle / fringe / image / glyph / 3D geometry composite front-to-back as drawn — never collapse into unordered passes): a tessellated-triangle path (libtess2 fills + 8×/4× MSAA; the tessellator runs in double precision with its asserts off over input the shared expander cleans first, so any closed outline is safe to hand it: in single precision a foldedcurveThroughring crossing itself within a few pixels put its sweep's vertex order out and the asserts took a live window down fromwithClipanddrawShape(2026-10-26);TESSrealisdoubleby a noted one-line change in the vendored header,NDEBUGis set inPackage.swiftas the page's build always had it, andFillExpandermerges consecutive points within a millionth of the largest coordinate, drops a ring of under three distinct points or one along a line, and keeps a self-crossing ring whole; a quarter million generated folds tessellated without an assert, and.cleaned TessellationRobustnessTestscarry two that asserted), an instanced-SDF path, a fringe-stroke path (the high-quality stroke renderer), a textured-quad image path, and a glyph-atlas path. Gamma-correct linear-light compositing in argba16Floatintermediate that a final present pass tone-maps + dithers to the sRGB drawable. The dither (ditherEncoded, one helper for the opaque present, the alpha-keeping one, and the web page's tail) reaches at most one level, and within a level of black or white onlydistance + 0.3levels, so exact 0 and exact 255 never move (a two-level picture exports two-level, a black ground feeds no noise to a video encoder) and nothing near an end leans on the clamp; 0.3 sits under the 0.41 level at which this GPU's 8-bit sRGB encode already rounds black up (measured: full reach moved 17.6% of black and 12.2% of white). Black reads up to a quarter level high from about 0.5 to 1.5 levels with or without the limit, which is that encode's straight segment, not the dither.PresentDitherTests(3: exact ends, the middle still dithered, the mean within 0.4 of a level of either end). A built-in shape's outline is the share of each pixel between the band's two edges (ollin_band_shareover the strokes'ollin_edge_share; the edge's step over a pixel is the distance's two screen derivatives for a region shape and, for a disk, the field's own slope carried through the coordinate's screen step, never a screen derivative of the distance; the fill's ramp is untouched), and a circle's outline whose inner edge is within a pixel and a half of the center is the ring, the exact disc out to the outer edge less the exact disc in to the inner one, faded into the band by two and a half. A run of analytic shapes draws through the shape fragment built for what it holds (ShapeNeedsbits onGeometryBatch, carried inPipelineKey, set as function constant 19,.shapeNeeds kOllinShapeNeeds; read insideregionCoverage,diskCoverage, andollin_sdf_coverage): the fragment's cost follows what it carries, taken or not (the exact ring written into the one fragment cost a field of plain dots 11% and stroked boxes 20%; built for the run, plain dots draw in a third less GPU time than before and outlined boxes in an eighth less), so a new part of that fragment is gated by a build constant and timed on a run that never takes it. A long stretch of one kind is a run of its own: once 64 instances in a row ask for one set and the run holds something else before them, the run is cut where the stretch began (Drawer, the stretch's state on the.noteShapeNeeds GeometryBatchitself), so every dot and then every box is two draws through two small builds, in call order; shapes that alternate stay one mixed run, a fifth dearer than before (aLongStretchOfOneKindIsARunOfItsOwn). A look never depends on the build (aShapeDrawsTheSameWhateverSharesItsRun); the paint pipelines, the composed fields, and the 3D marks leave the constant unset and carry the whole; the page has one build and defines the four constants true (WebShaderCompat), and.constantValues shapespulls infringefor the edge. A curve is cut by its bend (CurveSampling: the larger of the length's count, six pieces and one per 8 units, and Wang's count for a tenth of a unit;StrokeExpanderthe same for a circle, held to a count while still a.circleSegments Doubleso a radius that is not finite never traps): facets under 0.1 px at every radius, never fewer points than before.Path/.contour( tolerance: ) shape(tolerance:)name the distance for a value;drawShape { },drawCurve,drawBezier, and text along a path passDrawer, a tenth of a pixel of the surface drawn into under the current transform (.curveTolerance CurveFlatteningTests, 6 tests over 24 cases;CurveFlatteningUnderATransformTests, 2 over 6).drawPolygonhands an outline that is not convex to the triangulator under the nonzero rule (Drawer.isConvex, one pass of comparisons: every turn one way and the outline round once), so its raster agrees with the<polygon>its vector export writes.blendMode(_:)(.normal/.add/.subtract/.multiply/.screen/.lightest/.darkest) is stack state carried as aPipelinecache-key parameter, not a renderer-per-mode. A color reaches the blend weighted by its coverage, and a surface's alpha stays a coverage (the derivation isARCHITECTURE.md§ Blend modes: what the blend is handed, and what a surface's alpha means)..normal,.add, and.subtractweight a straight color in their own source factor and build the fragments as written, byte for byte;.multiply,.screen,.lightest, and.darkestbuild every fragment withkOllinBlendForm(function constant 17, fromBlendMode: 1 weighted, 2 weighted for the maximum, 3 the shape as it lies over white for the minimum), which.fragmentForm ollin_blend_readyreads at every blended fragment's return (ollin_blend_ready_premultipliedon the image path).BlendReadyFragmentTestsreads the segments and fails on a fragment that returns its color bare; a fragment no mode reaches is listed there with its reason. The maximum and the minimum cannot be weighted, so.lightestcompares the shape as it lies over black and.darkestas it lies over white: exact at full cover, a soft edge tighter than exact and never past the ground or the shape, and along a soft.darkestedge light past white is cut to white. A fragment that covers nothing hands those two a color no ground loses to (60,000 either way) and is not discarded, so a stroke medium's claim on its samples and a depth write are what they are under.normal(the one fragment that is dropped is the rim a stroke's ribbon carries past its edge, which is no part of the stroke under any mode). Alpha:.add,.screen, and.lightestcover by the over rule, so over nothing they leave the shape itself;.subtract,.multiply, and.darkestleave the surface's alpha alone, so over nothing they leave nothing and a multiply wash tints a layer's picture and leaves its bare parts bare; a clear color is weighted by its alpha on the way into the pass (mtlClearColor). The statements areEffectInvariantTests(A layer): the weighted arithmetic of every mode on nine drawing paths, an ink of no alpha over light past white and below black, the over-nothing rule, the wash, and every edge between the ground and the shape. The page twins all of it (blendReadyunderuBlendForm, the factors insetBlend, a layer's clear weighted by its alpha as the page clears, the color and the alpha recorded apart so each stays a straight line in the parameter that drives it), played against the Mac bythePageBlendsAsTheMacDoes. The page's own canvas is opaque: a background's alpha reaches nothing there (WebControlTests), so a see-through canvas background shows whole on the page where the window shows it over black. HDR / tone-map —toneMap((_: exposure: ) .clampdefault /.reinhard/.aces/.neutral), a frame-wide mode over the float pipeline (Docs/Drawing/HDR.md)..neutralkeeps a bright color's hue (the Khronos PBR Neutral curve,toneMapNeutralin thepresentlibrary block, so the web page's present pass carries it through the translator): the per-channel curves turn a bright saturated color toward a primary (linear (4, 1, 0.2) is an orange at 12.6°;.acesshows it at 45°,.reinhardat 32°), where the neutral curve scales the three channels by one factor and holds it within a degree; below its knee (0.76) a color keeps its hue and loses only the curve's toe (0.04 at most).ToneMapTests(the hue, the toe),FrameInvariantTestscarries its scalar form; the Guide figureToneNeutralbeside the clamp and ACES pair;Rendering/cycles four. Accumulation surface —ToneMapping noClear()/clearEachFrame(), a persistent float canvas drawing piles onto;background(_:)is the in-mode wipe (Docs/). The kept canvas is single precision by default (ruled 2026-11-28 with the feedback layer's, under Layered effects: a wash that keeps 0.98 was 3.4% dark after 100 frames in half float, and a long faint exposure leveled off);Drawing/ Accumulation .md noClear(halves its memory, which is every sample of the multisampling (45 MB at 1080).precision: .float16) .float32makes the MSAA target and resolvergba32Float(Drawer,.accumulationPrecision MetalRenderer; a change reallocates and clears like a size change) and the canvas encode keys every pipeline on it through its.accumFormat canvasColorFormatargument; the two readers that assumed half float follow it: the frame grab's mip chain takes the source's format, and the linear capture copies 16-byte rows and narrows them to half on the CPU (LinearCapture)..colorIsSingle LightAccumulationTests/.singlePrecisionPileKeepsAdding aLongFaintExposureReachesItsSum(0.25 + 300 x 8 x 0.00005: float32 reads 0.37, half float holds 0.25),EXRExportTests. The EXR writer clamps alpha to 1, a guard since every blend mode now keeps the surface's alpha a coverage (added coats on an opaque canvas once held A = 3). The SDF path covers a broad analytic-shape catalog (.aSinglePrecisionPileIsWrittenAtItsSum drawPoint/drawCircle/drawEllipse/drawRect/drawOrientedBox/ circulardrawArc/drawTriangle/drawNgon/drawStar/drawRing/drawHeart/drawMoon/ … +hollow(_:)band mode,strokeAlign(_:), a disk's coverage the exact share of each pixel it covers and an outline band that conserves its ink; a disk's ink is its area wherever it lands (diskCoverageoverollin_unit_disc_coverageinShaderShapes.metal: the pixel as a parallelogram in the space where the disk is the unit circle, read from the screen step of the coordinate and never of a distance, the exact shared area under three pixels of radius, by four corner reads where the pixel is a rectangle there (ollin_unit_disc_rect_share: a circle, an ellipse square to the screen, every particle) and by a walk round its sides where it is not (ollin_unit_disc_walk), and a straight edge pulled in by the arc's mean bow past that size; a dot under a pixel on both axes its area shared by a tent a pixel wide on each screen axis, faded into the exact share over the last fifth of a pixel so a size running through one pixel never steps (ollin_dot_tent_share; the two forms place up to 4% of a pixel differently where they meet, and a quad and a point disagreed by 37 levels on a pile of one-pixel marks until they were joined), and one thin on one axis a one-pixel floor on that axis with the coverage scaled by the true area; a fragment that can never need the walk does not carry it (squareDotCoverage, the particles' entry: the walk compiled in and never taken cost 1.8 ms on a million marks); and a covering quad whose margin is a pixel and a half, in pixels alone for a disk with no outline (the disk's quad alone: every other shape keeps two units, which is what cuts its outer halo short in a coarse layer and leaves a cell drawn into a simulation field on its own texels); within 3% of the area from 0.2 to 3 px at a hundred phases, under a scale, a turn, an uneven stretch, and a canvas zoomed out eight times; what exactness costs was measured and accepted on 2026-11-12, the commit before beside this one on an M2 in release: a million particle marks one to three pixels across 15.1 to 17.9 ms of GPU time, 200,000 small circles 10.8 to 12.8,Rendering/LineSpray17.8 to 19.1, a frame of 24,000 thin lines 39.4 to 42.1 ms, a frame ofShapes/InkPen5.6 to 6.2, down from 53.8 ms on the marks for the first exact form; a change to the dot or stroke fragments is timed the same way, old build beside new, before it is called done); a rectangle's corners round one radius each throughcornerRadii:(CornerRadii .top(r)/.bottom/.left/.right/ the four named), the box readingparam0= (top-left, top-right) andparam1= (bottom-right, bottom-left) whenever any of them is set andextraotherwise, so four equal radii collapse on the CPU to thecornerRadius:instance byte for byte (RoundedCornersTests) and every box drawn with one radius keeps its old distance; the per-corner SDF picks the quadrant's radius then runssdRoundBox's own expression; radii are fitted before they draw, all four scaled by one factor where two on a side add up past it, the rule stylesheets use; the dashed outline, the hollow band, the combinator leaf (SDF), the SVG (.rect( width: height: cornerRadii: ) <path>with anAper rounded corner,<rect rx>kept for one radius) and the PDF (tangent arcs) all read the same four); the fringe path covers every stroke (drawLine/drawBezier/drawPolyline+ polygon/shape/elliptical-arc outlines, honoringstrokeJoin/strokeCap/strokeProfile, translucent + gradient paint; a stroke's ink is its width at any angle and wherever its edges fall (ruled 2026-11-12: the ribbon's vertices carry how far inside each of the stroke's two edges they sit, unclamped, andollin_fringe_coverageinShaderCore.metaltakes the exact share of the pixel between them from the pair's own screen steps; the ribbon's rim runs a fringe and a half past the edge so the multisample mask never cuts a pixel that carries coverage, and is discarded; a hairline keeps a one-pixel footprint scaled by its thinness; the fringe that sizes both is a pixel of what is drawn into, a texel of the layer where the layer is coarser than the canvas (Drawer.fringeWidth); a medium or shader-paint ribbon rebuilds the second distance throughollin_ribbon_coverage, and a line through the 3D camera and the page's eight-float vertex carry both; within 2% of the weight from 1 to 17.3 px, and 5% from 0.3 to 0.7, at four angles and eight positions; the outline of an analytic shape is the SDF path's band, not this path, and keeps its two pinned defects);drawArrow(composes a shaft on this path with a solid SDF-triangle head, the whole mark painted with the stroke so one color states the arrow — head defaults scale with the weight, shaft stops at the head's base so translucent arrows lay one coat, and composition over the existing primitives is what makes SVG export inherit it — catalog figurefrom: to: headLength: headWidth: ) Docs/, exampleFigures/ DrawArrow .swift Shapes/Arrows(a field aimed at the cursor, plus a translucent ring sweeping the head geometry — the one-coat property drawn),Docs/); the triangle path covers fills (Drawing/ Drawing .md#arrow drawShapefor concave/holed, curved via thePathbuilder +drawCurve;drawPolygonis a fan and fills convex only — hand it a concave outline and every dip is bridged straight across, so an area chart or any dipping profile goes throughdrawShape) and elliptical/full-arc fills. Collection sugar:drawCircles/drawPoints/drawRects. Kaleidoscope symmetry —symmetry(/_: mirrored: ) noSymmetry(), stack state: every 2D draw call replicates through canvas-space fold matrices (each local rotation/reflection conjugated by the CTM at thesymmetrycall — fold 0 stays the exact identity, so the primary copy is byte-identical). Load-bearing: replication is per emission funnel — SDF instances and combinator groups left-multiply their per-instancetransform(groups share one node program), the triangle/fringe/image/glyph paths range-copy canvas-space vertices viaDrawer.replicatedwhose body must stay within one batch kind (wrap a fill section and its stroke separately;isReplicatingpasses a nested funnel through, and folds are rigid so screen-space AA/fringe widths stay exact), andsvgRecordreplicates commands so--export-svgfolds too; 3D geometry, GPU particles, and depth scenes are untouched by design. ExamplePatterns/(declaresKaleidoscope loopDuration); snapshotsymmetry;SymmetryTests. Clipping —withClip(, the standard stencil clip (increment/decrement): the region triangulates through the fill path into a stencil-onlyshape/ rect/ circle) { } .clipPushbatch (CTM baked at the push), content batches carry aclipLeveland stencil-testequalto it, and the block's end appends a fullscreen-decrement.clipPop; nesting intersects. Load-bearing: astencil8MSAA attachment (memoryless unless the pass is heavy, below) joins a pass only when that surface clips (Drawer/.usesClipStencil RenderTarget— an unclipped frame is byte-identical), and in a stencil-carrying pass every pipeline key must declare.needsStencil stencilFormat(skybox and raymarch-upsample included) or Metal validation rejects the draw; never passsetDepthStencilState((validation rejects nil — usenil) noDepthState); clipping is per surface (a layer opened inside a clip block starts unclipped);background(_:)inside a clip block re-emits the open pushes after the wipe (reemitClipPushes); clip edges AA at MSAA resolution (the clip shape rasterizes binary per sample);--export-svgemits native<clipPath>defs + nested<g>groups. ExampleShapes/Clipping; snapshotclip;ClipTests. A refresh the GPU has no room for is dropped, not waited on —MetalRenderer(a frame count kept in lockstep with the.canStartFrame frameBoundarysemaphore, since a semaphore can only be asked by waiting on it) is read at the top ofSketchRunner, before.draw( in: ) advance/performDraw, so a heavy sketch gives a low frame rate and a window that still answers the mouse instead of both stopping (the drop is early, so nothing is drawn and discarded and an accumulating canvas keeps its ink; the clock is real time, read on the next refresh that lands). A take is the exception, playing or recording: a replay consumes one recorded frame per refresh.FrameRingProbes(Tests/) pins the three halves (the ring reports full and empties, a full ring drops the refresh, a take keeps every one), the drop test verified red by sabotage. The load-bearing renderer rules (the vertex-buffer ring, the SDF tagged union, coverage models, the present/float pipeline) live in Shaders & the Metal back end + Rendering performance above.OllinTests/ FrameRingTests .swift Docs/. A heavy pass takes backed attachments (Drawing/ Drawing .md Renderer/): a pass's MSAA color, depth, and stencil are memoryless unless its counted geometry (PassStorage .swift Drawer, a quad per SDF shape, particle, or splat, a third of every vertex list, the copies of an instanced mesh) passes.primitiveCount( on: ) MetalRenderer(1M triangles), then.backedAttachmentPrimitives .private. A pass the tiler cannot bin whole needs a partial render, which stores the attachments and loads them back; a memoryless attachment cannot be stored, so the GPU refuses the whole command buffer ("Too much geometry to support memoryless render pass attachments") and the frame came back empty with nothing said (aLineSpraypast ~9.5M points a frame on a 256-pixel canvas). Measured edges on the M2 (4x, half float): one-pixel marks 7.7M (4096²) to 10.6M (64²), 40-px 3.6M, 200-px 0.56M; private drew 40M. Private costs the memory behind the samples and nothing else below the edge (GPU time equal to within 2% from 0.2M to 5M marks), and the pixels are the same. Every finished frame's command buffer is read (GPUFailures, from both live completion handlers andcommitHeadless): a failed one writes one stderr line per distinct sentence, and an overflow turns every later pass private (GPU-grown geometry, mesh fields, strands, the ocean, is not counted and is caught that way). Pools and caches (targetTexPool/targetDepthPool,mainMSAA/mainDepth, the clip stencils, the glass pass) are keyed by storage too.HeavyPassTests(ten million marks on the canvas and in a layer, red with the budget atInt.max). What a long run keeps is counted and held flat:MetalRendererand.census Drawer.censuscount every cache, pool, and slot table either keeps across frames, andSoakTestsdrives 20,000 live frames that churn all of them and fails when a count in the last half passes the most it reached by frame 4,000 (a margin for caches that fill and clear on a cycle; a planted texture a frame verified red). A new cross-frame cache goes into its census.leaks, run at exit over headless exports, is the other half (Tests/README, What a long run leaves behind). The blobby cross's distance is floored by the diamond through its four tips (sdBlobbyCross, the shader and the CPU copy alike): past a tip the formula clamps its closest point to the parabola's end and reported a fraction of the distance there, so the coverage ramp drew a faint spike from every tip to the quad's edge; and below a blobbiness of about 0.35 the tip sits at the parabola's end, so the mapping capstipUnitat 1 and the shape reaches itsradius.Wide gamut & HDR output (
Sources/+ the present twin inOllin/ Color/ ColorOutput .swift Renderer/).ShaderEffects .metal Sketch.colorOutput(declared, likecanvasSize, since the drawable is built from it once) opens the last step of the pipeline:.standard(8-bit sRGB, the default),.wide(Display P3 through anrgba16Floatdrawable),.extended(+ values above 1 shown as highlights, and an HDR10 video export).Color(/displayP3: green: blue: ) displayP3Components/isOutsideSRGBname a color outside sRGB, stored as the extended sRGB components that decode back to it. Load-bearing: the wide/HDR present is a twin fragment (ollin_present_wide_fragment) beside the byte-for-byte-untouchedollin_present_fragment(the fast-math re-contraction rule), and the newOllinPresentUniformsfields are appended so the shipped fragment's reads keep their offsets — proven by a clean-HEAD worktree double record (185/185 identical); no out-of-sRGB authoring needed a shader change because the shippedsrgbToLinearalready decodes a negative component through the curve's straight segment, so the CPU encode (linearToSrgb,c*12.92below the knee) is its exact inverse and a P3 color survives the ordinary vertex path;PresentEncodingdistinguishes.linearDisplayP3(stops at white) from.linearDisplayP3Extended(starts unbounded, so a headless render keeps the highlights an exported HDR video is for, with a live host pulling the ceiling down to the screen's reported headroom every frame — the system grants and withdraws it); tone-map curves and.extendedpull against each other by construction (.reinhard/.acessqueeze into 0…1, which is what an HDR display does not want), so the default.clampis the right one there; HDR video is PQ-encoded on the GPU into the same float texture and handed over askCVPixelFormatType_64RGBAHalf(VideoToolbox writes 10-bit HEVC Main10 withkVTHDRMetadataInsertionMode_Autosupplying the mastering-display + content-light metadata), 1.0 = 203 cd/m² (BT.2408 reference white), peak 1000; a still keeps the range too, in HEIC (--export frame.heic; the path's extension picks the format; PNG clips at white). The files keep their depth (Export/): a float frame is quantized at the file, never by a Core Graphics conversion (which rounds a slow gradient into bands and may bend a frame past white rather than clip it): a PNG at 16 bits and the HEIC's picture at 16, which the writer stores as 10 (ruled 2026-10-17: within 0.4% of the frame, no banding, and smaller than a dithered 8-bit picture, which sat two levels off on a dark pixel), both under the Display P3 curve and clipped at white; the 8-bit sinks (aFrameBytes .swift .wideclip's frames, a wide window's recording) take the present's TPDF dither on the CPU (a curve table indexed by each half's bits, the same end rule so 0 and 255 stay exact, a position hash so an export repeats).aWidePNGKeepsSixteenBits,aWideHEICKeepsTenBits,anEightBitFileOfAWideFrameIsDithered(the wide ProRes clip's gradient: 3 runs to 1,006),SessionRecorderWriterTests, each red under its plant..aWideTakeIsDithered Export/writes an ISO 21496-1 gain map beside a base picture that is the frame clamped at white (what the PNG carries), returningGainMapExport .swift OllinApp(.StillExport peak,keepsHighlights). Load-bearing: the map is built here, never derived by Core Image, whose ceiling comes from frame statistics and so deletes a small highlight (measured at 4x white: 0.1% of the frame → 0.99x back, 1% → 1.75x, 5% → 3.63x, 25%+ → exact) and which ignores a declaredcontentHeadroomdespite its header saying it drives the calculation (the value is live: the tone-map filter reads it); a ready-made map passed as.hdrGainMapImagewrites the legacy Apple aux type, not the ISO one, so the file is assembled with ImageIO directly; the map carries a gain per channel because clamping is per channel (an amber core of (4.0, 2.2, 0.72) clamps to (1, 1, 0.72): one channel for all three read green +81% / blue +300%, three read within 0.6%); the base is written at quality 1.0 (within a level of its bytes, measured) so a still stays as faithful as the PNG; a frame at or below white carries no map and says so. Reconstruction is(; the file keeps the map's color at half resolution (4:2:0), each sample at the left of its block, and a per-channel gain is that color, so the map is written at four times the frame's size (base + offset) * 2^( e * GainMapMax) - offset GainMap.mapScale; twice once the map would pass 24 Mpx): a highlight's antialiased rim rebuilt 40% off at 1x, 4% at 2x (a quarter of the neighbor's color), 1.7% at 4x (2.1% on the test's drawn rim;aGainMapKeepsAHighlightsEdge, red at 1x and at 2x).GainMapExportTests(12; the per-channel map and the true-peak ceiling both verified red by sabotage). Spatial video stays.standard.Sketchreads what the display actually granted (1 headless), through the sketch's own ceiling (.displayHeadroom setDisplayHeadroom(): the screen's value is what it grants to whatever on it asked, another app's window included (1.76 read on this desk's panel by an app that asked for none), so afromScreen: ) .standardor.widesketch reads 1, pinned headless inColorOutputTests. The float drawable is cheaper, not dearer (M2 release, paired runs: 1080² present 0.44 → 0.23 ms) because the 8-bit path's dither + transfer curve outcost the extra bytes, so the case against.wideas a default is consumer compatibility and re-record churn, never speed. ExampleRendering/;ColorOutput ColorOutputTests(10, the gamut-matrix sabotage verified red); no pixel snapshot beyond the byte-identity gate (a wide frame's whole point is invisible in an 8-bit reference). Mechanism + the measurement:ARCHITECTURE.md§ Wide gamut and HDR output.Docs/; Guide Ch 45 § Brighter than white: HDR output.Drawing/ ColorOutput .md Spectral color (
Sources/+Ollin/ Color/ Spectrum .swift Renderer/; data vendored inSpectralTaps .swift External/, MIT — see THIRD-PARTY-NOTICES.md).CSpectralData Spectrum— 81 samples, 380–780 nm at 5 nm, read as reflectance in daylight: a color's curve is its linear r/g/b times three basis spectra (a partition of unity, so white is flat 1), and the return conversion goes through the matrix inverted from those same tables, which is what makes color→spectrum→color exact to float rounding rather than to the data's fitting error..paintjoinsColorSpace(Kubelka-Munk over the curves, soRamp(in: .paint)and every mix surface get it too);mixedAsPaint(is the typed form;with: _: ) */+filter and add spectra;Color(wavelength:)(peak-normalized locus) andSpectrumare the physical doors. GPU trio:.blackbody( _: ) Filter.thinFilm(true two-beam interference per tap, thickness in real nanometers;.iridescencestays the styled sibling),Filter.diffraction(grating orders, offset ∝ λ so red reaches farther; premultiplied accumulation, so streaks pass a silhouette; tap colors sum to white by construction, so a flat field cannot tint),Combine.paintMix(the GPU form of.paint; the aux's coverage gates the mix per pixel, so an uncovered pixel passes the base bit-exact — note a never-rendered aux target is pooled garbage, a pre-existing combine-wide fact, which is why the guarantee is per-pixel coverage, not per-target). All three read a cooked tap block (SpectralTaps.block, tap count viaresolveDispersionTaps) whose XYZ→RGB inverse is computed from the taps themselves, keeping zero-amount and equal-input identities at every quality tier; both spectral filters also early-out at amount 0 (the premul/unpremul round trip alone costs a level). KM clamps reflectance to [1e-4, 1−1e-4]; a near-black saturated paint legitimately drags a mix toward dark, as on a real palette. ExamplesColor/Mixing(six bands) +Effects/SoapFilm+Effects/PigmentMix(.paintMixbeside.mixover one pair of layers, both combine spellings); snapshotspectral-color; testsSpectrumTests(11, pure) +SpectralEffectsTests(7, Metal);Docs/; Guide Ch 2 § Blue and yellow make green: mixing inDrawing/ Spectrum .md .paint. The film's color on the CPU —Spectrumis the two-beam reflectance of a symmetric lossless film over the full 81-sample curve (the same optics the.interference( thickness: ior: ) .thinFilmfragment evaluates per tap:R = 2r²(,1 − cos δ) / ( 1 + r⁴ − 2r² cos δ) δ = 4π n d / λ), andColoris that curve divided by the peak.interference( thickness: ior: ) 4r² / (1 + r²)²(full constructive interference reads as full brightness, the filter's convention; a channel may pass 1 on the most saturated films). The GPU filter at.detailand the CPU color agree within 0.54 levels through 600 nm and within 3.5 past it, where the crowded bands outrun 31 taps (InterferenceColorRenderProbes, pinned at 1 and 4).InterferenceColorTests(nothing at no thickness or at index 1, never past the peak and reaching it, the draining film's order by dominant channel at 150 / 250 / 300 / 350 nm, the ramp a stroke takes through.alongPath); exampleColor/PearlStrokes;Docs/; Guide Ch 2 § Light by wavelength:Drawing/ Spectrum .md#physical Spectrum.Variable-width strokes (
Sources/+ the expander inOllin/ Drawing/ StrokeProfile .swift Core/).Drawer+Tessellation .swift strokeProfile(_:)/noStrokeProfile()is stack state shaping width along a path: theStrokeProfilevalue type (.uniform/.taper(start:end:)/.ramp(from:to:)/.nib(/angle: thinness: ) .values(_:)+ the closure forms) returns a multiplier onstrokeWeight, read at path fraction 0…1 plus the local direction (what.nibuses). The fringe expander carries a half-width per path vertex (Drawer), so a segment quad becomes a trapezoid, exact for a linear ramp along a straight run. Load-bearing: width is sampled per path vertex, not per segment, which is why joins stay simple (both segments at a corner agree on the width there, so a corner is the constant-width corner problem at the local width) and why joins/caps just read their own vertex's width; a non-uniform profile subdivides like a gradient does (.strokeHalfWidths maxLength: 12) since the profile can only follow the points it's given;.uniformis the untouched path (isUniformgates the expander, the outline builder, and the vector recorder) and the coverage ramp is the shipped one either way, so a profiled and an unprofiled stroke of the same width lay down the same ink and every existing snapshot is unchanged; the analytic SDF shapes carry one width by construction and ignore a profile with a one-timenoteOnce. Vector export stays true:svgRecordroutes a profiled stroke tovariableStrokeOutline(trapezoids + join wedges + caps, each wound the same way into one nonzero-woundShape, so the union needs no boolean work), recorded as a filled path rather than astroke-width; PDF replays the same commands. ExampleShapes/; snapshotStrokeProfiles stroke-profiles;StrokeProfileTests(the family, arc-length sampling, outline winding + area, rendered taper falloff).Docs/.Drawing/ Drawing .md#strokeProfile The stylus beyond its press (
Sources/;Ollin/ Core/ Stylus .swift Sketch.stylus, the tablet reads inSketchView.swift, the.styluscase inTake.Event). What a tablet says about a stylus other than where it is and how hard it is pressed, which was alreadypressureand reaches a trackpad too:stylus.tiltis the lean, -1…1 per axis and.zeroupright, whose direction is what a broad-edged nib is laid across and whose length is how far from upright the pen is;stylus.twistis an art pen's barrel turn in radians, folded into one lap;stylus.isEraseris which end is down;stylus.isNearbycovers hovering as well as drawing;stylusanswers from the events the way.tiltIsAvailable pressureIsAvailabledoes. Load-bearing: the tablet fields onNSEventraise when read off any other event, so the guard checks the type first and readssubtypeonly on the four mouse kinds that have one (||and&&short-circuit, and that is the whole protection); a tablet's motion arrives as an ordinary mouse event with thetabletPointsubtype while proximity arrives on its own, andpointingDeviceTypeis readable only on the proximity event, which is why the end being used is carried forward rather than re-read;tiltIsAvailablelatches on (a stylus lifted out of range would otherwise take the pen path away mid-stroke), while a lift zeroes the lean and the turn so nothing stale is read as current; the pen and the pressure never write each other. Recorded into a take and replayed with the rest of the input (Take.Event.stylus, the file version unmoved since an old take still decodes). Six tests inStylusTests: the lean is held to its range and the turn folded to one lap (a non-number reads upright); a sketch with no tablet reads as one; the pen path stays offered once a pen has been seen and a lift says so without forgetting; the erasing end is its own thing; the pressure and the pen are separate; a take carries the pen through a replay exactly. The latch and the replay were both verified red by sabotage. The AppKit mapping itself is desk work: no test can synthesize a tablet event, so the tilt, the turn, the eraser end and the proximity edges owe a hand with a stylus.Examples/Input/Pen(a chisel nib across the lean, the press for width, the eraser end taking ink away, and a panel that says what the tablet is sending);Docs/§ pen; Guide Ch 17 § Painting as it happens: stroke dynamics + the NibAndLean figure.Helpers/ Input .md Pinch and turn (
Sketch.pinchScale/turnAngle, the hooksfingersPinched()/fingersTurned();reportGestureinCore/, the phone's pair inSketchView .swift PhonePointer). Two fingers on the trackpad as this frame's change:pinchScaleis a factor, the product of1 + magnificationover every magnify event since the last frame,1when still, andturnAngleis radians clockwise on the canvas, the sum of each rotate event's counterclockwise degrees negated and converted, soangle += turnAngle; rotate(follows the fingers. Both are gathered between frames and surfaced inangle) advance()the way the scroll is, and a hook sees its own event's value. An event reaches the sketch once: the SwiftUI hosts' gesture plumbing can take gesture events before responder dispatch (it takes pressure), so a local monitor over.magnify/.rotate, gated on the window and the view's bounds, reports beside themagnify(with:)/rotate(with:)overrides, and the last reported type and timestamp is skipped; an event that moves nothing (a gesture's start or end) is not reported. A factor at or below zero is held at 0.01 and a non-finite value is dropped. Takes record.pinch(scale:)/.turn(angle:)(the format version is unchanged: the cases are additive).viewControl()zooms by the pinch about the pointer (onezoom * pow(, so a scroll alone is byte-identical) and the orbit rigs dolly bybase, scroll) * pinch goalRadius /; both count a pinch as the viewer taking over. The phone showing the sketch (pinchScale PhoneScreen) reads its first two fingers as a pair: a reading with the same two ids as the last, moved, is.pair(from:to:), a changed pair starts over so nothing jumps, and the change is measured on the canvas (Pair.change(to:in:), the turn wrapped the shorter way) and applied only in Sketch mode. The sketch installed on the phone (OllinMTKView, multi-touch off) reads one finger only.PinchAndTurnTests(realNSEvents from a gestureCGEvent: type 29, field 110 the HID type, 8 magnify with the value in field 113, 5 rotate in 114),PhonePointerTests,PhoneTouchTests;Examples/;Input/ PinchAndTurn Docs/; Guide Ch 42 § Two fingers on the trackpad: pinch and turn. The live window's route through a SwiftUI host is a desk check: the screen was locked when this shipped.Helpers/ Input .md#pinch Typed text (
Sketch.typedText()/textTyped()/composingText/caretPosition,String;.append( typing: ) Core/). The keyboard read as a text field reads it:TypedText .swift OllinMTKViewadoptsNSTextInputClient(an isolated@MainActorconformance) and hands everykeyDowntointerpretKeyEvents(after the key hook, so the system's input methods compose a dead key's accent, an input method's confirmed word, and the emoji viewer's pick into_: ) insertText, and a Return that confirms a composition still findscomposingTextholding it.key/keyPressed()are byte-identical (a repeat still fires no hook; it types again). A Command chord types nothing (a shortcut no menu claimed); inserted text keeps\n(a carriage return reads as one) and\tand drops other control characters; the editing commands a text field answers by editing are typed as characters (insertNewline:and its kin\n,insertTab:\t,deleteBackward:the backspace\u{8}thatappend(typing:)reads as taking a character away), and every other command is swallowed without the beep. The client's only document is the composition still under way (markedText/markedSelectionon the view):selectedRangeis{0,0}with nothing marked,markedRange{NSNotFound,0},unmarkTextcommits what was shown, andresignFirstResponderdrops a half-written composition with nothing typed (abandonComposition, which also discards the context's).firstRectplaces the candidate list belowcaretPosition(canvas coordinates throughviewRect, so a fitted projection is honored) or below the pointer. Takes record.typed(text:)/.composing(text:)(additive; the format version is unchanged) and a replay gates live text off. A headless export types nothing; on iOS nothing types yet.TypedTextTests(the client driven byinsertText/setMarkedText/doCommand, a real repeat throughkeyDown, the take);Examples/;Input/ TypedText Docs/; Guide Ch 42 § Text the way a text field takes it: typed text. The input system composes only for the active app's key window, so a test process cannot drive the layout's own dead keys (the context accepts the event and composes nothing: probed with a real Option-E); the real route (a dead key, a Japanese input method, the emoji viewer) is a desk check.Helpers/ Input .md#typed-text Stroke dynamics (
Sources/+Ollin/ Drawing/ StrokeDynamics .swift StrokeMark.swift). The width-profile sibling driven by how a mark is made rather than where you are along it: aStrokeMarkrecords the pointer (record(, sugar_: deltaTime: pressure: ) Sketch) measuring speed and press force, runs both through a.record( into: ) StrokeDynamics(oneStrokeResponseper axis over aStrokeInputof speed/pressure/direction/distance), and keeps the resulting width + opacity at each point;drawMark(_:)strokes it. Load-bearing: a profile can't express this because a mark in progress has no length to take a fraction of, and a recorded hand's points are not evenly spaced (dense where it slowed), so.values(_:)genuinely doesn't fit andStrokeProfile(values at given fractions) is the general form.values( _: at: ) drawMarkbuilds; speed is measured over real elapsed time with skipped sub-minSpacingframes banking their dt (frame-rate independence, pinned byrecordingIsFrameRateIndependent), smoothed by aOneEuroFilterper axis fed a scaled signal (a px/s speed runs in the hundreds, and the filter'sbetais in the signal's units); the two axes are separate and each defaults to.unchanged(a shared preset with per-axis defaults silently drove both, the bug the first probe caught); the first point is held until a second gives it a heading; the ambientstrokeProfilemultiplies with the mark's widths; the mark's opacity is carried in the existing per-vertex color alpha via an internalstrokeOpacityShape(.uniformdefault → every other stroke byte-identical, and a.uniformmark is byte-identical todrawPolyline). Pressure is plumbed through the one platform-neutral input surface (Sketch.pressure/pressureIsAvailable, capability latching on the first press), so it reaches standalone + gallery + OllinLive — but not viapressureChange: the SwiftUI hosting layer consumes.pressureevents before responder dispatch and its recognizers override the view's.primaryGenericwith deep-click (reads ~0 across the whole normal force range), soOllinMTKViewfeeds a view-owned local.pressureevent monitor andmouseDownre-claims the stream withpressureConfiguration?; never read.set( ) associatedEventsMaskon a.pressureevent (the access raises and AppKit swallows the raise, silently dropping the report — a pressure event is itself the capability proof), and mouse/drag events from a pressure-capable device seed zero, then go quiet once the stream is live (theirpressurefield is the legacy constant 1). Mechanism:ARCHITECTURE.md§ Trackpad pressure delivery. Vector export keeps width exactly (the profiled filled-outline path) and flattens opacity to its length-weighted average with anoteOnce(one fill, one alpha per path; free for the one-pen plotter case). ExampleShapes/Brushwork(class renamed offStrokeDynamicsto dodge theSlitScanshadowing trap);StrokeDynamicsTests(mapping, measurement, arc-fraction placement, three rendered probes, no pixel snapshot since dynamics is interactive).Docs/.Drawing/ Marks .md Brushes (
Sources/+Ollin/ Drawing/ Brush .swift Core/). The third mark axis beside the width profile and the recorded mark:Drawer+Brush .swift strokeBrush(_:)/noStrokeBrush()is stack state that replaces the ribbon with a row of stamps. TheBrushvalue type carries atip(.circle/.square/.shape(Shape)/.image(Image)),spacing,sizeJitter,angle(.followPath/.fixed/.random),angleJitter,scatter,count,opacityJitter,seed, plus the.round/.chisel()/.spray()/.scatter()presets; size comes fromstrokeWeightand color fromstroke, so a brush is texture only. Load-bearing: every distance is a fraction of the stamp's own size, which is what keeps a brush's texture constant across weights (pinned byspacingScalesWithTheStampNotTheCanvas); stamps are placed by arc length, not per vertex (a recorded mark's points bunch where the hand slowed, and a brush must not bunch with them); randomness is a pure function of stamp index +seedvia a privateSplitMix, never the sketch'srng(the halton/sobol rule), so adding a brush cannot shift a sketch's other rolls; the ambientstrokeProfile/strokeOpacityShapeare read per stamp and multiply, and the step is taken at the local size so a tapering mark crowds rather than going gappy; a stamp draws through the ordinary draw methods (drawCircle/drawOrientedBox/drawShape/drawImage) with fill/stroke/brush swapped and restored, so vector export, symmetry, clipping, and retained batches all work with no knowledge of brushes (and recursion is impossible);strokedAsBrush(is called ahead of every stroke entry point's_: closed: ) svgRecordershort-circuit (drawLine/drawBezier/drawPolyline/drawMark/drawArc, anddrawShape/drawPolygonwhich re-enter fill-only then stamp) or the vector path would silently export the bare path instead of the stamps — theappendFringeStrokehook is the catch-all for internal callers; a brusheddrawMarkkeeps its varying opacity in vector export (each stamp is its own shape) where the ribbon must flatten it; opacity over a gradient stroke is the one thing a brush cannot vary (it would mean rewriting the ramp) and notes once, as do the analytic SDF outlines (thestrokeProfileprecedent).Brushis notSendable/Equatable(anImagetip is neither). ExampleShapes/Brushes; snapshotbrushes;BrushTests.Docs/.Drawing/ Marks .md#brushes Stroke media (
Sources/+ the ribbon emitter inOllin/ Drawing/ StrokeMedium .swift Core/,Drawer+Tessellation .swift ollin_ribbon_vertexinShaderCore.metal,ollin_medium_fragmentinShaderStrokes.metal, the coat and ground inMetalRenderer+Effects/.swift +Targets.swift).strokeMedium(_:)/noStrokeMedium()is stack state shading the ribbon per pixel in its own coordinates:StrokeMediumis.dry((withtooth: softness: roughness: palette: seed: ) .pencil/.charcoal/.pastel/.pastel(as its settings),palette: seed: ) .bristles,.dryBrush,.wet,.oil; the stroke's color is the pigment, its alpha the density. The ribbon's coordinates ride a second vertex slot (ruled 10-21): a ribbon run (a medium stroke, and every shader-painted stroke) writes twoOllinVertexslots a vertex, the second carrying (arcLength, across) inaaand (halfWidth, seed, along, length) incolor, read as one byollin_ribbon_vertexand drawn at half the count (GeometryBatch), so symmetry, retained batches, kept passes, and trims carry it unchanged and every other run keeps one slot, byte-identical (the whole snapshot table held unrecorded). The distance along is the path vertex's arc length plus the offset along that vertex's tangent (the bisector of its two segments), one affine map around each path vertex so every triangle meeting there agrees and a cap runs past the ends; a closed loop's last segment is told by its triangles naming both the last and the first path vertex, which there reads the whole length (never the expander's emission order:.isRibbon OllinExpanderis pinned to the committed WebAssembly copy by hash); a dash reads its place on the whole path; across is the offset over the local half-width (floored at half the fringe), signed as the shader paint's distance.ShaderInfoon a paint gainsarcLength/across/halfWidth(0 / edge over half-width / half-width on the analytic path; 0 on fills);halfis a Metal type, never a variable name in a generated wrapper. One coat per stroke: each medium stroke is its own batch (currentPaintCoat), its vertices ordered every core triangle ahead of every fringe triangle (a fringe triangle is one with a zero-coverage corner), drawn once underClipStateKey(equal to the clip level with bit.Stencil .coat 0x80clear, invert that bit) and once more by a no-color draw of the same triangles under.coatClear(zero bit0x80), so a crossing reads one coat, the next stroke starts clear, a second mark layers over the first, and clip levels (which never reach bit 7) are untouched; Metal keeps stencil results in primitive order inside a draw, which is what lets a core beat a fringe; the fragment never discards, so a bare-paper pixel still claims its samples; the canvas then carries a stencil (usesCoatStencil,usesCanvasStencil), a layer setsneedsStencil. The dry media's tooth is the paper's: canvas-fixed, seeded by the medium alone, two octaves of value noise evened out to near-uniform by a logistic of their spread, so a density reads as the share of grains inked (a third-density pencil line inks under 0.6 of the full line's share with each inked pixel as dark: specks, not a fade); a brush's streaks are seeded per stroke from its first point on the canvas. Wet ground (ruled 10-21: this frame minus wet strokes, never the previous frame):encodeStrokeGroundPassdraws the frame once more with everyreadsGroundrun skipped (skippingWetStrokes, inside replayed batches too) into a cached MSAA target resolved forollin_medium_fragment, which drags eight taps back along the screen gradient of the arc length (exact inside a triangle); on a piling canvas the pass blits the accumulation MSAA in and loads it, so the ground is the pile plus this frame's other marks; nil and no second draw when no canvas stroke reads it; a wet stroke in a layer has no ground and notes once. Routes: the analytic shapes with a polygonal outline hand it to the ribbon (withDashedOutline), the rest note once, as do a brush (it wins), a shader stroke (it paints), outline-glyph strokes, 3D lines, and feature edges. Vector export writes the flat ribbon (a note; the line a plotter draws). On the web page every medium crosses (.dry/.pencil/.charcoal/.pastel,.bristles,.dryBrush,.wet,.oil): each stroke is aWebSource.ribbonsof its prepared runs (deduplicated, subdivided, a half-width and a color per point, fractions for a dash, the whole length, the seed), item.ribbonswith the medium's twelve rows (WebStrokeMedium, the last the drag's reach and oil's relief); the ribbon's coordinates come from.rows RibbonFrameinOllinExpander, the one place both the Mac'sappendRibbonand the page'sWebSourceExpander(wasm export.expandRibbons ollin_expand_ribbons, thirteen floats a vertex, cores then fringes) work them out; the shading is themediumlibrary section ofShaderStrokes.metal(ollin_medium_dry_ink,_palette_index,_bristles,_dry_brush,_relief), called by the Metal fragment and translated for the page'smediumFragmentTail; the coat is aSTENCIL_INDEX8on the drawn buffer (bit 0x80, equal-then-invert, then a no-color zeroing draw), none where a surface keeps depth for marched fields. The wasm routes every stroke through one@inline(never)strokeVerticesso it holds one copy of the expander (108 KB). A wet or oil stroke on the canvas drags the canvas the page draws first (the item'sreadsGroundflag, set only on the canvas;drawItemsdraws the same items once more into a pooled surface with every flagged stroke left out, as the Mac's ground pass does, and binds it to the fragment's drag; the drag reads the window gradient of the distance along,mediumFlipturning the ground's row (1 - ywhere the surface rasterizes upright,ywhere it does not) and the relief's screen y (-flip); in a layer it keeps its pigment, as on the Mac). The one refusal left is a wet stroke over a canvas that keeps its paint (noClear: the Mac's ground starts from the pile, the page's would not).WebStrokeMediumTests: the round trip within float steps, the dry page at 0.30 mean with under 1% far pixels (speckles a float step tipped), the wet and oil page at 0.09 mean and 0.01% far, red under a missing ground (4.05), a flipped ground row (4.1% far), and the relief lit from below (2.7% far), and the pile refusal by name. The press, onStrokeMark:pressureDeadZoneandpressureCurveshape the raw reading before the filter and every response, andmaxWidthChangelimits the width multiplier's change per point traveled atstore(append(_:)takes samples as given). ExampleShapes/; snapshotsShadedStrokes stroke-medium-pencil/-charcoal/-pastelandstroke-media;StrokeMediumTests(the speckle reading, one renderer, both pigments across a bristle stroke, one coat at a crossing and inside a clip and two coats for two marks, the wet drag's red share against the tap geometry both ways and on a pile, the ribbon fields at pixel centers and a closed loop's last side, the analytic route, the paper's seed, a retained replay, the flat SVG, the web refusal, the press's shaping); figure17-MarksAndMedia/.StrokeMedia Docs/; Guide Ch 17 § Pencil, chalk, and paint along a stroke: strokeMedium. The pen (Drawing/ Marks .md#media .ink() is the one medium drawn on a wider ribbon than its line and the one that lays two coats. The drawer addsfeather: pooling: amount: speed: seed: ) ribbonSpread(three feathers) to every half-width before expansion and runs the ribbon square past the ends; the fragment takes it back off (halfWidth - 3 * reach) and antialiases the nib's own edge as a signed distance, flush, round, or square as the stroke's cap was (carried on the medium ascap, so the batch splits on it); past that edge the feather reads a fiber field fixed to the canvas (three value-noise families 60 degrees apart, each stretched4 * feather + 6along its own direction and a little thicker than the last, cubed to an even spread) against the pixel's distance over a reach offeather * (, with a thin even halo under it. The pen's pace rides the first slot's1 + 1.5 * dwell) * ( 1 + 0.6 * pool) aa.y(a sample's speed overspeed, 1 for a point with no timing;strokePaceShape, set bydrawMarkfor a mark with timing, keyed to the points' real fractions like the width;StrokeMarkis the dynamics' smoothed speed,.Sample .speed nilfromappend), so every other medium's vertex keeps its 0 there. Poolspooling * (withexp( -a / w) + exp( -( L - a) / w)) wa pen width; a hurried pen (pace over 1) thins byamountand gates streaks whose threshold sits above the noise's whole range at pace 1 or under (a line at writing speed is whole; a threshold inside the range left single specks mid-line).laysOneCoatis false, so ink asks for no stencil and no batch of its own (consecutive pen strokes share one) andencodeMediumRundraws it plain, which is what lays the second coat at a crossing. On the page a ribbon vertex is fourteen floats (the pace last, 0 under every other medium;paceFlag/pacesPerPointFlagon the record, one value or one per point after the fractions),vLengthreaches the fragment flat for the pools, anddrawRibbonsskips the stencil for kind 6; the WebAssembly expander was rebuilt for it.StrokeMediumTests(the feather's rim grows with dwell and an untimed line reads as written, the pools above the middle and absent at pooling 0, two coats at a self-crossing and across two strokes, skips at three times the writing speed and none at it or atamount0); the pen line onWebStrokeMediumTests' dry sheet crosses within the sheet's 0.30 mean. ExampleShapes/InkPen; figure17-MarksAndMedia/;InkPen Docs/; Guide Ch 17 § Ink from a nib, and a line drawn by hand: the pen.Drawing/ Marks .md#ink Lines drawn by hand (
Sources/).Ollin/ Geometry/ HandDrawn .swift handDrawn(onwobble: bow: overshoot: seed: ) ContourandShape, plusblot:onStrokeMark, each returning its own type, through one walk (HandDrawn.apply). The line is resampled every 3 points with its own points kept (only an own point can be a corner, a turn past 35 degrees); each run between corners (an open line's ends count) bows4f(1 - f)across its chord, signed and scaled per run by hash; the wobble is two octaves ofGestureMark.smoothby arc length (26 and 7 points) along the point's own normal, and on a closed loop fades into its own start over the last fifth (60 points at most) so the seam is smooth; an open line's ends run short or long along the end tangent (a trim walks points off and moves the end onto the cut); the blot multiplies a mark's widths by1 + 0.5 * exp(. The stream is the seed alone (plus the outline's index in a shape) and everything is measured in the line's own frame, so a moved line carries its wobble whole and a family wants a seed per line. A mark's widths and speeds interpolate through the resampling and its opacities ride the nearest recorded point; the mark's recording settings are copied.-s / blot) HandDrawnTests(5: the seed and the anchor, the amplitudes and the zero case, the ends over a dozen seeds, a closed square's corners, bow, and fill, the mark's blot and what it keeps).Docs/; Guide Ch 17 § Ink from a nib, and a line drawn by hand: the pen.Drawing/ Marks .md#hand-drawn Fill media (
Sources/+ the bands inOllin/ Drawing/ FillMedium .swift Core/,Drawer+FillMedium .swift ShaderFills.metal,encodeFillMediumRuninMetalRenderer+Effects)..swift fillMedium(_:)/noFillMedium()is stack state shading a fill from its distance to its own edge and the direction out through it:FillMediumis.impasto(,edge: relief: swell: detail: size: second: mottle: seed: ) .knife(...),.wash(withwater: flow: angle: reach: size: edge: seed: ) .gouacheits dry end,.chrome(,edge: relief: reach: ) .glass(,edge: relief: refraction: ) .facetedGlass(...),.rock(...),.marble(,veins: spacing: angle: sharpness: edge: seed: ) .sand(, each with a default static; the fill's color is the pigment (the tint, for chrome and the glasses), its alpha the opacity. The distance rides the geometry (RULED 2026-10-24: rings, not a measured field per shape):grain: edge: sparkle: second: mottle: seed: ) FillRings.makecuts the fill into bands between successive round-joined Clipper2 insets of the cleaned region (offset(by: 0)first, so any winding works), out to the depth the look reads (reachIn: the edge, twice it for sand, more for rock) in 4 to 16 steps of about a point and a half, each band triangulated by libtess2 (even-odd over the two rings) and every corner looked up again by its float position for its ring's distance and the ring polyline's averaged outward normal (sign from the largest contour's area, so either orientation convention works); past the last inset one flat piece. A corner lies exactly on its inset, so the distance is exact at every corner (pinned on a 256-gon disc within 0.05 and the outward direction within 0.99 of the radius, the bands tiling the disc's area within 0.1%); a triangle with all three corners on one ring is off by at most a step. The bands are cached two frames per (contours, winding, reach, step) inFillRingCache, so aShaperedrawn undertranslate/rotateis cut once (cutting a 160-point blob costs 1.9 ms at 12 steps and 2.7 ms at 16 in a release build, about 4,000 to 5,600 triangles). Vertex pairs like a ribbon: a.trianglesrun withGeometryBatchset is.fillMedium isRibbon(count halved), the second slot carryingaa= (distance in canvas points, 0) andcolor= (outward on the canvas, the shape-local place times the CTM's scale), read byollin_fill_medium_vertex, which turns the direction and scales the distance under a retained replay; the pipeline is the triangle key withfillMediumKeyswapped in (MSAA edge, no fringe, no stencil: bands never overlap, so one coat is free). Symmetry folds are laid by the emitter, notreplicated(which moves a place but not the direction in the second slot; a half-turn fold lit from the wrong side without it,aMirroredCopyIsLitFromTheSameSide); a direction maps by the inverse transpose. The relief is the quintic smoothstep (slope and the slope's rate both zero where the rise meets the flat inside): the light follows the slope, and the cubic smoothstep's jumping rate bent the light 2.3 levels a pixel there against the quintic's 1.3 and a straight rise's 5.3 (thePaintMeetsItsFlatInsideWithNoCreasebounds it at 2, measured at a relief that keeps the flank out of the highlight's narrow lobe). Textures sit in the shape's own coordinates (they move with the shape, the light stays on the canvas;theSeedPicksThePaintAndAMovedShapeCarriesIt). The knife's ridges are Voronoi sides of a stretched jittered grid (straight under the stretch), found by the two-pass edge-distance method; the later pass (by hash) ends in a lip, the earlier lies in its shadow. The wash ismix(: at water 1 and no flow it never lightens the ground by a level, at water 0 and no flow it is the flat pigment within a level; the ground is read in six taps back along a direction that drifts with position, out tocover, min( dragged, mix( 1, pigment, density)), water) reach · flow · ((the dry end drags farthest; a bar's trail sits more than 2.5 times as far under gouache), and gouache picks the ground up only in streaks. Chrome and the glasses take a rounded rim1 − 0.75 water) 1 − (1 − t)³(C2 where it flattens); glass reads the ground at−n, straight through the flat middle (column correlation over 0.98 at lag 0) and bent at the rim (under 0.5), Fresnel by.xy · refraction · edge · 0.9 (1 − n.z)³; chrome reflects a studio (sky above a dark floor, the horizon low on the rim) mixed toward the groundr.xy · reachout as the rim turns, over a slow ripple so the middle carries the horizon. The ground-readers (wash, gouache, chrome, glass, faceted glass) share the wet strokes' ground pass:GeometryBatchcovers both media, so the pass leaves them all out and fires for either; inside a layer they draw from their color and note once. The impasto's.readsGround mottle0 is no second color at all (a threshold that never reached "none" left lighter patches; caught by the crease probe). Routes:drawShape,drawPolygon, and the analytic shapes with a polygonal outline throughwithDashedOutline(the fill goes to the bands,bodydraws only the stroke); a shader fill keeps its shader and notes once. Vector export writes the fill flat (a note); the web page refusesfillMediumby name, in a batch too.FillMediumTests(12: the bands' distance and coverage, the lit flank, no crease, the wash never lightening and the dry wash covering, the drag's reach, glass straight and bent, the seed and a moved shape, the mirrored copy, a retained replay, the flat SVG, the web refusal); figure17-MarksAndMedia/; exampleFillMedia Shapes/PaintedFills;Docs/; Guide Ch 17 § Paint, glass, and stone inside a shape: fillMedium.Drawing/ Marks .md#fill-media Dashed strokes (
Sources/+ the cut inOllin/ Drawing/ StrokeDash .swift Core/).Drawer+Tessellation .swift strokeDash(_:)/noStrokeDash()is stack state cutting every stroked path into dashes: theStrokeDashvalue type (lengthsas dash/gap/dash/gap in the path's own units, an odd count repeated the way SVG reads one,phasesliding the pattern along,.dashes(_:gap:)/.dots(spacing:),period,isSolid) andContour.dashed(_:)/Shape.dashed(_:)as the same cut on geometry. Load-bearing: the cut happens once, at the two stroke funnels (strokeRunsinsideappendFringeStrokeandappendBrushStamps, never per entry point), so every path stroke, stroked text, and a brush dash through one rule; each run carriesfractions(where its points sit on the whole path), whichstrokeHalfWidths, the along-path color, and a brush's width/opacity (Drawer.fractionMap) read, so a profile or gradient runs on across the gaps rather than restarting per dash (aProfileReadsTheWholePathAcrossTheGaps); a positive phase carries the dashes forward (the pattern position at arc lengthsis(, the opposite sign from SVG'ss - phase) mod period dashoffset, sophase: time * kmarches); a closed path's seam dash is merged (last piece + first) so the join at the first point stays a join, and one dash covering the whole loop leaves it closed; a zero-length dash is nudged 1e-3 along the path so its caps have a direction (a dot under.round, nothing under.butt), and a zero-length dash exactly on the first or last point counts; the analytic shapes with a polygonal outline hand it over throughwithDashedOutline(circle/ellipse viaSDFOutline.ellipsesampled atcircleSegments(, rect viafor: ) SDFOutline, the three triangles, ngon, star, trapezoid, parallelogram): the fill stays the instance with the stroke cleared and the outline expands as a closed path, so a dashed ring also takes a profile and a brush for as long as the dash is on, while the traced shapes (heart, moon, ...) keep their band and.roundedRect noteOnce;svgRecordmakes the same cut (dashCut, the sameSDFOutlinesamplers for the two analytic elements) and writes the dashes as one<path>of open subpaths, the fill recorded first as the element it was (a plotter lifts the pen at eachM; PDF and G-code replay the same commands,strokePathsreading the open contours), and dash + profile goes throughvariableStrokeOutline(; each dash records its ownfractions: ) WebSource, so the page expands them as the Mac does; a pattern pastmaxDashesPerPath(20,000) on one path draws whole and notes once. No dash is the byte-identical path (strokeRunshands the input back as one run withfractions == nil). ExampleShapes/; snapshotDashedStrokes dashed-strokes;StrokeDashTests(the pattern rules, the cut, the seam, dots, the profile across gaps, the shape handover, the SVG subpaths, web sources, and three rendered probes).Docs/.Drawing/ Drawing .md#strokeDash Instanced meshes (
drawMesh(+_: instances: ) MeshInstanceinSources/; theOllin/ 3D/ MeshInstance .swift .meshInstancedrecorder inDrawer.swift, the encode arm inMetalRenderer+Effects, the shadow legs in.swift MetalRenderer+Targets,.swift ollin_mesh_instanced_*inShader3D.metal). One mesh, many placements, ONE draw: the base mesh expands once per call into its own frame array/ring (LOCAL space, model NOT baked — the per-mesh path's expensive per-copy re-bake is the thing this removes) and each copy is anOllinMeshInstance(OllinShaderTypes.h: model float4x4 + tint, stride 80) applied per vertex on the GPU; the[MeshInstance]form composes the CTM per copy at record time (T·R·S,rotationaRotation3Dwhose matrix goes through the drawer's own axis-angle helper, pinned bit-exact against the equivalent translate/rotate(_:)/scale sequence;Rotation3Dis the three angles the old.euler( x: y: z: ) Vector3form meant, within float rounding of the rotateX/Y/Z sequence), the GPU-resident form (ComputeBuffer<OllinMeshInstance>, carried in the batch'sparticleBufferlike the point-cloud path) is absolute world space by design (the kernel owns placement). Load-bearing: the instanced vertex emits the solid path's ownMeshOutand reusesollin_mesh_fragment, with the whole lit binding set shared through thebindLitMeshFragmentlocal function in the encode loop (extracted from the.mesh3Darm — the two arms must never drift), so copies take fill/finish (PBR included), lights, shadows received, IBL, GI, and fog identically (pinned within tolerance by the A/B render test); the normal transform is the adjugate of the model's linear part, computed in-shader (exact under non-uniform scale after normalization) — deliberately no normal matrix in the struct, so a compute kernel fills only model + color; batches carry explicit vertex/instance start + count (never next-batch run-length arithmetic — no other batch creator records these starts); copies cast into the 2D shadow map (.meshInstancedShadow) and the point cube (instanceCount = copies × 6, face = iid % 6, copy = iid / 6; the layered-topology gate inmakeShadowPipelinekeys onpointShadowOp != 0because both point-shadow vertices writerender_target_array_index), and a frame whose only casters are instanced still renders its maps (the shadow-pass guard takes instanced casters as geometry); the[MeshInstance]form is added to the traced scene as one instance per copy (MTLInstanceAccelerationStructureDescriptorover the plain meshes' structure plus one per instanced batch's base mesh — so a copy costs a matrix there, never a triangle list), which is what puts a copy in a ray-traced reflection, under a traced point/area shadow, and in the GI bounce. Load-bearing, four parts: the base vertices are appended to the mesh buffer after the plain ones so ONE pointer still serves the hit fetch (tracedMeshVertexCountreserves the room wherever the buffer is asked for; no room = copies left out, never a write past the end); the hit-lookup table replaced the flat per-geometry offsets with count, then one five-uint record per instance (base vertex, the copy's tint as three float bit patterns, and the run's material slot), then the per-geometry offsets (ollin_rt_hit_lookup,OLLIN_RT_PLAIN_MESHmarking the record that reads the geometry table instead) — every directgeoOffsets[...]read goes through it; a copy's normal takes the transpose of the query's world-to-object matrix (the inverse transpose, exact under non-uniform scale); and every traced signature is nowinstance_acceleration_structure+intersection_query<triangle_data,(28 + 18 sites, the stand-in structure wrapped to match, and every encoder that binds the scene callsinstancing> useTracedScenebecause an instance structure reaches the structures under it indirectly and they are not resident on their own), so there is one structure type and no per-scene shader variant. The extra structure level is not free, and one line pays for it: every query now declares the scene throughollin_rt_params(assume_geometry_type(+triangle) force_opacity(, so a hit commits inside traversal and each caller's candidate loop never runs; since 2026-11-29 that hint is the shadow rays' and the thickness walk's alone: the closest-hit walks force non-opaque so that two faces at one distance are settled by order, the 3D bullet's tie rule, which gives back part of what the hint bought them, 1.3 ms of a 53 ms mirror frame). Measured (M2), and the sign differs by ray kind: the reflections example at 1080² read GPU 24.75 → 21.23 ms (14% faster) than before this work with no copies in it at all, while the soft-shadow stress benchmark at 2160² reads 22.08 → 23.46 ms (+6.3%) at 1 ray and +9.7% at 64 — closest-hit rays gain more from the opacity hint than the instance level costs them,opaque) accept_any_intersectionshadow rays gain less.assume_identity_transformswas measured too and recovers only ~2%, so the level itself is the cost, not the transform. Read the first of those two figures narrowly:--bench --gputhen encoded no deferred reflection pre-pass, so the mesh fragments took the inline trace and the number describes that path, not the live frame (which reads the pre-traced layer). The harness was fixed with the resolution tier below; the live frame reads 20.23 ms on the same scene. All three placement forms reach the traced scene, the two GPU-held ones (theComputeBufferform,MeshField) throughollin_rt_instance_write(MetalRenderer+RTInstances): only the COUNT is CPU-known, so the build reserves the instance slots and one thread per copy fills both the 64-byte.swift MTLAccelerationStructureInstanceDescriptor(its layout mirrored in MSL,optionspassed in rather than hardcoded) and that slot's five-uint hit record, from the same placement buffer the draw reads — which is why the hit table is now written CPU-side as head + tail around the GPU gap rather than as one array, and why a run whose pipeline will not build is dropped whole (stale descriptors would be traced). A field's base meshes append after the instanced ones (one expansion per distinct mesh, never per copy) and each entry takes its own structure; every copy joins, culled or not (the raster cull is against the camera; a reflection sees what the camera cannot). A traced copy costs ~2 µs of GPU per frame on an M2 whatever placed it (measured 1→8,000 copies: GPU 4.19→19.56 ms, the shipped list form reading the same curve), soMeshField(default 20,000) keeps the 240,000-copy case from spending the whole frame there: over budget the field leaves the traced passes whole and says so once, naming both numbers. Copies reach the path-traced export too, which is what the fifth uint of the hit record is for: that export resolves a finish per geometry, and every copy of one base mesh shares a single geometry, so each run takes its own slot past the plain geometries in the same.tracedCopyBudget OllinMaterial/OllinPTTexEntrytables (the map gates lowered, since a copy's raster draw binds no maps) and a hit reads it throughOllinRTHit.mat. A batch the traced scene turned away (an over-budget field, a matcap prop) keeps rastering over the traced layer rather than vanishing:pathTracedCopyBatchesis the set the composite arm consults, and the export's own traceable-scene guard now takes a frame made only of copies. One envelope, stated rather than silent: a glowing copy is not sampled as a mesh light (the CDF weighs each emissive triangle by its world area, and a copy's triangles are unplaced — for the two GPU-held forms the CPU never sees a placement at all), so its hit emission takes full MIS weight throughcopiedand its light arrives by the paths that find it, unbiased but grainier. The remaining exclusions are documented, never silent: textures/wireframe/matcap fall back to the solid look with a one-time note, not in the screen-space pre-passes (contact shadows / SSAO normals / scatter mask) or the mover velocity pass, refused insidemakeBatch(the retained-mesh shadow rule), spatial export records the array form per copy and refuses the GPU form with a note, SVG skips meshes as ever. Measured (M2, 1080², release, lit + shadowed 12,398-copy field): CPU record 11.99 ms/frame per-copy loop vs 0.23 ms instanced (53×); GPU identical (~56.6 ms in that stress scene) — the win is CPU elimination, the roadmap's own framing. ExampleRendering/(A/B parameter vs the per-copy loop); snapshotInstancedMesh instanced-mesh;InstancedRayTracingTests(the traced probes, live and path-traced, each verified red by sabotage);MeshInstanceTests+MeshInstanceRenderTests(the A/B equivalence + the pipeline-build test that keeps the RT-dev-machine-unreachable cube leg compiling) +MeshInstanceBenchmarkTests(Scripts/). Per-copy motion (benchmark .sh instancing InstancedMoverRange,Drawer,.recordInstancedMover ollin_mesh_velocity_instanced_vertex): a list draw insidewithMotionkeeps its composed copy matrices under the block'sMoverKey(sharing the block's draw counter with mesh movers) ininstancedMoverHistory(pruned likemoverHistory, counted by the census); a frame whose count equals last frame's appends last frame's matrices tomoverPreviousInstancesand records a range, copy i to copy i; a changed count, a first sighting, or a skipped frame records nothing and restarts. The velocity pass uploads the frame's instanced base vertices, placements, and previous matrices into its own ring slot (one per encode, 256-byte-aligned regions), so no caller passes instanced buffers; every main-canvas instanced draw now occludes in phase 1 (the list form from the upload, the compute form from its own buffer; before, copies neither moved nor hid a mover), the movers draw in phase 2 withpreviousOfCurrentthe identity. Pinned: each copy's own delta, the instanced field equal texel for texel to onewithMotionblock a copy, an instanced wall hiding a mover, an export's streaks against separate movers and repeating byte for byte (InstancedMotionTests, two planted defects red). The compute-buffer andMeshFieldforms note once and keep the camera's motion (DESIGN-NOTES, 3D mode). Mechanism:ARCHITECTURE.md§ Instanced meshes and mesh fields.Docs/; Guide Ch 30 § Ten thousand of the same thing: instancing.3D/ Instancing .md Mesh fields (GPU-culled worlds) (
Sources/;Ollin/ 3D/ MeshField .swift encodeMeshFieldCulling+ the.meshFieldarm inMetalRenderer+Effects; the field shadow legs in.swift +Targets.swift;ollin_mesh_field_*inShader3D.metal). A retained world of many distinct meshes + copies drawn by ONEdrawMeshField(_:):place(_:at:)expands each mesh once into a concatenated base-vertex buffer and appends its copies (OllinMeshInstance) plus anOllinFieldEntry(local bounding sphere, vertex run, copy run, compact region — all inOllinShaderTypes.h); per frame a GPU cull kernel (one thread per copy, sphere-vs-frustum through the copy's matrix × the draw-time field matrix, Gribb-Hartmann planes from the unjittered view-projection) atomically compacts survivors per entry (under a fixed clock the camera set compacts in copy order instead: a SIMD-group count, one serial scan that also gives each entry its base and count, a ranked write, since copies meeting at equal depth draw whichever lands first and the example came out three ways in four renders; culled then equals unculled to the pixel; the shadow set stays atomic, since a depth map keeps the nearest depth in any order), and an encode kernel writes oneMTLDrawPrimitivesIndirectArgumentsper entry withbaseInstance= the entry's compact offset, so[[instance_id]]lands directly on that entry's slice of the compacted-index buffer and the vertex fetchesinstances[compacted[iid]]with zero per-draw bindings; the render arm issues one indirect draw per entry (CPU cost per KIND, never per copy). Load-bearing: the draws are GPU-authored but deliberately NOT anMTLIndirectCommandBuffer— Metal rejects the RT-compiled lit fragment inside an ICB pipeline ("Fragment shader cannot be used with indirect command buffers"), and indirect draws carry the identical payload with no fragment restriction, so copies keep the FULL solid shading (the sharedbindLitMeshFragmentset) on every device; culling must never change the picture (a culled copy is off-screen by definition;cullingChangesNothingInThePicturepins it, andfieldis the public A/B switch); the cull runs at drive level (.isCullingEnabled = false encodeMeshFieldCulling, afterencodeComputein every depth-carrying drive) and the draw arm requiresdepthFormat != nil, which doubles as the stale-arguments gate (the 2D-only accumulating drives never cull, so they never draw a field); surface color bakes atplace(mesh base color × per-vertex colors × per-copy tint — the draw-timefilldeliberately does not tint a field); shadows cast UNCULLED from the field's own retained buffers (ollin_mesh_field_shadow_vertex+ the cube sibling withiid % 6face routing; a caster behind the camera still shadows the view); a field can be drawn more than once a frame: every draw is a batch with afieldView(its place among the frame's draws of that field) and is culled through its own pass's view into products of its own (MeshField: view 0 is.cullProducts( view: for: ) GPUResources.first, a later view is made the first time a frame draws the field that often and dropped when the field regrows; the ordered compaction's scratch is one for all views, since a view's three passes finish before the next view's begin), so one field on the canvas and in a layer shows each view its own visible set, and a draw under another matrix is the copies placed again; a draw that repeats an earlier placement (the same field under the same matrix,fieldPlacementRepeats) is the same copies seen again, and whatever counts the world passes over it (the shadow cull and both shadow draws, the traced structure,tracedMeshVertexCount), so two views cast once; spatial export walks the CPU-kept placements per copy;placeafter realization bumpsgenerationand re-uploads. A field also stands in the traced scene (its base meshes appended to the frame mesh buffer, one structure per entry, one GPU-written instance per copy — see Instanced meshes), the path-traced export included, bounded bytracedCopyBudget(default 20,000; over it the field leaves the traced passes whole with a one-time note naming both numbers, since ~2 µs of GPU per traced copy per frame would make the 240k case unusable — in the export it then rasterizes over the traced layer, which is the difference between out of the mirrors and out of the picture). The old RT-device point-caster exclusion is therefore gone: a field now casts a traced point shadow like a plain mesh. The 2D shadow pass culls against the light's own frustum (exact: anything culled would have been clipped by the map's rasterizer; the cube pass stays uncculled, omnidirectional) — and the shadow-cull dispatch must rebind the instance buffer at index 0 (the encode dispatch just repointed it at the draw-arguments buffer; missing that rebind culled against garbage matrices and silently dropped real shadows, found by the culled-vs-unculled A/B). Measured (M2, 1080², release, the example's 240k-copy plain, lit + shadows + fog): GPU 18.5 ms culled vs 50.8 ms unculled (2.7×), CPU record ~0 ms (Scripts/). Examplebenchmark .sh field Rendering/MeshField(240k solids, fly-through, culling parameter); snapshotmesh-field;MeshFieldTests+MeshFieldRenderTests(field == equivalent instanced draws; culling == no picture change; the RT-unreachable cube shadow leg compiled explicitly) +MeshFieldBenchmarkTests; the two-view statements are inLayerCameraTests(one field in two views against two twins, one field placed twice against two fields, a repeat's missing shadow cull read off the frame's dispatch count). Mechanism:ARCHITECTURE.md§ Instanced meshes and mesh fields.Docs/§ A field that culls itself; Guide Ch 30 § A world the camera trims: MeshField.3D/ Instancing .md Strand fields (in-draw grass) (
Sources/;Ollin/ 3D/ StrandField .swift ShaderStrands.metal, the first mesh-pipeline segment;makeMeshPipeline+ the.strandsarm in the renderer).drawStrands(grows grass-like blades ENTIRELY inside the draw call through a Metal 3 mesh pipeline (_ field: StrandField) MTLMeshRenderPipelineDescriptor, built from the same runtime-compiled library — the[[object]]/[[mesh]]stages compile throughmakeLibrary(,source: ) <metal_mesh>included byShaderCore): no vertex, index, or instance buffer exists anywhere; every blade's root, height, lean, bend, sway phase, and tint derive from hashes of its index (the shader library'shash22/hash33), so aStrandFieldis a plain value with zero GPU state to invalidate. Load-bearing: the object stage runs one threadgroup per tile (frustum-culls the tile's AABB —isCullingEnabledis the pinned A/B: skipping tiles must not change a pixel — and grades the tile's per-blade segment count 4→1 betweendetailNear/detailFar; thedetailparameter is that dial's A/B), and the mesh stage emits bundles ofOLLIN_STRAND_BUNDLE(24) blades, one thread per blade, into the solid path's ownMeshOut, so blades shade throughollin_mesh_fragment(full lit set viabindLitMeshFragment: lights, shadows RECEIVED, IBL, GI, fog, the current finish) — a mesh pipeline pairs fine with the RT-compiled lit fragment (probed; unlike ICBs, which reject it);MTLGPUFamily.metal3is the only honest capability signal, and everything nearer the failure lies — a paravirtualized GPU (a VM's display, a hosted CI runner) compiles the[[object]]/[[mesh]]stages, builds the descriptor, and answersrespondsToSelector:true forsetObjectBytes:and its siblings, then raiseslength: atIndex: unrecognized selectoron the first one called, which is an uncaught Objective-C exception, so what should have been a missing feature was a killed process taking every other test in the run with it (it crashed the CI test job twice on 2026-09-01, the second time through a selector probe that the stubs defeated). Measured on the runner:Apple Paravirtual device,apple5/mac2true,apple6-apple9andmetal3false, pipeline built, all four selectors true,setObjectBytesexit 134. SoMetalRendereris.meshShadersAvailable( on: ) supportsFamily((with.metal3) OLLIN_NO_MESH_SHADERS=1forcing false), the arm leaves the field undrawn with anoteOncewhere it answers no, andSnapshotgates the two tests that draw one (.hasMeshShaders strandPipelineBuildskeeps the plain Metal gate, since building is all it asks, and it does build there); mesh capacities are sized inOllinShaderTypes.hfrom the bundle andOLLIN_STRAND_MAX_SEGMENTS(240 ≤ 256 verts, 192 ≤ 512 prims — change either, re-check both); a dead mesh thread still writes degenerate zeros so the fixed layout stays initialized, and thread 0 alone setsset_primitive_count; sway is driven by the sketch clock (computeUniforms), so exports reproduce and the same frame renders byte-identically (pinned); the blades exist only in-draw, so they cast no shadows (they receive), the spatial exporter refuses with a note, SVG skips,.time makeBatchrefuses. The honest pitch is architectural, per the platform's own guidance (mesh shaders earn their place only where draws cannot express the geometry — a blade's per-length bend is exactly that): measured (M2, 1080², release, the 511,584-blade meadow, lit + shadows + fog): ~22.5 ms GPU, zero geometry memory, zero per-frame CPU; distance grading saves a further ~15% (1.15×) over full detail (Scripts/). Examplebenchmark .sh strands Rendering/Grassland(detail parameter); snapshotstrands;StrandFieldTests+StrandFieldRenderTests(pipeline build, byte-exact determinism, tile-cull invariance) +StrandBenchmarkTests.Docs/3D/Strands.md; Guide Ch 30 § Grass that was never built: strand fields.The ocean (
Ocean/WaterSurface/OceanFieldinSources/;Ollin/ 3D/ Ocean .swift makeOceanField(+_: at: resolution: ) drawOcean(;_: segments: tiles: water: ) Renderer/, theShaderOcean .metal .oceanorigin and batch in the renderer). A wind sea written as a spectrum (Phillips, from Tessendorf's published account, credited inATTRIBUTION.md) and turned into a surface by one inverse Fourier transform of it, then drawn as water by a grid with no geometry buffers anywhere: each vertex works out its corner from its own index and reads the field for where the water has carried it. The field is an ordinary layer (rgba32Float, one texel per grid point: sideways x, height, sideways z, fold) so it filters, combines, and draws like any other. Load-bearing:waveHeightis a measurement, not a dial (significant wave height in world units) because the variance of the surface is the sum of the spectrum over the whole grid, a closed form the CPU evaluates once per sea state (cached on the drawer, 65k terms at the default resolution) and scales the spectrum by, which is what holds the height steady across resolutions and wind speeds (theSurfaceStandsTheHeightItWasAsked/theHeightHoldsWhenTheGridChangesmeasure it off the GPU's own output); one transform carries the whole surface, the height in rg and the two sideways shifts packed as one complex number in ba, since both are real fields; the fold (the Jacobian of the sideways shift) is read in the resolve pass by neighbor differences, never by a second transform; h0 comes from a hash of the grid index through Box-Muller rather than from stored state, so a field is a pure function of (sea state, time) with nothing to invalidate andseedreproduces exactly;loopSecondsrounds every frequency down to a multiple of one step, which makes the whole surface periodic (pinned: t = 0 and t = period match inside 2 levels while the halfway frame differs); the normal is read per pixel from the field (four taps, central differences of the moved surface) rather than carried down from the vertex, so the light runs over the water at the field's resolution rather than the grid's; the reflected ray is folded up at the horizon (r.y = abs(r.y)) or an environment's flat ground reads as pale plates lying on the water with the map's own horizon for an edge (a real fixed defect); the sun glitter uses the same Fresnel term the sky does, or it spreads into flat white plates wherever the sea is smooth (the second fixed defect); foam is a smoothstep on the fold broken by noise at two scales, since a ramp from nothing whitens half the sea and a flat patch of white reads as paper. Like a strand field the geometry exists only in-draw, so it casts no shadow, is not in the ray-traced structures, and the vector and spatial recorders skip it with a note;material(_:)does not apply (its own water fragment). Measured (M2, 1080², sky environment + sun,Scripts/): 1.4 ms GPU at 160 segments over a 256 field, 1.8 ms at 320/256, 2.8 ms at 320/512, 3.7 ms at 512/512 (doubling either the grid or the field costs about a millisecond at that size).benchmark .sh ocean OceanTests(12: the height, its proportion, its steadiness across grids, wind moving the energy rather than the height, the fold, determinism, the loop, the drawn surface moving, plus the closed form with no GPU); snapshotocean; example3D/Geometry/Ocean;Docs/3D/Ocean.md; Guide Ch 30 § The sea, from what a sea is made of: an ocean spectrum. The amplitude cache is bounded (256 sea states, then cleared): a sea state that follows the clock added an entry a frame (SoakTestsfound it).Retained batches (
Sources/+Ollin/ Drawing/ Batch .swift encodeRetainedinMetalRenderer+Effects)..swift makeBatch { }records a drawing once into aBatch(persistent, made insetup()and held — theFeedbackshape) anddrawBatch(_:)replays it from the handle's own once-written per-deviceMTLBuffers — the escape from per-frame re-recording for static heavy content (measured M2 1080² release: 150k circles ~13.5 ms/frame per-frame vs ~0.003 ms replayed; example parameter flips the two live). Load-bearing: recording is an array swap on theDrawer(per-frame arrays + batch list + gradient-row table), so recorded runs index the handle's arrays and baked gradient rows are handle-relative — the replay binds the batch's own strip texture, never the frame's; the body runs style-scoped (pushState/popState) from an identity CTM with the target/clip stacks swapped out, and the.retainedreference batch supplies the draw-time context (CTM + target + clip level +depth(at:)); the draw-time CTM is carried in flag-gatedUniformsfields every 2D vertex shader applies to its output position only (flag 0 outside a replay → ordinary paths byte-identical, snapshot suite unchanged; identity replay byte-identical to the per-frame drawing, pinned byBatchRenderTests; SDF analytic AA stays exact under any replay transform because shape-local interpolants never change); unsupported content is gated at its funnel with a one-time note (meshes + 3D fields would silently lose shadows/reflections; particles; layer blocks; clipping;background; nesting) — never dropped after recording, which would corrupt the next-run count derivation; point clouds record camera-less and replay through the frame's camera (the 2D replay CTM doesn't touch them); draw-time symmetry does not fold a replay (record folds inside the block); vector export flipsOllinAppfor the whole.isVectorExporting recordVectorFramedrive (setup + warmup included) somakeBatchcapturesSVGCommands instead anddrawBatchsplices them under the composed CTM — SVG/PDF see every stamp. ExampleRendering/; snapshotRetainedBatch retained-batch;BatchTests/BatchRenderTests. Mechanism:ARCHITECTURE.md§ Retained batches.Docs/.Drawing/ Batches .md Kept shapes (
Sources/+Ollin/ Geometry/ ShapeMemory .swift drawShapeinCore/, the plain-stroke path inDrawer+Text .swift Core/). ADrawer+Tessellation .swift Shapedrawn again unchanged copies its fill triangles and stroke instead of working them out again. Load-bearing: everyShapecarries aShapeMemory(aletbox allocated at init, shared by copies, outside==, which is written by hand over contours and winding); it recognizes its shape by holding the contours array and comparing buffer identity plus winding, so an edit to any copy must copy the contours first and can never match stale geometry, and no observer allocates a box per edit; nothing is kept until the second draw (a fill on its second draw; a contour's stroke on its second draw under the sameStrokeKey: half-width, join, cap, andctmScale, the last because the fringe is about 1px on screen), handed back from the third, so a shape made and drawn once a frame pays a lock and nothing more; a stroke is kept only whenstrokeIsPlain(solid paint, no brush, no dash, uniform width and opacity, no web sources recording); kept stroke vertices are pre-transform (position + coverage) and take the frame's color and transform as they are appended; the kept triangles are theVector2striangulatedFillreturns, so a gradient fill still reads its paint at full precision. Every plain solid stroke, kept or not, expands into a list of its own and is appended in one pass (appendExpandedStroke), its batch checked once a stroke: a per-vertexensureBatchwas three quarters of a stroke's CPU. Byte-identical: 150 of 150 frames of a peer's 195-outline sketch match HEAD, and the snapshot and stroke suites pass unrecorded. Measured on an M2, release: 124 ms to 5.9 ms kept; a stand-in of 196 outlines, 107 ms to 28 ms as new shapes and 5 ms kept. A stored field changesShape's layout, so a sketch dylib built against the old module must be recompiled (a live host that reloads one segfaulted; filed).KeptShapeTests(6; seven plants red).Docs/§ drawShape; Guide Ch 19 beside batches.Drawing/ Drawing .md SDF combinators (
Sources/+Ollin/ Drawing/ SDF .swift Renderer/; 3D inShaderCombinator .metal Sources/+Ollin/ Drawing/ SDF3D .swift Renderer/). Compose signed-distance fields so shapes merge instead of stack — the field-combining axis the per-instance SDF path can't express. The typedShaderRaymarch .metal SDFvalue type (leaf region shapes +.union/.smoothUnion(_:k:)/.subtract/.smoothSubtract/.intersect/.smoothIntersect/.morph, the hg_sdf joint + detailing ops (the chamfer/stairs/columns trios +engrave/groove/tongue/pipe— crisp nearer-side/body color; the detailing ops are value-type-only (the morph precedent), columns gets block forms; they assume frankly-crossing surfaces — near-parallel faces within the radius echo the pattern, the documented envelope), and.rounded/.onion/.at/.rotated/.scaled/.stretched/.colored/.mirrored/.repeated/.repeatedRadially) draws viadrawSDF(_:)honoring the current fill/stroke/CTM, the stroke tracing the merged outline; the scoped block forms (smoothUnion(+ hard/mirror/repeat variants, and the statefulk: ){ … } sculpt { }block whoseadd()/carve()/blend(_:)verbs mutate per-child mode/melt mid-block — built for the live-coding loop) capture bare region draws atDrawer.appendSDFas leaves, reaching every fillable region shape. Rendering is an "SDF VM": the tree flattens (CPU) to a flatSDFNodeprogram (ownSDFGroupInstance+.sdfGrouppipeline beside the per-instanceSDFInstancepath, which is full at 144) walked per pixel with two fixed-depth stacks (cap 16); smooth ops also lerp the operands' colors (the melt look). Load-bearing invariants: leaves carry no transform (all positioning is XFORM nodes → method-chain order exact:a.at(p).repeated()tiles the moved shape,a.repeated().at(p)shifts the tiling); the leaf distanceollin_sdf_distanceis kept in sync by hand withollin_sdf_fragment's switch (a new region shape goes in both; the per-shape switch stays untouched so single-shape snapshots are byte-identical); polar/radial repeat is the shared sel-5 XFORM (2D fold around origin, 3D around anaxis), the single-evaluation kind (wedge-symmetric content exact, else a seam); region shapes only (lines/open-arcs/Béziers skipped with a one-time log); a field past the caps (depth 16, ~256 nodes) is logged + skipped, never mis-drawn; the buffers thread all 9encodesites. 2D gradient paint samples in field space (in.field; along-path falls back to solid; a solid-leaf field is byte-identical). Per-axis sizing:stretched(x:y:[z:])(iqopElongate, an exact SDF, the preferred tool) vsscaled(x:y:[z:])(true non-uniform, only a conservative bound — rescales by the min scale component for a safe Lipschitz march, so blends distort under strong anisotropy). The raymarched 3D sibling —SDF3D+drawSDF3D(_:): the same ops over the 3D leaves (sphere/box/roundBox/torus/capsule/cylinder/cone/octahedron/ellipsoid/plane + line-between-points/hexPrism/pyramid/cappedTorus/link) plus the sculpting distortions.twisted/.bentand.displaced/.roughened(every distortion/displacement is a distance bound, so flatten attaches a conservative Lipschitz rescale that keeps the march hole-free), sphere-traced through the active camera and depth-composited with the rasterized meshes (a parallel path: ownSDFNode3D+.raymarchpipeline). Load-bearing: the march runs in world space (the 4-tap gradient normal + written[[depth(any)]]come out world-space with no normal matrix); one fullscreen triangle per field bounded by its world AABB (a miss bails O(1)); shading reusesmeshLitColorunchanged, honorsmaterial(_:)per batch (ensureSDF3DBatchrecords the finish — the genericensureBatchrecords none, the bug that left field materials silently ignored) and adds the same IBL ambient the mesh fragments add (incl. the traced-reflection swap underrtReflections; gated oniblEnabled→ byte-identical with no environment;resolveFieldLightingcarries the same setup so the half-res tiers light identically). A field is absent from the deferred reflection layer (that pre-pass traces the mesh carriers only), so every encode that bindsollin_raymarch_fragmenthands it lighting withrtReflectionDeferredcleared and the field traces inline; with the flag set, the ambient's deferred branch reads the fragment's zero stand-in sample and traced reflections silently no-op, leaving the raw environment in place of the traced scene — at the silhouette, where grazing Fresnel mirrors the environment at full strength, that read as a 3-4px blown-white rim band plus one dark pixel, invisible to every patch mean and found by eye (the rasterized mesh beside it swapped in the traced scene and stayed smooth; without ray tracing the two rims match, band and all, so the band itself is the honest picture of a hot environment under the clamp tone map, not a field defect). Pinned byGlassRenderProbes, an edge-aligned rim scanline probe (verified red against the deferred-flag leak). Residual envelope: the rim compresses the mirror image, so the field's single inline reflection ray can read one bright pixel where a mesh's supersampled deferred layer averages (.aFieldRimShadesLikeAMeshRim Docs/§ the field rules). The infinite plane is the one unbounded leaf (flattener marks the field3D/ Combining .md unbounded, marches the near..far span; value-type-only). The block form reaches 3D too — SDF-able mesh builders capture leaves viaDrawer, positioned by the model matrix decomposed to translate+rotate+uniform-scale (the only similarity an SDF respects); a non-primitive.drawMeshPrimitive Meshis ignored (one-time log). Screen-space gradient paint (3D, by each hit's projected screen position); analytic silhouette AA (the ray's closest approach vs the pixel cone). Shadows (gated oncastShadows(), byte-identical off): self-shadows via iq's standardmin(k·h/t)penumbra — not the previous-step refinement, which divides by zero on a receding ray and false-shadows lit faces — plus the full field↔mesh cast/receive matrix across every light type; the per-receiver-pixel point-light cast is trimmed by a conservative AABB early-out + a half-res field-shadow pass. On a device that traces, a field in a pass that traces nothing marches through the build without the traversal (twentyfold cheaper on a GPU that traces in software; see A pass that traces nothing under 3D). Quality dial (raymarchQuality/raymarchResolution): a field's cost is bound to pixel count, not step count, so the dial scales internal resolution via a reduced-res pre-pass (point-sampled depth keeps the silhouette crisp) whose fraction is a coverage-adaptive budget, not a fixed downscale (min(— a dollied-out field traces at full res, the zoom-out-blur fix); the coverage estimate must stay honest or the blur returns: a combine's AABB grows by each op's provable outward reach (smooth/chamfer/stairs1, fraction/ √coverage) k/2, columns/pipe/tonguek, subtract/intersect/morph zero — morph'skis a blend fraction, not a length), never a blanketk, which compounds per nested op until a dollied-out field reads near-screen-filling (a real re-blur bug), and per box the estimate takes the smaller of the corners' clipped NDC rect and their convex-hull area; the automatic tier is live-preview only (export resolves.detail, full-res → default-tier snapshots byte-identical; an explicit fraction/tier is honored on export, adaptively); uses the sharedRenderQualitymodel with the other three quality parameters.ollin_sdf3d_eval's switch stays in sync withSDF3DShape. ExamplesShapes/Combinators*(2D) + the3D/Raymarched*set; snapshotssdf-combinators+ its-gradient/-stretch/-joinery/-detailing/-sculptand-3d*variants. Full mechanism, rationale, and the field-shadow matrix:ARCHITECTURE.md§ SDF combinators.Docs/. Fractal leaves (Drawing/ Combinators .md SDF3D/.mandelbulb( power: iterations: radius: ) .mengerSponge(/iterations: size: ) .mandelbox(, shape tags 15-17, value-type-only): distance estimates read off each fractal's own iterated map, drawn by the same tracer. Load-bearing: the Mandelbox uses thescale: iterations: size: ) (form, never the plain|z| - |scale-1|) / |dr| |z| / |dr|— the plain one is unsigned (≈0 through the whole solid) and over-reaches near the surface (29% of samples 0.01 above a face would step through it), so a grazing ray crossed the face plane and stopped on interior pocket walls whose four-tap normal read as noise (a dark, dusty box; lit correctly only when viewed head-on), while the subtracted form goes negative inside and reaches less far outside, which fixed it with no safety factor. Fractal fields ask for a wider normal step throughSDF3DGroupInstance(the old.normalEpsilon _pad0; 0 = the 0.0008 default, so every non-fractal field is byte-identical): bulb 0.008·radius, box 0.004·half-side, sponge 0 (a clean signed bound), propagated by the flattener as the max over leaves and scaled through.scaled; below it the estimate's sub-step noise, not the surface, sets the normal (the bulb read beaded at the default step). Bounds: the bulb maps its escape ball2^(1/(n-1))ontoradius(AABB padded 5%), the sponge is exact, and the Mandelbox scales the cube its canonical set sits in (2(s+1)/(s-1)per axis fors > 1, 2 fors < 0, measured) ontosizeand clips to it, so it stays bounded for every scale (|scale| held ≥ 1.1).halfis a reserved word in MSL (afloat halfparameter fails the whole library compile, which the headless export used to swallow as "no Metal device";OllinAppnow prints the error). The sponge's carpet test also caught a pre-existing ortho bug in the silhouette AA: the pixel cone was.headlessRenderer t·kPixelfor every projection, but under an orthographic camera the footprint is flat, so the cone inflated by the eye distance, drew a soft halo at every ortho silhouette, and swallowed gaps narrower than it (the level-2 shafts rendered as pinholes); the cone is nowkPixelwhenprojection[2][3] == 0, perspective byte-identical.FractalFieldTests(7 tests on flat top-down renders: the carpet's(8/9)^kcoverage, the see-through center, deeper-only-removes, the bulb's 8-fold turn with a power-5 bulb failing it, the radius bound, the box's octahedral symmetry, size as an exact scale); snapshotsdf-combinators-3d-fractals; example3D/;Raymarching/ RaymarchedFractals Docs/§ Fractal leaves; Guide Ch 33 § Infinite detail: the fractal leaves. A flat field as a slab (Drawing/ Combinators .md SDF→.extruded( depth: ) SDF3D;ExtrudedFieldTests13, figure33-SculptingWithFields/, exampleStandingSlab 3D/,Raymarching/ StandingField Docs/, Guide Ch 33 § A flat field stood up: extruded): the 2D program is lifted node for node into the 3D walk (Drawing/ Combinators .md#slab SDF3D.lifted: a 2D leaf as kind 7 EVAL2D overollin_sdf_distanceat the point's x and y, combines/modifiers/RESTORE_P shared, a 2D transform as the 3D one in the plane with a rotate about z from the packed cosine and sine, a polar fold about z, and a per-axis scale with z at one, where a zero would blow the point up ten thousandfold), then kind 8 EXTRUDE combines the flat distance andabs(as a box's two sides (the exact extrusion), so the melt stays in the plane and the faces stay flat, and an extruded rect isp .z) - half depth SDF3D.boxbyte for byte (the test pins it; the circle equals the cylinder within two levels across a rotation). Bounds, depths, and grow rules are the 2D flattener's with z at ±half depth; the slab stands as the canvas shows it: the lifted program sits inside a half-turn scope about x (one XFORM before it, one RESTORE_P after, theMesh.textturn), with the flat nodes carried exactly as written; a mirror of y instead (negating the leaf's y and every translate's y) made a mirrored field vanish, since the walk's mirror folds onto one side and a fold's mirror image is not a fold (theSlabStandsAsTheCanvasShowsIt: a triangle's apex stays up; the mirrored-and-tiled test is the one that went black); a one-block slab undervoxelizedmust sit half a block off the grid (the blocks' rule). The page carries it:shapesjoined theraymarchsection closure and the page VM has both kinds. The chamfer, stairs, and columns scopes hold a radius at zero from below, as their value forms do (the scopes handed it over as written, and the two spellings drew two pictures). Every public scope, switch, quality setter, camera rig call, text metric, and simulation factory is paired with its core call in six tables of the shapeBareFormsTestsset (SwitchFormsTests,QualityFormsTests,CameraRigFormsTests,CombinatorScopeFormsTests,TextMetricFormsTests,SimFactoryFormsTests: 115 pairs, each also read against a third case it must differ from). A field of many parts is written with skips, and a heavy one is drawn in passes (SDF3D.flatten,SkipBound,skipReach, kind 9 inollin_sdf3d_field;MetalRenderer,.fieldPasses ollin_stippled_out;FieldSkipTests,FieldSkipPictureTests,FieldPassesTests, and the CPU twinFieldTwin; mechanism and proofs inARCHITECTURE.md, A field's skips and A heavy field in bounded passes). Skips are exact or absent: a program of 24 instructions or more gets a SKIP ahead of each combine's second operand (and one past a run of neighbors in a small box), taken where the combine would return its first operand untouched. The field's distance and color are the same bit for bit with and without (the twin at 48,000 points, seven scenes byte for byte on the GPU, the 126-capsule picture identical at 1080 by 1920), so a bound that cannot be proven is not written: an ellipsoid, a Mandelbulb, a plane, an extruded flat field, or a ribbed joint as an operand, and an intersection, a bead, or a morph as the combine. The node limit counts the field's own instructions, never the skips;Draweris the tests' switch; the page gets the program with its skips taken out (.sdf3DSkipPolicy strippingSkips, which rewrites a voxelized scope's backward count). What it buys, measured: every far operand still costs its skip, so 64 scattered capsules read 74 of their 127 instructions a step, and the 126-capsule shadowed picture reads 9.2 billion instructions a frame against 16.7 and draws in 4.8 s against 10.4 (M2, 1080 by 1920, export quality). Passes divide a tile's work in blocks: the count iswalkWeighttimes the reads a pixel can make, times 1,024, times what the build costs a read (1; 1.25 beside a traced shadow and 20 with traced reflections, on software tracing), over a budget of 8 million instructions, 16 passes at most. Each pass shades its share of the sixteen 8-pixel blocks of a 32-pixel tile into the field's own target (the reduced march's, at any scale), and one composite shows them; the cast into a 2D shadow map is divided the same way. A share must be blocks, never single pixels: the GPU shades neighbors together and a group runs as long as its busiest pixel, so a one-pixel stipple made two passes cost twice one and bounded nothing (a light field at 1080 by 1920: 109 ms in one pass; in sixteen, 1,400 by pixels and 192 by blocks). The picture in several passes is the single pass's within a level, and to the byte at a reduced march. Not reached: a field in a layer, under a blend other than the ordinary one, or in the hidden layer's peel (one pass, as before), and a mesh's own march of a field's shadow. A chain of combines is flattened from a list (126 links overflowed a 512 KB stack through the recursive form).User-supplied shaders (
Sources/+ the wrapper/compile/error path inOllin/ Effects/ Shader .swift MetalRenderer). A sketch writes its own fragment shader and runs it through the effect graph. The contract is Ollin-native, not raw Metal: definefloat4 shade((uv 0…1 top-left, return straight sRGB — input layers are read back as straight sRGB too) and Ollin generates the surrounding fragment + vertex. Thefloat2 uv, ShaderInfo info) Shadervalue type (Sendable) carries inline-Stringorresource:in:source,params(up to 32 floats, read viaparam(info, i); the readersparam/sample/sampleAux/sampleRaw/sampleAuxRaware free functions takingthread const ShaderInfo &, never macros —sampleis a member function on every Metal texture type, so a function-like#definerewrotet.sample(s, uv)inside anything the shader included, refused a three-argument call outright, and blocked a helper of the author's own by that name; as overloads a member call is never a candidate, and the whole snapshot table stayed byte-identical through the change), and aModulesopt-in set (.color/.hash/.noise/.sdf/.domain/.visual/.complex; the last is the complex arithmetic on afloat2(cmul/cdiv/cinv/conj/cabs/carg/cpolar/cexp/clog/cpow/csqrt/the trigonometric and hyperbolic set, C's names), thecomplexPlaneframing (imaginary axis up, the domain-coloring generator's own frame atspan = 3 / zoom) anddomainColor(an OKLCH wheel at one lightness plus the modulus and conformal rulings), depending on.color; every helper mirrors the CPUComplexvalue,ComplexShaderTestspaints each one over a grid against it, and the page cuts the section like any other,Arguedin the page-versus-Mac table); routing reuses the effect-graph enums — a.shader(Shader)case onGenerator/Filter/Combine.Kind, so input count is the variant (generate(0,.shader( s)) layer1,.filtered( .shader( s)) a2) — with no new render-graph plumbing. Each shader compiles once per composed-source hash (its own.combined( with: b, .shader( s)) makeLibrary(; failed compiles are cached too, so a broken shader doesn't retry every frame; all caches clear on a framework-shader reload). Friendly errors are the headline:source: ) Shader.initcaptures its call site and the wrapper emits a#linedirective, so Metal diagnostics land at the real, IDE-clickable sketch line (ShaderErrorTestspins the off-by-one semantics for no-newline literals); errors surface via stderr (once per hash) and the pull-modelonUserShaderErrorchannel into the OllinLive overlay — a shader error and a Swift compile error never clear each other. The runner forwards that channel throughShaderErrorRelay(Core/, a change forwarded once, and the next frame's answer forwarded whatever it is afterShaderErrorRelay .swift invalidateUserShaders(or a library reload), so a host never clears the error itself: a) .metalsaved with the same mistake used to match the last report and was never said again, and OllinLive, which cleared its copy on the save, showed a green chip over a broken shader (ShaderErrorRelayTests). TheOllinShaderLibhelper segment (color/hash/noise/sdf/domain +palette/OKLab + the once-compute-only helpers) is one source of truth used three ways: the framework's own segments build on it, it splices into every user shader, andcomposeComputeSourcesplices it into every compute kernel (one helper set,hashNMnames, everywhere); the 2Dsd*distance catalog lives in itssdfsection, shared withShaderShapes;using:keeps only marked sections — a compile-time lever, default[ .noise, .sdf] .all, and now also the escape hatch for a name clash: every public helper sits in a section that can be turned off (lumamoved tocolorandrotate2Dtodomainon 2026-08-27, out of the always-spliced part), so an included file defining one at the same signature can narrow it away; only what the generated fragment itself reads (srgbToLinear/linearToSrgb/ollin_unpremul) is unconditional, and a clash needs a matching signature, not merely the name. Hot-reload covers both forms in OllinLive: an inline shader reloads with the sketch; a.metalresource shader reloads on its own with no swiftc pass (Shader(stores the bundle-resolved path; a watched-resource: in: ) .metalchange routes toSketchRunner); a framework-segment.invalidateUserShaders( ) .metalstill routes to the full library reload (dispatch by path). ExamplesShaders/HelloShader(a Toby-Howard-homage plasma generator, inline beside the hot-reloading.metal-file form) /ShaderFilter/ShaderBlend; snapshotuser-shader. Mechanism:ARCHITECTURE.md§ User-supplied shaders.Docs/+ the per-functionShaders/ Shaders .md Docs/. A pipeline the device refuses is a remembered failure like a failed compile (Shaders/ ShaderLibrary .md userShaderStatechecks the recorded error before building, since the library stays cached; a paint pipeline is remembered by its own key inrefusedPaintPipelines): unremembered, it was asked of the device on every frame.RunLifecycleTestsplants the refusal and counts the asks. What a shader is told about its layer, and what it can hand back.info.resolutionis the layer in its own texels;info.pixelis one canvas pixel inuv(OllinShaderUniforms, filled by.pixel encodeUserShader(fromscale: ) LayerMeasure.pixel, the measure every built-in pass steps by), soinfois the layer's.pixel * info .resolution scale, and at a scale of 1 it is1 / resolution, which is why a shader that ignores it draws the bytes it drew. A combine's is its base's; a kernel's is its field's (runSimulation(); a paint's is one over its pass's size in canvas points (scale: ) bindPaint(), since itsviewport: ) uvspans the shape, soinfois its place on the surface on a Retina drawable, under.position * info .pixel --render-scale, and inside a scaled layer alike. The page's twin is the uniformollin_pixel, the Mac's two floats written aspxon a user shader's layer record and on no other.linearToExtendedSrgbis the encode past white and below zero, exact at 1, the inverse ofsrgbToLinear; it sits in the library sectionuser, which noModulescase names:filterLibModuleskeeps a section it has no module for, and the page takes the section for a user shader's program alone (WebUserShaderGLSL), so a page's own programs and the generated site hero, which carry.make basewhole, weigh what they weighed.sample/sampleAuxstill read through the curve that stops at white; a shader that wants the light above it readssampleRaw.ShaderCanvasPixelTests(9): a disc of 20 canvas pixels reads 20.00 to 20.01 at layer scales 0.25, 0.5, 1, and 2 where the texel reading draws another picture, a filter's step of (10, 6) moves the picture (10.00, 6.00), a combine's 14 lands 14, every kind (generator, filter, combine, kernel) is toldpixel * resolution == scale, a paint finds its place to 0.0004 on the canvas, on a canvas drawn twice as large, and in a half-size layer, a whole-frame shader in a window 1, 1.5, and 2 times the canvas's size is told that scale, and a returned (4, 1, 0.25) is stored as that wherelinearToSrgbstores (1, 1, 0.25). On the page:WebEffectsTestsin the page-versus-Mac table (0.083) and.ScaledUser aUserShadersCanvasPixelTravels. Fourteen plants, each red.Docs/§ Sizes in canvas pixels and § Light past white; Guide Ch 18 § Sizes that hold on a smaller layer: info.pixel; mechanism inShaders/ Shaders .md ARCHITECTURE.md§ User-supplied shaders.A shader as paint (
Paint.shader,Sketch/.fill( _ shader: ) stroke(_ shader:); the.paintvariant of the user-shader wrapper inMetalRenderer+Pipelines,.swift paintPipeline(). Afor: kind: key: ) Shaderfills or strokes any 2D shape, itsshade(uv, info)run per pixel in the shape's own coordinates on all three 2D paths. One shader per run, and the run carries it:GeometryBatchis one more thing.paintShader ensureBatchbreaks on (beside kind, blend, depth, clip, light set), set around each emission byDrawer(.currentPaintShader appendSDF,emitTriangle, the fringe expander,appendStrokedPath), so consecutive shapes under one shader are one draw and an SDF shape whose fill and stroke are two different shaders is recorded twice (fill, then stroke over it; composites as one instance would). The pipeline is the shader's own library, composed like a layer shader's (the helper library with.sdfforced in, thenShaderCore.metal+ShaderShapes.metalwith their quoted includes dropped, the user's source under its#line, and three generated fragments), compiled once per composed hash through the shareduserShaderLibrary(, with a pipeline perfor: variant: ) PaintPipelineKey(hash + the plainPipelineKey's blend/depth/stencil/color format) built by the samemakePipeline(the framework pipelines use, the vertex stages the framework's own (vertex: fragment: using: ) ollin_vertex/ollin_fringe_vertex/ollin_sdf_vertex, compiled into the paint library from the spliced segments, so a paint batch is placed exactly as a plain one); a shader that does not compile skips its batches and reports once (reportUserShaderError). The data rides where a color would: the SDF tag's three-bit paint slots take kind 5 (EncodedPaint, no slot data,isPositionalfalse, the framework fragment painting middle gray if it ever meets one),SDFOut/VertexOut/FringeVertexOutgained acanvasvarying (info.position;FringeVertexOutfrom.opacity aa.ytoo), and under a shader a triangle or fringe vertex'scoloris(withu, v, along, distance) aa.ythe opacity profile (OllinVertexstride unchanged at 32; the plain paths writeaa.y = 0and read nothing, byte-identical). uv is the shape's box:p / (2 size) + 0.5on the SDF path,Drawer.PaintBoxon the others (the outline's bounds for a fill and a closed stroke, inflated by the half-width for an open stroke, the wholeShape's box for every contour, the text run's outlines for outline text; atlas text under a shader fill takes the outline path).distanceisollin_sdf_signed_edgeon the SDF path (the region leaf distance onioned by a hollow band; the capsule, Bezier, and arcs as their painted edge), the expander's new signedStrokeVertex.offseton the fringe path (sign flipped byDrawer.signedAreaso inside a closed outline is negative whichever way it was drawn; the WASM expander rebuilt from the same source,WebExpander.wasm), andDrawer.farInside(-1e6) on a tessellated fill, which has no measured edge;alongis the SDFpathT/ the arc-length fraction on strokes and 0 on fills. Coverage after the shader, exactly as the plain fragments apply it after their paint, so a constant shader equals a flat color byte for byte (pinned over 13 forms, fill, stroke, both, and mixed). A mesh underfill(shader)reads the shader as its base texture, baked once per frame per shader into apaintBakeSize(1024) square generator layer (paintBake, generators fill before any geometry pass, so a mesh in any layer samples this frame's picture), which is why it reaches every pass a texture reaches; no uvs → white and a note; instanced meshes draw untextured (a note). Fallbacks: SVG/PDF/embroidery writePaint.shaderStandIn(middle gray); the web recorder refuses with the call named (fill(), inside aShader) or stroke( Shader) drawBatchtoo; 3D lines and feature edges draw white under a shader stroke with a note; a combine leaf under a shader paint takes no color (white).ShaderPaintTests(13: the constant-shader identity over 13 forms, uv at the corners on both paths within a level and under a quarter turn, the signed distance at pixel centers, a stroke'salonganddistanceand the inside sign on both stroke paths and both windings,position, params, the mesh against the rectangle (mean under 1.5 levels, corners oriented), one run per shader, a broken shader drawing nothing, the web refusal, the SVG gray,Paintas a value); snapshotshader-paint; exampleShaders/ShaderPaint;Docs/,Drawing/ Color .md#shader-paint Docs/; Guide Ch 18 § Paint, not a layer: fill and stroke with a shader.Shaders/ Shaders .md#a-shader-as-paint Including another shader file (
Sources/). Metal's runtimeOllin/ Renderer/ ShaderIncludes .swift makeLibrary(has no include search path, so every quotedsource: ) #includein every shader Ollin compiles at runtime is resolved by hand before the compiler sees it, in the built-in segments, in a user's ownShader(a.metalresource or an inline string), and in aComputeKernel. The rules are the load-bearing part: a file is spliced once per compile (so a diamond defines nothing twice), the root is seeded into that set (rootKey) so a file naming itself is the cycle it is rather than a second copy, a cycle and a nest pastdepthLimit(32) are reported rather than followed, a#lineon each side of a splice means a mistake inside an included file is reported against that file at its own line (the property that makes the include worth having), and#include <angle>forms pass through untouched so a helper can still compile on its own. A spelling that names a place of its own (leading/or~) is taken as it is, which is how a sketch reads a shader library cloned elsewhere on the machine, and that library's own files then resolve from where they sit, so one line brings the whole chain (verified against a real LYGIA clone:generative/pulls six more files and compiles; most of its Metal port does, and what fails fails in its own file at its own line, which is the resolver working). Any other spelling resolves against the folder of the file that named it: its ownsnoise .msl .metal, or the.swiftan inline string was written in (ComputeKernelgained asourcePath, captured from#filePathor the file it was read from, for the same reason). An include problem is raised as the shader's ownShaderCompileErrorbefore the compiler is asked, since what follows would only be undeclared identifiers pointing away from the real mistake. The built-in segments now declare what they need with an#includeat the top, soMetalRendereris an unordered (alphabetical) set and the concatenation order falls out of the declarations: adding a segment is a name in that list plus its dependencies in the file, not a slot in a hand-kept sequence..shaderSourceNames theBuiltInSegmentsCompileInAnyOrdercompiles five orders (listed, reversed, three seeded shuffles) on the real device and is verified red by sabotage; writing it found two dependencies nobody had ever declared, because the fixed order happened to satisfy them (Shader3DreadsShaderShapes'diskCoverage,ShaderPathTracereadsShaderIBL's equirect helpers). The composed user-shader library text is cached perModulesset (userShaderLibraryText, dropped on invalidation), because the compose runs once per shader per frame.ShaderIncludeTests(16).Docs/§ Pulling in another file; Guide Ch 18 § One helper, two shaders: the include line + the SharedHelper figure.Shaders/ Shaders .md Checking a shader (
Sources/+ theOllin/ Effects/ ShaderCheck .swift OllinChecktarget, behindollin check <file). A shader is compiled by the sketch that uses it, so the only way to learn whether it compiles was to launch something that draws it, and the first sign of failure was a blank layer..metal> ollin checkcompiles the file on the real device through the samecomposeUserShaderSourcepath a sketch uses, so a shader that passes here cannot fail in a window, and it builds the pipeline too, not only the library (a shader can compile and still be refused there). It reports the compiler's complaint at the author's own line throughcleanShaderDiagnostics, the shape inferred from the layer readers the shader calls (0 generator / 1 filter / 2 combine, the effect graph's own rule;--asnames it instead, and a wrong shape failing is itself the useful answer), theparam(info, i)indices it reads with a gap called out (an index nothing writes reads as zero and is usually a slip), and the files it included. The readers are matched as calls, not words, sodiscSample(andsampleCountare not layer reads.--usingnarrows the spliced library to the same section list aShader'susing:takes (all/none/a comma run), so a shader written against a subset is checked the way it runs. Several files per run, nonzero exit if any failed.ShaderCheckTests(10); no pixel snapshot (the output is text).Docs/; Guide Ch 18 § Trying a shader on its own: ollin check.Tools/ ShaderCheck .md Visual chains (
Sources/+ theOllin/ Effects/ Visual .swift visualsection ofOllinShaderLib). The fluent composition tier over the effect substrate:.metal Visualis a value type (struct over anindirect enum Node, theSDFshape) recording a chain of per-pixel ops in five families — sources (.oscillator/.noise/.voronoi/.shape/.gradient/.solid/.layer), coordinate warps (.rotated/.scaled/.pixelated/.repeated/.kaleidoscope/.scrolled), color adjustments (.brightness/.contrast/.saturation/.inverted/.posterized/.thresholded/.luma/.hueShifted/.tinted/.colorCycled/.channel), combines (.blended(over the typedwith: _: amount: ) BlendMode,.mixed/.differenced/.masked), and modulations (driver overloads of the warps:.displaced(by:),.rotated(by:),.scaled(by:),.pixelated(by:),.kaleidoscope(by:)— one chain's color perturbs another's sampling coordinate).compile()walks the tree once and emits ashade(uv, info)body overollin_vis_*library functions; the whole chain (drivers included) is one fragment shader, one pass, run through the user-shader path (Shader+ the compile-once source-hash cache). Load-bearing: the generated source depends on the chain's structure only — every numeric argument becomes a params-buffer slot in traversal order (VisualTestspins this), so a chain rebuilt eachdraw()hits the cached pipeline and animated values/@Paramparameters never recompile (structural selectors — blend mode, channel — are spelled as literals by design); the params buffer is 16 rows / 64 floats (OLLIN_SHADER_PARAM_ROWS, raised from 8 —paddedParamsand the wrapper both read the macro), overflow bakes literals with a one-time note; the codegen's fresh-variable counter starts at 1 (st0is the root the body declares — 0 collides);.layerleaves dedupe by target identity and cap at the wrapper's 2 textures (routing by count: 0 →generate, 1 →.filtered, 2 →.combined; extras sample black + one-time note);.layer(_ feedback:)reads the previous frame (video feedback);BlendModeis kept in step with.visualIndex ollin_vis_blend's switch; ops aspect-correct inside the function (coordinates stay 0…1 sofractwraps compose), colors are straight sRGB per the user-shader contract, and.noiseis signed so displacement wobbles about zero;Modules.visualsplices the ops into every user shader (dependencyvisual → hash+noiseinfilterLibModules). ExamplesShaders/VisualSynth(one deep chain) +Shaders/(all five families as a switchable contact sheet); snapshotVisualCatalog visual-chain(all five families + a layer read);Docs/+ the module's function table inShaders/ Visuals .md Docs/.Shaders/ ShaderLibrary .md Layered effects (the substrate;
Sources/). Draw into off-screen layers, filter them on the GPU, composite back with blend modes (the OPENRNDROllin/ Effects/ RenderTarget/Filter/composemodel):makeRenderTarget(→ an off-screenscale: ) rgba16FloatRenderTarget;withTarget(_:) {}redirects drawing into it (scoped likewithState;background(_:)inside clears that layer, and the canvas'sbackground(_:)keeps every layer run recorded before it: with any layer run in the frame,keepOnlyLayerRunsrebuilds the shared lists from the layer runs alone, every implicit start, explicit range, SDF group node range, and web source rebased, so the frame is byte for byte the one whose canvas drew nothing before the wipe; a frame with no layer run takes the old full wipe untouched;BackgroundKeepsLayersTests, nine plants red);target.imagecomposites it back;target.filtered(_:)→ a new layer;postProcess(_:)filters the whole frame. A blur or glowradius(.gaussianBlur/.bloom/.halation) is a pixel count, blurred at sigmamax(0.1, radius), so a share of the canvas written there spreads nothing;Drawernotes a radius in (0, 1) once on both roads (.noteSubPixelSpread postProcess,recordFilter), zero stays silent as the way to ask for no spread (FilterSpreadNoteTests, 3, sabotage-verified). Four examples shipped a fraction there and never glowed. A gray is read as the sketch wrote it (ruled 2026-11-10, in since 2026-11-15). A layer stores light and a sketch names a gray by its display value, so an effect that takes a gray level, works on tones, or reads a layer as numbers goes throughollin_as_written(ShaderEffects.metal: the sRGB curve carried past white and mirrored about zero, and exact at 1, wherelinearToSrgbcuts both ends and lands one float short of 1, which a half float stores a whole step lower) and writes back throughollin_as_stored. The pair lives in the effects segment and not in the library's core, which every program on an exported page carries whole: in the core it added 7 KB to every page and tripped the page's size pin. The tone filters:threshold(a soft ramp is written as grays, the hard cut writes 0 and 1 bare),levels(a channel above the white point is white, and light that came in past white stays as bright as it was: the result is capped at the brighter of white and the texel, so a stretch cannot blow a channel out and a highlight is not cut),posterize,solarize,lumaKey,invert, and the contrast ofcolorGrade(its brightness, saturation, and hue stay on light). A color's brightness there is the gray of its luminance: the curve applied to the luminance, never the luminance of the curved channels.invertat 0,levelsat 0, 1, 1, and alumaKeyband that keeps everything hand the texel back untouched, and a contrast of 1 skips its step. The maps:ollin_map_vector(ShaderCombine.metal) is the one readingdisplaceand the.vectorfield of the line integral convolution share, red and green as written about mid-gray under the map's alpha, with a vector shorter than one 8-bit step counting as none (a half float lands a step under 0.5 and a picture has 127 and 128 either side of it; the zone is round, so a weak push keeps its direction, and the push is continuous, the rest shortened by the step and stretched so a full push along an axis is 1). The.anglefield and the luminance ofmaskread the written gray, the mask under the gray's own alpha, so a soft white mark is its alpha as before. The angle is never held to black and white: a value below zero turns the other way by the mirrored curve, which is what keeps a signed noise one smooth field (a clamp there laid half ofEffects/FlowStreaksflat, andgenerate(is that signed noise, the visual chain's, whenever the call names only.noise( scale: )) scale).normalMapwrites its vector as a written color, flat being (0.5, 0.5, 1), for those two readers. A new reader of a level or of a map goes through the same pair, orColor(white: 0.5)means 0.214 to it. On the stored value still:.disperse's aux and the measured field's brightness cut (unruled,DESIGN-NOTES.md),gradientMapandduotone(they color data), the halftone family (ink by light), and a glow's threshold (light)..defocusand.anaglyphread depth throughlinearToSrgb, as they did. Two rulings of 2026-11-26:coloramalays the hue wheel along the gray as written and keeps each pixel's own value (black stays black, a gray takes a color), where it turned the pixel's own hue and left a gray gray; and amotionBlur'sdistanceis a fraction of the layer's height at any angle, taken as two rows of taps through a scratch (Filter), so it is a pair on the Mac and on the page. The readings of 2026-11-28, each a fix: a.motionBlurTaps radialBluris the same two rows, in even steps of the size's logarithm (Filter: sizes multiply, so two rows are one long row; each tap weighed by its size, which is the plain average over the sizes; a texel apart or closer at the corner, where sixteen taps sat 25 px apart at an amount of 0.5 on a 1080 layer; the amount is held to 1 and stops a texel short of the middle);.radialBlurPair wave's amplitude,perturb's amount, anddisplace's are fractions of the layer's height along both axes (a row moved twice as far as a column on a 2:1 layer);dither(levels:)takes the levelsposterizewrites, even steps of the written gray, and mixes the two around a tone by the share that keeps its mean light (two levels are the same pixels as before); a measured field's direction is zero wherever its distance is held at the reach (the ladder carries a seed about twice as far as asked); every angle the effects and the patterns take goes throughollin_angle, which answers 0 for a vector of no length (noEffectTakesABareAnglereads the two segments), a lens split with a falloff of 0 and a brushwork with a sharpness of 0 no longer ask for 0 to the 0, and three even powers of a signed base are multiplied out, which a page's shading language leaves undefined; and liquid metal reads its aspect for the noise that wobbles the flow, the one part of its look not laid over the layer's box. A two-color filter or pattern mixes its colors under their alpha (ollin_mix_inks), and a mirrored fold is the identity on its first cell (ollin_mirror_repeat); a new fragment that mixes two sketch colors or folds a coordinate goes through those two. A size is canvas pixels at any layer scale (ruled 2026-11-10, in since 2026-11-15), soscalesets how finely a layer is kept and nothing else.LayerMeasure(EffectPass.swift) is the one place a pass turns a size into what its fragment needs, and it has three forms, one per way a fragment works:pixel, one canvas pixel in the layer's 0 to 1 coordinates, the step of every kernel (edges,sharpen,emboss,median,toon,normalMap,schlieren, the taps ofbilateralandoilPaint, the arrows, whose edge ramp is the row's third slot, a texel's width in canvas pixels and never under one, so an arrow over a coarse field keeps an edge one texel soft, the edge mode of the chromatic split, and the four flow filters, whose tensor blur is two canvas pixels);canvas, the layer's size in canvas pixels, for a fragment that turns a coordinate into pixels itself (bubbleWrap,chrome,holographicFoil,vhs,mirage,anaglyph, the fluted glass's margins and frost, the texture generators and their strips, which is also what puts a shader's own pixel constants on the canvas); andinTexels, for a fragment that addresses texels (the blurs, the layer styles and the field under them,dither,filmGrain, the box blur's whole-texel radius,defocus, the flat light's reach). A measured field's ladder runs in texels and its resolve multiplies by the canvas pixels one texel is (the fourth slot ofMeasuredField.row, which the page'srunFieldpasses through), so a sketch reads canvas pixels; a style measures its own field in texels. At a scale of 1 every one of the three is the number it was handed, so a full-size layer and every whole-frame filter are byte-identical. Three filters stay on the layer's own texels because those are their subject (antialias,grain,jpeg),relightkeeps its own texel stencil (it divides its slope by the layer's width and widens its span with the texel count, so its relief never followed the scale, and a canvas-pixel step would put its taps under a texel on a coarse layer), a simulation'sscaleis the size of its grid, and aShaderis still handed the layer's texel size. A new filter that takes a size or steps a kernel takes one of the three forms and a row in the sized lists ofEffectInvariantTests; The snapshot suite passed with one new reference:effects-compose, whose half-size blurred layer now matcheseffects-layers, the full-size scene it claims to be (0.6 of a level apart, 10.6 before); the four flow-filter scenes hold their half-size still life in a layer of its own pixels andeffects-arrowswrites its sizes doubled, each to the bytes it had. Fourteen plants, one per multiplication: thirteen red, and one no statement can see (the direction field's blur left at two texels where two canvas pixels are meant moves the picture by less than a layer differs from its twin, so that one is held by reading).Filteris a catalog in six families — blur/glow, color/tone, stylize/optical, retro, uv-warp distortion, and the design filters (.flutedGlass/.water/.paperTexture/.melt/.bubbleWraptransform the layer;.liquidMetal/.heatmap/.gemSmoke/.holographicFoil/.chromeread its alpha shape — draw a shape, filter it). Material textures (Geometry/,Patina .swift Geometry/,Terrazzo .swift Geometry/,Crease .swift Effects/;TextureTable .swift Docs/, exampleGenerators/ Textures .md Effects/Textures, snapshotmaterial-textures,MaterialTextureTests12 +MaterialTextureRenderTests6):.rust(andblobs: count: radius: seed: tones: background: lightAngle: lip: blisters: drips: grain: ) .verdigris(are one generator kind (…tide: drips: grain: ) .patina, with acrustthe rust sets to 0 and the verdigris to 1: the bloom's masses and lip fade out and a mottled film with worn patches, mineral crust, and a frayed, powdery edge fades in, so the two are different structures rather than a recolor, which is what @eaviles asked for at the desk;dripsruns tapering streaks down from each blob's lower edge in either) over aPatina(blobs whose radius wavers by four harmonics, 2/3/5/8 waves around, soboundaryRadius(at:)stays withinradius * (; two nested masses at 0.62 and 0.36 shifted by1 ± swing) massOffset; 2 to 4 blisters;scatter(keeps centers 0.75 of the two radii apart) andin: count: radius: seed: ) .terrazzo(over achips: chipRadius: density: gap: seed: tones: background: hatching: grain: ) Terrazzo(Cook's dart throwing in three tiers attierScales1/0.55/0.3 coveringtierSharesofdensity, every circle clear of every other bygap, so no pair is ever under the rule; chips are 5 to 8 corners at 0.72…1 of the radius with one corner on the circle, star-shaped about the center, which is what makes the GPU's sector test exact). Both travel as aTextureTablestrip (the foil's layout: a cell grid, candidate lists, then N texels a record, in layer pixels; 7 a bloom, 4 a chip; the default scatter cached by its arguments), uploaded byencodeGenerator, which now binds a generator pass's.tableinputs (a generator reads no layer, only its strips), and the web recorder carries them as any pass's tables. A handed-in scatter paints byte-identically to the one the generator builds with the same arguments (aHandedInScatterPaintsTheSameAsTheBuiltOne), so geometry stroked from it lands on the paint. Every edge inside the fragments' candidate loops is a fixed pixel of coverage from the ring or edge distance itself, neverfwidth(a derivative inside a loop with a per-pixel trip count is undefined)..bubbleWrap(is one single-pass fragment over a hex lattice (the nearer of two interleaved rectangular lattices), the lens read after the per-pixel identity return so it namesradius: gap: magnification: lightAngle: highlight: amount: ) level(0);radius0 oramount0 return the layer untouched.Heightfieldfolds a field along a polyline in normalized coordinates by.creased( along: width: amplitude: ) creaseProfile(at:), one closed form (a cuspexp(√f − √(s² + f)), f = 0.004; an asymmetric step0.3·tanh(; a trough2s)·exp( −s²/ 8) −0.35·exp(), read at eight widths past eight:−( |s| − 2)²/ 0.5) tanhof a far distance overflows under Metal's fast math and the first render of the paper filter went NaN-black wherever a crease was more than ~44 widths away. The same kernel (ollin_crease_profile, its slope by a central difference) shapes.paperTexture'sfolds: five seeded straight creases with soft ends, w = 0.03 of the sheet, tilting the normal along each crease's perpendicular, which moved every paper-texture picture (thedesign-filterssnapshot re-recorded; the Ch 19/20 figures that use it re-rendered). The crease test reads the field against the closed form at five offsets to 1e-9, and the positive side is where the segment's direction crossed with the offset to the sample is positive..holographicFoil(is one single-pass fragment over two lookup strips: the sheet (facets: spacing: crinkle: seed: bands: bandWidth: bandAngle: bandShift: lightAngle: lightElevation: relief: creases: glints: amount: phase: ) FoilTable.pack, a cell grid in front of the facets, two texels a facet in layer pixels, so the strip never depends on the layer's size and a sheet built over the canvas lands where it was built; the default crumple isFacetField.crumpledover the layer, cached by its arguments) and the spectrum (256 texels, read by texel so a steppedRampkeeps its edges). The GPU facets are the CPU facets: the fragment finds a pixel's facet by its cell's candidate list and a barycentric test, rebuilds the normal from the two corner-height differences the strip carries (plusrelieftimes the layer's luminance at the corners, sampled atlevel(0)since they follow a loop a pixel leaves early), andHolographicFoilTestsreads every facet's centroid pixel against the CPU normal's shade within 3 levels, the handed-in sheet byte-identical to the default it rebuilds, a pixel off a handed-in sheet a flat facet,amount: 0no byte, the stripe changing across most creases of a crumpled sheet and few of a flat one,reliefmoving nothing two facets from its mark, the creases round-tripping through SVG, and two frames of a moving foil differing. The band break is one line:u = p·along + bandShift · (withn .xy · off) offthe band direction turned by 0.65 rad, so nearly every crease moves the bands (read straight along them, a crease across the bands would leave them whole);Facetis its CPU twin. Creases are lit by how the light's planar direction crosses the edge (.bandCoordinate( angle: shift: ) |cross|, a direction-free read so both sides of a shared edge agree) or by the facet's facing, glints are a cross at every corner of a facet whose facing passes 0.74, written past 1.0 for a.bloom. The pass is on the web door (two tables travel with it;WebEffectsTests). Snapshot.Foiled holographic-foil;Docs/§ Design; Guide Ch 21 § A sheet of holographic foil: holographicFoil + the CrumpledFoil figure; exampleDrawing/ Effects .md Effects/(the sheet lifted every frame, the creases inked over the fill on a switch).CrumpledFoil .chrome(is the fifth alpha-shape filter and the airbrush convention rather than optics: one signed distance to a horizon athorizon: warp: waves: sky: floor: core: coreWidth: breakWidth: wire: amount: phase: ) horizonof the layer's height, bent bywarp · (withsin( k x + phase) + 0.55 cos( 2.37 k x − 0.61 phase)) k = 2π · waves /; thewidth skyramp read from the layer's top to the horizon and thefloorramp from the horizon to the bottom (both travel as 256-texel strips read with a lerp between texels, so the page needs no float filtering; defaultsRamp.chromeSky/Ramp.chromeFloor), a black breakbreakWidthtall at the horizon, thewireof the same height just above it, thecoreband fading into the floor overcoreWidthunder it, each band's edges a pixel of coverage (fwidth) and a break thinner than a pixel keeping its ink by coverage; the layer's unpremultiplied color multiplies the chrome, amount 0 changes no byte. One single-pass fragment (ollin_fx_chrome), so it is on the web door (WebEffectsTests). Snapshot.Chromed chrome-lettering;ChromeFilterTests(the identity, every band on its stated row in its stated color with the warp off, the break following the bend formula at nine columns and two phases within a pixel, the shape's edge kept, the tint); exampleEffects/(three palettes on a parameter); Guide Ch 21 § Airbrushed chrome: chrome. The stripe spectrumChromeLettering Ramp.holographicand the steppedRamp(Ramp.stepped(_:)/stepped(stops:),isStepped,color(at:)holding the last stop at or belowt,reversedmoving each band to1 - next,RampStepTests) came with it;.channelMixer(_:),.lensDistortion(, andamount: quartic: center: fillsFrame: ) .cornerPin(are three single-pass entries sharing one rule, the identity changes no byte (topLeft: topRight: bottomRight: bottomLeft: ) ChannelMixerTests,LensDistortionTests,CornerPinTests, each with a sabotage gate): the mixer is aColorMatrix(four rows of[r,,g, b, a, offset] .gray/.gray(/red: green: blue: ) .swapping(_:_:)/.identity) applied with its color weights on the premultiplied color and scaled by the new-over-old alpha ratio, written as exactly one when the alphas are equal, because dividing the alpha out and back in is fast-math and moved two rim bytes; the lens is the Brown-Conrady radial readr(1 + k₁r² + k₂r⁴)withra fraction of the far corner's distance in aspect-corrected space, the read written as the pixel's own uv plus a displacement that is exactly zero at zero coefficients,fillsFramea CPU scale of one over the largest factor on the boundary (a quadratic inr²overnear²…1, so an endpoint or its vertex), and a CPU inversion of the model lands a dot grid within 1 px; the pin packs the internalHomography(the same map.shaderInverse Installationruns on the present pass) as three rows, a nil map (no area) as zeros so.Projection w ≤ 0draws nothing; both warps read throughollin_fx_read_within, transparent past the layer's edge with a 1 px fade placed a quarter pixel outside it so an identity read at half a pixel from the edge keeps full coverage; a black pixel reads 0 or 1 after the present pass's dither, so a test for an empty pixel says<= 1; snapshotlens-pin-mixer; the web page probesMixed/Distorted/PinnedinWebEffectsTests; Guide Ch 21 § Through a lens, onto a wall, and through a mixer: lensDistortion, cornerPin, and channelMixer;.brushwork(is the anisotropic Kuwahara filter (Kyprianidis, Kang, and Döllner 2009 with the polynomial sector weights of Kyprianidis, Semmo, Kang, and Döllner 2010, both written from the paper, credited inradius: stretch: sharpness: ) ATTRIBUTION.md): three passes inMetalRenderer+Effects(the Sobel structure tensor of the display color over white paper summed across RGB, its Gaussian blur at a fixed sigma of 2, and the sector filter, whose brush is an ellipse of.swift radiusdrawn out tor·(α+A)/αalong the tensor's minor eigenvector and squeezed tor·α/(α+A)across it, cut into eight overlapping sectors by[(x+ζ) − η·y²]₊²under a Gaussian of sigma 0.4 on the unit disc with ζ = 2/r and η at 3π/2N, the sector means blended by1/(1 + s^q)with the spreadson the 8-bit scale the paper assumes). Four rules, each pinned byBrushworkTests:stretchis the brush's aspect ratio at full anisotropy, so the paper's α is1/(√stretch − 1)and a stretch of 1 is a round brush whatever the tensor says (the stripe invariant: three-texel stripes keep their full contrast under the stretched brush and lose three quarters of it under the round one, which holds only if the stretch follows the tensor's own direction); the means are of the premultiplied linear color, so the result composites and keeps the layer's alpha, while the variance is of the display color over white paper (a transparent region reads as paper, and the sharpness exponent is on the scale the paper quotes); the tangent isollin_xdog_tangent's two-spelling eigenvector, since the textbook(λ1 − E, −F)is zero on a vertical edge; and a hard edge stays within two columns and blurs across four only whensharpnessis 0, the counterfactual for the sector weighting. Multi-pass, so the page export refuses it by name. Snapshoteffects-brushwork;Examples/+ the FilterCatalog tile;Effects/ Brushwork Docs/; Guide Ch 20 § Paint that follows the picture: brushwork.Drawing/ Effects .md .xdog(is the flow-based extended difference of Gaussians (Winnemöller 2012 over the structure-tensor flow of Kyprianidis and Döllner 2008, both written from the paper, credited inradius: sharpening: threshold: softness: flow: foreground: background: ) ATTRIBUTION.md): four passes inMetalRenderer+Effects(the Sobel structure tensor of the brightness, its Gaussian blur at a fixed sigma of 2, the one-dimensional.swift (taken across the tangent, and the response gathered along the tangent under a Gaussian of1+p)·G_σ − p·G_1.6σ flowtexels, then cut), so it stays with the renderer and the page export refuses it by name. Four rules, each pinned byXDoGTests: the brightness is the sRGB-encoded luma of the layer composited over the paper (the background's luma, a transparent background counting as white), so the threshold sits on the display scale and empty space is paper, never ink; the tangent is the perpendicular of whichever spelling of the major eigenvector does not vanish on an axis-aligned edge (E ≥ G ? (), since the textbookλ₁−G, F) : ( F, λ₁−E) (λ₁−E, −F)is exactly zero on a vertical edge and only worked through the flat-texel fallback; the walk along the tangent keeps its heading through the stored sign's flips (the line-integral rule) and stops at the layer's edge, so a straight edge gathers nothing and the flow-0 and flow-6 renders of one are identical to the level; and the cut is the published1 + tanh((u−ε)/s)averaged over the pixel's footprint through its running integral (s·ln(below the threshold), so a softness of 0 is still anti-aliased and a ramp wider than a pixel is exactly as written. Snapshot1+e^{2( u−ε)/ s}) effects-xdog;Examples/;Effects/ InkDrawing Docs/; Guide Ch 20 § A line where there is an edge: xdog;Drawing/ Effects .md .shock(is coherence-enhancing filtering (Kyprianidis and Kang 2011, written from the paper, credited initerations: flow: radius: smoothing: threshold: ) ATTRIBUTION.md): a round of six passes inMetalRenderer+Effects, repeated.swift iterationstimes (the color structure tensor as brushwork takes it, kept from the previous estimate where the gradient's magnitude is under the paper's relaxation threshold of 0.002 so a flattened region still knows its flow; its Gaussian blur at a fixed sigma of 2; the line integral convolution along the tensor's minor eigenvector in unit second-order Runge-Kutta steps with the tensor sampled bilinearly, under a Gaussian whose sigma adapts to the pixel's anisotropy as¼·flow·(1+A)²; the tensor and its blur again over the smoothed layer; and the gradient-directed shock across the major eigenvector, whose sign is a scale-normalized one-dimensional Laplacian of Gaussian at0.75·radiusmade zero-sum so a straight ramp reads as no curvature, negative pastthresholdtaking the brightest texel center withinradiusalong that direction and positive the darkest, from the layer or, whensmoothingis set, its blur), then one convolution along the flow at a fixed sigma of 1.25 over the last tensor to anti-alias the steps. Seven tests, each pinned byShockFilterTests: a flat tone is left alone; a smoothstep edge narrows and more rounds narrow it further (a straight ramp only clips at its ends, since its interior has no curvature, which is why the probe bends); a hard straight edge stays put in every row; noise along a line averages away while the line keeps its contrast against the gap beside it (the walk follows the line); a noisy edge straightens and its sides calm; a red-to-blue blend loses its middle and never makes green (no color is invented, since every pixel is a blend along its contour or a texel the layer holds); and empty space reads as paper and stays transparent. The paper's line-thickness rule holds: a feature thinner than the Laplacian's scale is fattened to it, so a shaded rim becomes a bold contour, and dense noise turns into the maze its Figure 7 shows unlesssmoothingblurs the sign's source. Multi-pass, so the page export refuses it by name. Snapshoteffects-shock;Examples/+ the FilterCatalog tile;Effects/ Coherence Docs/; Guide Ch 20 § Regions with crisp edges: shock;Drawing/ Effects .md .hatching(draws the layer as pen work along its own flow (the line integral convolution of Cabral and Leedom 1993 over the structure tensor, cut into strokes by the tone-as-density rule of pen-and-ink illustration, credited inspacing: length: directions: foreground: background: ) ATTRIBUTION.md): three passes inMetalRenderer+Effects(the color structure tensor.swift brushworktakes, reused as-is; its Gaussian blur at a fixed sigma of 2; the hatching, which walks that flow once per direction). The rank is the load-bearing part: a box average of value noise of cell sizespacingalong the walk is bell-shaped, not uniform, so the average is standardized by the noise's own measured spread (0.046) over the count of independent draws the walk took (its samples divided byspacing, since that is how far it travels before it reaches a new cell) and pushed through the normal distribution as its tanh form, which Metal carries anderfis not; the answer is near enough uniform on 0…1 that inking every mark under the pixel's darkness covers that share of the paper, which is what makes the drawing hold its tone. Layer 0 runs along the tensor's minor eigenvector, 1 across it, 2 between them; every layer but the last is capped at half the paper and hands on(D − c)/(1 − c), so a second direction crosses the first instead of thickening it and the tone still comes out right. The cut is anti-aliased over the rank's own screen-space derivative, so every rank is computed before any is used (a walk skipped where the paper is light would take a pixel out of the quad the derivative is read from). Seven tests, each pinned byHatchingFilterTests: the ink covers as much of the paper as the picture is dark at a quarter, half and three quarters (within 0.05, and within 0.03 on a canvas big enough to hold the sampling error); white stays bare and black fills; the marks run along the flow and turn when the picture turns (verified red by walking across it instead); half the spacing lays more than twice the strokes; a second direction crosses the first and both reach the same tone (verified red by returning the raw average, which is the same sabotage the tone test catches); nothing but the two colors is on the page; and empty space counts as paper, sobackground: .clearleaves it empty. Multi-pass, so the page export refuses it by name. Snapshoteffects-hatching;Examples/;Effects/ Hatching Docs/; Guide Ch 20 § Strokes that follow the picture: hatching;Drawing/ Effects .md .antialias(is the post-process pass for a layer a fragment shader wrote per pixel (aamount: threshold: quality: ) Generator, a raymarched field, an imported shader, a finished chain), which none of the four anti-aliasing paths reach: a brightness range test that returns early, a second-difference test for whether the edge runs across or down, a walk along it to both ends with a growing stride, and the low-pass term for a lone pixel with no span (FXAA, written from the paper, credited inATTRIBUTION.md). Four rules, each measured. Every tap nameslevel(0)(the early return is exactly the case that leaves a derived mip level undefined). The orientation test is tie-broken by|lN-lS|against|lW-lE|, because a shader writes hard two-value edges that tie the published sums constantly, and>=alone then answers across for every edge including the ones running down (the steep probe is red without it). The brightness the walk compares against is read from the layer at the half-pixel tap, never averaged from the two neighbors already in hand: this layer is linear-light where the technique assumes display-encoded input, and across black and white an averaged brightness and the brightness of the average differ by 0.235 against an end test of 0.25, which ends nearly every walk at its first step. The signal reads the layer over a mid-gray backdrop (a black silhouette on a clear layer carries premultiplied color 0 on both sides of itself; sabotage-verified) and sRGB-encoded on past 1 rather than clamped there (a layer is linear and the tone map is at the present pass).amount: 0and a layer under the threshold are both byte-identical. Measured on a 1-in-8 slope: edge wander 0.286 px to 0.140 px, half rather than none being what a pass reading the finished image can buy; it cannot tell a stair-step from genuine one-pixel detail, which is why it is placed rather than automatic. ExampleEffects/Antialias, snapshoteffects-antialias,AntialiasFilterTests(8);Docs/.Drawing/ Effects .md .meltis the luminance melt (one displacement vector both warps the field's domain and shifts the layer sample — keep them shared, that coupling is the recipe; sampled brightness mixes into the field before the 4-stop sRGB ramp; the sway sines are non-commensurate, so it never perfect-loops — exampleImages/, snapshotLuminanceMelt luminance-melt); Chromatic aberration is a mode axis, not one look (ollin_fx_chromatic, one fragment for the whole family):.magnify(default; a per-channel scale about the center, byte-identical to the pre-mode filter) /.lens((a shaped radial slide;radius: falloff: ) radius:is0, falloff: 1 .magnify, which is why the default is the named scale rather than a degenerate lens) /.offset(angle:)(flat, the only mode that splits the frame's center) /.edges(along the luminance gradient, scaled by its strength; a negative amount gives the cool purple-fringing halo) /.axial(a 12-tap golden-angle disc per wavelength: focus, not position; the sign picks which end stays sharp), plusspectral:(quality-sized wavelength taps, 7/15/31 viaresolveDispersionTaps) and the aux-drivenCombine.disperse/.dispersed(by:). Load-bearing: the spectral weights are three cosine lobes normalized per channel (over 15 taps green collects ~5.0 and red ~3.0, so an un-normalized loop tints every flat area green), three taps reduce to the exact R/G/B basis so the shipped picture is unchanged, every tap is unpremultiplied before its channel is read and repremultiplied by the pixel's own coverage (else a soft-edged layer grows a dark rim; a fully transparent texel still carries no color to borrow), the split is computed in a space scaled by(aspect, 1)and written back to uv (.magnifyneeds no correction because a scale about the center is already aspect-free, so the design note's claim that the shipped filter was anisotropic was wrong;.lens/.offset/.edgesdo need it), and every mode is an exact identity atamount: 0. Not done and deliberately so: dispersion is not read off a camera the way.defocustakes its blade count from the depth layer's, because aFilterruns on a layer and there is no camera attached to one. ExampleEffects/Dispersion; snapshoteffects-dispersion;DispersionTests(9, three sabotages verified red); Guide Ch 21 § One filter, five pictures: chromatic aberration + the Dispersion figure. full per-filter list inDocs/; new built-ins are written from the published technique, credited inDrawing/ Effects .md ATTRIBUTION.md, never in.swift..drosteis the picture inside itself (ollin_fx_droste; the Escher construction Lenstra and de Smit completed): the ring betweeninnerand the layer's edge is straightened by a complex log, repeated along the strip, and mapped back by exp. The twist is a complex multiply in the log plane, not a shear ((1 - ik)·w,k = twist·period/2π): one turn around the middle then advancestwistperiods along the strip and exactly one turn of the source, which is what keeps the map single-valued and the spiral closed (dropping the second component leaves the picture no longer self-similar, sabotage-verified). The wrap isx -= period·ceil(, so the sampled radius stays inx/ period) [inner, 1)and the hole is never read (a marker disc insideinnermust not appear in the output).zoomcounts periods, sozoom + 1returns the same picture, which is what makes an endless fall loop exactly. The claim the tests measure is the theorem, not the look: the picture is unchanged by one scale-and-turn,log γ = period/. Only( 1 - ik) |z| ≤ 1in units of half the layer's shorter side is ever sampled (a tall layer read past its sides in half heights and smeared its edge columns), so the layer's corners never appear, and the join between copies shows unless the content clears both edges of the ring (the example and the Guide figure both end the ring on flat ground). ExampleEffects/Droste; snapshotdroste;DrosteTests(6, two sabotages verified red); Guide Ch 21 § A picture inside itself: droste + the PictureInsideItself figure..diffuseis the diffusion-curve solver (Orzan 2008), and the only filter that makes a picture rather than changing one: the layer's own drawn pixels are Dirichlet sources and everything else relaxes to the average of its four neighbors (drawDiffusionCurve(lays the two-sided form). Four load-bearing pieces: the constraints are carried down a premultiplied pyramid (color × w, w) instead of being resampled per level, and each level sums its 2×2 block with the weight clamped at one, so a block with any held texel in it is a hard wall at every coarser level (the sum is the operators' scale — a texel a level up stands for four times the curvature — and a weight that fell off with the size left the coarsest levels nearly free to drift, so the correction they sent up grew with each cycle and a 1080 canvas went white in three); the ladder runs down to 4 texels, not 32 — Jacobi error falls with the square of the size, so the bottom is where the long waves are solved and it is nearly free (starting at 32 left a closed ring's interior stuck at three quarters of its color,_: left: right: ) aRingFillsWithTheColorItIsDrawnInpins it); the coarse-to-fine cascade is only a first guess and multigrid V-cycles do the solve — the finest level's residual is restricted down (×4 a level, zero at a wall), the correction is relaxed at each level with every held texel a wall of zero correction, and prolonged back up where a texel is free — because a cascade alone hands a region held by one side of a thin curve the mean of both sides (a hairline's two sides land in one coarse texel), andsharpnessbuys cycles (3 at 0, 6 at 1; each takes about half of the far field's remaining error, since the residual against a wall lands in the wall's own block half the time and is dropped there;aCurveHoldsItsFarSideOffTheAlignmentpins the far side at a curve that is not on a power-of-two texel boundary, the alignment that hid the leak); and every neighbor sample nameslevel(0)since a fragment may sample past a branch its quad did not take. The tests are the theorems: away from the marks a pixel equals its neighbors' average (worst deviation ≤ 6/255), no color appears that was not put there, and a closed mark fills its interior.Docs/, exampleDrawing/ Effects .md Effects/, snapshotDiffusionCurves diffusion-curves, Guide Ch 22 § A picture made of a few marks: diffusion.Generator+generate(_:)fills a procedural pattern into a target: the four basics (.noisetakes awarp:domain-warp parameter — 0 skips the warp path so it stays byte-identical), the.cellularWorley source (.cells/.borders/.mosaicstyles; feature points wander sinusoidally on hashed orbits, sophaseis periodic over 2π and a whole lap loops — exampleEffects/Cellular, snapshotnoise-toolkit), the.gaborNoisesource (sparse Gabor convolution from Lagae et al. 2009: a Poisson field of Gaussian-enveloped cosine kernels, so the spectrum is designed bywavelengthin pixels,bandwidthas a fraction of the frequency,angle, andspread(0 one direction, π isotropic);impulsesper kernel is the quality,phaseperiodic over 2π, and a field atangle + πis the same field. Load-bearing: the output is normalized by the paper's closed-form variance, so the mean is 0.5 and one standard deviation is a sixth of the range at any impulse count; every kernel is filtered against a σ = 0.5 px Gaussian footprint in the frequency domain (the product of two Gaussians is a Gaussian, so the filtered kernel is a Gabor kernel with a lower frequency, narrower band, and less gain), which is why a wavelength driven toward two pixels fades to gray instead of aliasing and why the contrast at 2.5 px matches the closed form to 1%; the per-cell impulse stream is a Borosh-Niederreiter congruential generator seeded by an integer hash of the cell and a 24-bit seed, stepped in single precision on both sides, so the CPUGaborNoise(the typed value;gaborNoise(the sugar) computes the field the GPU paints to within the dither (pinned) and a sketch can place marks by a field it never reads back; the seed is a parameter, notx, y, ...) noiseSeed's, for the same reason; the pass carries the layer's pixel size and render scale so a 2x export keeps the picture; the shader-librarygaborNoise(p, ...)is the same code, and the fragment translates for the web page; exampleEffects/GaborNoise, snapshotgabor-noise,GaborNoiseTests(11 laws: mean and sigma, the spectral peak at 1/wavelength, the band narrowing, one direction is one direction, spread π isotropic, phase a period and half of it a negation, seeds, the closed-form fade, GPU = CPU)), the design-pattern set (cross-read against Paper Shaders, written from the canonical techniques, per-technique credits inATTRIBUTION.md), the pattern fields, and the escape-time fractals plus.orbitTrap(the same iteration colored by the orbit's closest pass to a point/cross/circle/square trap through an expglowramp, the trap turned byangle; escaped and trapped pixels color alike, the escape test only ends the orbit; exampleEffects/EscapeTime, snapshotsescape-timeandorbit-trap; all five complex-plane generators frame the plane one way,centerin the middle, 3 / zoom units across the shorter side, the imaginary axis up with the uv's y negated once on the way in, which the escape-time pair and the orbit trap did not until 2026-09-27 (they read the axis down and nothing said so, so a Julia withcoff the real axis drew mirrored and the Guide's marked-cfigure marked the conjugate point; measured per generator before the change, then flipped at @eaviles's ruling);ComplexPlane(Math/:ComplexPlane .swift centerandspan,init(center:zoom:)with span = 3 / zoom,canvasPoint(of:in:)andplanePoint(at:in:)against the rectangle the picture was drawn in undistorted) is that framing as a value, andGenerator.planehands a generator's own back after the factory's clamps (nilfor a generator with no plane), so a mark lands on the picture without the sketch redoing the arithmetic;ComplexPlaneFramingTests(11) pin the round trip, the shorter-side rule, and per generator that a feature at a known number (the unit disk's edge, a Julia's CPU twin, a Mandelbrot window off the axis, an orbit-trap knot, a zero's winding, a Newton root) sits within a pixel of where the plane says, with the mirrored mapping red on each),.newton(Newton's method from every pixel over a polynomial given by up to eight placed roots, the step the reciprocal of the sum of 1/(z - rᵢ) so no coefficient is ever formed; each pixel colored by the root it lands on off the palette wheel at i/n plusphase, shaded by a continuous step count (the quadratic-convergence renormalization, clamped to one step for the linear cases) with a contour per step; a pixel within a thousandth of the framed span of a root has landed, one that never lands or hits a critical point paintstrapped,relaxationscales the step; exampleEffects/, snapshotNewtonBasins newton-basins,NewtonBasinsTests(7 tests: root inside its basin, the third-of-a-turn symmetry, the Wada property at 95% of boundary pixels within 12 px, the z³ - 2z + 2 pools, shading, phase, eight roots)), and.domainColoring(a complex function painted over its own plane: the value's direction walks a wrapping palette wheelollin_pat_wheel— the last stop blends back into the first, so a turn has no seam; the plane is written with the imaginary axis up, so the uv's y is negated once on the way in, and every placed zero/pole then reads as written —ComplexFunctionis.rational(with up to four of each packed two per params row (so the colors always start at row 7) pluszeros: poles: ) .power/.exponential/.sine/.tangent/.logarithm;DomainShading.modulus/.conformalrule size and direction off|f|andarg fdirectly, never the palette position, sophaseonly ever recolors; the argument principle is the test, not the look: a simple zero must lap the wheel +1 and a pole -1, a double zero +2,z^3+3 —DomainColoringTestspins it, verified red by removing the y flip; exampleEffects/, snapshotDomainColoring domain-coloring);generate(fills an explicit-size layer so patterns compose per-layer instead of squashed full-canvas fills (the Shader and Visual_: width: height: ) generateforms have the same overloads). Feedback —makeFeedback(→ a persistentscale: ) Feedbacklayer (made once insetup()and held — its identity carries the ping-pong state across frames) +withFeedback(. A loop keeps single precision by default (ruled 2026-11-28): a half float is stored cut off toward zero, never rounded (a fragment's store and a kernel's write alike; a blend is worked out in single precision and cut once), which is the conversion rule the graphics APIs write down for a float narrowed to a smaller float and no quirk of one GPU, so a loop in half float loses beyond its gain every frame: a fade at 0.98 is 3.4% dark after 100 frames, 10% after 300 at 0.99, and a mean keeping 0.98 settles 4% dark with an alpha of 0.976._: ) { prev in … } makeFeedback()andnoClear()therefore default to.float32(a filter or a combine over a feedback layer is single precision too, by the chain rule, with no exception),.float16is the opt-out at half the memory,Feedback.initandDrawer.noClearfall back to half float whereLayerPrecisionis false (the default device's.gpuKeepsALoopInSinglePrecision supports32BitMSAAandsupports32BitFloatFiltering), a simulation field stays half float by default (its presets were tuned on that store and its steps would cost several times more), and the exported page keepsRGBA16F(filed inDESIGN-NOTES.md). Cost on the M2 at 1080: a feedback layer 0.30 ms and 18 MB in half float, 0.37 ms and 36 MB in single; a blur of 8 over it 0.17 against 0.71 ms, a bloom 0.64 against 1.53; a kept canvas 45 MB and 0.15 ms more. The remedies measured and declined (a half step, a dithered store, half-float filters over a single-precision loop) and the tables are inARCHITECTURE.md§ A half float is stored cut off, and what that costs a loop;Scripts/reads the numbers again. Simulation fields —benchmark .sh loops makeSimField(→ a persistent_: scale: ) SimFieldrunning aSim(.reactionDiffusion(Gray-Scott /feed: kill: ) .predatorPrey(the Rosenzweig-MacArthur predator-prey kinetics on the same 9-point diffusion, prey in red and predators in green over a prey-at-capacity rest state (so a drawn green mark is a release), the dimensionless form where the prey's growth rate and the capacity are 1 and Holling's saturating responsehalfSaturation: predatorGrowth: predatorDeath: steps: ) u/(u+h), one explicit Euler step of the fixedSim(0.05) per substep and.predatorPreyTimeStep stepssubsteps a frame, the state clamped to 0...4;PredatorPreyTestspins the period of a uniform field's prey mean against the model's own Jacobian stepped as the Euler map (within 3%), the invasion front's steady outward pace and the oscillating wake behind it, and the full-prey rest state /.gameOfLifeConway /.lenia(...)continuous CA /.smoothLife(Rafler's SmoothLife (the disc of radiusradius: birth: survival: intervalSoftness: cellSoftness: ) ra/3and the ring out tora, each an area-normalized filling with the paper's one-texel anti-aliasing ramp at every rim, the sigmoid steps1/, the transition( 1+exp( -( x-a)·4/ α)) σ2(and the discrete time-stepping where the new state is the transition itself; the defaults are the paper's glider parameters,n, σm( b1, d1, m), σm( b2, d2, m)) ra21, birth 0.278...0.365, survival 0.267...0.445,αn0.028,αm0.147;SmoothLifeTestspins the rule texel for texel against a double-precision CPU reference over two generations, the two fixed points (empty stays empty, full dies in one generation), and a notched-disc seed that keeps its mass within a band and moves the same vector between checkpoints, the glider) /.ripples(wave-equation pool /speed: damping: ) .sandpile(Bak-Tang-Wiesenfeld /pour: topplings: ) .fallingSand(Toffoli-Margolus block-CA sand, water, and walls /passes: friction: ) .fluid(...)real-time fluid /.multiScaleTuring(McCabe /scales: seed: ) .cyclic(...)Griffeath's cyclic CA /.excitable(...)Greenberg-Hastings /.briansBrain()Silverman /.forestFire(Drossel-Schwabl (empty/tree/burning; starts bare and grows itself in — no seed fill, and the per-cell coin isgrowth: lightning: neighborhood: ) hash12(so a run replays exactly; with both rates at 0 the rule is deterministic, which is whatcell, field age) StateAutomataTestschecks cell for cell against a CPU reference, since a GPU hash has no bit-exact CPU twin; rates at 1 pin the other branch, and the corner test separates the two neighborhoods — both sabotage-verified) /.hodgepodge(...)Gerhardt-Schuster's oscillating-reaction machine /.wireworld()Silverman's computing automaton (empty/conductor/tail/head; a conductor fires on exactly one or two heads, which is the clause a diode and every gate are built from; the field starts empty and a circuit is typed as text and stamped,WireworldCellnaming the four grays; the eight-cell count cuts a ring's corners, so a nine-by-five ring is a clock of period twenty) /.schelling(Schelling's segregation on a bounded board (empty/first/second, the seeded fill holdingpreference: vacancy: mobility: passes: seed: ) vacancyof the cells empty through a thirdstateSeedFillfield, whose seed goes throughShaderSeed.foldedlike every public seed handed to a shader as a float (a shader's hash is single precision: a seeded start came out in blocks from about ten million, in bars from fifty million, and flat past a hundred million, and two seeds a float cannot tell apart were one start; a seed under 131,072 passes as written, so no start made before moved, and a larger one is mixed down from its bits), negative for the even split cyclic/hodgepodge keep, so those fills stay byte-identical; an agent is content when its like share reachespreference, an unhappy one hops to an empty cell within an 8x8 block that walks half a block per pass, the sand's Margolus scheme scaled up because 2x2 blocks jam at any vacancy a board can show, content cells taken first in raster order with the mover's own cell counted vacated; the per-agent coin ishash12(undercell, pass, seed) mobility, so at 1 the rule is deterministic andStateAutomataTestsmatches it cell for cell against a CPU reference, and at 0 nothing moves) /.ising(the Ising model by checkerboard Metropolis (down/up as 0/1, the seeded fill an even split; a pass updates one parity oftemperature: field: sweeps: seed: ) x + y, matching the pass index's parity, from the other parity's four wrapped neighbors, two passes to a sweep andsweepsper frame; on a wrapping side of odd length the first and last cells share a color and are neighbors, so one of the two sits each sweep out, turn about, the rows on a slower turn than the columns (Sim.fieldRowstells the kernel which sides wrap, on the Mac and on the page; flipped together from each other's old spins they raised a cold field's energy, 20 unlike pairs to 22 on a 9 by 6 field, and a side that does not wrap is visited whole every sweep); the flip energy is2 s (in -1/+1 spins, taken when it is <= 0 and otherwise whenneighbors + field) hash12(, the pass count running on across frames from the field age so a run replays; at a temperature of 0 no coin is thrown, which is the deterministic limitcell, pass, seed) < exp( -change / temperature) StateAutomataTestsmatches cell for cell against a CPU reference, tie flips included, and what theQuenchedpage-versus-Mac case runs;Simis Onsager's.isingCriticalTemperature 2 / ln(1 + sqrt 2)and the default; the magnetization and coarsening invariants were pinned from a numpy prototype first, 0.999 cold and under 0.03 hot after thirty sweeps from an ordered stamp, the seeded mix within 0.4...0.6 after one deterministic sweep, andfieldat 4 magnetizing every spin in two sweeps;IsingSpinnames the two grays) /.selfWarp(motion feedback — the picture's own measured motion drags the field's history) that you seed/force by drawing into it (amount: refresh: decay: smoothing: ) withField(_:_:),force:);SimField.imageis the raw state,.filtered(_:)recolors it through theFiltercatalog, and reading either registers the field so it steps (Drawer) — a sim only evolves while its layer is one of the frame's render targets, which used to mean a.ensureFieldSteps withFieldblock was mandatory, and a self-organizing sim that needs no seeding would otherwise sit frozen and read black with no hint why (an empty-block wart the Turing work surfaced; existing sketches register viawithFieldfirst, so target order is unchanged). A simulation of your own isSim: a user.shader( _: inject: substeps: rest: ) Shadercompiled as the.simStepvariant of the user-shader wrapper (readerscell(info)/cell(info, dx, dy)/sampleRaw(info, p)/input(info, i)over the state bound at texture 0 and up toSimField.maxInputsextra layers fromSimField.inputs(a drawn or generated layer as this frame left it; afiltered/combinedoutput one frame late, since filters resolve after the sims:keepDelayedInputsblits each one, after the filter ops, into aDelayedInputSlotper field and slot that the next step reads, empty on the first frame or after a frame it did not resolve, pruned with the field;UserSimTests, red under a skipped copy and under the old blank), a raw tail that stores the returned.aFilteredInputArrivesAsItResolvedTheFrameBefore float4as data with no color conversion, and two rows the renderer appends after the user's 16 parameter rows (ollin_params[16]= texel/pass/age,[17]= substeps/input count) soOllinShaderUniformsnever widens), with an optional inject kernel (.simInject,mark(info)= this frame's marks un-premultiplied in linear light, coverage in.a) that runs where the block drew, which is how gpu-io's region steps map onto Ollin's drawing model: the region is whatwithFielddrew, and the kernel is the inject; without one,ollin_sim_inject_datalays marks on by alpha and keeps the state's alpha (a kernel may store data there).SimField.edge(FieldEdge,.wrappingdefault /.clamped/ per axis) is the sampler, not a shader branch: the twelve wrapping sims (Sim.honorsEdge) tapuv + d * twith nofract, and the renderer bindssimSampler(for:)(repeat or clamp-to-edge per axis, the image sampler's filtering) for their passes, which is byte-identical for the torus (a tap at a texel center lands on the same texel under either sampler;StateAutomataTests' cell-for-cell toroidal references held unrecorded) and lets a clamped border cell read itself past the edge (an insulated boundary for a diffusion, and whatUserSimTestspins against a CPU reference under every axis pair); ripples, the sandpile, the falling sand, Schelling, and the multi-pass pipelines keep the image sampler. The web page mirrors it by settingREPEAT/CLAMP_TO_EDGEon the two scratch textures the steps read while they run (WebSimNode, JSON.wrapsX/ wrapsY wx/wy), then clamping them again for the pool.precision: .float32onmakeSimFieldthreads the field's format through the slot, the scratch pool (acquireFilterTexture(), every pass's pipeline (format: ) encodeEffectFragment(, the user pipeline's hash carries the format), every multi-pass pipeline's own textures (the fluid's four and its scratch, the watercolor's ten and its scratch, the Turing field's scratch, and the self-warp's and datamosh's source and history, whose first-frame and per-frame copies from the seed are blits and need one format on both sides: atformat: ) .float32they copied a single-precision seed into half-float textures) and the seed pair: the marks draw through pipelines built for the target's format, so a seed MSAA/resolve pair left at half float read back as noise (alpha 1.875 on a full mark; the first run of the precision test).SimField.snapshot()returns aFieldSnapshot(width/height/valuesrow-major, a clamped subscript) through a reader closure the renderer sets on every field it steps (weak self), which reads the texture behindimagechosen by the sim the field runs when it is asked: the slot's front for a one-pair sim, the dye for the fluid, the history for the self-warp and the datamosh, the display for the watercolor (it wasnilfor those four, and afterfield.simchanged it returned the old sim's state): a blit of that texture into a shared buffer, committed and waited for, so a call fromdraw()reads the state the last frame left;UserSimTestspins readback == image on two instances of one deterministic run.Filter(.arrows( spacing: scale: color: width: ) ollin_fx_arrows, asinglePass, carried to the page) reads any two-channel layer'srgat each cell center and draws shaft plus barbs as segment distances over the 3x3 neighborhood, the shown length held to the spacing so that neighborhood is every arrow that can reach a pixel;ArrowsFilterTestspins direction, count, and the empty field. A user sim is refused by the web export by name (itsstepFragmentis empty). Snapshotseffects-simfield-shader(clamped heat plate with an inject and an input layer) andeffects-arrows; exampleSimulation/Wind;ShaderCheckinfers the two kernel shapes (simulationfromcell,injectfrommark). Modulated regimes —.reactionDiffusion(+feed: kill: toFeed: toKill: ) SimField.modulation: a layer's brightness lerps feed/kill per texel (black → the first pair, white → thetopair), so one continuous field runs different regimes in different places and the pattern crosses the boundary instead of seaming (a camera matte as the map is theVision/TuringMirrorexample; snapshoteffects-simfield-modulated). Load-bearing: the modulated step is a separate fragment selected only when the map layer was drawn this frame (membership in the frame's render targets, which resolve before the sim passes) — the plain path stays byte-identical, an undrawn map falls back to the uniform black-end field rather than sampling stale, and afiltered(_:)output can't be a map (filters resolve after the sims). Params row z/w carry thetopair; x/y stay the plain pair the unmodulated kernel reads. Self-warp —.selfWarpis a multi-field sim like the fluid (ownSelfWarpSlot: previous clean source + quarter-res flow pair + history pair, evolved byrunSelfWarp; exampleSimulation/SelfWarp, snapshoteffects-selfwarp): draw the scene into the field and a GPU two-level windowed least-squares motion fit (Lucas-Kanade, on luminance, coarse sixteenth-res for reach then quarter-res refinement, temporally steadied bysmoothing, flow stored in uv units so passes are resolution-independent) measures how the picture moved since last frame, then a semi-Lagrangian pass carries the history along it and mixesrefreshof the fresh drawing back in. Load-bearing:strengthpicks the regime and 1 is nearly invisible — below 1 the picture outruns its history (ribbons trailing the motion, the default 0.6), at 1 an accurate fit lands the carried ghost exactly back under the mover, above 1 ghosts are thrown ahead, negative reverses (SelfWarpTestspins both directions on an overshooting dot plus the exact still-scene null — a static picture solves to zero displacement, so the field converges to the drawing); the first frame primes source and history from the first seed (zero measured motion, not a jump from black); and the motion is measured on the GPU by design, never routed through Vision per frame (a per-frame canvas→Vision→texture trip breaks the substrate's no-CPU-round-trip rule, cadence, and determinism —FlowTrackerstays the measurement tool). A main-canvasbackground()before or afterwithFieldleaves the seed (see the layer rule above). Depth-capturing targets — a target a 3D scene is drawn into resolves a sampleable depth buffer;target.depthis a gray layer (0 near … 1 far) that feeds.defocus(set the cameranear/farto bracket the scene); two-tier opt-in so 2D never pays. Compose DSL (Effects/) —Compose .swift compose { layer { … }, composited bottom-to-top in declared order; pure sugar over the substrate. Multi-input combine (.post( _: ) .blend( _: ) .scale( _: ) … } Effects/) —Combine .swift basewith nine ops:.combined( with: aux, op) .mask/.displace/.disperse/.mix/.seamlessClone/.lineIntegralConvolution/.defocus(near/far-separated bokeh-gather depth of field; artifact history in [[ollin-depth-of-field-gather-artifacts]]) /.ambientOcclusion(SSAO over depth + the mesh-normal G-buffer) /.screenSpaceReflections(SSR: trace → resolve → temporal → composite);aside { }+.masked(by:)/.displaced(/by: amount: ) .mixed(/with: amount: ) .cloned(from:)/.streaked(/along: length: field: ) .defocused(by:)is the combine'scomposesugar..lineIntegralConvolution((length: field: ) ollin_fx_licinShaderCombine.metal) brushes the base along a direction field read from the aux layer: each pixel is the box average of the base along the streamline through it, walked both ways in Euler steps (lengthis a fraction of the layer's long side; the step count is capped at 128, the step stretched to keep the length). Three readings of the aux (Combine):.FieldEncoding .vector(rg recentered at linear 0.5, a normal map or a drawn flow),.angle(turns:)(luminance timesturnsas a heading, noise into swirls),.contour(the perpendicular of the central-difference luminance gradient, so streaks run along a gradient's level lines). Every field is unoriented: a step whose direction points back against the last heading is flipped, which is what carries a walk through an.anglefield that turns past a half turn (aFieldThatTurnsBackIsWalkedThroughgoes red without it); the walk stops at a zero field or the layer edge, so a still field returns the base byte-for-byte and the length is honest at the border. All taps namelevel(0). One gotcha with a hard tone edge in an.anglefield: the half-covered AA texel reads as the mid angle, a wall along the edge that traps walks, so harden a seam with.threshold(0.5)first (the probe does).LineIntegralConvolutionTests(6) pins the smear across a stripe, the whole stripe along it, the still field, the radial contours, the turn-back, and the length clamp. ExampleExamples/; snapshotEffects/ FlowStreaks line-integral-convolution;Docs/.Drawing/ Effects .md .seamlessClone(is gradient-domain compositing (Perez 2003) in the membrane form: the aux layer's own alpha is the region, its rim carriesamount: threshold: ) base - patchas boundary values, the harmonic field between them is added back under the patch's coverage, so the rim lands exactly on the base (S + (T - S) = T) and the inside is the patch plus the smoothest correction reaching it;amount0 is a plain paste, the honest before picture. The solver is a convolution pyramid (Farbman 2011), not the.diffuseJacobi ladder, and the split is load-bearing in both directions. A pyramid interpolates scattered values (a source votes, weighted by coverage) and settles in ~23 passes against Jacobi's ~210; a relaxation's source is held, so it walls off what is on either side of it. The clone has one closed rim with nothing to separate, so it takes the pyramid; diffusion curves are named for that wall, and under a pyramid a curve one texel wide stops dividing its sides (a red/blue probe returned blue 172 on the warm side against a limit of 110 -aCurveCarriesADifferentColorOnEachSidepins it; no weighting fixes it, since at the coarse levels both sides land in one texel and get averaged). Three non-obvious pieces, each a real defect first, each pinned: the pyramid's intermediates arergba32Float(PipelineKey, defaulting to the shared linear format so every other effect pass is byte-identical) because the fitted kernels are unnormalized (h1 sums to ~2.7, so magnitudes climb ~7x per level down and fall ~20x per level up) and a layer's worth of levels leaves half float at both ends - the tell is underflow, the weight channel reaching zero deep inside a wide patch so the normalize has nothing to divide by and the raw patch returns as a speckled blob ringed by concentric ripples, exactly where the answer should be smoothest (worst error at radius 240 on a 512 layer: 179/255 -> 1/255); rescaling h1 to sum to one is an exact identity and no help (scale h1 by s, take h2 to h2/s^4, level zero is unchanged) since it only trades the overflow end for the underflow end; and the normalize's floor sits at 1e-30, not a comfortable small number, since a legitimate deep-interior weight lands around a millionth. The tests are theorems, not tastes: with a flat backdrop the rim values are all equal so the field between them is that same value, and the clone must hand the backdrop back (<= 2/255 incl. the present pass's dither); the patch's own flat color must leave no trace whatever it was; and the middle of a wide patch must be as right as its edge. Envelope, both from what it does rather than the implementation: only the low, slow part of the color is replaced, so the patch's range of tone is kept and a contrasty patch on a much darker backdrop clips its shadows to black; and the rim is the whole answer, so a rim across a hard edge in the base smears that edge inward..effectFormat Docs/, exampleDrawing/ Effects .md Effects/, snapshotSeamlessClone seamless-clone,SeamlessCloneTests. Load-bearing invariants (terse — mechanism and why inARCHITECTURE.md§ Layered-effects substrate + § Screen-space combine effects): theDrawerstays a pure recorder and the renderer resolves the deferred graph atrender()/image(of:)time, entirely GPU-resident (layers are attachments, filter inputs sampler binds, never a CPU round-trip), premultiplied linear, the no-targets path byte-identical; everyGeometryBatchbegin snapshots all the*Startoffsets (omitting one zeroes a preceding batch's count — theSceneDefocusbug);withTarget/withFeedback/withFieldpush/pop the drawing state around the block (ablendModeset inside a layer block must never leak to the canvas — was a real bug); design-pattern fragments animate by an explicitphaseparam (deterministic export, no hidden clock) and blend palettes internally in sRGB (mixed in linear they read washed-out pastel — a real bug);Feedbackmirrors.filtered( _: ) SimField;.filtered( _: ) Sim.paramsis an array ofSIMD4rows the renderer binds after the texel row (a new sim never widens therunSimulationcall site, it returns more rows),SimField.simis a public var re-read every frame (live growth parameters; the evolved state carries), and Lenia is the paper-faithful continuous CA (exponential kernel core in up to 3 β-rings, normalized in-loop by the summed weight, gaussian growth, clipped dt integration; Orbium defaults R=13/T=10/μ=0.15/σ=0.015) whose dying / labyrinth / rings / maze looks are all real regimes — seed it densely (sparse mass starves, the documented envelope, not a bug);.ripplesis the height/velocity interactive-water kernel (state h in r, v in g, both signed; 6 substeps; clamped taps, soft absorbing border rim) whose per-sim inject is load-bearing:Sim.injectFragmentroutes it toollin_sim_inject_height, which adds the drawn mark's premultiplied luminance to height only — the generic replace-by-alpha inject pins the surface and writes color into the velocity channel (the exact bug that parked the 2026-07-07 attempt, see [[ollin-ripples-sim-parked]]); the coupling gainspeedmust stay under 2 (clamped to 1, default 0.5): 2 is the CFL boundary where the Nyquist checkerboard sits on a repeated λ=−1 root and grows linearly, settling ~22× the ring amplitude under any damping and shading into glitter — substeps went 3→6 so the ring pace is unchanged (wave speed ∝ √gain); soft radial-gradient dabs are the drop contract (hard discs legitimately ring at every frequency), and the rawimageis a debug view (shade with.relight);.sandpileis the Bak-Tang-Wiesenfeld toppling CA on the generic single-texture step path (no dedicated pipeline; Dhar's abelian property licenses any parallel schedule, andSandpileTestspins the settled pile cell-for-cell against a sequential CPU reference, the edge variant verified red against its counterfactual) with five terse invariants: the step is the k-fold parallel formq' = fract(— topple as many times as a cell can per pass, identical to single toppling in the critical regime but load-bearing at a hot source, where single toppling pools for thousands of passes (a saturated blob's interior is net zero: lose four, receive four back); grains stored in quarters (stable cells read 0/¼/½/¾, gradientMap-ready; exact in half float to 2048 grains), state read fromq) + Σ floor( q_n)/ 4 .ronly (a luminance dot is off by an ulp and the toppling floor/fract must be exact), boundary open — reject the position before sampling, never wrap or clamp (the clamping sampler reads the edge texel back as its own neighbor, a reflecting wall; on a torus sand accumulates until every cell topples forever), and the inject addsrint(luma·pour)whole grains (an AA fringe pours whole grains or none; nothing erases);topplingsissubsteps, the pacing dial (an avalanche front moves one texel per pass), the classic relaxed figure is drop-and-relax (one heavy mark on one frame, then settle — a steady heavy pour keeps a molten super-critical core by design), andrunSimulationbindssim.paramsto the inject pass too (pre-existing injects read none — byte-identical);.fallingSand(ollin_sim_falling_sand+ollin_sim_inject_grainsinShaderSim.metal;SandMaterialnames the four levels) is the Toffoli-Margolus block CA on the generic step path: every cell settles its whole 2x2 block from the same four reads and writes back only its own corner, so the update is conflict-free with no ordering. The origin walks the block's four corners over four passes (x flips every pass, y every second;passesis rounded up to a multiple of four so a frame runs every tiling equally), which sets the pacing (a grain falls one cell per two passes, water spreads one cell per pass, each diagonal roll comes once per four) and is load-bearing: with only the two diagonal tilings a cell owns a single diagonal and half the grains on a heap's edge can never roll off it, so a pour stacked a solid tower over a proper cone (seen in the first render, fixed by the four-corner walk). The block rule is falls first (the heavier top cell sinks: sand through empty and through water, lifting the water), then in a block where nothing fell one diagonal roll taken with probability1 - frictionby one hash per block seeded by the field's frame age (FeedbackSlot.age, not the renderer's frame index, which cycles mod 3), then water swaps with an empty cell beside it in either row (a surface cell drifts one cell per pass in a parity-decided direction, so a pool spreads as a wedge and levels over time); the field's edge is a closed box (outside reads as wall). The inject snaps in sRGB terms (linearToSrgbbefore rounding to thirds) soSandMaterial.color(Color(white: raw/3)) lands as the named material through the linear-light layer, alpha-gated so an AA fringe writes nothing.FallingSandTestspins the rule cell-for-cell against a CPU walk of the same block rule (falls, the sink through water, the roll and its order after the falls, the spread, the closed edge, the four-corner walk: reverting to the two-tiling alternation, swapping the roll and spread order, or rolling in a block where another cell fell all turn it red), plus the tower at friction 1 and a cell-identical replay; headlessimage(of:frame:)has runpasses * (passes. Example: theframe + 1) sandrule inExamples/; snapshotSimulation/ Automata falling-sand;Docs/. the state automata (Drawing/ Effects .md .cyclic/.excitable/.briansBrain/.hodgepodge/.forestFire/.wireworld/.schelling) share one encoding — integer state s of N levels stored as s/(N−1) in.r, decoded withrint(exact in half float well past N=200) — and three load-bearing pieces:.cyclic/.hodgepodgestart as seeded random states via the first-allocation fill (Sim.stateSeedFill→ollin_sim_state_seed; a uniform field is a fixed point of both rules, so the Turingfill:hook generalized toinitialNoiseFill), a probability roll drawsollin_uniform24(PCG3D taken to 24 bits: the forest fire's growth and lightning, Ising's flips, Schelling's moves), neverhash12, whose last float product lands on exactly 0 about once in 1,800 rolls and floors any chance below about 5e-4 (aSmallLightningStrikesAtItsOwnRate,aColdMagnetKeepsItsSpins), the draw-to-spark pair carries snapping, alpha-gated injects (ollin_sim_inject_excite/_brain, and the sRGB-snapping_wire/_kinds/_fireoverollin_sim_inject_levelsfor the rules whose grays the reference names (the two…Cellenums, and the forest fire's mid-gray tree, which the plain blending inject had landed in linear light as bare ground): a solid mark writes the nearest meaningful state, a soft fringe writes nothing, though two one-texel rims beside one gap reach the three-quarter gate, so a dense stand is planted by its outline (aMidGrayRectPlantsATreeAndLeavesItsNeighborsBare) — a blended AA rim decodes as refractory/resting cells that block every birth, the bug that killed the first Brian's Brain seed), and.hodgepodgeis Dewdney's formulation of Gerhardt-Schuster (healthy ⌊A/k1⌋+⌊B/k2⌋; infected ⌊S/(A+1)⌋+g, S summing the cell and all its neighbors, the +1 counting the cell itself among the infected — the divide-by-zero guard; ill → 0; everything caps at n). A solid blob legitimately dies under Brian's Brain (the interior rests together and a flat edge shows three neighbors where a birth needs exactly two) — sprinkle loose soup instead, a rule fact verified on a CPU model before suspecting the renderer.StateAutomataTestspins each rule cell-for-cell against a sequential CPU reference (both neighborhood shapes, the toroidal wrap, the injects; sabotage-verified red), with two probe gotchas worth keeping: per-texel stamps must bedrawPolygonunit quads, notdrawRect(an SDF rect's ~1-render-px analytic halo leaves edge-adjacent texels hovering at the injects' 0.5 alpha gate), and headlessimage(of:frame:)runs frame+1 generations (it renders draws 0...frame inclusive);.relightmeasures slope over a span, not a texel (taps on the half-texel grid for a free 2×2 box, gain divided by the span, span growing with resolution past 1080) — slope weights a wavelength by 1/L, so a per-texel Sobel lights few-texel content as steeply as the real relief; smooth relief is preserved to ~1% (effects-relightdid not need re-recording). Don't soften a finish's specular exponent to chase speckle — a broad lobe lifts the highlight on flat areas too (apow(sh,60).liquidwashed the Guide's Organism background several shades lighter), so fix the normal, not the lobe; headlessimage(of:frame:)renders every warmup frame whendrawer.usesFeedback(feedback / sim fields / SSR — else the ping-pong never evolves); fluid keeps its ownfluidSlotsbesideFeedbackSlotso the single-field sims stay byte-identical;.multiScaleTuringis McCabe's rule (activator/inhibitor disc averages at several scales, least-disagreement scale fires, renormalize each step) and runs its own multi-pass pipeline (runMultiScaleTuring) like the fluid while sharing the one-pairFeedbackSlot(so flip/prune/repeat are the shipped ones), with four load-bearing pieces, each of which was a real defect first: the field starts as seeded noise, not a constant (a flat field is a fixed point of the rule, sofeedbackSlotgrew afill:override besiderestState); the blur pyramid is Gaussian (Burt-Adelson binomial), not a 2x2 box (a square kernel has square preferred directions, so the labyrinth came out rectilinear); a radius gathers a 9-tap disc two rungs finer than the radius match, never a single tap at the matching rung (that rung holds one sample per feature, so the pattern locks to the lattice, unfixable by any kernel since the information isn't there); and variation is averaged over a per-scalevariationRadius(read at a point, a fine scale's disagreement crosses zero along every contour of its own structure and, since least disagreement wins, it claims a dense web of pixels and buries the coarse scales). Two parameter facts are equally load-bearing because renormalization couples the scales: equalamounts across rungs (the hardest-pushing rung sets the range and squeezes the rest toward mid gray) and a ladder starting at radius 2 (radius 1 works on single texels and reads as speckle).TuringScale(6) must equal.maxScales OLLIN_TURING_MAX_SCALES, andMetalRenderer(12) must equal.turingPyramidLevels OLLIN_TURING_LEVELS(it sizes the texture-array binding; a shallower pyramid repeats its top rung to fill it). Deliberate v1 cut: the winning-scale index is not carried in the state (color-by-scale would muddy a channel the display and the extent reduce both read as gray);layer(_:)'s draw closure is@escaping @_implicitSelfCapture(without it, bare draws insidelayer { }needself.and the p5 feel breaks); SSAO's and SSR's stabilizer sets each fixed a worse artifact — don't undo any of them ([[ollin-ssao-normal-gbuffer-followup]], [[research-before-implementing]], [[verify-perceptual-temporal-fixes]]); DoF/SSAO/SSRqualityis aRenderQualitytier resolving to a per-GPU budget (DoF: the bokeh tap budget viaresolveDofTaps— M2 1080²:.default192 ≈ 14 ms; benchmark back-to-back on a cool machine, single runs drift 50% under thermal load, enough to invert an A/B)..defocusis the canvas lens's gather over a layer (ollin_fx_lens_dof_layer_prepass+ theollin_fx_lens_*passes inRenderer/, theShaderCombine .metal .defocusarm ofapplyCombine): the same five passesapplyDepthOfFieldruns, fed by the layer prepass and the ramp law (zero insidefocus ± range, growing with the distance from the band tomaxBlurat the map's ends; growing tomaxBluronerangepast the band, the earlier law, gave every depth past a narrow band the same blur, the masked-blur look a sketch complained of; the gather'sDofLawnames which law sizes a signed blur, affine in inverse distance for the lens and in depth on the ramp, so the continuity test holds for both, and sameness of depth is a hundredth of the range rather than of the distance). The layer prepass resolves a drawn map's anti-aliased rim to its nearer side: a pixel whose depth lies strictly between the nearest and the farthest within two pixels of it (past one gray level, so a smooth ramp is untouched) takes the nearest, which is what the canvas's nearest-sample depth resolve does on its own; the earlier two-size prepass (a neighborhood max the pixel received by, to consume the in-focus seam a rim leaves where it crosses the focus, and a radius-2 min it scattered by, to stop the rim flinging the color under it across its in-between blur) consumed a thin line in focus along with the seam (a 1.2 px bar kept 4% of its light). Measured on the study scenes against the earlier running-average gather (bars at eight depths, four small highlights, a near bar over a subject in focus, 512 px,.detail): light kept by a near bar 0.48 to 0.99 and by a thin bar in focus 0.04 to 1.00, a near highlight's light 0.27 to 0.98 with its peak over its mean 6.8 to 1.3 (an even disc rather than a core in a halo), the rim at an in-focus silhouette 1.099 to 1.000, and the near bar over the subject 0.0365 to 0.0229 RMS against the analytic layered reference at each law's own radius (the canvas reads 0.0222 at the lens's). What the layer filter still shares with the canvas's far field: a far object much sharper than the backdrop behind it keeps a little less of its light than the canvas does (a bar at a tenth of the backdrop's blur 94.9%, a highlight 91.1%; 84% under the averaged model).maxBlurunder half a pixel hands the layer back untouched. The opening is a parameter of the gather, not a second path (blades/irisAngle/catsEye, now carried in the gather's fourth parameter row): the reach test divides the tap distance by how far the opening reaches that way (ollin_dof_aperture), so a round opening with no cat's eye takes the arithmetic the canvas takes (the canvas asks for neither, byte for byte). A polygon is taken at the area of the round opening it replaces (R = sqrt(), so a blade count changes shape, not size, and the tile size and the gather's rim move out topi / ( n sin( pi/ n) cos( pi/ n))) maxBlur * Ror the corners are cut off.catsEyeintersects two discs pushed apart bypinchalong the line to the frame's middle (reachsqrt(,pinch^2 c^2 + 1 - pinch^2) - pinch |c| cthe cosine to that line), capped at 0.9 so an opening never closes; it changes shape only, never brightness (.vignettedarkens), which holds only because every density in the gather and the sprite draw divides by the opening's own area (ollin_dof_opening_share:(of the round opening for a round one, the rim walked at 64 angles for a bladed one;2 acos p - 2 p sqrt( 1 - p^2)) / pi piwith no pinch, so the canvas pass and a round layer are byte-identical), never bypi r^2: divided by the round disc's area, a pinched disc carried only its clipped share of the light, whole inside its own silhouette (normalized by its own weights) and that share outside, a step at every near silhouette toward the frame's edges (a fifth of the brightness across four pixels on the Defocus example's largest disc, found by profiling one disc against the lens's convolution;theBarrelKeepsTheLight,theBarrelLeavesNoStepAtASilhouette). A flat disc follows the lens's convolution within 0.015 at every radius in both paths (aDiscFollowsTheLensAtEveryRadiusinDefocusTestsandDepthOfFieldTests, againstlensDiscCoverinLensDiscSupport, the overlap of two circles): the first thing to run when a blurred edge looks wrong, before any theory about the composite. The depth gray is read perceptually, and that conversion is the filter's (.swift ollin_dof_depthislinearToSrgbof the luminance):Color(white: 0.47)in a linear-light layer is stored as 0.19 and read back as 0.47, so the gray a sketch draws is the depth it means, andollin_fx_depth_normalizesRGB-encodes a target's.depthso it reads back the same; a sketch never converts.bladesdefaults to the camera's ownCamera3D, stamped on the depth layer through.apertureBlades DepthReconstruction, so the live blur, the flare ghosts, and the path-traced export share one lens; a hand-drawn depth map carries no camera and stays round. Envelope: the shape is only as clean as the tap budget, so a source smaller than the tap spacing (sqrt(pi/budget)·rim, ~13% of the rim at.default) is found by some taps and missed by others, which the moved spiral and the median mostly even out, and a hexagon's corners (13.4% of the rim) sit right at that limit.ApertureBokehTestspins it (reach ratios 0.952 flat / 1.0996 corner, the tangential-vs-radial cat's-eye split, the camera stamp), all verified red by sabotage. The snapshots' mean-diff tolerance averages every one of these away (they all live in a band around a silhouette), soDefocusTestspins them behaviorally — reach for a probe here, not a whole-frame diff. A layer that carries additive light wants an opaque background..addsums alpha as well as color (sourceAlpha:), so an additive draw over already-covered pixels leaves the layer's alpha above 1, and compositing it back (.one, destinationAlpha: .one src·a + dst·(1 - a)) then subtracts what is behind: a white sphere under an additive glow came back green over magenta. Clear the layer withbackground(_:)inside thewithTargetblock so it composites as a picture, or add the glow at the canvas instead of inside the layer. Credits: AsyncGraphics + ofxFX + orx-fx/OPENRNDR + Apple MPS (ATTRIBUTION.md, never in.swift).Docs/; examplesDrawing/ Effects .md Effects/*(Layers / FilterCatalog / GeneratorCatalog / GaborNoise / Glitter / MeshGradient / Feedback / Aside / FlowStreaks / Defocus),Simulation//GrayScott Automata/Ripples/Fluid,3D//Effects/ SceneDefocus AmbientOcclusion/ScreenSpaceReflections; snapshotseffects-*+line-integral-convolution+lenia+ripples+sandpile+falling-sand+cyclic-automaton+excitable-medium+brians-brain+hodgepodge+wireworld+schelling+mesh-gradient/design-patterns/design-filters/scene-defocus-3d/ssao-3d/ssr-3d.RipplesTestspins the wave sim behaviorally (rest stays rest, rings expand, channels decay). The film look is two filters:.halation(reuses bloom's bright pass and MPS blur and adds the tinted halo back throughthreshold: radius: tint: amount: ) ollin_fx_halation_combineweighted per channel by the room left below white (1 - saturate(b.rgb), the alpha by the max-channel key), which is what makes it a fringe around a white core rather than a glow over it; an empty bright pass adds exactly zero, so a frame with nothing above the threshold and anamountof 0 are byte-identical (pinned, and the room rule is pinned over a red field where the ring's green must rise four times its red)..filmGrain((amount: size: seed: ) ollin_fx_film_grain, a single pass) is the Newson-Delon-Galerne Boolean grain model in its Gaussian limit applied per channel on the encoded picture with a residual apply into linear (a value above white keeps its excess): the spread is2·amount·sqrt(with a 1e-6 dead zone on the tone weight (the encode of white lands a float's rounding under 1 and flips eight-bit ties, the ColorLUT lesson), so black and white are byte-identical and the mean of a flat region holds to the level; the draw is ae·( 1-e)) size-pixel lattice of triangular values under a quintic fade, divided by the spread its own weights predict so every pixel carries the same spread at any size (pinned: 25.5 levels at amount 0.1 whatever the size) and set half a pixel back so size 1 is white noise; theseedreaches the shader asFilter, a hash of the Double's bits under 4093, so a fractional seed is its own pattern and a frame count never rounds in a float. On the web page halation is the third page-owned pass (.grainPattern( of: ) ollin_web_halation, its add-back binding two rows) and the grain crosses as data. ExampleEffects/FilmLook; snapshotfilm-look;FilmLookTests(14, three sabotages verified red); theFilmedfixture inWebEffectsTests. A layer's write target names itsFeedback/Accumulator/SimFieldweakly (RenderTarget.Owner), and the drawer holds each owner it records until the frame renders: the strong back-reference was a cycle that kept every such layer and its GPU slot for the life of the process (leaksover the feedback example found it), and the slot tables prune on a dead owner. Fill order (Drawer,.layerSchedule( ) Effects/, 2026-11-27): every layer is filled after the layers it reads: a drawn layer (plain, feedback, accumulator, a field's seed) after the layers its runs read as pictures (LayerSchedule .swift GeometryBatch: an image, a depth image, a mesh's picture, matcap, and maps), a filter after its input, a combine after both of its layers. Ties go by kind (generators, oceans, plain layers, feedback, accumulators, fields, then the ops) and then record order, so a frame in which no layer reads a later one is filled exactly as before, and the block order a sketch wrote decides nothing else. Layers that read each other put the lowest of them by that rule.layerPictures early(the plain layer of a plain-and-feedback loop, as it always was), reading the other as the frame before left it, and the renderer says so once (LayerSchedule). A carrier (.earlyNote RenderTarget: a layer's depth and normals, an accumulator's mean and sum) waits on its owner;.isCarrier Feedback.previouswaits on nothing, resolved byresolveFeedbackFronts(at the top of every encode, which is also what makes) previouson a frame with no block the last block's picture (it was the one before). A field waits on no filter (its filtered inputs stay a frame late, by its own rule). A layer the renderer makes belongs to the frame that asked for it:beginFramelets go of the texture of every filter's and combine's result, generated pattern, and ocean field, so one kept in a property and drawn on a later frame draws nothing (it showed frame 0's picture forever in a sequence export, nothing in a single-frame export, and in the window whatever the pool had put in that texture three frames on), a filter over it makes nothing, andLayerScheduleraises one note naming it. Three more reads follow the same rule: a.unmade snapshot()or a glyph mosaic of a plain layer the frame left alone isnil(encodeLayerReadbacks), the slit scan's delay map is a read (Filter.layersReadinopInputs, so a map layer is filled before the scan and filled empty when left alone), and a layer's window (below). A plain layer the frame reads and never opened is filled empty (LayerSchedule; ruled 2026-11-27: a layer holds one frame's drawing, kept handle or not, where a kept one showed its last picture in a sequence export, nothing in a single-frame export, and in the window its last picture for two frames and then another layer's), so a combine or a filter over it reads an empty layer; a clear color is reset where a frame first opens a layer, never per block. The web recorder fills in the same order, and the page's player resolves every feedback layer's front ahead of its layer loop, as the Mac does (a layer that drew.unopened previousahead of the feedback layer in the list read a blank before).backgroundin a layer's block wipes the whole layer, earlier blocks included, and leaves a second layer drawn inside the block: the block's runs are cut off the lists when nothing else has drawn since it opened, and are otherwise handed in place toDrawer.wipedRuns, a surface no pass draws, never taken out of the middle (a run's extent is up to the next run's start, and the mover ranges index the mesh lists).withTargeton a layer the renderer makes (a filter's or a combine's result, a generator, a depth layer:RenderTarget) skips its block with one note (ruled 2026-11-27, over a thrown error and over drawing on top)..takesDrawing composelays each finished layer at the canvas's own origin (Drawer), so a transform or a symmetry in force applies once..placeAtCanvasOrigin Accumulator.reset()keeps the passes of the frame it is called in, wherever indraw()it falls.filterChainFormatis set for the length of one op.LayerBookkeepingTests(22 tests, and with the eight statements unpinned inEffectInvariantTests, twenty-four plants in six rounds: twenty-three red in their own tests, and one that found nothing and says why, the op's format left set after the op, which no picture a test reads shows),LayersReadOpsTests, the page sceneOrderedinWebEffectsTests;ARCHITECTURE.md§ The order layers are filled in. A layer is aVideoFeed(RenderTarget:,VideoFeed frameits live image,frameSizeits size):environment(wraps the sketch's own drawing round a scene so a metal reflects it: a scene on the canvas reads this frame's layer (the bake runs again after the layer passes), a scene inside another layer the frame before's, or the neutral sky for a layer made that frame; the fed layer is a read in the fill order (.feed( layer)) Drawer, handed in by.environmentLayer Sketch.environmentsince the feed table is the main actor's), so on a frame that drew nothing into it it is filled empty and lights nothing, where it kept reflecting an older picture; a layer is a per-frame handle, so it is a new feed every frame, and the renderer's per-feed bake states are reaped on a new feed and never hold a texture-backed image (a layer's image owns its target, which kept a per-frame layer alive forever);GestureMarks3DTests. Layer precision:.aLayerIsAFeed makeRenderTarget(/precision: ) makeFeedback(takeprecision: ) LayerPrecision(.float32 rgba32Float) for a layer whose values are sums; the format is carried inPipelineKey(nil for the canvas and every half-float layer, so those keys are untouched), the target pool and the feedback slot key on it. Precision follows the source through a chain:.colorFormat recordFilter/recordCombinegive the output the input's (the base's) precision, the filter loop setsMetalRendererfrom each op's output around that op only (so a frame filter or a sim step never sees it),.filterChainFormat acquireFilterTexture's default format reads it, andencodeEffectFragment/encodeUserShaderkey the pipeline on the output texture's own format when none is named, so no pass in a float32 chain meets a half-float pipeline (only fragment, MPS, and explicit-format passes live underapplyFilter/applyCombine; a blit or a geometry pipeline added there would have to follow the same rule). No example or Guide figure renders through a float32 layer, so nothing published moved.DistanceFieldTestsreads a dot's field 1,400 to 1,408 px away on 1080x1920: 0.29 px of scatter in half float (the rounding), about 0.1 in float32, through a blur too, and red when the chain format is planted nil;.aSinglePrecisionLayerMeasuresFarDistancesToAFractionOfAPixel precisionFollowsTheLayerThroughAChainpins the recorded precision.combined(with:_:)onFeedback,Accumulator, andSimFieldforwards besidefiltered(_:)(the sim field's keeps it stepping);PersistentLayerCombineTestsdraws each against the.exposure(stops: 0)hop it replaces, pixel for pixel, plus a blank-base twin that must differ. A whole-frame filter's scale is the window's (found 2026-12-03):postProcessruns over the frame, and a live window's frame is as large as its drawable (pictureSize), sorender(hands_: viewport: in: ) applyFrameFiltersthe drawable's height over the canvas's as thescaleevery layer filter already takes; an export's frame is the canvas's size and keeps 1, so no export moves. Before it, a blur of 6 measured 6.00 canvas pixels wide in a window the canvas's size and in the export, 4.00 in a window 1.5 times as large, and 3.00 at twice (EffectInvariantTests, the live path driven through an offscreen view at three drawable sizes, with a mosaic's cells beside the blur; red on the plant). The accumulating live path applies no whole-frame filter. Each of the three is a combine's second input too:.aWholeFrameFilterIsAsWideInAWindowOfAnySize combined(with:_:)on a layer and on all three takes aFeedback(its picture of this frame,image's), anAccumulator(the mean), or aSimField(its state) through one internalcombineLayerper type, and a field's asks it to step, so a self-organizing field read nowhere else still runs. The same suite draws the twelve pairings against the hop on the second input's side with a blank twin that must differ, each kind against a plain layer that draws its image, a feedback layer on a frame that opens no block on it, and a multi-scale Turing field that nothing else reads.Accumulator(makeAccumulator/withAccumulator(,_: passes: ) Origin.accumulate): the block renders like a geometry target into a transient layer and one compute dispatch (MetalRenderer) adds it into a persistent.accumulateKernel rgba32Floatsum and writes thergba16Floatmean beside it, dividing by the passes the drawer counted at record time (passesAtRecord, so a repeat encode of one frame divides by the same count and adds nothing); a pass of.lightparticles alone (Drawer, which a stencil or depth need also refuses) is drawn single-sample into an.drawsOnlyLight( on: ) rgba32Floattexture from the filter pool, its pipelines keyedsingleSamplewith that format (thelayerFormat:override onencode), the light particles takingollin_particle_splat_vertex/_fragment: a particle at or under one texel spreads over the texels around it in bilinear shares(from each center, its quad reaching a sixteenth of a texel past one so no center with a share is lost to snapping, which keeps a sub-pixel point's light exactly and lands it where it falls (the multisampled one-texel quad's box without its eight-sample steps); a disc over a texel keeps the area ramp. Load-bearing: half float stops adding a sample once a pixel holds one to two thousand times it (a truncating blend, measured: 0.001 adds stalled at 2.0), and one frame's pass piles a focused dot's every point on four pixels, so the half-float pass kept 1.0, 0.5, and 0.05 of an in-focus dot's light at 100, 1,000, and 16,000 points a pass; every Apple GPU blends1 - |dx|)( 1 - |dy|) rgba32Floatbut only Apple7 on multisample it (Metal's feature tables), so anything else in the block keeps the half-float multisampled pass every layer has, byte-identical;makeAccumulator(draws that multisampled pass inprecision: .float32) rgba32Float(Accumulator, carried by the write layer, so the target pool and every pipeline drawn into the pass key on the format as a.precision .float32render target's do;MetalRenderer, the device's.multisamplesSinglePrecision supports32BitMSAAread once, sends the pass back to half float on a GPU that cannot multisample the format, and is a variable only so a test can turn it off on a renderer of its own): one pass of faint squares summing to 0.5 read 0.491 in half float up to 2,000 squares, 0.125 at 5,000, and 0.063 at 16,000 (it stops at 1,250 to 2,000 times a square), and 0.503 at every count in single precision, measured 2026-11-05 on an M2; the resolved layer is 16 bytes a pixel against 8 and the multisampled attachment twice its half-float size wherever the pass is too heavy to stay in tile memory; the default accumulator and the light-only pass are untouched (aPassOfFaintInkKeepsEveryShapeInSinglePrecision,aSinglePrecisionPassStaysHalfFloatWhereTheGPUCannotMultisampleIt, each red under its plant); the light pass is a quarter of the multisampled one's memory and was measured 10% faster on four million points (43 ms against 48); a particle of size 0 is degenerate in both light vertex shaders (all six corners at one spot past the frame), so a kernel's empty slot costs no fragment.reset()flags a replace consumed at the next encode;usesFeedbackincludes it so a headless drive renders every frame; the web export refuses it by name.Filteris the sandpainting print: exposure, Reinhard, the ground added after the curve as display components, the result written as the display value (.develop( exposure: ground: ) srgbToLinearof it into the intermediate).Accumulator/.developed LineSpray.developedrun it over the mean.LightAccumulationTestspins the mean (six passes read as one,passes:divides, a reset restarts), the float32 feedback climbing where float16 stalls, and the print recipe.The sketch's own drawing, read back (
Sources/,Ollin/ Effects/ LayerReadback .swift LayerHistory.swift;Docs/§ snapshot() and § makeLayerHistory(capacity:) and Filter.slitScan,Drawing/ Effects .md Docs/,Video/ SlitScan .md Docs/; exampleDrawing/ GlyphMosaic .md Effects/;ScannedByItself LayerReadbackTests, 8 tests and 11 cases, each red under its own plant; Guide Ch 19 § The drawing read back: snapshot and the slit scan).RenderTargetreturns the layer's pixels a frame late and never waits on the GPU. Calling it records a.snapshot( ) LayerReadbackRequeston the drawer (layerReadbacks, per frame) and returns the frame before's answer at the same position: the n-th request reads the n-th entry oflayerReadbackResults, of the same kind at the same pixel size, elsenil(the first frame, a layer the frame did not fill, a request that moved), because a layer is a per-frame handle and the one that asked last frame is gone. The renderer encodes every request at the end ofencodeEffectTargets, after every op has resolved: a present pass under.premultipliedalpha into a display texture of the layer's pixel size and a blit into a shared buffer (the frame grab's road, so the bytes are the layer as shown, tone-mapped and sRGB-encoded; the headless image of the same picture matches to the byte, mean 0), delivered as aLayerReadbackBatchon the main run loop from the command buffer's completed handler on the live path (one frame late; 0.12 ms more on a saturated 1080² frame of 6.15, measured 2026-10-25 in a debug build) and synchronously bycommitHeadlessafter its wait, so an export's snapshot is exactly the frame before and the drive renders every frame whenreadsLayersBack(and returns the rendered one, or the kept frame renders twice); a repeated encode of a frame (statefulEncodeIsRepeat) encodes no readback, a discarded headless frame drops its batch. The storage is pooled like the grab's and let go of on a frame nobody asks. The glyph mosaic of a layer (glyphMosaic(/of: layer .image) drawGlyphMosaic() is the same request of kindlayer .image, …) .cells(:columns: rows: ) ollin_layer_cells(ShaderEffects.metal, built throughlibraryComputePipeline), one threadgroup a cell over the CPU mosaic's integer cell bounds, encodes every texel as the present stores it (ollin_present_map,linearToSrgb, premultiplied under the coverage, no dither) and averages throughsimd_sum, so the mosaic of a layer chooses what the mosaic of the layer's snapshot chooses (tones within a level, glyph flips only where a tone sits on a ramp boundary); the 2.6 ms a 72-column mosaic adds to a live frame is the CPU's glyph choice over 5,184 cells in a debug build, not a wait.Filterover a.slitScan( _: delay: ) LayerHistory(makeLayerHistory(, persistent likecapacity: ) Feedbackand keyed by identity inlayerHistorySlots): atype2DArrayofcapacityslices in the scanned layer's size and format, allocated on first use or a change and zero-filled; the layer is blitted into slicenextonce a frame (lastAppendstamped withlastStatefulEncode, never on a repeat encode; the stamp is the drawer's serial and its own count of frames begun,Drawer.frameSerial, never the sketch's frame count, which starts over at 1 when a run is started over on the same drawer and made that run's first frame read as a second encode of the old one, so a still restarted with a new seed showed its feedback layers and fields unstepped) however many scans read it, andollin_fx_slitscanreads slice(, the CPU scan's rounding, withnewest - rint( d × ( count - 1))) mod capacity dfromSlitScanDelay(.acrossuv.x,.downuv.y,.radialthe distance to the center over 0.7071,.map(image)the premultiplied luma of a picture's stored bytes through its data texture, or of a layer's linear light encoded, the shader told which), so it matchesSlitScanfed the layer's snapshots to 0.25 levels under every delay; it counts asusesFeedback, so an export renders every frame and never redraws a discarded one, and its memory iscapacity × width × height × 8bytes at half precision, the scanned layer's ownscalebeing the lever. The web page refuses all three by name (LayerReadbackRequest; the filter through its missing single pass, "the slitScan filter")..Kind .callName Image.layerTargetis the internal accessor for the layer an image wraps, renamed from the web-only name it had.Depth of field from light (
Sources/; the sandpainting lens over the substrate above).Ollin/ Effects/ LineSpray .swift LineSpray(makeLineSpray(/_: sampling: passesPerFrame: bokeh: ) drawLineSpray(_:)) renders[SprayLine](world-space segments carrying linear RGBlight/endLightper pass asSIMD3<Double>, the stored value, with thecolor:intensity:initializer converting a tone on the way in throughColor.linearRGB, and aweight) as depth of field: each frame one dispatch ofpointsPerPass × passesPerFramethreads (LineSpray.kernel, over thebuffers:form: theOllinSprayLinerecords, a point-to-line table under.byLengthonly, the particle buffer of a two-deepPingPong) samples a spot on each line, takes it into camera space, pushes it byballSample × max(with the defocus measured along the view axis, fades it bystrength × defocus^power, minSize) exp(, and projects it through-attenuation × defocus) ollin_project_eye; the particles go into the spray'sAccumulatorunder.addin the.lightstyle withpasses:. Load-bearing: every point deposits its line's share (passesPerFrame start), so a line's light per pass is its color × intensity under either.w = 1 / points on the line Sampling(.perLine(n), each line itsweight's share ofn, rounded, at least one and at mostn; or.byLength(sharing by length × weight with at least one point per line,pointsPerPass: ) LineSpray); under.pointCounts .perLinethere is no table: a pass is the lit lines'nslots end to end, a thread finds its line aspoint / n(layout.xin the params, 0 to read the table), the records are packed lit-first and padded to the lines given (so a changing lit count or weight rewrites the ring and never rebuilds it, which happens only for a new line count), each record carries its count inend.w(edge1.wfor a quad), and a slot past it writessize = 0and returns before any of the lens, which is the weight as ruled 2026-10-17 (a share ofn, not a multiplier past it, so a light line never makes the rest carry idle slots); a primitive with no light (both ends zero for a line,lightzero for a quad) gets no points under either sampling and no part in a.byLengthshare, so three pieces with two dark dispatch the lit one's points and draw its picture to the byte (aDarkPieceCostsNothing), and a spray of nothing but dark primitives still records its accumulator block with no particles, a pass of no light, so a scene that goes dark develops dark rather than holding the last mean (aSprayThatGoesDarkDevelopsDark); the in-focus dot keeps its whole light at every count through the accumulator's single-precision light pass (aSprayedDotKeepsItsLightAtAnyCountAndFocus, against the analytic total, each dot read at an exposure off the print's floor and ceiling;aSprayedDotKeepsItsLightWhereverItFallsOnAPixel, walked across a pixel in eighths, one total within 1%, on at most four pixels, its centroid on the dot within 0.02 px); a print is read back through the curve alone (m / (1 - m)of the byte), sincedevelopwrites the display value with no sRGB step, and an sRGB decode first had read a focused dot 2.6 times too bright at 100 points (the pin's own error) and a six-blade aperture 3% off the ball's; a point's alpha is4 /, so its whole light lands in its disc and the exposure is independent of( π × pointSize²) pointSize; each point is one vertex (recordParticles(, the one-vertex path under Compute & GPU particles): four million points at 1080 square draw in 8.9 ms a frame where the six-vertex quads took 32.9, the kernel 3.4 ms of either, and... maxSize: pointSize) aSprayedPointLandsWhereItsQuadLandedpins the single-sample splat drawn both ways to the dither, a dot in focus and one out of it; aSignatureof camera,Bokeh, point size, canvas size, and line count resets the accumulator on any change (Blurry's reset-on-control-change);setLinesis a per-frame call: the same lines again return before anything happens (SprayLineisEquatable), so a sketch rebuilding its scene every draw converges under--settle, changed lines mark the spray and reset the average, and the GPU side is brought up to date inrecordat most once per frame (refresh(frame:), keyed on the sketch'sframeCount): while the layout holds (under.perLinethe line count, under.byLengthevery count) the records are rewritten in place (ComputeBuffer, internal) into a ring of.replaceContents MetalRendererrecord buffers, one slot per frame, so a slot is only rewritten after every frame that read it has completed (the same count the vertex ring rests on; a second draw of one frame rewrites the same slot rather than advancing), and changed counts rebuild the records and the point table, never the particles: the.maxFramesInFlight PingPongevery point lands in is grow-only with a sixteenth of headroom in 4,096-point blocks (particleCapacity() and is handed back only under a quarter full, since both dispatches and the draw takefor: ) countoutright and nothing reads past it. Sized to the count exactly (!=), a.byLengthscene whose lengths change (rings that breathe, where one that only turns holds its totals) drifted by a few points a frame and remade both buffers every frame, 576 MB of fresh zeroed shared memory at 6M points, which wedged a live desktop (found by a sketch in use; 80 exported frames: 11.9 s to 10.2, system time 2.1 s to 0.7, peak 959 MB and climbing to 642 MB flat). The tables stay allocate-on-change on purpose: they are CPU-written, an in-flight frame may be reading the old one, and a breathing scene measured no dearer than a still one (setLinesEveryFrameKeepsOrRestartsTheAverageAsTheLinesAskpins the kept average, the reset, the ring's depth, the kept table, the rebuilt table and the kept particles under.byLength, and that a rewrite reaches the GPU by the light's centroid following the lines);Bokeh.poweris a continuous exponent (1 and 1.5 are the reference's two settings); no camera means no draw.developed(prints the mean; with the reference's deposit (a one-pixel point, its radiance into its pixel) the exposure that matches its print isexposure: ground: ) 1 / 0.0019 ≈ 526. Surfaces beside the wires (SprayQuad,setQuads(_:)): a quad is the parallelogram two edges span from acorner, sampled over its area through its own kernel (LineSpray,.quadKernel OllinSprayQuad, stride 80) and its own point-to-quad table and record ring, so a scene can be made of faces rather than a wireframe of one. Load-bearing: lines and quads are one picture (both dispatches write into one particle buffer, the quads at an offset the params carry, and onewithAccumulatorblock records the lot, so what the two draw together is what they draw apart, added, inside the print's slack); a quad'slightis the whole quad's, not per unit area (corner.wis one over its point count, the line's rule one dimension up, so a one-unit and a hundred-unit quad at the same light deposit the same light per pass); under.perLine(n)every primitive getsnpoints while.byLengthgives the quads a pool of their own shared by area times weight, since a length and an area are not the same units; the quads keep their ownlastQuadWriteFrameso one refresh cannot consume the frame the other tests against. The aperture has a shape (Bokeh.aperture,Aperture):.round(the ball, unchanged),.blades(for an iris of straight blades (count: rotation: ) .blades(6)is the hexagonal sparkle; under three reads round), or.picture(_:)for a mask read across the hole, which covers an iris a sketch drew into a render target and one it loaded alike, since both are anImage(nothing is bundled). Load-bearing: the blades are sampled exactly and without rejection (bladeSample: one draw picks the wedge, two place the sample in that wedge's triangle with a square root, since every wedge of a regular polygon has equal area), so nothing is thrown away and there is no per-sample texture fetch; an aperture moves where a sample lands and never how much light it carries (a hexagon, a triangle and the ball print the same total light, pinned below the print's ceiling, since a shape that crowds its middle clips and reads short); a mask is read at the spot the sample took, so the mark's own center moves toward the side the hole is open on (the invariant is the centroid, not the skew: a half disc's skew about its own mean is small, which cost a wrong instrument before the right one);.roundis byte-identical to what it drew before the aperture existed, which is what let this ship without moving a committed image, and the probes fixrandomSeedbecause the spray takes its per-frame seed from the sketch's generator. Blades scatter in the aperture's plane with no depth jitter, and a flat hole spreads a little wider than the ball, whose projection crowds the middle. Four sabotages verified red (an ignored rotation, blades falling back to the ball, a mask read away from its sample, plus the quads'). Measured on a real 1080x1920 portrait frame rather than only derived: three defocused marks read 1.035, 1.059 and 1.053 wide against tall at -19.8, +61.1 and -9.7 degrees, and it is the scatter of the angles that says round, since a projection that disagreed with the viewport would elongate every mark along one axis; the residual few percent is neighbors in a busy frame..blades(5)reads as a pentagon by the same frame's radius-against-angle profile, a cosine at 5 cycles a turn standing ten times its own neighboring harmonics where.roundraises none. A probe that reads aperture shape off a rendered spray must pick the dots, never the brightest marks: a traveling line blurs to an open smear with no closed edge, which loses half a half-max walk's rays, and brightness selects for exactly those. A picture the quads read (LineSpray.picture,SprayQuad): the two random numbers that place a sample on the surface also read the texel at the matching spot, so a photograph or a glyph sheet becomes light the lens defocuses; bound through.pictureBounds ImageComputeTextureover the image's ownlinearTexture(for:), so a picture a sketch already drew is uploaded once and everyImagebacking answers; apictureBoundsof no size is what tells the kernel to read nothing. Read from the reference implementation's surface, written here (the sampling, the budgets and the texel read follow its shape; credited inATTRIBUTION.md).LightAccumulationTestspins the point counts, the defaults, convergence (the mean after twelve frames within a tenth of two), the pass count, the reset on a lens change, the settled export (a still and a sequence counting N passes per written frame), the quads' area shares (a parallel-edged quad has no area and falls to one point), their light invariant, the patch a quad carries, and the additivity of the two primitives in one picture. A turning camera in an export wants--settle N, since every frame restarts the average.Docs/; examplesDrawing/ DepthOfField .md Rendering/LineSpray(the reference's own scene and viewport, built from its description) andRendering/(the same pipeline from the primitives).DepthOfField The frequency domain (
Filter.fourier(of:)/.inverseFourier()/.spectrum(gain:);Renderer/, the ladder inShaderFourier .metal MetalRenderer+Effects). The 2D discrete Fourier transform over a layer, both ways, as a Stockham autosort radix-2 gather: each rung reads two texels and writes one, so a fragment shader runs it with no scatter and no bit-reversal pass, rows then columns,.fourierLadder 2 . log2(n)passes. Written from the published algorithm, credited inATTRIBUTION.md, never in.swift. Load-bearing: the spectrum's handle is.float32whatever layer it was taken from (Drawer.recordFilter), so a combine or a filter over it is single precision too: a mask over a spectrum taken from a default layer wrote half float, eleven bits for a sum in the hundreds of thousands, and a 512 square's white came back 0.376; the ladder ping-pongs throughrgba32Float(the pooledacquireSATTexturepair) because the sum a transform builds is the whole picture added up and a 512 square's low frequencies run to hundreds of thousands, far past half float's useful range; a texel carries two complex fields (rg and ba) and the butterfly transforms both at the price of one, which is what lets the ocean carry its height in one pair and its two sideways shifts in the other; the forward pass ends with a quadrant shift so the lowest frequency sits in the middle (a mask drawn over the spectrum then covers what it looks like it covers) and the inverse begins by undoing it; the1/nnormalization is applied in the last rung of each axis, so it costs no pass of its own, and the ocean asks for the raw sum instead (normalize: false), since its spectrum is written as wave amplitudes rather than as a transformed picture; a layer that is not square with a power-of-two side comes back untouched, with the note printed atDrawer.recordFilter(where the sketch's own call is) rather than silently as a black rectangle;.fourier(of:)names the channel because a transform works on one signal and a color layer is three, so the round trip is gray. Frequency-domain filtering needs no new op:spectrummultiplies both parts by a real mask, which is exactly a filter by scale (with the ringing a hard cut brings, documented). Round trip measured inside one 8-bit level on a 256 square..combined( with: mask, .mask( )) FourierTests(5: the round trip, a grating landing at its own frequency on each axis, a flat field as one spot in the middle, the refusal path); snapshotfourier-spectrum; exampleEffects/Fourier;Docs/; Guide Ch 22 § A picture read as waves: the Fourier transform.Drawing/ Fourier .md Measured distance fields (
Filter/.distanceField Filter.fieldMap; the passes inShaderEffects.metal, the ladder inMetalRenderer+Effects). The counterpart of the authored.measuredDistanceField SDF: a field measured back out of a drawn layer. TwoFiltercases and no new plumbing —.distanceField(writes r = signed distance in pixels (negative inside), gb = the unit direction to the nearest edge, a = 1, sofrom: threshold: maxDistance: ) pixel + dir * abs(is the edge point (which is what an outline, a push-apart, and a picture-keyed Voronoi actually read; a distance-only field would be redone the first time one was wanted), andd) .fieldMap(reads it back through a_: from: to: repeating: ) Ramp/Colormapover a pixel window (repeatingwraps → contour bands; a ramp turning over at one distance is dilate/erode; a narrow band is an outline). Jump flooding (Rong & Tan 2006) with the leading step-1 pass of 1+JFA (2007), credited inATTRIBUTION.md, never in.swift. Load-bearing: the seed is the sub-pixel crossing found between two pixels (linear interpolation to the axial neighbor across the threshold), never the pixel that holds it — snapping to the center grows every measurement by a whole extra pixel and steps the field along the grid (theEdgeIsFoundBetweenPixelsRatherThanAtTheirCenters+cuttingTheFieldGrowsTheShapeByThatMuchboth go red on that sabotage); the ladder ping-pongs throughrg32Float(a half float spaces integers a whole unit apart past 1024, which would quantize the sub-pixel seed away), and the resolve writes a layer of the measured layer's precision, so a.float32source keeps far distances to their fraction (see Layer precision) pooled per ring slot likefilterTexPool; the first rung is the smallest power of two whose ladder reachesfar(a rungkplus every halving carries2k - 1), somaxDistancegenuinely shortens the work (12 passes over a 1080 square, 8 at 64 px); every tap is a clampedreadthroughollin_field_taprather than bounds-branching (same answer — a clamped tap is still a real seed position and the pass keeps the nearest — for ~15% less GPU, since the ladder is read-bound; it differs from the branching form only at the canvas border, 44 px at ≤2/255); it replaced a clamped pixel-spacefilter::nearestsampler so the page can run the same fragments, measured 1.00x that sampler in one process with the GPU saturated (2.28 to 2.30 ms against 2.26 to 2.34 a whole-canvas field), and the three passes returnfloat4(therg32Floattargets keep two components) for the same reason; a pixel the flood never reached reads the far value with a zero direction ("nothing within reach"), never a direction pointing nowhere. The user-shader seam had to grow a raw read:sample/sampleAuxreturnlinearToSrgb(, which mangles a distance and cannot carry a negative, sounpremul( c)) sampleRaw/sampleAuxRaw(ollin_layer_read) hand back the stored values untouched — without them the direction channel is unreachable from any user code. Cost on an M2 at 1080 square: ~4.9 ms GPU whole-canvas, ~2.9 ms capped at 64 px. Two test-writing traps, both paid for: a drawn circle's half-covered contour is not at its nominal radius (thin-mark coverage is remapped to perceptual alpha, putting it ~0.26 px out), so accuracy is checked against the shape itself rather than against the radius it was asked for; and a hard pixel count of a disc wobbles ~0.08 px of radius with where the grid falls, so areas are summed from an antialiased cut in linear light instead. The ladder is data (MeasuredField: source, threshold, reach, the row, the steps), read by the renderer and by the web recorder, so the page runs the identical ladder:ollin_web_fieldrunsollin_field_seed/ollin_field_flood/ollin_field_resolveover page-ownedRG32Ftargets read bytexelFetch(NEARESTfilters, or the texture is incomplete and reads 0), falling back to the page's half-float layers whereEXT_color_buffer_floatis missing.DistanceFieldTests(7, two sabotages verified red); snapshotmeasured-field; exampleEffects/;DistanceField Docs/; Guide Ch 22 § A field you measure: the distance field.Drawing/ DistanceFields .md Layer styles (
Filter.outline/.dropShadow/.innerShadow/.outerGlow/.innerGlow/.bevel;ollin_fx_outline/_glow/_bevel/_shadowinShaderEffects.metal, described as data byFilter.styledPass). A layer's edge given a style read from its alpha: a preparation (the measured field of the alpha cut at 0.5, held to the style's reach plus 2 px, or the hardware Gaussian of the layer, sigma = radius asgaussianBlur) and one composite pass reading the layer at texture 0 and the preparation at 1. Filters on the chain, ruled 2026-10-08 (no style value that groups them): chained order is stacking order. Every style is one of two premultiplied composites, written so weight 0 is the layer's own bytes (c + 0): under (c + paint·k·(: outside outline, outer glow, drop shadow) and inside (1 - c .a) c + (: inside outline, inner glow, inner shadow, bevel); never an unpremultiply-and-lerp (not exact at 0,paint·c .a - c)·k aClearColorOrAZeroReachHandsBackTheLayersOwnBytesgoes red). The layer's AA edge is composited once by its own coverage, so no seam. Outline: a 1 px ramp at|d| = widthoff the field, centered = two half-width bands; below 1 px the band's ink is held to its width by6w /(a box-filtered edge carries( 1 + 3w + 3w² - w³) w²/unscaled, a sixth of a pixel at width 0). Glow:2 + w/ 2 + 1/ 6 - w³/ 6 (1 - d/r)², faded in over the first pixel of radius. Shadow: the blurred alpha read atposition - offsetfrom the four nearest texels with zero past the border, so a whole-pixel offset lands on one texel and the shadow slides off the canvas; inner =1 - that, past the canvas counts as empty. Bevel: steepness is the profile's at the measured distance (roundeddepth·π/2·cos(πt/2), chiseleddepthwith its crease AA'd over one pixel), direction is the field's gradient by a Sobel stencil at 2 px spacing, never the direction channel: the field is the distance to discrete edge points, so its direction (and a 1 px difference of it) turns by up to atan(0.5/d), 7° RMS on a disc in a numpy model, which lit draws radial streaks; the 2 px Sobel holds 0.8° RMS (2.5° max), and a ridge's shorter gradient levels the slope (outward = g /); light normalized so facing = full highlight and taking none = full shadow, flat top exact (max( |g|, 1) rise == 0returnsc). Measured precision (linear light, area-summed, against a 360-gon's symmetric edge; the analytic disc's perceptual edge leans 0.07 px for an inside band): one-sided outline within 0.06 px of its width, centered within 0.125 (near-edge field overestimate below 2 px, filed as the Gustavson-Strand AA distance transform); drop shadow bit-equal to the blur moved bydrawImage(blurring the moved shape instead differs by the hardware blur's own position dependence, up to 8 half-float steps); glow band means within 0.004 of the curve, single pixels by the edge's coverage steps (~0.26 px of distance on 8x MSAA). Web: each crosses asollin_web_field:or<fragment> ollin_web_blur:, the first row the preparation's and the rest the fragment's; probes within 0.06 mean of the Mac.<fragment> LayerStyleTests(13 tests, 25 cases; seven plants each red, plus the direction-channel plant at 0.080 against 0.0072 on the ring);WebEffectsTests(aDistanceFieldAndTheLayerStylesAreThePagesOwn, six probes); snapshotlayer-styles; exampleEffects/LayerStyles;Docs/; Guide Ch 22 § A field you measure: the distance field (shown; the family section waits on a structure review).Drawing/ LayerStyles .md Light in a flat sketch (
Combine.light/ComposeLayer;.lit( by: ) ShaderRadiance, the ladder in.metal MetalRenderer+Effects). Radiance cascades over the effect substrate (Sannikov, credited in.radianceCascades ATTRIBUTION.md): base = the scene (its alpha stops a ray), aux = the lamps (its rgb gives light off), out comes the light arriving at every pixel, an ordinary layer. Soft-with-distance shadows, 1/r falloff, beams through a gap, and color bleed all fall out of one measurement, and the cost tracks the layer and thereach, never how much was drawn. Rung i puts a probe everys0·2^ipx with4^(i+1)directions over a span ofs0·4^istarting ats0·(4^i - 1)/3, stored as one2^(i+1)-texel block per probe, so every rung is one texture of the same size and the ladder costs one rung times the rung count. Load-bearing: the probe grid is padded to a multiple of2^(rungs-1)(a grid that cannot be halved that many times puts one rung's probes out of step with the next one's, which draws as a grid of cells rather than as light); each of the four merge neighbors is reached by its own ray, ending where that probe's own ray begins (the published "bilinear fix") or rings of light appear at every hand-over distance (measured against the exactasin(R/r)/πanswer for a disc lamp: 0.900…1.108 of it with one shared ray, 0.902…0.952 with four, 0.926…0.972 once each ray is a cone — over 1 is light nobody emitted, andtheLightMatchesWhatTheGeometryAllowsgoes red on that one-line sabotage); each ray is a thin cone, not a line (ollin_rc_trace, half the rung's angular spacing wide,halfTan): a surface it passes counts by the straight-edge share of the cone's width it covers, measured across the ray (the field's distance over the sine of the angle to its nearest edge), and a surface its axis enters is walked in one to three jumps to tell a wall crossed obliquely (opaque, however thin: the far face looks straight back) from a lamp's limb grazed (its share, then the march goes on), with a ray within 45° of head-on blocked outright. A line either meets a lamp or misses it, so a lamp nine rays wide read as eight, nine, or ten from one probe to the next and every penumbra moved in steps of a ninth, cells the size of the rung's probe spacing at every quality (halving the spacing moves the same lamp one rung up, so.detaildid not cure it); two probes pin it, a one-ray lamp's shadow edge climbing without a dip (theShadowEdgeIsOneSmoothRamp, 0.054 → 0.018 of the peak) and reading evenly around a ring (0.113 → 0.072 RMS), and a lamp narrower than about three cones is the one case it errs on, bright; the field's alpha marks whether the nearest surface emits (ollin_light_mark, one pass per ladder run, since a bounce turns walls into emitters), which lets a ray skip reading a dark wall, and that skip pays for the cone: measured old against new in one process through live shader reload (the only GPU A/B that holds here: a separate process drifts 30% with the GPU's state, and frames submitted back to back inflate one buffer's span with its neighbors'), 0.94…1.02× at.performance/.defaultand 1.03…1.12× at.detail; the march is sphere-marched against the shippedmeasuredDistanceField, built once from the combined coverage (a lamp occludes too) and shared by every rung and every bounce, steppingmax(d - 0.5, 0.5)because the field is half-float and a step longer than the truth walks a ray through a thin wall, and reading the emission 1.5 px inside the surface it stopped on; every tap nameslevel(0)(the loop returns from inside a conditional, so there is no footprint to derive); the top rung is cut atreach(rungs come in whole steps of four, so a reach of 90 px would otherwise light 340 and the parameter would read as inert); and a bounce steps *outside* — a probe inside a shape meets it at once, so the field inside a wall is dark by construction, and the field's direction channels are what let a solid pixel read the light standing just off its own face (spread over 5 taps growing with depth, cosmetic only: no ray ever reads deeper than a shape's shell, so this decides only how a solid shows its own lit face, and a wide round shape still shows a soft seam where its two sides meet). Quality is probe spacing 4 / 2 / 1 px and 16 / 24 / 48 march steps; measured M2 release 1080² one bounce 11.3 / 23.4 / 79.6 ms (7.8 / 13.1 / 42.0 with none).LightTests(8, the merge-ray sabotage verified red); snapshotlight-2d; exampleEffects/Light;Docs/; Guide Ch 22 § Light that works itself out:Drawing/ Light .md .light. Mechanism and the measurements behind it:ARCHITECTURE.md§ Light in a flat sketch (radiance cascades).Local averages (
Filter.boxBlur/Filter;.adaptiveThreshold ollin_sat_*+ollin_fx_box_blur+ollin_fx_adaptive_thresholdinShaderEffects.metal, the build inMetalRenderer+Effects). A summed-area table (Crow 1984) built by recursive doubling (Hensley et al. 2005), so the average over any rectangle is four reads whatever its size, and two.summedAreaTable Filtercases built on it with no new plumbing:.boxBlur(radius:), whose cost does not grow with the radius, and.adaptiveThreshold(, the Bradley & Roth (2007) local cut (all three credited inwindow: bias: inverted: ) ATTRIBUTION.md, never in.swift). Load-bearing: the table isrgba32Floatand nothing narrower (a canvas of ones adds past a million; a half float spaces integers a whole unit apart long before that), pooled per ring slot likefilterTexPool; elements go in biased by -0.5 (Hensley's own recommendation, worth one bit of mantissa) and the consumers add it back after dividing, since the mean ofv - 0.5is the mean ofvless 0.5 whatever the window; a box that hangs over the border is clamped and divided by the area it really covered, or every edge darkens by the fraction that fell outside; the adaptive cut is a fraction of the local mean, not a distance below it, and is taken in linear light (illumination multiplies what a page returns, so only a proportional test in a linear space is invariant under it — the published form works on gamma-encoded bytes, where it is not), and its mean can come straight from the table only because luminance is linear (unpremultiplying first would make the mean a different quantity than the sample). The precision is the structure's one weakness and it points the useful way: a running total spends aboutlog2(w * h)bits of the mantissa on itself, leaving an absolute box-sum error that the reader divides by the area, so it falls as the window grows — on a 1080 square, ~7/255 in the worst corner of a 3-px window and under 1.5/255 from 37 px up, which is why the docs send a narrow radius togaussianBlur. Cost on an M2 at 1080 square: ~6.2 ms GPU to build (about twenty bandwidth-bound passes), so one a frame is comfortable and a dozen are not. Test-writing trap, paid for: the -0.5 bias makes a mid-gray probe nearly blind to an area error (its biased value is near zero, so the sums are tiny and dividing by the wrong area barely moves the answer — the sabotage read 3/255 at gray 0.72 where 0.25 and 1.0 read 7); flat-field probes sit at the ends of the range, never the middle.SummedAreaTests(5: a CPUDoubletable as the reference, flat-field drift at both ends, the illumination-invariance theorem with.thresholdas its counterfactual, and the small-window precision bound; two sabotages verified red); snapshotsummed-area; exampleEffects/SummedArea;Docs/; Guide Ch 22 § Averages of a neighborhood, at a flat price: the summed-area table.Drawing/ LocalAverages .md Fitting (
RadialBasis+Fit.minimize,Sources/+Ollin/ Geometry/ RadialBasis .swift Fit.swift). Two plain-Swift substrate pieces the ROADMAP's technique tier named.RadialBasis<Point,puts a smooth field through values known at scattered places: generic over the place (Value> Vector2/Vector3viaRadialBasisPoint) and over what it carries (Double/Vector2/Vector3/ColorviaRadialBasisValue), six kernels (.thinPlatedefault,.linear,.cubic,.multiquadric,.inverseMultiquadric,.gaussian),smoothingfor noisy data.Fit.minimizewalks a handful of parameters downhill against a caller-written cost (adaptive per-parameter steps, Kingma & Ba 2015; central finite-difference slopes; optional per-parameterbounds). Techniques credited inATTRIBUTION.md, never in.swift. Load-bearing: the system is the kernel block bordered by a degree-1 polynomial tail with a zero corner block, which is what makes a conditionally-positive-definite kernel solvable and what reproduces a flat plane exactly (aFlatPlaneComesBackExactlyfails away from the points without it while still passing at them); the solve pivots, because that bordered matrix has zeros down part of its diagonal by construction and the first unpivoted division is a division by zero; the fit runs on points shifted to their centroid and divided by their own mean spacing (and any kernelscaledivided to match), which leaves the answer alone — the scale-free kernels are homogeneous — but is what makessmoothingone parameter that means one thing: raw smoothing is not scale-free, and at 1 it did nothing over hundreds of pixels while flattening the same layout measured in fractions (smoothingMeansTheSameThingAtAnyScalepins it; a mean-of-|K| normalization is not enough for thin plate, whoser² log rpicks up an extralog sunder scaling); channels share one factorization, so aColorfield costs aDoublefield; collinear points return nil rather than a guess (the tail is undetermined). Cost: the fit is cubic in the point count and each read is linear in it, so fit insetup(), read indraw();minimizecalls the cost about twice per parameter per step.RadialBasisTests(9) +FitTests(5), every one an invariant (interpolation, affine reproduction across all six kernels, smoothing monotonicity, scale invariance, channel independence, a known bowl, parameters on wildly different scales, bounds, a recovered circle); snapshotscattered-fit; exampleShapes/Scattered;Docs/; Guide Ch 14 § A field you pin down yourself: radial basis functions. Slopes:Drawing/ Fitting .md gradient(at:)(a field of numbers, returning the point type through itsRadialBasisValueconformance) andderivative((any value, linear in the direction) come from each kernel's closed-form φ'(r)/r (at: along: ) Kernel), zero at a data point (thin plate's limit, the linear cone's choice), and cost about one value read. Read against central differences of the value at 1e-6 relative over all six kernels, smoothed and not, a fitted plane's gradient exact everywhere, a warp's Jacobian columns, and a color field's per-channel rates; thin plate's.slopeOverDistance + 1is an equivalent mutant (the side conditions, Σw = 0 and Σw·x = 0, cancel its whole contribution), so no test can see it.FieldSlopeTests(6), three plants red; exampleMotion/;ContourWalkers Docs/§ The slope of a field.Drawing/ Fitting .md The Hopf fibration (
hopfFibers/hopfFiber/hopfBases/HopfFiber,Sources/). The picture half of the ROADMAP's technique-substrate trio, and a geometry emitter rather than a shader: every point of a two-sphere lifts to a great circle of the three-sphere, stereographic projection carries it into space as an ordinary circle, and each fiber comes back as a plainOllin/ Geometry/ HopfFibration .swift [Vector3]fordrawTubeor any 3D path. Hopf 1931, the explicit circle parameterization credited inATTRIBUTION.md, never in.swift. Load-bearing: the emitter works in the construction's own convention (special axis third) and hands back in the world's y-up one, and the two are a quarter turn about x, not a swap of two coordinates — a swap mirrors the figure, and a mirrored fibration links the other way round, which is a different object with the same shape (theBottomPolesFiberComesBackStraightcatches a sideways emit; the whole 3D set would otherwise have shipped lying down). The base set must be structured (hopfBases(rings, each turned a half-step against the last so the circles interleave instead of forming spokes, orlatitudes: perCircle: spanning: ) hopfBases(), because the linking only reads when neighboring circles are neighbors and a scattered set draws as wool. Color is taken from the base point (hue around, lightness up), which is what shows the tangle is an image of a sphere; a draw-order rainbow says nothing. The base at the bottom pole lifts through the projection's own pole and comes back as a straight line — the axis every other ring is threaded onto — handed over as a two-point path withspiralCount: ) isStraightset and areachlength (a line has no size of its own), never dropped;spanningdefaults to keeping clear of it, so a rings sketch addsVector3(0, -1, 0)by hand, whilehopfBases(already reaches it. Circles grow without limit as the base nears that pole.spiralCount: ) HopfFibrationTests(10, every one a theorem: lifted points on the three-sphere, the map sending a fiber back to its base, each fiber flat-and-round about a solved center — the parameter's equal steps are not equal steps around the projected circle, so a centroid-based check fails on a good circle — the top pole's fiber being the unit circle, the straight one standing up, every fiber linking the top pole's circle exactly once counted by disc crossings, and no two fibers meeting; one sign flip in the lift turns five of them red). Snapshothopf-fibration; example3D/;Geometry/ HopfFibration Docs/; Guide Ch 28 § A shape from four dimensions: the Hopf fibration (a pointer; the section and its figure are on the reference page).3D/ HopfFibration .md Optical and print looks (
Filter.anaglyph/Combine.anaglyph/.mirage/.schliereninEffects/andFilter .swift Effects/,Combine .swift ollin_fx_anaglyphinShaderCombine.metal,ollin_fx_mirage+ollin_fx_schliereninShaderEffects.metal;misregistered(onoffsets: rotations: ) PrintSeparationandProcessSeparationover the sharedresamplePlane;Ramp;.wavelengths( from: to: stops: in: ) ChromatographyinGeometry/;Chromatography .swift OpticalLookTests10, snapshotoptical-looks, exampleEffects/Phenomena;Docs/,Drawing/ Effects .md Docs/,Output/ PrintSeparations .md Docs/§Drawing/ Color .md Ramp,Docs/§ A drop that spread; Guide Ch 21 § Depth, density, and hot air: anaglyph, schlieren, and mirage, Ch 46 § When the plates slip: misregistration and § A drop that spread: chromatography, Ch 2 § Light by wavelength). Six looks, each one call. The anaglyph reads the red channel from a copy shifted one way and green and blue from a copy shifted the other, half a parallax each, a transparent pixel counting as white paper under each copy (so a dark mark on nothing prints as a cyan and a red copy meeting in a fused dark, and a photograph as the doubled print); the filter form is one parallax for every pixel, and the combine form reads the aux as a depth map through the sameGenerators/ Textures .md ollin_dof_depthreading.defocusmakes (luminance, linear to sRGB, 0 near to 1 far), the parallaxseparation * (, depth sampled at the destination pixel (one gather, no inverse map); a positive parallax moves the red copy left and the cyan copy right (the pair that reads as behind the page), so a near pixel's red copy lands to the right. The depth route is the shipped one for every depth combine (depth - focus) scene); the main canvas's 3D depth never reaches a filter, and no default reads it (ruled 2026-10-20: the same route as.combined( with: scene .depth, …) .defocus, no second mechanism besidedepthOfField). The mirage shifts each row above the horizon byamount * (and inverts the picture below the line with a wave growing with the distance down, fading to the ground under that band (full to 18% of the way down, gone by 70%);y/ h)^2 * ( two slow sines + a stepped hashed fault) Filter.mirageShiftis the CPU twin ofollin_mirage_shift, the fault hash written in single precision on the CPU (mirageHash) so it lands onhash11's value, and the test reads the row shift of a drawn line against it within 1.2 px at three rows. Schlieren maps the luminance gradient (central differences of the premultiplied luma, so transparent is no density) along the knife to brightness about sRGB mid-gray (the 0.5 is perceptual, converted to linear on the way out, so a flat layer reads byte 128), gain 10 per unit slope per pixel, the alpha the widest of the taps. Misregistration resamples each coverage plane bilinearly from the destination pixel's center moved back by the offset and turned back about the sheet's center, paper (0) past the sheet, a whole-pixel offset with no rotation exact (the ink count is kept); it is a plane transform, so it chains beforehalftoned/ditheredand each plate keeps its own screen angle. The wavelength ramp isstopsColor(wavelength:)hues placed evenly, the ends clamped to 380…780, reversed whenfrom > to. Chromatography rings are polygons at fractions of the drop's radius (the core atcoreFraction0.22, the rest crowding toward the edge ast^0.85with a seeded nudge), each sample wobbled by three noise frequencies two of which every ring of a drop shares (what keeps the rings from crossing); one cap per ray for the whole drop: the nearer of the Apollonius line where the two fronts meet (reach(, counted only where the ray heads toward the other drop, so the small drop's far side is free) and the other drop's core plus a one-pixel hair, ruffled inward by a 14-cycle noise, and every ring takesfrom: along: toward: ownRadius: otherRadius: ) min(nominal, cap), so a stopped outer ring can never drop inside an unstopped inner one (the first cut ruffled per ring and did). Fibers root at 0.84…0.9 of the outer front and reach 1.04…1.14 of it, never on a stopped ray.bandsare the core disc and the annuli asShape(outer:holes:);linescloses every ring for a plotter. The test pins every ring point outside every neighbor's core, the order along every ray, fibers rooted inside and reaching past, at least two fronts stopped, and the seed.Tape and lens looks (
Filter.vhs/.jpeg/.tiltShift/.progressiveBlur/.lightLeak/.pagePeelinEffects/,Filter .swift Generator.scratches,Sim.datamosh;ollin_fx_vhs/_jpeg_forward/_jpeg_inverse/_varblur/_light_leak/_page_peelinShaderEffects.metal,ollin_gen_scratchesinShaderPatterns,.metal ollin_mosh_blocks/ollin_mosh_decodeinShaderSim.metal;TapeAndLensTests14, snapshottape-and-lens,WebEffectsTestsfixturesTapedandPeeledplusaTwoPassFilterIsAPairThroughAScratch, exampleEffects/TapeAndLens;Docs/§ Tape and lens; Guide Ch 21 § Looks from tape, a codec, a lens, and paper). Eight looks, each one filter, one generator, or one simulation. Two-pass filters areDrawing/ Effects .md Filter.pairPass→EffectPair, read by the renderer and the web recorder alike: the first fragment over the layer into a scratch (single precision on the Mac,acquireSATTexture), the second into the result reading the layer as.layer(0)and the scratch as.layer(1); on the page it is the page-owned nodeollin_web_pair:, its first row the scratch's size and whether the second reads the layer, so a new two-pass filter needs no page code. The JPEG is the real baseline transform: 8 by 8 blocks from the top-left, a partial edge block padded by repeating the edge (the coefficient scratch is padded to whole blocks), JFIF YCbCr over the sRGB-encoded values with a half level shift, the orthonormal DCT, each coefficient rounded to its step in the Annex K tables scaled by the IJG curve (<first>: <rows>: <second> Filter.jpegTables: 5000/q below 50, 200 - 2q above, (base·scale + 50)/100 held to 1...255, steps in levels), 4:2:0 by default (subsamplesChroma, ruled 2026-10-22: the chroma averaged over 2 by 2 into one 8 by 8 block a 16 by 16 macroblock, its coefficients in the macroblock's top-left texels, the scratch padded to whole macroblocks, read back with the cosines taken at the pixel's place in the half-resolution grid) or 4:4:4 with it off, clamped to the eight-bit range on the way back, alpha kept; the tests DCT every block of a 4:4:4 frame read back and find fewer than 1 in 100 coefficients between steps at quality 10 (the dither and the clipped blocks), quality 100 at 4:4:4 within a level in 99% of channels, and a one-pixel colored line's hue shared with its pair under 4:2:0 while its neighbor stays gray at 4:4:4. The tape:amount0 returns the layer exactly (early out); per-line jitter on the tape's 480 lines re-rolled at 29.97 frames a second, the burst asmoothstepof slow noise scaling the wobble and the crease, the head-switch band the bottom 3.5% scaled bymin(damage, 1); YIQ over the encoded values, luma one tap at the warped point, chroma ten taps trailingsmearweightedexp(-0.3k)by each tap's alpha; a 4% brightness beat. The variable blur (ollin_fx_varblur, across then down) takes sigma fromollin_varblur_sigmaper pixel, sigma under 0.05 returns the center texel read at its center, so a tilt-shift's band is byte-identical (pinned), taps to 3 sigma (capped 240), the radius capped at 80; past the progressive blur's end it matchesgaussianBlur((MPS) within 3 levels, mean under 0.5. The light leak screens emitted light asradius: ) base + light·max(per channel (so it never darkens, HDR included) and1 - base, 0) alpha + lit·(; the ramp mixes in encoded values (1 - alpha) Color.simd4), white past heat 1. The page peel is a gather of up to four candidates composited back to front with a one-pixel coverage edge: the ground (transparent, a shadow just past the curl fading to nothing by 3R), the flat sheet (crease shadow0.35·exp(s/0.5R)plus the flap's shadow by its mirrored box distance), the curl's underside atasin(s/R), and the back (the curl's top atπ - asin(s/R), then the flap ats' = πR - 2sreflected),amount0 an exact identity, the shadows gated bymin(amount·20, 1). The datamosh runs on the self-warp's slot and motion fit (measureWarpMotion, shared), the slot'sframesits clock: a block's fate re-rolls atfloor(, held when its roll is underframe/ period + hash( block)) amount(1 holds every block), its vector the 4 by 4 mean of the flow over the block in pixels timesmotionplusdriftpluswanderalong a heading from slow noise; a refreshing pixel is the drawing read at its center (all-refresh is the drawing, pinned exact), a held one the last decoded picture atuv - v/size(all-held is the first frame moved by the drift, pinned within the dither's two levels). The wander is on by default (ruled 2026-10-22: the measured motion is zero in flat color and a still picture). The scratches: lanes across the direction, one scratch per lane per life of 12 to 48 frames, 70% of lanes filled, on/off and strength flicker scaled byflickerat 24 frames a second (flicker 0 holds every line still within a life), coverage0.5·thickness + 0.5 - dscaled by thickness below a pixel. On the web page every one but the datamosh crosses (the six filters as single passes or pairs, the generator as one pass); the datamosh is refused by name like the self-warp and stays with video.Wipes, copies, and a glowing edge (
WipeOrder,Combine.wipe/Filter.wipe/ComposeLayerin.wiped( to: _: progress: feather: ) Effects/Wipe.swift;Filter.repeated+Filter.CopyLayoutinEffects/;Copies .swift Filter.edgeGlowwith the layer styles;ollin_wipe_order/ollin_wipe_amount/ollin_fx_wipe/ollin_fx_repeated/ollin_fx_edge_glowinShaderEffects.metal,ollin_fx_wipe_combineinShaderCombine.metal;WipesAndCopiesTests10, snapshotwipes-and-copies,WebEffectsTestsfixtureWiped, exampleEffects/;WipesAndCopies Docs/§ Wipes and copies and the aside list,Drawing/ Effects .md Docs/§ An edge glow; Guide Ch 19 § More ways to use a finished layer: wipes, copies, and a readback, Ch 22 § Light running around an edge: the edge glow). A wipe's order is three rows (Drawing/ LayerStyles .md WipeOrder.rows, kept in step withollin_wipe_order) and its modifiers apply in one fixed order whatever the call order: fold, tile, bands, shuffle, checker, diamond, reverse; the shuffle, checker, and diamond need pieces (bands, else cells), and a continuous order ignores them. The shuffle is a permutation drawn on the CPU (Fisher-Yates overSplitMix64from the seed) and travels as a.tablestrip, so every piece keeps a slot and the page draws the same order; cells cap at 128 a side. Progress 0 and 1 are exact by early returns in both fragments (the smoothstep front,(, misses 1 by a float step at the far corner otherwise); the front is centered on the progress, so the half-way test holds one layer a side. Copies come from a CPU strip (progress·( 1+f) − t)/ f Filter.copyStrip, two texels a copy, front first: place, turn, scale; opacity, hue turn), so the jitter is seeded once and the page reads the same copies; four draws a copy whatever the jitter, so a nudge keeps its direction as it grows; composited back to front premultiplied, four rotated-grid taps below a scale of two thirds, the hue turned in OKLab; the ring's radius is in layer heights with its x divided by the aspect. The edge glow is a styled pass over the field reaching two and a half widths, and both its profiles are windowed to end by 2.4 widths: beyond the measured reach the field holds its cap, and an unwindowed tail showed as a haze over the whole layer (7.6 levels at four widths out). Spots blend into their mean around the ring within one to four band widths of the center, or a shape crossing its own middle shows a spike there. The glow is screened as emitted light (never darkens, raises alpha over transparency); width 0 or no colors is the layer byte for byte. All five fragments cross to the web page as door fragments.Blocks from a field (
SDF3Din.voxelized( size: gap: jitter: seams: occlusion: seed: ) Drawing/SDF3D.swift; the voxel scope,OllinVoxelCache, andollin_voxel_*inShaderRaymarch, the page's walk in.metal WebExport.swift;VoxelBlocksTests5, snapshotblocks,WebFieldTestscaseBlocks, example3D/;Raymarching/ RaymarchedBlocks Docs/§ Blocks; Guide Ch 33 § A field rebuilt from cubes: voxelized). A cell is a block when the child is negative at its center, and the block takes the child's color there. The scope is a loop in the field walk: flatten emits BEGIN (kind 5), the child, and END (kind 6:Drawing/ Combinators .md kthe size,extrahow far back BEGIN is,geo0gap/jitter/seams/occlusion,geo1.xthe seed); END reads the child at the point (the probe), then at cell centers by jumping back, and pushes the blocks' distance. The jump back carries its own limit (vReads): a scope reads each of its eight cells at most once, so a ninth read, or a cell index outside the eight, ends the scope with what it has. The bookkeeping of which cells are read was the only thing stopping the walk, and on one system it did not: the fragment never finished and the frame locked the GPU (theBlocksfigure, November 2026), so a walk that steps backward counts its own steps. A scope nested in another is stripped at flatten (one state in the walk). The distance: the probe less a block's half diagonal is safe when it exceeds half a cell; inside that band the cells are the eight nearest (the point's own and its neighbors toward the nearest corner), read nearest first, skipping cells the per-ray cache already read and cells the probe rules out (a center no farther than the probe's distance cannot be inside), stopping once the next unread cell's box is no nearer thanmin(; the result isbest, region edge) max(, the same whatever the order or the cache, which is why the page's read-everything walk matches the Mac (0.08 levels). On a block's face (best under 0.02 of a cell) the three cells the crease shading reads are read too. A field whose last node is END takes its normal from the nearest block's face in one walk (through the transpose offar, min( best, region edge)) inverseModel) instead of four taps, exactly square to the grid. Cost, measured saturated in one process on an M2 at 1080 square: about three times the child whatever the block size (a three-leaf melt 15 ms plain, 45 as blocks), shadows about double; plain fields A/B'd against the previous shaders unchanged (15.3 to 16.0 ms against 15.2 to 15.9). The cell traversal along the ray is filed in DESIGN-NOTES. A slab meant to be one block thick must hold a row of cell centers, half a block off the grid lines.Watercolor wash (
Sources/+Ollin/ Effects/ WatercolorSim .swift runWatercolorinMetalRenderer+Effects+ the.swift ollin_wash_*section ofShaderSim.metal). The three-layer wet-paint simulation (shallow water / pigment deposition / capillary; Kubelka-Munk optical rendering; credit inATTRIBUTION.md):Simruns on a.watercolor( pigments: ...) WatercolorField(aSimFieldsubclass, made withwatercolor(...);SimFieldis no longerfinal), painted throughwithFieldwith seed rgb = up to 3 palette pigments (premultiplied = dilution) and alpha = water;WatercolorPigmentcarries K/S triples + density/staining/granulation (12 published measured presets;overWhite:/overBlack:derives K/S via the paper's inversion). Load-bearing: the velocity update isA + μB(the continuous equations'+μ∇²u; the printed pseudocode's sign reads inverted and anti-diffusion detonates) and relaxation runs divergence-reducing in gather form; the staggered grid packs (u right face, v top face, p, M) per texel, off-canvas taps read dry via bounds-rejection (the clamp sampler would reflect the edge), and dry-bordering faces re-pin to zero in every velocity-writing pass; pigment advects in 4 substeps of dt = ¼ with |u| ≤ 1 so the four-face outflow can never exceed the cell (pure gather, no rescale);transfer_dep/transfer_pigencode from one snapshot (exact conservation); the inject's dry-brush height gate applies to both halves (flow and pigment) or gaps hold flat unsimulated stamps;dry()bakes the wash into the dried R/T glaze stack (fresh textures swapped into the slot, never in-place) and caps saturation below the mask-expansion threshold or the sheet re-wets itself and dry() never sticks;blot()lifts water keeping pigment parked (the paper's authored damp state), and a held water touch blooms the backrun where a single tap only nudges (one frame's pressure relaxes away); K-M math runs in display-space sRGB (linearized only at output; CPUKubelkaMunkreference andollin_wash_km_layerkept in step); a stroked mark rings stamps with pigment-free water, so painting blocks callnoStroke(). Deterministic end to end → pixel snapshotwatercolor-sim;WatercolorSimTests(K-M inversion round-trip + edge-darkening / dry-brush / dry-freeze / backrun-counterfactual / byte-replay probes); exampleSimulation/; Guide Ch 24 § Paint that behaves: watercolor. Mechanism:Watercolor ARCHITECTURE.md§ The watercolor wash.Docs/.Simulation/ Watercolor .md Compute & GPU particles (a core capability, GPU/Metal in
Ollin). Runtime-compiled MSL kernels over persistent buffers/textures feeding the instanced render path — 10⁶ particles update + draw GPU-side, the sandpainting depth-of-field at scale. Types inSources/:Ollin/ Compute/ ComputeKernel/ComputeBuffer/PingPong/ComputeParams/Particles(buffer half) andComputeTexture/PingPongTexture/Simulation(texture half — reaction-diffusion / cellular automata / image kernels drawn as anImage). Facade:compute(_:over:)/compute(/_: reading: writing: ) compute(_:writing:)/stepParticles/stepSimulation/drawParticles. Kernels inline or in a.metalfile (ComputeKernel(); shared types + the fullresource: in: ) OllinShaderLib(the same hash/noise/curl/disc + palette/OKLab/sd*helpers fragment shaders get,hash12not the oldhash21) auto-splice. Gotchas: ping-pong (not in-place) for any buffer the render path also reads; a file usingOllinParticlemustimport COllinShaders; theCOllinShadersclang module is stale-cache-prone (swift package cleanafter adding a shared struct); kernel compile errors are swallowed → missing particles, not a crash; headless export runs intermediate sim steps viastepCompute; seed once via a flag (frameCountis 1 on the firstdraw()). AComputeTexturealso bakes a map a mesh then uses (texture.imageintotextured(_:)/normalMapped(_:)/surfaceMapped(...), dispatched once and kept, which is what the planet does): written values are read linear with no sRGB decode (author throughsrgbToLinear), the alpha of a base-color map is the surface's opacity so a field parked there draws a half-transparent solid, and a GPU-written texture carries no mip chain, so a surface seen nearly edge-on reads a whole triangle's worth of texels at once and its silhouette breaks into the mesh's own teeth: measured on the planet's cloud shell, halving the map does not help and finer triangles only make finer teeth, while keeping the shell's overhang under a pixel removes it. Up to ten buffers of any element types bind throughcompute(at indices 0…9 (the thread count defaults to the first buffer's), and_: buffers: count: params: ) compute(takes two element types, so a kernel reads a static geometry buffer and writes an_: reading: writing: ) OllinParticlebuffer with nothing packed into the other;ComputeBindableis public with the Metal realization behind an internalComputeRealizable(a conformance of your own binds nothing). A kernel reads pictures (compute(, up to eight_: buffers: textures: count: params: ) Images at texture 0…, theimageSampler(linear, clamped) at sampler 0;stepParticles(, up to four, read in the generated step as_: custom: textures: ) picture(, which declares all four slots and binds a clear 1-pixel stand-in for an empty one so every declared slot is bound): every picture reads as linear light, premultiplied (index, point) ImageComputeTexture(→readsLight: true) Image.texture(for:), the sRGB upload decoded on read; the olderlinearTexturedata read stays forLineSpray). A dispatch that reads a layer runs after the layer passes, and so does every dispatch recorded after it (Drawer,.firstLayerReadingDispatch encodeCompute(with_: into: part: ) .beforeLayersahead and.afterLayersright afterencodeEffectTargetsin the live, image, and benchmark drives; the accumulating paths andstepComputedraw no layers and take.all), so it reads this frame's picture and the recorded order holds; a layer drawn from what it writes shows it a frame late. Such a dispatch counts asusesFeedback, so a headless drive renders every warmup frame rather than only stepping the compute, or the kernel reads no layer before the captured frame (ComputeTextureReadTests, each red under its plant: no split, no warmup render, the data read). A kernel projects through the sketch's camera:cameraParams()packs the activeCamera3D's publicviewMatrix/projectionMatrix(as anaspect: ) OllinCameraMatrices(128 bytes, the head of aComputeParams;append(for any camera) and the library'scamera: aspect: ) ollin_project/ollin_project_eyereturn canvas points, view depth, and clip w (≤ 0 behind the camera);ballSample(float3)is the uniform ball scatter besidediscSample. Two particle styles:.marks(perceptual coverage, sRGB color, the default) and.light(drawParticles(: plain area coverage, linear color,_: style: ) color × alpha × areawherever a particle lands; a particle at or under one texel takes the one-texel path, its quad sized fromUniforms.pixelScale, the depositπ/4 d²continuous across the boundary, so a million one-pixel points cost a million fragments), selecting theollin_particle_light_*pipeline. One vertex a particle (drawParticles(and the_: count: style: maxSize: ) Particlesform'smaxSize:,GeometryBatch,.particleMaxSize MetalRenderer, the point twins in.particlePointFits Shader3D.metal,ollin_particle_point_vertex,ollin_particle_light_point_vertex, andollin_particle_splat_point_vertexwith their fragments): a batch whose largestsizethe sketch named draws each particle as one point primitive ([[point_size]], the fragment reading its offset from its own place on the attachment, less the center the vertex hands it) when that size fits the GPU's cap of 511 texels at the pass'spixelScale, the square being the disc plus its margin on the coarser axis (size × scale + 2.5for.marks, the disc and every texel its coverage reaches held whole under the multisample mask,size × scale + 2for.light, a one-texel light point always;aNamedSizeFitsAPointUpToTheCap); unnamed, or past the cap, every particle keeps its quad, now a strip of four vertices instanced once a particle where a list of six was (a quad is affine in screen space, so its interpolants and their derivatives are the same over either diagonal). Every deposit is one helper both fragments call (particleMarkDeposit,particleLightDeposit,particleSplatDeposit), a mark's color is turned to linear light once by its vertex stage (a particle has one color; every fragment doing it was a millisecond on a million marks), and a point's fragment reads its offset from the particle off its own place on the attachment (particlePointOffset; the point coordinate runs over the square as the rasterizer placed it, and read a small light disc up to 3% over its area), so the points land where the quads land to the rasterizer's own snapping of a quad's corners:aNamedSizeDrawsEachParticleAsOnePointOnTheSamePixels(both styles at 0.5, 1, 2 and 6 points, three thousand particles drawn both ways underMetalRenderer, three levels over black and 0.2% of the light),.drawsParticlesAsPoints aPointJustPastTheEdgeLandsItsShareInside(a point is clipped as its square, not thrown away by its center, so a particle a few tenths past the edge lands the share inside either way),aLightDiscPastThePointCapKeepsItsArea(a 900-point disc is the quad's draw to the byte),drawParticlesRecordsTheNamedSize. The vertex stage was most of what a spray of sub-pixel points cost, measured on four million one-pixel light points at 1080 square in one process with the GPU saturated (150 frames a lap, three rounds, the variants swapped throughreloadShaderLibrary(): the frame went from 32.9 ms on the six-vertex list to 20.7 ms on the strip and 8.9 ms as points, the kernel 3.4 ms of each, the draw's vertex stage alone (every particle degenerate) 14.8 ms on the strip against 2.2 ms as points, the fragments 2.5 to 3.3 ms either way; the fragment helpers cost nothing (the list drawn through them read 32.2 to 33.1).fromDirectory: ) LineSpraynames itspointSize, theDepthOfFieldexample names 1.LightAccumulationTestspins the deposit's linearity in size (a half-pixel disc a quarter of a one-pixel one, marks reading brighter), the one-texel landing, the kernel agreeing withproject(_:), and the ball's statistics.Docs/; examplesShaders/ Compute .md Compute/CurlField,Compute/,ReactionDiffusion Rendering/,DepthOfField 3D/Geometry/Planet. An inline kernel that includes no file is found byComputeKernel, worked out once when the kernel is made, so only its first dispatch composes the shader library around it; the check the key replaced (an empty source path) could never match, since an inline kernel records the Swift file it was written in, and every dispatch of every frame recomposed and rehashed the whole library (.quickHash anInlineKernelIsFoundWithoutComposingTheLibrary).GPU artificial life (
Sources/+Ollin/ Compute/ SpatialHash .swift ParticleLife.swift/PPS.swift/Physarum.swift). The compute path's first cooperative primitive + three emergent-behavior sims on it.SpatialHash(public) is a GPU uniform-grid fixed-radius neighbor search (Hoetzlein counting sort: clear → count → serial exclusive-prefix-sum → scatter, the four kernels sharing one source); it's the enablerParticleLife/PPSquery and a sketch builds its own sim on via theneighborStep(facade + the_: over: reading: writing: ) OLLIN_FOR_NEIGHBORSmacro. Load-bearing: the shared struct isOllinSpatialGridinOllinShaderTypes.h(stride 32; distinct from the pre-existingOllinGridParams, the 3D ground-grid uniform, whose name it must not reuse); the grid/neighbor helpers (ollin_grid_cell,ollin_torus_delta, theOLLIN_FOR_NEIGHBORS/OLLIN_END_NEIGHBORSmacro pair) live unmarked at the tail ofOllinShaderLibso.metal filterLibModulesalways keeps them (compute-only; never bloats a user fragment shader'susing:subset); cell edge = query radius over a toroidal domain so all in-radius neighbors sit in the wrapped 3×3 block, which needsgridW/gridH≥ 3 (init clamps, soworldSizemay round up pastbounds) or the wrap double-counts a cell; atomics power the count/scatter (atomic_fetch_add) and never appeared in this codebase before, and the serial compute encoder (defaultmakeComputeCommandEncoder() orders the build passes with no explicit barriers (same as) Simulation's substeps); buffer-index contract0/1particles read/write,2sortedIndices,3cellStart,4cellCount,5grid,6+sim-specific (ParticleLife's matrix at 6);nilgaps in aRecordedDispatcharray bind nothing (index = array position). All three sims reuse.buffers OllinParticle(no new struct): type/heading are stored in the freeseedAscratch; each is a@MainActor final classrecording its step by appendingRecordedDispatches directly (theParticlesmodel, not the 1-2-buffer.recordStep compute()facade).Physarumuses no hash (trail path): agent buffer +r32FloatPingPongTexturetrail + an atomicUInt32deposit grid (fixed-point, avoids Metal's undefined concurrent-texture.writerace), stepped clear→agents(sense/steer/move/deposit)→diffuse+decay→colorize; draw via.image. Load-bearing anti-lattice-artifact trio: bilinear trail sensing + a per-step motor noise (heading jitter) + a 1-2-1 Gaussian diffuse (not a box mean); without them the faithful-Jones steering (which keeps heading exactly when all three sensors read equal, i.e. in the empty region an agent forages into) sends escaping agents ballistically straight, and those coherent parallel escapes self-reinforce on the square lattice into cardinal-axis spurs (the motor noise is the decisive one, turning the ballistic escape into an even-spreading wander). Reproducibility (load-bearing): the counting-sort scatter lists a cell in GPU-atomic-race order, and the sims are chaotic, so a sum over neighbors taken in that order grows into a different picture within seconds (31 to 78% of the pixels by frame 480 inParticleLife,Swarm,ParticleFluid). Under a fixed clock (Drawer: an export, or a take playing back; never.runsOnFixedClock --bench) a rank pass puts every cell in index order, so the same seed exports the same frames on one machine: one thread per member counts the smaller indices in its cell, the work cut into 32-member chunks the serial scan counts (chunkStart, binary-searched per chunk), because one thread per particle diverged on the densest cell of each SIMD group and one SIMD group per cell put a packed cell on a single core (a ParticleLife frame took seconds); the rank costs a clumping sim about a fifth of its step (ParticleLife 21.3 → 26.3 ms, Swarm 38.4 → 45.6, ParticleFluid 8.6 → 8.7), which is why a live frame skips it (a wall clock never repeats a run). Still no pixel snapshot (another GPU's arithmetic can take a chaotic run elsewhere);SpatialHashTestspins counts, the exact prefix sum, the permutation, per-cell bucketing and the neighbor set on both paths, and index order within every cell on the export path over a packed layout (one cell of 300, others at 31/32/33/64/65). Facade factoriesmakeSpatialHash(/in: radius: count: ) makeParticleLife(/count: kinds: radius: …) makePrimordialParticles(/count: radius: …) makePhysarum(defaultagents: resolution: …) boundsto the canvas andseedtovariation.Docs/+Simulation/ ArtificialLife .md Docs/; examplesShaders/ Compute .md#spatialhash Simulation//ParticleLife PrimordialParticles/Physarum+Compute/(the raw primitive, the one example thatNeighborSearch import COllinShadersforOllinParticle, wired via the extendedexample(). A seed is any…, dependencies: ) Int:ParticleLife's rule matrix,ParticleLenia's opening disc, andEvolution's gene pool each converted a seed already handed over as its bit pattern through a signed integer a second time, which trapped on every seed below zero;SimSeedTests.Emergent matter and heritable rules (
Sources/+Ollin/ Compute/ ParticleLenia .swift SwarmChemistry; shared header structs.swift OllinLeniaParams, stride 112, andOllinSwarmChemistryParams, stride 48, both bound at buffer 11). Two more per-particle-rule sims overSpatialHash, deliberately two systems rather than one: a rule that makes matter organize and a rule that is itself heritable are different questions, and fusing them (genome + bonds + energy + construction) is the step from a recipe to an environment, which the framework lane refuses. Both reuseOllinParticleand follow the artificial-life reproducibility rule (no pixel snapshot: a neighbor sum's order is atomic-race-ordered, so a run is not bit-reproducible even at one seed, and the tests measure what each term does against the run with that term made inert).ParticleLeniais the energy-based formulation (Mordvintsev/Niklasson/Randazzo): one neighbor pass accumulates the ring-kernel fieldU, its gradient, and the repulsion gradient, then∇E = ∇R − G'(U)∇Uand the particle steps down it. Load-bearing:wKis derived, never tabulated (the closed formπσ(reciprocal, which reproduces the paper's 0.022 at μ=4/σ=1) soμ√π( 1+erf( μ/ σ)) + σe^{−( μ/ σ)²}) muGkeeps meaning the same crowding when the ring moves; growth is the only attractive term and repulsion the only one with an opinion at short range (the kernel is a ring, so coincident particles add nothing to each other's field and growth alone would let them pile up) — the two oppose each other on nearest-neighbor distance, which is what both counterfactual tests read, and neither is measurable as population spread (the opening disc already sits near the settled size); the seeded disc holds ~1 particle per unit² of area (a canvas-wide scatter opens outside everyone's kernel and shows a minute of nothing); a step is never larger than the published 0.1, so more pace means more substeps, each with its own hash rebuild.SwarmChemistry(Sayama 2009 kinetics + the 2011 evolutionary layer) gives every particle its own eight-valueRecipein a ping-ponged float buffer (stride 12: 8 values + lineage + pad, buffers 6/7), transmitted on contact with mutation, direction set by aCompetition(.faster/.slower/.majority). Load-bearing: the published ranges were chosen for a world whose particles sit ~50 units apart and they carry length (separation is length²/step²), so recipes are stored in published units and the kernel converts by alengthScalederived from the world's own density (lengths and speeds by it, separation by its square) — dropped in unconverted on a 1080 canvas, separation runs ~8.6× too strong and the swarm is an even gas;perceptionLimitandcontactRadiusderive from the same spacing, so a particle sees about as many others as one in the published world did and a sketch names onlycountandkinds. Randomness is listed beside cohesion/alignment/separation, not instead of them (replacing them means a recipe withc4 = 0.33, which real published recipes have, spends a third of its steps with no cohesion at all and nothing coheres), and "steer randomly" is the samedesired − velocitytoward a random heading at the recipe's own normal speed in both the straying and the randomness branch. Transmission is a pull: a thread takes the best of the contacts that beat it, ties broken on the lower index so the neighbor sort's order cannot decide it;.majoritycompares same-line neighbor counts stored one step stale (a thread can count its own neighborhood, not a neighbor's). Mutation is per contact, not per generation (default 0.01 againstEvolution's 0.04) because a crowded particle makes contact several times a second; a mutant keeps its parent's line, so lines only ever die out and the tally is a contest. Opening state is a design decision both times: a handful of recipes each held in quantity, since one random recipe per particle leaves nothing for a structure to be made of. FacadesmakeParticleLenia(/count: spacing: ) makeSwarmChemistry(+count: kinds: ) stepParticleLenia/stepSwarmChemistry+drawParticles. ReadbackssnapshotRecipes()/snapshotLineages()/snapshotLineageCounts(stall on the GPU (call them a few times a second).) ComputeBuffernow returns the pending seed before first bind, so a sketch can read a sim's state in.snapshot( ) setup(). ExamplesSimulation/+ParticleLenia SwarmChemistry;ParticleLeniaTests(8) +SwarmChemistryTests(9), each verified red by sabotage;Docs/; Guide Ch 26 §§ Matter that decides what shape to be: Particle Lenia + A rule that spreads by winning arguments: swarm chemistry with a figure each.Simulation/ ArtificialLife .md Steering at scale (
Sources/; shared header structOllin/ Compute/ Swarm .swift OllinSwarmParams, stride 96, bound at buffer 11). The Reynolds steering vocabulary as a GPU sim overSpatialHash, reusingOllinParticle(seedA= last heading,seedB= the wander walk's angle).Swarmcarries eight behaviors as weights (separation/alignment/cohesionneed neighbors;seek/flee/arrive/wander/flowdo not), plusmaxSpeed/minSpeed/maxForce/separationRadius/viewAngle/slowingRadius/the wander + flow parameters, all live; facadeswarm(+count: perceptionRadius: colors: size: bounds: seed: ) stepSwarm+drawParticles,boundsdefaulting to the canvas andseedtovariation. Load-bearing: every behavior returnsdesired − velocityso all eight forces share one unit and their weights are comparable, and the weighted sum takes one truncation atmaxForce(the published combination method) before the paper'struncate(integration;velocity + acceleration, maxSpeed) arriveis the one behavior that must not be normalized (its ramp lives in the magnitude);fleeis notseeknegated (negating the force leavesdesired + velocity, notdesired − velocity); the three neighborhood behaviors share one pass over the 3×3 block and honor a field-of-view cut (viewCosine); the world is a torus like itsSpatialHashsiblings (so no containment behavior, deliberately); speeds/forces are per second where the CPUVehicle's are per step; the hash build is skipped when all three flocking weights are zero, which is what lets a million wanderers/seekers run (measured M2 release 1080²: 1M stepping at 60 fps, drawing them is the limit; 30k flocking drawn at 60; 120k at 34).minSpeed(default 0 = the published model) is an addition, and the fix for a dense swarm setting solid: a stalled agent is a wall the crowd jams against, so a floor keeps it flowing. Three numbers are coupled and a wrong-looking swarm is usually one of them: neighbors seen =count·π·r²/area(~20 works, far more washes structure into the global mean),separationRadius≈ 1–2× mean spacing (much larger saturates into an even gas), and the turning circlemaxSpeed²/maxForceshould be a few timesperceptionRadius(tighter and agents orbit inside their own neighborhood). Follows the artificial-life reproducibility rule (no pixel snapshot; the neighbor sort is atomic-race-ordered and flocking is chaotic) —SwarmTestspins each behavior against its counterfactual instead, and alignment is tested by local order (agreement with one's own neighbors, 0.98 by 4 s) because global consensus measures mixing time, not the rule (it does get there: 0.10 at 1 s → 0.97 at 20 s). Gotcha the tuning cost a session: a still frame shows density, not movement (agents move a few points per frame), so the look needs a translucent rect over an accumulating canvas — while accumulating,background(_:)wipes whatever alpha its color carries, so it leaves no trail at all (the rect form accumulates on the headless--export --frame Npath too, viadrawer.accumulates, so a Guide figure gets real trails). A dense space-filling swarm organizing into lanes, cells, and a labyrinth is the rules working, not a fault. ExampleSimulation/Swarm;Docs/.Simulation/ Swarm .md Chaotic systems on the GPU (
Sources/+ the Chaotic systems tail section ofOllin/ Compute/ AttractorFlow .swift OllinShaderLib; shared header struct.metal OllinAttractorParams, stride 208, bound at buffer 11). The million-particle leg of the strange attractors:AttractorFlowruns one of the eight published continuous systems (AttractorSystem, theSimstruct-plus-internal-Kindshape, factories mirroringStrangeAttractor's defaults and.attractorhanding back that CPU twin) under a million particles, each advanced by fourth-order Runge-Kutta on the GPU, drawn as camera-facing splats. It reusesOllinPoint, notOllinParticle, because a flow is 3D, which needed the one new draw seam: a GPU-resident point cloud (Draweropens a.recordPointCloud( buffer: count: ) .points3Dbatch carryingparticleBuffer, and the encode binds that instead of the frame's uploaded point list). Load-bearing: that batch leavescurrentKind = nilso a followingdrawPointCloudopens its own batch (a merged CPU cloud's points would be silently passed over, since a batch carrying a GPU buffer draws only that buffer); it is gated out ofmakeBatchlikedrawParticles. The MSL side is unmarked compute-only at the tail ofOllinShaderLib(the spatial-hash precedent, always spliced): the eight derivatives + the three iterated maps +.metal OLLIN_RK4_STEP(, a macro because Metal has no function pointers here (thestate, h, derivative) OLLIN_FOR_NEIGHBORSprecedent) whosederivativeis an expression in the sample point_p;ollin_attractor_field's switch is kept in step withAttractorSystemby hand (the.shaderIndex ollin_sdf_distancerule). One CPU orbit at build does everything else and is why a sketch names no per-system numbers: it measurescenter/extent, the pace, and the speed range, and it is where the particles start. Four invariants, each a fixed defect: the reach is a percentile, not the extremes (rare excursions make a maximum grow with sample size, the four-wing measuring 2.0 over 120k points and 3.5 over 400k, which moved the framing, the dot size, and the stray test with it); particles seed on the attractor, not in a box around it, because the transient is the system's own contraction rate (a fraction of a second for Lorenz, a minute of watching a filled ball for Aizawa) and the CPU tier'ssettlethrows it away for the same reason; the seeding jitter is load-bearing (exactly on the orbit every particle follows one trajectory forever and the picture is that curve with dots sliding along it; a hair off, chaos separates them into a million within a few laps); and the survey filters non-finite points, since constants nobody checked have no attractor and the diverging orbit's NaN otherwise spreads to every measured figure and traps the seeding range (a real crash the tests caught). The step isspeedworth of the system's own time split into substeps never larger than the published step (past it the integrator is solving a different system), so themaxSubstepsceiling slows the flow rather than coarsening it; a particle pastextent * 12is dropped back in the middle rather than left to streak. Color is speed, brightness is density, so the default ramp shifts hue and holds brightness roughly level (a dark-to-light ramp puts two facts on one channel and a slow crowded region reads like a fast empty one), andopacityis low by design so the pile-up carries tone. Follows the artificial-life reproducibility rule (no pixel snapshot) —AttractorFlowTests(12) pins the region the cloud occupies against its own CPU orbit, each with a counterfactual (a different system lands elsewhere; the sabotage check: a wrong constant in the kernel moves the cloud's middle 13 units and fails it). Measured M2 release 1080²: 1M particles stepping and drawing at 55 fps, 0.2 ms CPU. FacademakeAttractorFlow(+count: _: seed: ) stepAttractorFlow+drawParticles,seeddefaulting tovariation. ExampleSimulation/;Attractor Docs/+ the function table inDrawing/ Attractors .md#flow Docs/; Guide Ch 26 § A million following the same field: attractor flow + AttractorFlow figure.Shaders/ ShaderLibrary .md Evolution (
Sources/+Ollin/ Compute/ Evolution .swift Sources/; shared header structOllin/ Geometry/ Population .swift OllinEvolutionParams, stride 272, bound at buffer 11). Selection as a recipe, in the two sizes the technique actually comes in.Evolutionis the GPU tier: tens of thousands of individuals each fly a genome of steering impulses over a fixed trial, are scored on closest approach to atargetpast up to eightobstacles, and are replaced in one breeding pass.Population+Genomeare the CPU tier, Karl Sims' normalized parameter-set genotype judged by a person (breed(from:)for interaction,breed(scoredBy:)for a measure). Load-bearing: the population lives in a compute buffer, not aSimFieldbecause selection needs each child to read an arbitrary rival's score (a texel-local step cannot reach one), and it is tournament selection because that is the one method needing no total, no sort, and no normalizing (it only ever compares), so a generation breeds in one dispatch with no atomics and no ordering between threads, and a score's scale never matters, only its order — where the CPU tier can afford the wheel of fortune, whose sum is exactly what a GPU pass would have to stop and agree on; no explicit elitism because every child draws2 * tournamentrivals, so the best is passed over aboute^(-2·tournament)of the time (three generations in ten thousand at the default). Genomes are kept in their own buffer ping-ponged beside the particles (both swap together in the breed pass, buffers 6/7); the sim reusesOllinParticlewithlife= flying,seedA= closest approach,seedB= the score. The opening generation is a design decision, not a detail: genes drawn independently are a random walk whose steps cancel, so a whole population would mill about the start with nothing to select between — genomes open as smooth arcs (a heading with a per-gene turn), measured keeping ~0.48 of their length as displacement against a walk's ~0.18. Everything about the pace is derived from the start-to-target distance (top speed crosses it in ~2 s, trial is 1.7 crossings, thrust reaches top speed in a quarter trial), re-derived every frame so dragging the target re-paces the run, andspanToTargetis floored because a target on the start would otherwise divide every derived figure by zero. Scoring: closest approach squared (pressure where gains are small), a wall keeps a tenth, an arrival is its own band above every near miss and higher the sooner (the two bands must not overlap or a population that found the target can be out-bred by one that has not). Mutation nudges and clamps rather than replacing, which is why with it off every gene is bit-identical to one generation 0 held (the exact statement of what mutation is for, and the test; "stops improving" is not true at short range with a large population — initial variety carries it). Randomness is a pure function of index, generation, and the population's own seed, never the sketch's rng.measuresGenerationsopts into a per-generation readback (lastGeneration: best/mean/arrived/closest) taken without stalling the GPU, so it can be a frame stale. The default ramp shifts hue and holds brightness level (theAttractorFlowrule: a whole population leaves at one point, so a dark-to-light ramp reports the launch crowd as the leaders).Populationowns a seededSplitMix64(SplitMix64gainedSendable), carries the chosen genomes through untouched (keepsParents— one breeding is a big step when a person is judging), does nothing at all when nothing is chosen, counts a negative score as zero and picks evenly when every score is zero; itsmutationRatedefault is Sims' 0.2 against the GPU tier's 0.04, because a few hundred looks have to cover ground a scored run covers in millions. Follows the artificial-life reproducibility rule (no pixel snapshot; one flight's ulp changes a tournament) —EvolutionTests(13) +PopulationTests(15) pin each piece against its counterfactual, every one verified red by sabotage. Facadeevolution(+count: genes: from: to: seed: ) stepEvolution+drawParticles, andpopulation(. Examplescount: genes: seed: ) Simulation/+Evolution Simulation/Breeding;Docs/; Guide Ch 26 § Letting the sketch find it: evolution + Evolution figure.Simulation/ Evolution .md GPU fluids & soft bodies (
Sources/+Ollin/ Compute/ ParticleFluid .swift SoftBodies.swift). Particle dynamics in a walled box overSpatialHash, reusingOllinParticle; shared header structsOllinSPHParams(stride 112) /OllinSoftBody(32) /OllinSoftBodyParams(64).ParticleFluidis 2D SPH (Müller 2003 symmetrized EOS pressure + Clavet 2005 near-density/near-pressure for anti-clumping and emergent surface tension; quadratic/cubic spike kernels normalized for 2D by integration): per substep, predict (gravity + one-framepull/push) → rebuild hash over predicted positions (fixed 1/120 s look-ahead) → density pass → force/integrate pass, all pure gathers off one snapshot so pair forces cancel equal-and-opposite with no atomics. Load-bearing: densities are normalized to the seeded lattice (restDensity1 = as packed, parameters survive a radius change); the box is walls, not a torus — kernels use plain deltas and ther < htest rejects the wrapped 3×3's cross-wall candidates (safe because the hash world rounds down by less than one cell); the velocity clamp (0.45·h per substep) makes tunneling impossible, so a hitch can't detonate the sim; wall under-density compression is countered by near-pressure (raisingnearStiffness, not clamping pressure, is the intended lever).SoftBodiesis meshless shape matching (Müller 2005): a serial one-thread-per-body reduce (the prefix-sum trade) fits centroid + closed-form 2D rotation, then particles steer to rotated rest offsets atsquish(converted per substep, feel is frame-rate-independent); contacts are cross-body only and inelastic (overlap repulsion + each side sheds half the approach speed). Load-bearing: rest offsets are taken about the rest centroid (the lattice mean, not the disk center) — anything else leavesΣ(goal − x) ≠ 0and the body silently self-thrusts (a real bug: blobs hovered and pinned into corners; pinned byFluidDynamicsTests); spawns separate via.isolatedBodyConservesMomentum relaxCirclesbefore particle fill (an overlapped spawn explodes). Both run fixed substeps against a clamped frame clock (≤ 1/30 s), pack params at buffer 11 per substep, and follow the artificial-life reproducibility rule (no pixel snapshots; behavioralFluidDynamicsTests). FacadesmakeParticleFluid(/count: radius: ) makeSoftBodies(+bodies: radius: ) stepParticleFluid/stepSoftBodies/drawParticlesoverloads defaultboundsto the canvas andseedtovariation. ExamplesSimulation/(dam break, drag to grab) +ParticleFluid Simulation/(jelly pile, drag to knead).SoftBodies Docs/.Simulation/ Fluids .md Text. Three font kinds over one
drawText/textToShapes/ metrics surface (textFont/textSize/textAlign/textWidth):BitmapFont(default Cozette, BDF + Playdate.fnt),OutlineFont(Core Text.ttf/.otf, each glyph aShapetaking fill and — only once the sketch has set one (Drawer.strokeSet) — stroke, so the initial default black stroke never outlines glyphs (it eats thin light text on a dark ground;TextDefaultStrokeTests); variable-font axes; default.systemMedium),StrokeFont(Hershey.jhf, plotter polylines).textMode(.atlas)flips outline text to an SDF glyph atlas (GlyphAtlas, exact EDT, fourth glyph pipeline). Consecutive atlasdrawTextcalls with the same atlas, blend, depth, clip and target are ONE run (beginGlyphBatchextends the last batch when it is that run; quads carry their own color and size, and a run ends where the next batch starts), so text set a character per cell costs one draw call, live and in aBatchreplay (Cordeiro'sGente, four sheets of 16,000 cells: 125 to 11 ms a frame, every frame byte-identical);GlyphAtlasTestspins the merge and its splits,.characterAtATimeTextIsOneRun mergedRunsRenderAsTheyDidOneByOnethe pixels. The styled one-call label: everydrawTextanchor form (scalar,at:,in:box) takes optionalsize:/color:/align:that apply to that call alone (Drawersaves and restores exactly the touched fields) —.withTextStyle color:paints the glyphs whatever the font kind (fill, or stroke for a stroke font) and suppresses the outline decoration a standingstrokewould add; byte-identical to the four-call preamble it replaces (ConvenienceHelperTests). Per-glyph / on-path / box-wrap / metrics helpers; standard noticesdrawStatus/drawCaption. ExamplesText/TextBox(the wrapped box ruled onetextLeading()apart) +Text/Scripts(textMissingCharactersnaming what the font cannot draw, before it draws). Gotchas: glyphShapes must be.nonZero(even-odd cutse/a/gterminals); San-Francisco overlapping sub-contours need a Clipper2 union clean at reference scale 1024 then RDP-simplify (OutlineFont) per render size, or a per-frame fps regression; warp via bounded.simplifyClosed signedNoise, not rawcurlNoise;textToShapesreturns RAW uneven Core Text vertices (resampled(spacing:)respaces them evenly for dot/jitter effects); baretextFont(.builtin)is ambiguous — use the typed form. Glyphs extrude into 3D solids throughdrawText3D/Mesh.text(see the 3D bullet).Docs/. A full atlas page is never cleared: the atlas moves on to a freshDrawing/ Text .md GlyphAtlas.Page(its own bytes, its own texture) and leaves the full one as it was, aSlotnames the page it was placed on, and a.glyphAtlasbatch holds that page, so text placed earlier in the frame that fills the page, a retainedBatch, and a recording all keep sampling the bytes their glyphs were drawn with (clearing in place drew the wrong glyphs for everything placed before, once per fill).drawAtlasTextemits one batch and onereplicated { }per page run, since a symmetry copy is appended after its body and must land in its own run's batch. A page that gained cells uploads into a fresh texture, never into the one a frame in flight reads.GlyphAtlasTests:aFullPageKeepsTheGlyphsPlacedOnIt,aCallThatFillsThePageSplitsItsRunByPage(per-batch counts under three folds exactly three times the plain ones),theFrameThatFillsThePageDrawsItsEarlierTextRight(byte-identical to the frame that fills nothing), each red on the in-place clear or the one-replication form. The glyph atlas finds a face again after making a slot, since making one can fill the page and move on, which forgets every face (a held index crashed the first time a face already on the page filled it;aPageThatFillsMovesOnUnderTheFaceThatFilledIt, andSoakTestsfills page after page). The per-glyph route (drawText(_:along:),perGlyph:, the SVG run) takes the same cached glyph geometry the plain run fills (OutlineFont: cleaned of self-overlaps at a reference scale, simplified to 0.3 px), so a glyph along a path is the plain run's glyph to the pixel (.geometry( for: ) TextPlacementTests); flattening afresh there kept every curve point and carried 4.5% more ink on a 20 px O..alongAStraightPathIsThePlainRun Text in every script (
Sources/+Ollin/ Text/ TextClusters .swift ColorGlyphs.swift+LineBreaks.swift, plus the layout core inOutlineFont). The four places the one-glyph-per-letter assumption breaks, each fixed at the layout tier so every text path inherits it:TextDirection(textDirection(_:), stack state,ParamOption) forces the base writing direction where the text can't say it (.automaticdefault = today's behavior, byte-identical); cluster-aware runs replace per-glyph runs inglyphRun(per-glyphdrawText, text-on-path), soGlyphRunItem/TextGlyphcarrytext: String(+characteras the first char,isPicture) rather than oneCharacter; color glyphs (emoji) rasterize throughColorGlyphCacheand draw on the image path in the outline and atlas modes;LineBreaksreplaces the space split inlayoutBlock. Readbacks:OutlineFont/.fontsUsed( for: ) missingCharacters(+ the font-kind-agnosticin: ) Sketch. Load-bearing: the cluster unit is the grapheme, not the string index (a Devanagari syllable's glyphs report different indices inside one grapheme — bucketing by index splits it into pieces that overlap on the canvas), a grapheme with no glyph of its own joins the piece before it (a ligature is reported at its first character in either direction; one at the very start waits for the first piece instead), and clusters sort by.textMissingCharacters( _: ) originXwith a build-order tie-break so a right-to-left line comes out left-to-right on the canvas (TextGlyph.index0 is the letter read last, which is what a sweep across the drawing wants); a cluster's advance is the sum of the shaper's own advances, never a difference of neighboring positions (an Arabic mark is stored after its base at a larger x, so the difference goes negative, clamps to 0, and the total is wrong);glyphRunapplies both pen offsets (xandy) or Arabic harakat and combining marks drop onto the baseline (measured up to 0.063 em, invisible in a whole-line bounding box, so the test compares glyphs one at a time); a color glyph is told from an ordinary one only by the absence of a path (there is no flag), rasterizes once at 160 px = the largestsbixstrike Apple Color Emoji carries (read from the font's own table, so a bigger raster only upsamples), takes neitherfillnorstroke, is left out oftextToShapeswith anoteOnce, and counts as a skipped image in a vector export; the SDF atlas is one channel so a picture can never be stored in it (its own image batch, in call order);LineBreakscreates its tokenizer with no locale (measured identical toen_US/th_TH/current across English, Japanese and Thai, so an export can't depend on the machine) and a wrapped line is trimmed of its trailing space; the paragraph-style setting holds a pointer, so the two forced-direction styles are built with nestedwithUnsafePointer(letting it escape reads freed stack memory and the direction silently does nothing). Bitmap and stroke fonts have no shaping engine and stay left-to-right by design. No pixel snapshot (the layout and the emoji bitmaps come from the machine's own OS and installed faces, which a reference would pin instead of Ollin's code, matching the repo's system-font-free snapshot convention) —ComplexTextTests(21, all eight mechanisms verified red by sabotage) + two Metal-gated render probes pin it instead. ExampleText/Scripts; Guide Ch 8 § Shaping and direction: text in any script + EveryScript figure;Docs/.Drawing/ Text .md#scripts Writing in columns, and justification (
TextDirection+.topToBottom textJustify(_:), overlineStarts/layoutBlockinOutlineFont.swift). Tategaki: text down the page in columns that fill right to left, plus flush-both-edges justification in either axis. Load-bearing: the axis is its ownTextDirection, not a second parameter, and asking Core Text forkCTVerticalFormsAttributeNamedoes both halves at once — it substitutes the font's own sideways glyphs and returns positions already running down the column with the font's vertical origin applied, so Ollin rotates nothing and translates nothing (probe-verified:(goes 27.6×92.2 → 92.1×27.6, the comma moves corner to corner); whether Latin turns is the face's decision (Hiragino carries a turnedA, San Francisco does not), which is why the doc promises the font's shapes rather than a rotation. OnelineStartsreturns the point each line measures from — a line's left edge on its baseline, a column's center axis at its top edge — so one glyph formula (start + () serves both axes andx, -y)·size placedGlyphs/placedAtlasGlyphscannot drift; a column is one em across by definition (fixed block width whatever the text) and column pitch is the sametextLeading. The twotextAlignaxes swap roles (vertical says where a column starts, horizontal places the block),textWidthmeasures along the writing axis, anddrawText(_:in:)wraps against the box height. InglyphRunthe piece's distance is accumulated from advances, not read off a glyph (Core Text's y = 0 is the column top, one ascent above the first baseline — measuring from the baseline slides every column, the defectperPieceDrawingPutsInkWherePlainDrawingDoespins) and only the along-axis coordinate is made relative (ShapedCluster, sorted descending for a column since pen y falls as you read). Text on a path stays horizontal (the curve already carries the direction) and bitmap/stroke fonts note once and stay horizontal. Kinsoku needed no code: the system break set.anchor LineBreaksalready asks is UAX #14, which encodes the Japanese rules, so a comma arrives joined to the character it follows and greedy whole-piece filling is the push-out behavior — the old "the finer rules are not applied" claim was stale, andjapaneseKeepsForbiddenCharactersOffTheEdgesOfALinepins it with a naive per-character wrap as the counterfactual. Justification isCTLineCreateJustifiedLine(the engine knows each script's opportunities: spaces in English, between characters in Japanese), needs a box (only a box states the target), never squeezes, and the last line of each paragraph is left natural — which is whywrappedLinesreportsparagraphEndswhile it still knows them, since joined lines lose the distinction.TextJustificationlives on the drawer for the length of one box call. No pixel snapshot (system fonts + system layout, the complex-scripts rule);VerticalTextTests(18) + oneComplexTextTestsaddition, all eight mechanisms verified red by sabotage — including a reading-order test the first sabotage pass proved was missing (a reversed column measures perfectly and lands its ink correctly; only the character each piece stands for gives it away). ExampleText/Columns;Docs/+Drawing/ Text .md#vertical #justify.Hanging punctuation (
textHangingPunctuation(/_: ) noTextHangingPunctuation(, over) HangingPunctuationinLineBreaks.swift,Drawer, and.hangingWidth( of: ) layoutBlock's per-linehang). A stop or comma at a line end may sit past that end (ぶら下げ) rather than taking the character it follows to the next line. Load-bearing: the hangable set is stops and commas only (。 、plus their full-width and half-width forms, and the Latin.,) — a closing bracket is line-start-forbidden too, and hanging one would put it outside the thing it closes; the hang width is measured as the difference the last character makes to the line (textWidth(), not read off the character alone, so it carries whatever the shaping did about the pair, and only a line actually ending in a stop pays the second measurement. Two places consume it and both matter: the wrap fit test subtracts it (that is the whole visible effect, and it is why the piece the stop is attached to can stay), andline) - textWidth( line .dropLast( )) layoutBlockreports a per-linehangthatlineStartssubtracts from the extent, so a right-aligned or centered line lands where the line without its stop would land and a justified line stretches toextent + hang(the part that counts reaches the box, carrying the stop past it). Like justification it is scoped to the box call (textHangsInBox, set and cleared bydrawText(_:in:); only a box has an edge to hang past) while the setting itself is ordinary drawing state thatwithStaterestores. The extent half is outline-font work; bitmap and stroke fonts still wrap this way and still align on the whole line. Note the effect only appears where a stop would not otherwise fit, so a demo has to be tuned to a box width that produces one (Text/HangingStopsis, and a width sweep is how it was found). No pixel snapshot (system fonts + system layout);HangingPunctuationTests(10). ExampleText/HangingStops;Docs/.Drawing/ Text .md#hanging Mongolian columns (
TextDirection, over the same.topToBottomLeftToRight lineStarts/penOrigin/ geometry cache inOutlineFont.swift). Vertical text whose columns fill left to right, with the letters joined. Load-bearing, and the opposite of the tategaki path: this script is UAX #50vo = R, so its glyphs are stored in horizontal orientation and a line is shaped horizontally and then turned a quarter turn clockwise; asking forkCTVerticalFormsAttributeNameinstead gives every letter a full em advance and breaks the cursive joins (probe-verified againstCTLineDraw's own vertical output — the joined spine is the thing a still frame shows). The turn is(in local canvas space and matches Core Text's own rendering glyph for glyph;lx, ly) → ( -ly, lx) CTRunGetTextMatrixreports the opposite sense for these runs (its vertical text space is itself flipped), so never apply the run matrix here — a wrong turn still stacks and still measures, and only the joins failing to meet gives it away, which is whataColumnIsTheLineTurnedAQuarterTurnClockwisepins against the horizontal twin. A column is as wide as the face's ascent and descent rather than one em, and its axis sits one descent in from the block's left edge, because the turn puts the ascender side to the right; the pen formula becomesstart + (y, x)·size(both offsets added, no y-flip), and the turned glyph geometry is cached under its own key, built by turning the upright one, so a turned column stays a translate of cached vertices and the flatten happens once for the pair. The atlas quad takes the same turn corner by corner (a quarter turn keeps a quad a quad and carries each corner's UV with it). The face must have the script: the column width comes from the base face's own metrics, and the system font does not have it. No pixel snapshot (system fonts + system layout, the complex-scripts rule);MongolianTextTests(12), the turn verified red by sabotage. ExampleText/;MongolianColumns Docs/.Drawing/ Text .md#mongolian Images.
Imagevalue type (ImageIO decode — PNG / JPEG / HEIC / TIFF / GIF — from path / url / data / resource / CGImage;loadImagesugar), drawn bydrawImageon the textured-quad pipeline in call-ordered batches; lazy device texture cached on theImage, premultiplied, uploaded by hand into an sRGB format (see the gotcha at the end of this bullet).tint(_:)/noTint()stack state.imageSampling(_:)(ImageSampling:.lineardefault /.nearest) is stack state beside it: a picture drawn larger than its pixels keeps each one a hard square under.nearest, with no enlarged copy made (the batch carriesimageSamplesNearest, the renderer bindspixelSampler, magnification nearest and minification still linear through the levels, anisotropy 1 and clamped likeimageSampler; a picture drawn smaller is blended under either, byte-identical); the web page sets the picture's magnification filter per draw from a flag after the item's bounds; the SVG recorder skips pictures as it always did.ImageSamplingTests(16 flat cells to the byte at 2×, the seams blended under.linear, the reduction identical, the state restored); exampleImages/PixelArt.fit:(ImageFit:.stretchdefault /.contain/.cover) says what happens when the picture and the box are different shapes:.containshrinks the destination through the shippedRectangle(,fitting: in: ) .coverkeeps the destination and reads a centered source crop instead (Drawer.drawImage'ssource:rect, normalized, measured from the picture's top-left; theflipsVerticallyswap is applied after the crop, so a caller never works in texture coordinates) — so a covered picture needs no clip pass and stays one quad, byte-identical to before at the default crop.Rectangle(is the public other end ofcovering: in: ) fitting(max-scale, centered, runs past two edges).withViewBox(runs a block inside a rectangle as if that rectangle were the canvas (clip + translate + scale,_: fit: _: ) fit:reusingImageFitover the samefitting/coveringpair). Two remaps are what make an unedited piece run in a box:background(_:)inside one fills that box's virtual canvas instead of setting the frame's clear color (Drawer, a stack — the clear color belongs to every box at once, so one wipe would take the others), and the mouse arrives in box coordinates. The mouse is written straight into.viewBoxCanvases mouseX/mouseY, never throughsetMouse(that is the runner's input path: it logs a pointer event into a running take and is a no-op during a replay).width/heightdeliberately do not change — the code inside believes it has the canvas — so the virtual canvas takes the sketch's shape and a box of that shape is the un-letterboxed case. Boxes nest (clips intersect, mappings compose).ViewBoxTests(8 tests incl. two GPU probes: two boxes each keeping their own background, and the frame outside every box untouched); exampleRendering/ViewBoxes.viewControl(is the 2D pan-and-zoom counterpart ofcenter: zoom: in: ) cameraControl()(Core/View2D.swift+ theSketchface;viewCenter/viewZoom/resetView()): drag pans, scroll zooms, the arguments are the view's home after the first call: a constant framing changes nothing, a changed one (a@Paramturned in the inspector, an edit on the stage,carryRuncarries the wholeView2Dacross it) glides the view there at the camera rig's rate (homeGlideRate8/s, an exponential approach, landing exactly within 1e-9) whilerestsAtHomeholds, and the first drag or scroll ends that for good;resetView()opens on the current home (ViewControlTests: the glide lands and a constant holds, a taken view is left alone, the reset goes to the new home). Undamped on purpose (an orbit gains from inertia, a plane under a finger does not), so both gestures are exact equations rather than a feel: a drag moves content by exactly the pointer delta (center -= d / zoom) and a zoom is anchored on the pointer (center = anchored - (). It leaves a plain transform, so what is drawn before it stays put and a HUD goes after apointer - middle) / zoom' withState { }around it. The mouse is remapped into content coordinates for the rest of the frame;performDrawrestores the pointer arounddraw()(the runner only writes the mouse when it moves, so a remap left standing would reapply to itself and the view would crawl on still frames — pinned byaStillPointerDoesNotDriftTheView).ViewControlTests(10 tests incl. a GPU probe againstscreenPoint; the probe measures a centroid, since the first-found brightest pixel of a filled disc is its top edge, a whole radius off); exampleInput/PanAndZoom.ImageFitTests(10 tests: the crop is centered, one axis survives whole, what it leaves has the box's shape measured in the picture's own pixels, plus three GPU probes over a four-band 4:1 picture in a square, where.covermust show only the middle two bands); exampleImages/Fit. Part of a picture:drawImage((four source numbers after the box) and_: _: _: _: _: _: _: _: _: ) drawImage(, the source in the image's own pixels from its top-left, through_: in: source: ) Drawer, which cuts a part that runs off the picture and carries the same cut to the box (the off part draws nothing). Load-bearing: the batch carries.drawImage( _: in: sourcePixels: ) imageBounds(the part in texture coordinates) andollin_image_fragmentholds the sample half a texel inside it, choosing the level from the quad's own uv (gradient2d(), since the held uv stops moving at the edge; a whole-picture draw bindsdfdx( in .uv), dfdy( in .uv)) MetalRenderer(min past max) and samples exactly as before, and.wholeImage .coverkeeps reading across its crop (a photograph continues there). Drawn at its own size or larger a cell equals the same cell cropped first pixel for pixel at 1x, 3x, 4.5x, whole and quarter-pixel positions (ImageSourceTests, red with the clamp planted off: 113 px at 1x, 1,000 at 3x); drawn smaller, the mip chain averages across cells (padding is the answer, documented). The web page carries the bounds after the item's count and its image fragment holds the read the same way (textureGradon the quad's uv); the parity caseSpritesreads mean 0.029, and 2.44% far with the page's clamp planted off. ExampleImages/SpriteSheet. Pixel get/set via theImage[x, y]subscript (premultiplied, top-left origin; a GPU-backed image, a layer's, a compute texture's, a live feed's, answers.clearand drops the write onhasCPUPixels, before any buffer is set aside,ImageTests); blank.layerImageHasNoPixelsToReadOrWrite Image(+ bulkwidth: height: color: ) Image(. Gotchas: every texture is built by hand, never through the synchronouswidth: height: premultipliedRGBA: ) MTKTextureLoader— that loader decodes on a dispatch worker and parks the caller on its own semaphore, so with every worker already blocked (a test run with several blocking calls in flight) the main thread waited forever, the intermittent CI wedge the watchdog sampled on 2026-09-06;Image.texture(for:)draws the CGImage into a premultiplied sRGB bitmap on the calling thread andfillSmallerLevelsblits the mip chain on a command buffer, which also settles two things the loader got wrong for some sources (a context-made CGImage came back in a linear format holding sRGB bytes and washed out lighter; a straight-alpha PNG stayed straight while the pipeline blends premultiplied), andlinearTexture(for:)draws into the image's own color space so a value map's bytes are never converted; don't add a y-flip to the pixel buffer (it's already top-down).Docs/.Drawing/ Images .md Sample photographs.
OllinSamplePhotos(a product of its own, never part ofOllin, so an app that skips the import ships none of it), twenty pictures and one short film: four facesSamplePhoto/.portrait .scarf/.profile/.marigolds, four whole figures.reaching/.wrestler/.dancer/.handstand, two tables from above.breakfast/.desk, a pair of open.hands, four streets.alley/.street/.textiles/.city, two dusk landscapes.headland/.boats, a.pageunder uneven light, and two surface textures.talavera/.stone(+.all, in that order), eachload()ing a JPEG at 1600 on its long side through the library's ownBundle.moduleand carrying itscredit(photographer / place / source page / license / license URL;credit.lineis the one-line form). The JPEGs are.processed so they land flat in the bundle root; total 6.4 MB, each under 512 KB at quality 72 to 95 by request (a smooth dusk sky is the one case that wants the top of that range, since banding lives in exactly such a gradient). The two surfaces are 1024 squares, not 1600 on the long side (theSurfacesAreSquarePowersOfTwopins it): a texture is magnified and repeated, so it wants clean pixels at a size a GPU mips evenly, and neither fits the size budget at 1600 without artifacts a magnified surface shows. Every face is square (theFacesAreSquarepins it) so it crops to the canvas without choosing what to lose; a figure keeps whatever frame holds its whole body, which is upright forreaching/dancer/handstand, where a square would cut a raised arm or a foot off, and square for thewrestler, whose arena frame had the room. A sketch fits an upright one rather than covering it. Every figure was read by the joint model before it was bundled:reaching/dancer/handstandgive all 19 joints,wrestler17 (his ankles are behind the ring rope). The two tables were chosen by measurement, not by eye:breakfastyields 5 detections (2 cups, 2 bowls, a sandwich) where the wrestler it replaced inObjectDetectionyielded 3, one of them a misread;deskyields 7 rectangles and 5 text lines, and is cropped in as far as it is because the recognizer read nothing at the photograph's full width (the print is small, and what fits the frame decides whether it is legible at all). Reading it needsTextRecognizer's.accurate, not the.fastthe live tracker defaults to, and the first accurate pass in a process can cost ~47 s while the system prepares its reader (measured; a warm pass on the same 1600-square picture is ~140 ms, and a following process is usually warm), which is whyTextScan's caption says so rather than reading as broken. Who reads which is by what the technique wants: the frontalportrait(bare paper to solid ink in one face) for the trackers, the mosaics, shock, the filter catalog, and the halftone example; thescarf(full tonal range, but a dark ground and no bold mass) for XDoG, the dithers, and the reference halftone; theprofile(bold masses on a plain ground) for string art, the single line, the spanning tree, and the stipple (a mid-toned face stipples nearly EVEN, and an even stipple grows an even maze, which is how the scarf was tried and dropped for both); themarigolds(one hue, fine texture) for palettes and brushwork; and among the streets,alley(half of it plain sky, hard vertical edges, the most directional spectrum of the four) for the pixel sorter and the seam carver,city(a round dome in the middle distance) for both fit figures, since a round shape is the fastest tell for a stretch, andtextiles(a repeating weave in stripes) for the frequency domain, whose spectrum carries bands rather than the plain blob the marigolds it replaced gave. Crops are decided once and committed (centered on the face; the profile keeps the frame's full width, so the head sits left of center by design), so a face lands in the same place in every figure. A street is cropped to the largest square its original held, by request, which leaves two of the photographer's own edges untouched rather than trimming all four. The two landscapes are the only wide pictures (everything else is a square or an upright, so a sketch wanting a landscape had to crop one) and they share one shape,theLandscapesShareOneWideShapepinning it, so either drops into the same box the way any face drops into a square;headlandcost eleven percent of its height to get there, all of it unlit foreground.boatsis the one picture chosen by a filter's stated requirement rather than by eye:.seamlessClonemeasures its correction around the patch rim and spreads it inward, so a rim over a hard edge drags that edge in, and this is the picture whose brightness stays in a narrow band (0.6% near black) while its color runs pink to turquoise (hue spread 0.86); the example takes its left square, since the sun in the right third is the one hard thing in it, and keeps both slabs above the horizon.headlanddisplaced nothing: it was tried againstscarfinDithering(it is near monochrome, so the four extracted colors come back gray and half the lesson dies) and againstportraitinHalftone(its lower half is solid ink, so the dot ramp never shows), and it ships as the set's only silhouette-plus-gradient rather than as any example's source.handswas chosen by drawing the tracker's own overlay over the candidates, not by eye: thirteen were run throughHandTracker.detectat bundle scale and four gave two hands at a full 21 joints, but rendering the example's bones and tips over them is what separated open palms (ten chains straight out to ten separated tips) from a beautiful pair of pointing hands whose curled fingers bunch into a knot at the knuckles. Thehandstandit replaces reads two hands whose fingers are planted and half closed, so the tracker finds them and the drawing shows nothing.pagewas chosen by running the filter, not by the light meter: of twelve candidates the two with the strongest measured light gradient read zero lines (a book small in a dark frame), while this one reads 60 lines at 0.91 and, under.thresholdagainst.adaptiveThreshold, loses whole bands of text and gets all of them back, which is the demonstration. TheSummedAreaexample keeps its painted page and traveling lamp, since a still cannot show a global cut failing as the light moves; the still figure19-LayersAndEffects/takes the photograph instead, as a detail crop, because at tile size the whole page's type is unreadable and the two cuts then read as abstract shapes.LocalAverages talaverais the only bundled picture that tiles: its frame was found by searching crop size and origin for the smallest wrap error (769 px scored 0.155, and the 1544 two-period crop used here 0.207, both against 0.304 for a naive cut), which matters because a triplanar projection repeats whatever it is given regardless ofwrap. Its normal map is built on the CPU insetupfrom the picture's own luminance slopes; doing it on the GPU at the top ofdraw(a render target plus.normalMap) filled the canvas with the normal map and is the trap to avoid.stonecarries real relief and no repeat, so it went toParallax, where one picture serves as both color and height map and the sphere's own uv covers it once.textilesis also the one where red sits beside green oftenest (5.0% of its pixels, against 4.1% forstreetand 1.2% forportrait, measured over 537 candidates), so it is what a color-vision simulation collapses hardest.Image(CoreGraphics resample into an sRGB context) is the working-copy call every CPU technique now makes first, with.resized( width: height: ) cropped((clamped to the picture, so a crop off an edge comes back smaller rather than empty) andx: y: width: height: ) cropped(toAspect:)(the largest centered piece of a given width-over-height shape, nothing scaled) beside it for changing what is in a picture rather than how big it is; a texture-backed image has no CPU pixels and comes back blank. Terms: Unsplash License / Pexels License (free incl. commercial, no attribution required, no unaltered sales, no competing stock compilation, a person never shown in a bad light), the full record inTHIRD-PARTY-NOTICES. The Examples package links it as the.md .samplePhotossatellite, the hosts through the rootSatelliteenum.SampleClip.danceis the one film: 30 s at 960 square, 25 fps, 1.5 MB, silent, cut from a wider minute. The window and the crop were chosen together, since the dancer leaves a square frame between 0:31 and 0:47 and never once inside the first thirty seconds (measured over 300 sampled frames, no edge contact on any side). It is locked off, which is the property that matters: 63% of the square never changes, so a flow vector belongs to the dancer rather than to a moving lens, and the body model finds 19/19 joints in every frame sampled across the run. It is vended as a URL, not a player (SampleClip.url), becauseVideoPlayerlives inOllinVideoand no satellite depends on another; aVideoPlayeris both aFrameSourceand aVideoFeed, so it drops in wherever a camera goes.Vision/OpticalFlowandVision/ContourTraceread it when there is no camera (both opened a bareCamera()before and showed nothing headless),--photoforcing it as it does the stills. A fixed pixel scale in a flow overlay is a bug waiting for a different source: the arrows were length- and color-scaled against a constant 18 px, which suits a hand waved at a webcam and drew 4-pixel near-transparent lines for a dancer moving a few pixels a frame; they now read against that frame's own fastest sample, which adapts to either. Thirteen more Guide figures read the set rather than authoring their subject, taking the figures that read it to twenty-five, and three swaps were tried and put back. Chapter 34's four:MotionBrushandFlowArrowsstepSampleClip.danceone of its own frames at a time (the two-discStagePerformerthey each carried a copy of is gone),SlitScanDelaypushes 48 consecutive frames into the history and the swung arm comes back as a comb,ReadingTheDeskruns both detectors overdesk,AttentionAndLabelsruns saliency and the classifier overmarigolds(it lands on her face, andmarigolditself comes back at 7%, under the classifier's own default floor, which is now the lesson), andContourstraceshandswithdetectsDarkOnLight:, since the subject is the light half there, the palm creases coming back as holes. Thenfalse Melttakesheadland,TriplanarSkintalaveraat tile 2.2,SurfaceGrainstoneas a deliberately 96-pixel base with a mirrored patch of the same wall as its detail pair (grayed and centered on its own average, since a detail color map multiplies and 128 is its neutral),LiveRoomandLiveSurfaceholdalleywhere the webcam would be,DesignFiltersputscitybehind the three picture filters, andSeparationsseparatesmarigolds. Tried, rendered, and reverted, so do not re-try them:19-LayersAndEffects/(a photograph's spectrum is a noisy blob, where the test plate's stripes and hard edges are exactly what make the harmonic line and the cross readable),FrequencyDomain 02-Color/Dithering(a smooth ramp is the hardest thing to quantize and its banding is the whole lesson; a face posterizes into flat regions that read as a style rather than a failure, and the dithered panels lose the source's tone), and19-LayersAndEffects/(a photographic patch carries its own light and shade, so the cloned disc swings far off the destination's tone, where a flat-color patch shows color replaced and texture kept; a first attempt with the rim over a mortar joint blew out exactly as the filter's own rule predicts, and theSeamlessClone Effects/example already carries the photographic case). A figure that measures the film does it withSeamlessClone seek(to:)thensnapshot(), which is deterministic under the headless driver the figure runner uses.OllinSamplePhotosTests(7,theTablesAndStreetsAreSquare/theLandscapesShareOneWideShape/theSurfacesAreSquarePowersOfTwopinning the size and crop rules) +SampleClipTests(2) +ImageCropTests(3).Docs/; Guide Ch 9 § A picture on the canvas:Drawing/ SamplePhotos .md loadImageanddrawImage.Image as input (glyph mosaic
Sources/, pixel sortingOllin/ Text/ GlyphMosaic .swift Image/, single linePixelSort .swift Geometry/, slit scanSingleLine .swift Image/, halftoneSlitScan .swift Image/, string artHalftone .swift Geometry/, seam carvingStringArt .swift Image/, photo mosaicSeamCarve .swift Image/, autostereogramPhotoMosaic .swift Image/). Nine CPU readings that turn a picture into something else or into another shape of itself, all following the Dither bulk-pixel precedent (Autostereogram .swift premultipliedPixels(in,) Image(out) and all deterministic. Glyph mosaic —width: height: premultipliedRGBA: ) drawGlyphMosaic(+ the data form_: columns: characters: in: inverted: colored: glyphScale: ) glyphMosaic(of:)([GlyphMosaicCell]): brightness → glyph by measured ink coverage in the active font (bitmap lit-pixel count / outline signed shoelace area / stroke pen travel; ramp cached per (font, characters), normalized to its densest member); empty floor below half the sparsest glyph (shadows stay voids); transparency carries no ink in either mapping;GlyphSetcurated sets (Cozette covers the whole technical set);.technical/ classic/ blocks glyphScaledefault 0.85 keeps gutters so dense glyphs read as discrete marks (1tiles blocks seamlessly) — for the reference "marks" look, use a set that tops out below the solid blocks (the example does). Pixel sorting —Image(Asendorf's interval model): threshold-bounded runs along rows/columns sorted by brightness/hue/saturation, keys from straight color, alpha moves with its pixel, position tie-break → byte-deterministic; the iconic jagged look needs texture in the source (run boundaries must vary per line — a clean gradient sorts invisibly, and ascending on an already-dark-to-bright gradient is a near no-op;.pixelSorted( _: by: threshold: reversed: ) reversed: trueis the dramatic direction there). Single line —singleLine((pure, rng-free: grid-accelerated NN construction + neighbor-list 2-opt, ring searches use thethrough: closed: ) (r−1)·bucketSidestopping bound; open form cuts the longest edge) + thesingleLine(sugar over the seeded stipple;of: points: in: iterations: cutoff: closed: ) cutoffrounds bright grays to paper (the Kaplan contrast rule — without it light regions collect a wandering thread). Slit scan —SlitScanclass (push+image(delay:)closure/map forms): rolling CPU frame ring, delay 0 = newest / 1 = oldest held, first push fixes the size (mismatch/GPU-backed frames skipped with a one-time note), memory is w×h×4×frames so push modest sizes. Halftone —drawHalftone(+ the data form_: pitch: angle: in: inverted: colored: ) halftone(of:)([HalftoneDot]): classic AM dot screening as real circles (45° default screen); coverage is the per-cell mean of (1 − linear luminance)·alpha over exact rotated-cell pixel binning, and the radius inverts the sharedhalftoneCoveredFractionspot function — the same function the separations' raster screen thresholds (one source of truth inImage/;Halftone .swift PrintSeparationcalls it), so tone is area-exact and shadow dots merge into the checkered diamonds; the separations' 2% printable-dot clamp applies (below → no dot, above 98% → the corner-flooding.halftonePlane pitch/√2cap);pitchfloors at 2 (dot-count guard); dots emit throughdrawCircle/drawCircles, so SVG/PDF export writes true circles (the plotter path). String art —StringArt((of: center: radius: pins: chords: ink: minSpan: inverted: resolution: ) Geometry/), a stateful stepper with no rng at all (the same picture always winds the same thread): one continuous thread over a ring of pins (pin 0 top, clockwise), each chord the greedy pick by mean remaining darkness along it (mean, not sum, so a short dark chord beats a long gray one), the ink then paid down along the very samples the score walked; a pin pair never rewinds,StringArt .swift minSpan(default pins/10) keeps chords off the rim, and the winding stops at thechordscap or when the best mean drops toink/2(the over-inking floor). The working grid reads the picture's largest centered square atresolutioncells a side, linear-light darkness(, zero outside the inscribed circle;1 - luminance)·alpha invertedwinds luminance instead (bright thread, dark ground).threadis one openContour(the single plotter line),sequencethe pin order (the hand-winding recipe). Bold tonal masses read best; whole-frame soft gradients wind into fuzz. Pairinkwith the drawn stroke alpha so the solver's pass matches what a chord actually darkens; a caption over anoClear()accumulation must keep word-for-word stable text or it smears. The direction of the image-to-grid mapping is pinned by a sabotage-verified seek-the-dark test. Seam carving —Image+.seamCarved( toWidth: toHeight: energy: protecting: discarding: ) seams(_:along:…)([Contour]) +seamMap(along:…)(SeamMap:image(_:)/seam(_:)/sizes) +seamEnergy((Avidan-Shamir content-aware resizing; the default_: along: ) .forwardcost is Rubinstein's forward energy,.gradientthe original measure): one seam is one DP pass, and the picture is really carved between seams (gray/bias/origin shift left in place; the order map records the seam number at the pixel's original column, which is what lets one map serve every size and both directions of resize, and what a sequential-equals-batched test pins). The forward cost is the cost of the join, and each way in has its own price (C_L/C_Radd|up−left|/|up−right|to the crossing|left−right|; trade the two and the seam leans the wrong way, pinned by a hand-worked two-row test, the one thing no other test sees). Ties break leftmost, so a carve is byte-deterministic. Masks read brightness × opacity and add ±1000 (far above any real energy, which tops out near 3); a wrong-size or texture-backed mask is left out with a note. Growth duplicates the first k seams averaged with the right neighbor, capped at2·size−1(a seam is duplicated once). Height carves by transposing, sotoWidth+toHeightis width first then height and the mask travels through the first resize with the pixels. The honest form of the claim is texture survives and flat gives way: a plain object carves away like any other flat region (a straight seam through it creates no new edge), so hold it withprotecting:— which is why the snapshot scene and the example both grain what must survive. Autostereogram (Image/) —Autostereogram .swift Image+ the.autostereogram( _: pattern: seed: ) Autostereogramsettings (repeatWidth/relief/whiteIsNear) +drawAutostereogram. A depth map hidden in a repeating pattern: the picture is built column by column, each taking its color from the column one separation to its left, so the leftmost repeat is the only free choice and a pattern one repeat wide is enough; the separation shortens where the depth is near, which is the entire technique. Columns are joined through a union-find, so a chain of pairings stays consistent. Depth is read in linear light, and a transparent pixel reads as far. The invariants are exact: every paired pair of columns holds the same color, a flat map is a plain repeat, a white map repeats atrepeatWidth·(, and the shape reads back out (the smallest matching shift recovers the separation for >95% of pixels; the rest are the shape's own edges, where the depth changes inside one pair's span — comparing against the depth at the pixel rather than at the pair's midpoint reads as a band of disagreement along every edge, which is what the first version of that test measured). Four practical limits, all in the docs: draw at native pixel size (scaling resamples the very repeats the eyes pair), keep1−relief) reliefunder about a third (past that the eyes cannot fuse it), hard edges read best, and an exported frame is dithered so its repeats match to within a level or two rather than exactly (measured on the export: 46% of probed pixels pair byte-exactly, 89% within two levels). ExampleImages/;Autostereogram AutostereogramTests(8, sabotage-verified); no snapshot (a dithered, scaled reference would pin nothing the invariants do not).Docs/; Guide Ch 9 § A picture that hides a shape + the DepthInARepeat figure. Photo mosaic —Drawing/ Autostereogram .md Image→.mosaic( of: columns: rows: maxUses: ) PhotoMosaic(tilesin reading order, each carrying its cell'stargetcolor;frame(of:in:),uses(of:)) +Image+.averageColor( in: ) drawMosaic(. Each cell takes the library picture whose own average is nearest. The averaging is in linear light and that is the whole correctness claim: half black and half white is 0.5 linear, ~0.735 sRGB, and averaging the sRGB numbers answers 0.5, a quarter too dark (the pinned invariant, and the only one a wrong-space sabotage trips). Transparent pixels count for nothing rather than for black, and the returned alpha says how much of the cell was really there._: of: in: tint: ) maxUsesis spent in reading order and a starved cell falls back to the nearest picture rather than to nothing. The result is placements, not a new picture, so a per-cell rotation or gutter is the caller's to draw. The thing that decides whether a mosaic works is not the code: the target needs range and the library needs range in the same places (a flat dark target takes one picture everywhere;uses(of:)is the number to watch, and the first example wasted 98 of 100 pictures that way). ExampleImages/PhotoMosaic;PhotoMosaicTests(8, sabotage-verified);Docs/; Guide Ch 9 § A picture made of pictures + the PicturesFromPictures figure. All eight of the others need CPU pixels and so does this one (texture-backed images go throughDrawing/ PhotoMosaic .md snapshot()first;pixelSortedandseamCarvedreturn self, the others note once and return empty/nil). The example sketch classesSlitScanandStringArtshadow their types →Ollin.SlitScan/Ollin.StringArt(the@SwiftUIprecedent). Examples.Environment Images/GlyphMosaic/PixelSort/SingleLine/SlitScan/Halftone/StringArt/SeamCarve; snapshotsglyph-mosaic/pixel-sort/single-line/slit-scan/halftone/string-art/seam-carve;GlyphMosaicTests/PixelSortTests/SingleLineTests/SlitScanTests/HalftoneTests/StringArtTests/SeamCarveTests(19).Docs/,Drawing/ GlyphMosaic .md Docs/,Drawing/ PixelSorting .md Docs/,Generators/ SingleLine .md Docs/,Video/ SlitScan .md Docs/,Drawing/ Halftone .md Docs/,Generators/ StringArt .md Docs/.Drawing/ SeamCarving .md Data as input (
Sources/+Ollin/ Data/ Table .swift JSON.swift). The load-once material for data-driven drawing:loadTablereads CSV/TSV into aTable(aRandomAccessCollectionofRows;row["col"]/row[2]plusnumber/int/bool/colorand theirat position:twins,column(_:)/numbers(_:)) andloadJSONreads a document intoJSON(a@dynamicMemberLookupenum; reach by key/index then ask.text/.number/.int/.bool/.color/.array/.object/.keys/.count/.isNull). Both follow the palette-importer posture: total decode,nilrather than a throw or a trap, andresource:in:with no default bundle (the framework-wide rule). Load-bearing: the CSV parse is the published format as a byte scanner (every byte it compares is ASCII and no byte of a multi-byte UTF-8 character can be mistaken for one, so cell text passes through untouched), and its case order is too: separator and line endings are tested before the after-closing-quote whitespace case, since a tab is both a separator and whitespace and the separator reading must win (a TSV silently lost a column otherwise); the BOM is stripped or it joins the first column's name invisibly and every lookup of that name fails; a quoted cell is verbatim while an unquoted one is trimmed (quoting is how a file says it means the spaces, and the whitespace on either side of the quotes is not part of the cell); the blank-line rule keys on whether the record held quotes, because a line holding""is a row where a truly blank line and the newline closing the last real row are not (dropping it left a 0-row table that crashed the suite's firsttable[0]). Two things are guessed and an explicit answer overrides each (thepalettePerLine:precedent): the separator (most frequent of comma/tab/semicolon/pipe on the first line, outside quotes) and the header (a first row holding no numbers).Bool? numbers(_:)drops non-numbers (a series to scale by) whilecolumn(_:)pads to the row count (stays row-aligned) — the one place the two reads deliberately differ. Rows share one name-to-position map by class reference rather than each copying a dictionary, and a repeated column name resolves to the first. JSON: a missing key reads as.nullso a path chains without a check at every joint,.array/.objectare non-optional so a loop over an absent key runs zero times, andtrueis told from1byCFBooleanGetTypeID(the system reader hands both back as anNSNumberholding 1). Deliberately small: a document with a shape worth naming isCodable's job, and the docs say so. ExamplesData/Readings(a CSV as a range chart, notes holding commas and doubled quotes) +Data/Places(a JSON survey, a station with no color landing on the fallback);TableTests/JSONTests(no pixel snapshot: both are CPU value types). Guide Ch 9 § Numbers you didn't type: CSV and JSON + DataAsMaterial figure.Docs/.Helpers/ Data .md Live data (
Sources/). The live sibling of the load-once readers:Ollin/ Data/ DataFeed .swift DataFeedreads one address over and over on a background queue, so a piece draws what is true now anddraw()never waits for the network. Made with an address (or aURL) plusevery:seconds,as:aContent(.auto/.json/.table/.text) andheaders:(where an API key or a contact address goes); driven bystart()/stop()/refresh(); read asjson/table/text/bytesplusupdates/timeSinceUpdate/isRunning/isWaiting/failures/lastError. The bytes are parsed on the network queue, never in the frame that first asks, which is why the shape is decided at arrival rather than lazily. Load-bearing: an empty feed and an unreachable one are one state, not two (null/nilthroughout, withlastErrorsaying why), and a failure never clears what the feed already holds so a sketch keeps drawing the last good answer under the notice;updatescounts only answers whose bytes differed, which is what a sketch keys an entrance on (a poll that brought back the same document is not news); the next request is scheduled only from the previous one's completion, so a slow server can never stack requests, andrefresh()bumps the generation so the request already on the schedule is orphaned rather than running beside the new one (two chains ask twice as often as the feed promised); the storedETag/Last-Modifiedare sent back asIf-None-Match/If-Modified-Sinceand a 304 is a successful non-update, which needs an ephemeral session with.reloadIgnoringLocalCacheDataor the shared cache answers from disk and hides the very header that says so; failures back off by doubling up to 8x the interval and reset on the next answer;every:clamps to >= 1s;URL(string:)accepts a bare phrase as a relative reference, soDataFeed.parseinsists on a scheme rather than failing much later as an unloadable request; the export path reads once duringstart(), synchronously, andtimeSinceUpdatereads 0 throughout, because a feed fetching per frame would make an export render differently every run (the headless flag is read once instart()and stored, so the rest of the type consults it from any thread).start()is nonisolated, and deliberately: the flag it reads is the only thing that ever wanted the main actor, soOllinAppis.isRenderingHeadless nonisolated(unsafe)and a piece may start a feed from any context. The flag is only believed on the main thread (Thread), because a headless drive owns that thread from.isMainThread && ... setup()through the last frame: astart()anywhere else is not part of it, and taking a process-wide flag at face value off-thread is how a test process hands its own renders to every feed under test (which parked the pool and wedged a whole run before the gate went in). A hop there would be a hop in the tests too, and a hop from a suite that is not on the main actor waits behind every drawing test already queued (see Pushed live data for the measured cost). Deliberate v1 cuts: no response-size cap, no@Parambinding (the push transport is its own type — see Pushed live data). A test-onlyansweredBy:initializer takesURLProtocolclasses, so the suite drives every branch with no socket, and the suite is deliberately not@MainActorand touches the main actor nowhere at all. ExampleData/Quakes(a day of USGS earthquakes, rebuilt only on a change, the last good list kept through a failure);DataFeedTests(21) +DataFeedExportTests(2; the export read and the off-main start, both sabotage-verified red), with the unchanged-bytes guard, the conditional request, and the refresh generation bump each sabotage-verified red too, including one case through a realURLSessionload; no pixel snapshot (the output is values). Guide Ch 42 § Numbers that keep arriving: DataFeed + NumbersThatKeepArriving figure.Docs/.Helpers/ LiveData .md Pushed live data (
Sources/+Ollin/ Data/ PushFeed .swift PushTransport.swift). The held-open sibling of the polled feed:PushFeedkeeps one connection alive and reads messages the moment the other end sends them. The address decides the transport —ws/wssa web socket (URLSessionWebSocketTask), anything else a stream of server-sent events (the internalServerSentEventParser, written from the published wire shape: multi-linedata:, stickyid:,retry:in ms, comments as keepalives, a CR/LF pair split across chunks read as one ending) — and the surface isDataFeed's (json/text/bytes+eventfor the latest,updates,timeSinceUpdate,isRunning/isConnected/failures/lastError,headers:) plus the drainingmessages()(oldest first; an undrained feed keeps the newest 256, dropped is still counted) andsend(_:)(socket-only). Load-bearing: reconnection is the feed's own job — a drop redials with the retry base (retryEvery:clamped >= 1s; an SSEretry:hint wins) doubling per consecutive failure up to 8x,failuresresetting on anything arriving (message, keepalive comment, pong — an accept-then-drop server must not reset the backoff on open alone); an SSE redial carriesLast-Event-IDso a blink loses nothing the server still holds (sabotage-verified);greeting:is said at every open, never once (a subscribe message must survive the redial, which is why it is feed configuration rather than asendinsetup()); every decision point bumps the generation (start/stop/reconnect()/each redial), so a dead socket's second close report (close frame + task completion) can neither double-count a failure nor fork a second dial chain (sabotage-verified);updatescounts every message, byte-identical repeats included — a push is sent because the server had something to say, so the poll's changed-bytes rule deliberately does not carry over; a web socket is pinged every 20s (a failed ping is how a silent death is noticed) while the events side leans on the 60s idle request timeout; an SSE 204 ends the feed for good (no redial — the polite-client rule); the feed's lock only ever returns instructions (greeting send, semaphore signal, redial scheduling are carried in aFollowupacted on outside it) and transports deliver outside their own lock, or.opened→ greetingsenddeadlocks; each connection owns its ownURLSession, invalidated when done (a session retains its delegate until invalidated); headless export waits for the first message duringstart()(20s cap), closes, and holds it,timeSinceUpdatereading 0. The suite drives SSE end to end through a streamingURLProtocolstub (a terminal step on the heels of a body chunk must wait ~0.2s or the session drops the undelivered bytes) and the transport-agnostic redial logic through a scripted transport factory (carriedBy:) — no loopback socket anywhere, per the DataFeed environment rule. The suite is not@MainActorand touches the main actor nowhere, which is what keeps it honest: the drawing suites run one at a time on the main actor, so a hop from here waits behind every one of them already queued, and the wait is queue position rather than cost. Measured 2026-08-29 in one 3,107-test run: no hop 74.8 s, one hop 142.6 s, and the test that calledstart()twice 617.0 s, the run's only failure, against 2.5 s for the whole suite alone.PushFeed.start()is nonisolated so that no hop is needed (believing the headless flag only on the main thread, the drive's own, so an unrelated render is never mistaken for this feed's export), and every wait helper here probes before reading its clock, since a task starved past its deadline otherwise gives up having never looked; one real-URLSessioncase reads afile://event stream. ExampleData/Edits(the encyclopedia's edits as rain over the Wikimedia stream, verified live by headless export);PushFeedTests(35) +PushFeedExportTests(2; the export read and the off-main start, both sabotage-verified red); no pixel snapshot (the output is values). Guide Ch 42 § Messages that arrive on their own: PushFeed + MessagesThatPushThemselves figure.Docs/. A close frame is its own sentence: when a server closes politely, the receive loop hears of it first, as the socket's own error ("Socket is not connected"), ahead of the delegate's close callback, so the loop reads the task'sHelpers/ LiveData .md closeCodeandcloseReasonandlastErrorreads "the server closed the connection (code 1008): …" (WebSocketTransport)..closeSentence PushFeedWebSocketTests(11) runs the web socket transport against a server on the loopback through Network.framework, on a port the system picks: the handshake's headers, text and binary frames, the greeting again after a redial, a close from either side, and a port nobody listens on.The weather outside (
Sources/+Ollin/ Data/ Weather .swift Place.swift). ADataFeedthat knows its address and the shape of its answer:Weather(at:)/Weather(/latitude: longitude: ) Weather(,in: "Oaxaca") every:clamped to >= 60 s (default 900), the feed's ownstart()/stop()/refresh()andisRunning/isWaiting/failureCount/lastError, read asreading(aWeather.Reading, public memberwise with plain defaults, so a figure or a test draws a sky without asking for one) or field by field (temperature,apparentTemperature,humidity,cloudCover,precipitation,snowfall,windSpeed/windDirection/windGusts,pressure,isDay,condition,sunrise/sunset), all SI and fractions of one. Load-bearing: the provider is Open-Meteo (keyless, CC BY 4.0, non-commercial limits; named in the Docs page andATTRIBUTION.md, and the request askswind_speed_unit=msandtimezone=auto, so the answer's local times cross to instants through its ownutc_offset_seconds);updateCountcounts readings, never bytes (ReadingisHashable, and every answer carries a freshgenerationtime_ms, so the feed's own changed-bytes rule would call every poll news); the internalDataFeed.onChangehook is how the reader learns an answer landed, called outside the feed's lock on the network queue and, headless, beforestart()returns, with both captures weak (a feed holding its own hook never deallocated); a name is looked up once through the provider's geocoding, retried from 60 s rather than the weather's interval, and a lookup that answered with no match setslastErrorto "no place named …" and stops; the headless chain runs on the main thread by hand (the lookup read, then the forecast started from the same thread), because a forecast started from the geocoder's network-queue hook would not believe the headless flag and the export would render empty;Conditionis the openRawRepresentableset over the WMO codes (the raw value is the human word,Condition(code:)and.coderound-trip, an unknown code arrives as "weather code N");Place.sun(at:)is the NOAA low-precision solar model (geometric elevation, refraction left toisUp's -0.833°), checked against a forecast's own sunrise minute and against solar noon on both sides of the equator. The Mac's own location is not read: a bare executable gets no Location Services prompt on macOS 14+ without an embeddedInfo.plist(the-sectcreate __TEXT __info_plistthe reference command-line tool had to add), and embedding one in the hosts may re-attribute their TCC grants, so that half waits for the desk (DESIGN-NOTES.md§ Body data, and where the Mac is). ExampleData/Outside(the sky over Mexico City, the sun from the clock, clouds and rain from the reading);WeatherTests(13) +SunPositionTests(4); no pixel snapshot (the output is values). Guide Ch 42 § The weather outside: Weather + TheWeatherOutside figure.Docs/.Helpers/ Weather .md Audio (
OllinAudiosatellite).AudioAnalyzer(a rolling last-fftSizesample window — Hann + vDSP FFT re-run per chunk, sowaveformis a true rolling window and chunk size never costs resolution) →amplitude/spectrum/waveform/ band queries (bass/mid/treble/magnitude(in:)), plus the draw-shapedbands(_:)(log-spaced, adaptively normalized, attack/release) and beat detection (beatCount/timeSinceBeat/beat/beatSensitivity): spectral flux over log-compressed magnitudes (gain cancels in the log difference, so the threshold is loudness-invariant), peak-picked with the online conditions — trailing local max + an additive margin over a trailing mean (multiplicative-only false-fires on steady material — don't regress it) + a sample-counted refractory — and the whole beat surface on the sample clock (timeSinceBeat= samples, not wall clock), so detection is deterministic + testable. The note heard (pitch/nearestPitch/chroma, forwarded by every source):pitchis aDetectedPitch?(frequency,confidence,nearestPitch,cents, fractionalmidi) from YIN steps 1 to 5 as published (difference function over every lag, cumulative mean normalization, the absolute threshold at 0.1 taking the first dip so an octave low is never reported, parabolic interpolation; step 6 left out), nil under a 0.5 confidence floor (noise reads under 0.2, a chord reads at its common period or nil);chromais twelve classes C first, max-normalized, from the peak form of the pitch class profile (each spectral peak's power lands on the class of its parabola-interpolated frequency; a bin-sum profile leaked half a note's power into its semitone neighbor at this window length, so never regress to it), peaks floored at 1/300 of the strongest so a Hann sidelobe never counts. Load-bearing: the pitch window is set by the lowest pitch (40 Hz → 2×lagMax = 2,204 samples at 44.1 kHz), not byfftSize, so the sample ring is nowmax(rounded up and each window unrolls from its own distance behind the head (RMS stays over the lastfftSize, pitchWindow) fftSizesamples, soamplitude/spectrum/waveform/beats are byte-identical); the audio thread only publishes the window and the reader works it out on first read, once per window (stamped bysamplesSeen, cached underpitchLock, the window copied out ofstateLockfirst so the audio thread never waits on the million multiply-adds), so a source nobody asks costs nothing; neither read is smoothed.PitchTests(11 tests: sines and band-limited sawtooths within 3 cents, a missing fundamental, the tuner numbers, a five-octave sweep with zero gross errors, silence and noise nil, the rolling window, three chroma tests, the long-chunk path); verified red by sabotaging the normalization. ExamplesAudio/Tuner(the bundled violin,--mic, or a path) andAudio/GuitarTuner(the nearest of six strings bymidi, cents against that string's pitch, a pretend guitar through a real analyzer until the mic hears a note, since a running mic hearing a silent room must not blank the face); the FollowingANote figure. Sources:AudioInput(mic),AudioPlayer(file),Tone(oscillator),Soundtrack(any coreAudioTapSource, i.e. a playing video's audio). Headless export is deterministic forAudioPlayer(theHeadlessVideoReadersibling): underisRenderingHeadlessit skips the engine and follows the export clock — aFrameAdvancingsample playhead feeds each frame's slice of the decoded buffer to the analyzer (analyzer runs at the file's rate there, not the mixer's — hardware-independent), so framekreads the file atk/fpsand audio-reactive exports reproduce byte-identically; create the player by the end ofsetup(). Mic/Tone/Soundtrackstay live-only. ExampleAudio/Spectrum;Docs/. A start that waits on the permission prompt is a phase, not a flag (Helpers/ Audio .md AudioInput.Phase,stopped/;asking/ running Cameracarries the same three): the answer belongs to the start that is waiting on it, sostop()under the prompt calls it off and a secondstart()asks nothing. A start the engine refuses takes its tap back out, since the node allows one and a second raises an exception. The engine and the prompt sit behindAudioInput.Deviceand two package statics, and no test opens the microphone.AudioPlayer.play()carries on afterpause()and starts from the top everywhere else (Transport; a file that played out starts over): the live node cannot be asked its position once paused, sopause()reads it first (pausedAt), and that reading runs a render block ahead (about 23 ms, measured).SoundLifecycleTestsholds both players, the live one on a silent file.Synthesis (
Sources/). The playing side:OllinAudio/ Synthesis/ Synth(@MainActor,AudioSource) is a polyphonic instrument a sketch asks for notes (play(/_: velocity: for: after: ) noteOn/noteOff/allNotesOff/play(chord:)), over theVoicevalue type (waveform +Envelope+ optionalVoice.Filter+detune+gain, presets.pluck/.bass/.pad/.bell/.stab/.breath/.sine), pitched byPitch(ExpressibleBy{Integer,→Float, String}Literal 60/60.5/"C4"; MIDI as aDoubleso bends and non-equal tunings have somewhere to land), withDelay/Reverbslots on the output. Load-bearing: the renderer is pure and engine-free (SynthRenderer: events in, buffer out, no clock, no AVFoundation, noise from a per-voice SplitMix), which is what makes the sound testable at all and what a sound-carrying export would be built on — a feature that reaches for the engine from inside it is going the wrong way; the sketch reaches the render thread through a lock-free SPSCEventRingof trivially-copyable events (preallocated slots, two atomic counters, one written by each end, drop rather than wait when full) and continuous values are held in atomics (gainas aDoublebit pattern,activeVoiceCountpublished once per block) — never a lock and never a plain property, the render-thread rule's audio cousin; the render block is built in a free function (the@MainActor-closure SIGILL rule); the effect chain runs in the output's channel layout, not mono (the units reject a format the hardware end does not use, and the failure is a thrown exception, not an error to catch — the bug that killed the example on first run), and the units are wired once and mixed dry rather than attached on demand (rebuilding a running graph gaps the sound); voice stealing takes a fading note before a held one (so a melody over a chord eats its own earlier notes, pinned by measuring the chord's pitch against the held-melody counterfactual) and a stolen voice gets a ~5 ms fade while the new note's attack runs from the level already reached, which is what keeps both ends of a steal click-free; oscillators are PolyBLEP-corrected (triangle by integrating the corrected square at gain4·dt, measured peak 0.80…1.10 across 55…3520 Hz) and the filter is the exact Cytomic trapezoidal SVF (g = tan(π·fc/sr),a1 = 1/(1+g(g+k)), boundedv1/v2/v3tick), chosen because a cutoff that moves every sample must stay where it was asked for and stay stable;Envelopeis the closed form of what is actually played (pinned against the runner to 0.02, one-sample time base) so a sketch can draw the sound it designed. Deliberate v1 cuts: one voice per.level( at: heldFor: ) Synth, no sequencer, no sampler, no 3D placement, no audio in an export.Tonefolded onto the sharedWaveform+ anti-aliased oscillator (its naive saw used to alias). No pixel snapshot (sound);SynthTests(22) pins it behaviorally, andSynthAuditionrenders a listenable WAV underOLLIN_AUDITION(a sound cannot be snapshotted, so the audition render is the figure). ExampleAudio/Synth; Guide Ch 43 § A sketch that plays + Voices figure;Docs/. Per-note expression —Helpers/ Synthesis .md noteOn/playhand back aPlayingNote(@discardableResult, so a sketch that ignores it is untouched) andnoteOff(_ note:)/bend(_:semitones:)/press(_:_:)/slide(_:_:)reach that voice alone, through threeSynthEventkinds carryingnoteIDandamount;pitchBendis the whole instrument's, an event too so an export replays it where it fell. Load-bearing: a voice keeps its basepitchand a separatesoundingpitch (base + its bend + the instrument's), sonoteOff(_ pitch:)'s nearest-note rule still finds a bent note by the pitch it started on; expression glides per block (an 8 ms one-pole stepped once per render insettle), and a value arriving in the same drain as its note-on lands whole (a controller says where the finger is before it says the finger is down); every model cut to length at note-on gained aretunethat keeps the line's contents (WaveguideLine, the string's.setLength delay/eta, the sampler'sbaseStep, the wavetable's increment and level, the patch's increments), called only when the offset moves (tunedTo), while the oscillator readssoundingper sample and the struck body holds (its tones are the strike's);pressis the note's own drive on a driven voice from the first press (hasOwnPressure, else the instrument'spressure) and on any other voice raises the level tostruck + ((1 - struck) * pressureAmount * pressure Voice, 1 by default, applied only to a pressed note, so an unpressed note is byte-identical);.pressureAmount slidescales the cutoff by2^((slideAmount * ( slide - 0.5) * 2) Voice, one octave by default, skipped at exactly 0.5); the synth dedupes each note's last sent values so a per-frame hand-over costs the render thread nothing..Filter .slideAmount SynthExpressionTests(10): one voice bends alone; the handle and the pitch both release a bent note; the whole instrument bends; every model but the struck one follows an octave bend; a press lifts one bow and lands byte-identical at the instrument's own drive; a press raises a struck level 2.5x at velocity 0.4; a slide opens and closes the filter and rests byte-identical; an unexpressed chord is byte-identical with and without identities; an expression sent with its note lands whole. The voice filter's band-pass is unity at its cutoff (k * v1, the normalized band of the trapezoidal state-variable filter) whatever the resonance, so resonance narrows the band and never makes it louder; the bare band output peaked at Q, five times at resonance 0.9 (SynthTests). A full instrument gives up a note that was let go before one still being played, and among the played ones the oldest; a note given a length is being played until its length runs out (.theBandPassIsUnityAtItsCutoffAtEveryResonance claimVoice:isHeldis false for a timed note from its start, so it isremainingthat tells it from a released one). Read as released, the newest timed note went first, being the quietest voice while its attack rises.Algorithmic composition (
Sources/). The note-deciding half beside synthesis, which shapes the sound:OllinAudio/ Composition/ Rhythm(Bjorklund's even spread asRhythm(k, in: n), written-out patterns viaExpressibleByStringLiteral,onsets/intervals/rotated/inverted, 11 named traditional rhythms),Scale(root + intervals,Modecatalog, degrees running both ways past the ends,snap(_:)for a pitch decided by something that is not music,chord(stacking out of the key),on: noteCount: spacing: ) Chord(root +Quality+ inversion +spread(over:)),Arpeggio(a pattern over a chord's notes),MarkovChain<Element>(order-n with backoff,continuationsreading the learned counts back; in the core,Sources/, since it picks colors and lengths as readily as notes, its generator SplitMix64 started one step past the seed so every walk a seed gave before the move comes out the same, pinned inOllin/ Math/ MarkovChain .swift MarkovChainTests;learn(declares a table of counts with no sequence behind it, each call counted as that many occurrences would be, so the counts land under every shorter tail of the context and an unseen context backs off to them, and a table declared in a sequence's own order walks exactly as the learned sequence does; the Kawano recreations are its picture-side customers),_: after: times: ) StepCounter(beats in, step numbers out),Note(pitch + velocity + aNoteLength, played viaSynth), and the two values that know a second,.play( _: tempo: ) Tempo+NoteLength(in the core,Sources/:Ollin/ Math/ Tempo .swift beats(at:)/bars(at:)/seconds(of:)/seconds(beats:)/seconds(bars:)/secondsPerBeatoverbeatsPerMinute+beatsPerBar; the stave names.whole….thirtySecondwith.dotted/.triplet/*/+, a beat being a quarter; both literal-expressible, sotempo: 120andlength: 0.5still read). Load-bearing: every type answers a step number and owns no clock, which is exactly what keeps the tier free ofOllinMIDI(satellites can't depend on each other) and what letstime, a detected beat, and aTempoClockdrive the same pattern unchanged; randomness is seeded per object, never the sketch'srng(Arpeggio.randomis a pure function of step + seed, the halton/brush rule;MarkovChainkeeps its own generator, rewound byreset()); the Markov table is aDictionarybut every decision walks an array (successors in first-seen order,continuationstie-broken by that order) so a seeded walk can never depend on hash order — the determinism rule;.upDown/.downUpdrop both ends of the way back (repeating the turnaround reads as a stutter, pinned across counts 2…6) and.asPlayedis the only pattern that does not sort (a hand-made voicing is otherwise silently re-laddered);StepCounterreturns aRangebecause a frame is longer than a step at any real tempo, fires step 0 on the first call (a pattern starts on the downbeat), re-fires the landing step when time goes backwards (a loop's downbeat), and jumps rather than emptying the pattern into one frame pastmaxCatchUp(themaxTimestepprecedent);Chord.inversionmust not wrap (a full turn is the chord an octave up, a negative one drops notes from the top — the mod-only form silently returned the original); aTempoparameter is never overloaded against aDoubleunder one label (both take a literal, sotempo: 120is ambiguous, verified with swiftc; the tempo-taking calls takeTempoonly, and aDoublevariable isTempo(x)); the conversions keep the examples' own operand order (seconds * bpm / 60,beats * 60 / bpm), so a converted sketch lands on the same step in the same frame, pinned bit-for-bit inTempoTests; a@Paramtempo stores.number(bpm)so every payload consumer (the web controls, the room, the remote inspector, the source write-back) reads it as a number, andParamValue(a defaulted requirement) is what keeps.restored( _: keeping: ) beatsPerBaracross a reload; the MIDI and OSC binders hold a write closure rather than aParam<Double>, which is what letsbindtake aParam<Tempo>;NoteLengthis aParamChoicesmenu of the stave names, and a length off the menu reads as the first entry, the protocol's rule. Bjorklund is written from the paper's construction, and where its two notations for E(7,16) disagree the gap vector is the one the construction gives and the one Ollin follows (Rhythm's maximal evenness — gaps taking at most two lengths differing by one — is property-tested over every k,n up to 32).Scale.Mode/Chord.Quality/Arpeggio.PatternareParamOptions, so a key or a figure is a live parameter. Deliberate cut: no arrangement (nothing holds a whole piece with sections; the sequencer and the arpeggiator below hold a bar and a figure and read the beat handed to them, so a sequencer arrived without the tier gaining a clock). No pixel snapshot (pure CPU values);CompositionTests(35, twin-pair based) +MarkovChainTests(12, inOllinTests: the pinned walk, the declared table against the sequence it was counted from,times, backoff, a long context read by its tail) +TempoTests(12, inOllinTests, the bit-for-bit sweep and the parameter round-trips) + a tempo binding case in each loopback suite +CompositionAudition(a 40 s piece rendered through the engine-free renderer). ExampleAudio/Generative; Guide Ch 44 § Hits spread evenly: Euclidean rhythms withRhythm+ Euclidean figure;Docs/. The arpeggiator's hold keeps every key that went down since all were last up (Helpers/ Composition .md latchedonly grows while a key is held;playingis that chord whilelatchesis on, and switching the hold on takes the keys down now): keys never come up in the same frame, so a hold that followednoteskept the last key alone.Listening: speech and sound events (
Sources/). The audio sibling of the vision trackers, and the tier's input half beside synthesis:OllinAudio/ Listening/ SpeechListenerturns talking into words andSoundClassifiernames everyday sounds, both binding to anyAudioTapSourcethe way a tracker binds to anyFrameSource. No new core seam (the shippedAudioTapSourceis exactly right); what was added is conformance onAudioInput/AudioPlayer/Tone(anAudioTapRelayuses the existing analyzer tap, forwarding the whole buffer as mono, since an analyzer keeps one windowful but a listener transcribing words needs every sample) plus an internalAudioTapHub, one per source (theSourceAnalyzersmirror), which owns the single tap slot and fans out weakly, so aSoundtrack+ aSpeechListener+ aSoundClassifierover one microphone coexist where the old direct-slot grab silently unseated the previous consumer (Soundtracknow routes through it and releases the slot when the last listener goes). Speech is the modern on-deviceSpeechAnalyzer/SpeechTranscriber, notSFSpeechRecognizer, which settles the permission question the design note guessed at: probed, a bareswift runbinary transcribes withauthorizationStatus ==and no prompt (fully on-device, no TCC consent for recognition; the microphone keeps its own, attributed to the launching terminal as always). The result surfaces are picked per question, not inherited: speech gives.notDetermined caption(the running guess, tail included, trimmed tomaxCaptionWords) for drawing,transcript+ the drainingphrases()for acting (the whole point: an uncommitted result replaces the tail because that is what the recognizer is doing to it, so a trigger oncaptionacts on a word that can be taken back); classification gives a level (confidence(of:)/top/classifications) beside a trigger (drainingevents()+ non-drainingtimeSinceHearing(, both on the sample clock), where an event is a crossing from below so a continuing sound fires once and not once per window._: ) SoundClassificationandSoundEventlive in the core (Core/), not in this satellite, because a tethered iPhone's ears (SoundClassification .swift PhoneDevice.sounds, under iPhone capture app) report the same values and the satellites cannot depend on each other. Load-bearing: the recognizer takes a moment to start and audio arriving first is held, not dropped (a bounded 5 s pre-roll flushed in order, since the first words into a microphone are the ones worth hearing) withisListeningthe read for it, distinct fromisAvailable(which is true until something is wrong, model install included); both listeners are live only and say so underOllinApprather than sitting silently empty, with the deterministic one-shots (.isRenderingHeadless SpeechListener/.transcribe SoundClassifierover samples / URL /.classify resource:in:, no default bundle) the way into an export, reached fromsetup()through a new no-argumentwaitFor { }(theOllinVisionsibling; parks the caller, so never from an async context and never touching the sketch inside the closure); the classifier runs off the audio thread on its own serial queue (drop past 4 queued, a classifier being far slower than the audio it judges) while speech converts off it and drops nothing (a dropped block is a missing word); a sample rate of 0 must be rejected beforeSNAudioStreamAnalyzer, which throws an uncatchable ObjC exception on a zero-rate format (a real crash the tests caught).windowDurationdefaults to 1.5 s on measurement, not by feel: swept 0.5...3 s against synthesized tones and taps, 1.0 s is the one setting where a click train reads as a synthesizer (0.60) while 1.5 s keeps taps atclick0.74 and silence under 0.21. A user's own Core ML classifier is in scope (model:/modelAt:an.mlmodelc, theModelTrackerprecedent + the stable-compiled-path gotcha). Deliberate cuts: no per-word confidence, no speaker separation, no wake word, no@Parambinding (a confidence is already a plaindraw()read;@Smoothedif it jitters). No pixel snapshot (a sound cannot be snapshotted):ListeningTests(18) run over audio the tests synthesize, each claim against a counterfactual, and the two end-to-end speech checks speak to themselves throughAVSpeechSynthesizerso nothing recorded is committed. Gotcha that made both speech tests pass vacuously at first: the synthesizer delivers on the main queue, so the caller must let the main thread go (await in an async context, pump the run loop in a plain synchronous one like a figure's.write setup()); blocking on a semaphore collects zero frames and the test soft-skips silently. ExampleAudio/Listening; Guide Ch 41 § Words, and what that noise was: speech and sound events + the Listening figure (figure: unstable, both models being the system's: four real transcriptions of growing prefixes of one spoken sentence, the third of which is confidently wrong, beside three arithmetic sounds and what the classifier called them);Docs/. Everything a listener starts is in the listHelpers/ Listening .md stop()cancels, the installing notice included, and what a called-off preparation returns is dropped: a listener stopped within its first half second used to go on and report a model installing. The preparation sits behindSpeechEnginefor the test that holds it open..prepare MIDI files (
Sources/+OllinAudio/ Composition/ MIDIFile .swift MIDIFileReader+.swift MIDIRecording.swift). Standard MIDI Files read and written, from the MIDI Association's specification (no vendored reader):MIDIFilecarriesformat(.oneTrack/.parallelTracks/.separatePatterns),division(.perQuarter(n)or.perSecond(),framesPerSecond: ticksPerFrame: ) name,tracks,tempoChanges,timeSignatures,markers;MIDIFile.Trackisname/channel/program/notes/controls/bendswithisEmpty/lastBeat. In throughinit(contentsOf:)/init(/resource: withExtension: in: ) init(data:), out throughdata()/write(to:)(a String path, the house rule), built from notes byMIDIFile(. Reading across the piece:_: tempo: name: channel: ) notes,notes(from:to:),lastBeat,duration,tempo,tempo(at:),timeSignature(at:), and the tempo map from either side,seconds(at:)/beats(at:). ASynthwrites down what it is asked to play (startRecording(/tempo: name: ) stopRecording()/recordedSoFar()/isRecording), tapped at the singleemitfunnel so a take catches the same notes live or under an export. Load-bearing: it lives inOllinAudio, neverOllinMIDI, because a file arrives as music (its notes areScheduledNotes, soSynthtakes them with nothing in between) and satellites cannot depend on each other; a track plays on one channel (a chunk using several splits into one.play( _: tempo: from: ) Trackper channel, in first-appearance order, which is what makes the common format 0 file useful and what makes the write side exact); the first chunk of a parallel-track file is the tempo track (absorbed into the file's own map on read when it holds no channel event, so a round trip keeps its track count); note pairing is FIFO per channel and pitch (a pitch struck again before its first release pairs oldest-first;oneNoteStruckTwiceIsLetGoInTheOrderItWasStruckpins it) and anything still sounding is let go at the track's end; running status is the reader's one place a byte is pushed back (its rule releases at velocity 64, never 0, or a run read as the wrong kind still comes out right by being a note-off in the other spelling, which is how the first version of that test passed under sabotage); a meta payload is taken as its own array, since a slice keeps the file's indices and reading it from 0 traps; a note-on of no loudness is a note-off both ways, so the quietest note written is 1 of 127; a tempo is whole microseconds in a quarter note (120 and 96 exact, 112 a ten-thousandth off, so tempos compare with a tolerance) and the default 960 ticks divides by three, so triplets and swing survive;beats(at:)andseconds(at:)walk the map rather than dividing by one tempo, and are exact inverses; a film-timed file converts through seconds with the map integrated over it. Read and written: notes, control changes, bends, programs, track names, tempo, time signatures, markers. Read and stepped over: aftertouch, system exclusive, key signatures, the rest of the meta set, and any chunk whose kind is unknown (skipped by its own length, as the format says).MIDIFileTests(21) +MIDIRecordingTests(5); four sabotages verified red (the pairing order, the continuation bit, the borrowed status, and a missing end-of-track event). The outside reader is the test our own reader cannot be:somebodyElsesReaderAcceptsWhatWeWroteloads a written file throughAVMIDIPlayer, Apple's own parser, and holds it to the same duration (25 ms apart on the example's piece, tempo change and all) — drop the end-of-track event and every other test here still passes while that one alone goes red, which is exactly the class of defect a reader that wrote the bytes forgives. No pixel snapshot (the output is bytes). ExampleAudio/MIDIFiles(eight bars composed, written, forgotten, read back, and everything drawn and heard after that comes off disk); Guide Ch 44 § Music that travels between programs: MIDI files + the MIDIFileFigure;Docs/.Helpers/ MIDIFiles .md Sonification (
Sources/). Numbers read out as notes, the reading half beside the deciding half:OllinAudio/ Composition/ Sonification .swift Sonificationis a value type spreading a series over a pitch range, snapped through aScale, read by[step]/note(at:)/notes()/pitch(for:)— it answers a step number and owns no clock like the rest of the tier, soStepCounterdrives it. Four sources, one call each:[Double],Tablecolumn,Heightfieldrow:/column:/from:to:count:,Imagerow:/column:(luminance). Parameters:in scale:,pitches:(default"C3"..."C6"),bounds:(.extremes/.robust(ignoring:)/.fixed),polarity:,noteLength:(aNoteLength,.sixteenthby default), plusamplified(by:)/inverted()/reference(at:). Written from the published technique (Grond & Berger, The Sonification Handbook ch. 15; credited inATTRIBUTION.md, never in.swift). Load-bearing: pitch is spread linearly in MIDI note number, never in hertz (hearing is logarithmic, so an even-in-hertz spread crushes the bottom half of the data into the top of the range — the figure draws both, andpitchIsSpreadEvenlyInSemitonesNotInHertzpins the two mappings far apart so the test can't pass by accident), and loudness linearly in decibels (velocity = 10^(, so the floor is a real fraction rather than silence) — both are the perceptually linear units, which is what makes a linear transfer function correct; loudness does nothing unless asked (dB/ 20) loudness == nil→ every note at full level) because how loud something sounds depends on how high it is, so it is for a second series, not for saying the same thing twice;.robustuses interpolated quantiles (one outlier at 1000× otherwise flattens a whole series into one note — pinned against its.extremestwin at span <1 vs >30 semitones); values outside the domain are held at the ends, a flat series reads at the middle (no divide by zero), and an empty one plays nothing; the reference tone is the published grid-line idea (without it a listener needs absolute pitch for a note to mean anything) and lands exactly where that value would in the reading. No rng anywhere, so a reading is a pure function and an export repeats.SonificationTests(20, exact values + twins);SonificationAudition(four takes of one landscape row: chromatic / snapped / inverted / with a reference). ExampleAudio/Sonification(a terrain profile drawn and read out at once, playhead on the sounding note); Guide Ch 44 § Numbers you can hear: sonification + Sonification figure;Docs/.Helpers/ Sonification .md Composition polish: progressions, tunings, following a beat (
Sources/+OllinAudio/ Composition/ Progression .swift ChordSymbol.swift+Tuning.swift+BeatFollower.swift). Four of the five gaps the Composition page listed as not here yet, all pure values answering a step number and owning no clock like the rest of the tier.Progressionis a cycle of chords written as scale degrees, not names (roman numeralsI…VII, case ignored, any separator), so the qualities fall out of the key and the same four numbers are major or minor with nothing changed;pitches(at:)/degree(at:)/root(at:)/chord(at:)/transposed/rotated, named set (.pop/.fifties/.twoFiveOne/.blues/.andalusian/.circleOfFifths), andwandering(over a_: order: seed: ) MarkovChainlearned round the loop (loops: true, so the last chord returning to the first is a move) and seeded per call, never the sketch's rng.Chord(symbol:)+ExpressibleByStringLiteralparses chord symbols (root / accidentals / quality //bass); load-bearing: the quality is tried on the whole suffix before a trailing number is read as an octave, orCmaj7strips the 7 and becomes major in the wrong register (the bug the tests caught), and a bad symbol is nil frominit(symbol:)while the literal notes once and lands on C major (thePitchprecedent).Progression(/symbols: ) Progression(set the parallel[Chord]) writtenstore, so a progression is either degrees-in-a-key or named chords, andcount/pitches/root/rotated/transposedhonor both.Tuningis theScalesibling for pitches described by ratios and a period rather than semitones ([degree]/snap/cents/frequency/rooted(at:),.equal(_:period:)+.just/.pythagorean/.quarterTones/.nineteen/.thirtyOne/.bohlenPierce): ratios fold into one period and dedupe within 0.01 cent, degrees run past both ends, and becausePitch.midiis aDoublea non-twelve degree simply lands between the keys. Deliberate:Scaleis untouched and stays twelve-tone (a tuning is a separate type, not a setting, so nothing existing changed) and chords are not built out of one.BeatFollower+ the pureBeatEngine(theTempoClock/TempoEnginesplit: onset times in, musical time out, testable by handing it a beat) turn detected onsets intobeatsaStepCounterruns on, plustempo/steadiness/rhythm(steps:). Load-bearing: a tempo outside the believable range is halved or doubled until it lands inside (a detector firing on every eighth reports twice the tempo, which is the same music), the tempo is the middle of the recent gaps, never the average (one missed beat doubles a gap, which moves an average and not a middle), and the position re-anchors to the nearest whole beat on each onset so a missed one costs nothing.ProgressionTests(31, exact values + twins) +ProgressionAudition. ExamplesAudio/Changes(degrees) +Audio/ChordSymbols(the symbol path, typed into a text parameter) +Audio/Tunings(all seven, a triad held while the cents ladder shows what moved) +Audio/PlayAlong(a generated pulse standing in until the microphone is allowed); Guide Ch 44 §§ Chords that come out of a key:Progression/ Other divisions of the octave:Tuning/ Playing along with the room: tempo sync;Docs/.Helpers/ Composition .md Step sequencer and arpeggiator (
Sources/+OllinAudio/ Composition/ StepSequencer .swift Arpeggiator.swift+ScheduledNote.swift, over a wait inSynthRenderer).StepSequenceris a bar ofSteps (pitch or rest,velocity,probability,ratchet) withrate/swing/gate/seed/maxCatchUpon the bar, written out as a string literal ("36 . . 36";init?(pattern:)is nil on a bad token and the literal notes once and lands empty, theRhythmprecedent), from aRhythm+ one pitch (a drum lane), or empty to fill in;Arpeggiatoris the liveArpeggio(the figure recomputed fromplaying, which isnotesor thelatchedset),hold/release/notesset per frame,figure/next/nextStepfor drawing; both answer beats and own no clock (aStepCounterinside, so the tier's rule holds) and hand backScheduledNote(aNote+beat+step), whichSynthplays:.play( _: tempo: from: ) from:is where the music is now, so a note whose beat is ahead waits to the sample, andnilplays everything with the frame (where every other call lands). Load-bearing: the wait isSynth, a.play( _: velocity: for: after: ) delaySamples/delaySecondspair onSynthEvent: live, the renderer parks a delayed event in a fixed 256-slot pending store (no allocation on the render thread; past capacity an event lands at once, never late) and starts it inside the block on its own sample (one compare a sample while nothing waits), settling the fresh voice itself since the block's settle has already run;allNotesOffdrops pending notes (a waiting note is more held than a tail); in an export the wait is folded intoRecordedNote.atand the fields zeroed so the renderer cannot count it twice, andrecordinserts by place, not on the end, since a waited note can be asked for before an earlier-landing one; the look-ahead is the sketch's:events(upTo:)with the beat at the end of the frame andfrom:with the beat now, the pair the Docs teach, becausedeltaTimeis exactly1/fpsunder export and the measured frame live, and only that pair lets a swung offbeat land off the frame grid (at 120 bpm a frame is 17 ms and the shuffle's move is 42). Swing moves only the odd steps, by(2·swing − 1)·rate, so downbeats hold the grid; a ratchet subdivides the nominal step (not the swung interval) and thegateapplies per strike; probability is a pure hash of (absolute step, seed) (StepTiming.plays, theArpeggio.randommixer, top 53 bits), never the sketch's rng, so a bar replays; the arpeggiator's cursor is an index into the figure that restarts only on a chord after silence (notesempty → non-empty) and otherwise keeps its place modulo the new count (a note added joins the ladder on the next pass, no stutter, no restart, pinned),.randomreadsfigure[step]instead; a rate change re-anchors the counter at the last position throughreset(to:), so no burst and no skipped stretch. Verified on a rendered sample (SequencerLaws): a bar through the export path at 120 bpm has onsets alternating 4/3 and 2/3 of a sixteenth at swing 2/3 within 2 samples, downbeats unmoved, and a ratchet of three a third of a step apart; the renderer tests pin waits of 0 / 100 / 511 / 512 / 1000 / 5000 samples landing exactly, and a test that reads a whole bar in one call must raise.aSwungBarIsHeardWithItsOnsetsWhereTheNumbersSay maxCatchUp(the counter's stall rule fires at sixteen).SequencerLaws(25: twelve sequencer, nine arpeggiator, three renderer, two export). ExampleAudio/Sequencer(click a cell to toggle it); Guide Ch 44 § Steps with a feel: the sequencer and the arpeggiator + the Sequencer figure (taught);Docs/+Helpers/ Composition .md#stepsequencer #arpeggiator;Docs/for the wait.Helpers/ Synthesis .md Physical models: the plucked string (
Sources/+OllinAudio/ Synthesis/ PluckedString .swift StringVoice.swift). A voice worked out rather than drawn:VoiceSource(.wave(Waveform)/.plucked() is now what aPluckedString) Voiceis built from, withwaveformkept as a computed view over it so every existing call site, preset, doc, and example is unchanged;PluckedStringcarries the four controls a player has (pick/hardness/decay/damping) with presets.nylon/.steel/.harp/.muted(andVoicepresets of the same names), andEnvelope.pluckedis the stay-out-of-the-way gate the string's own fade runs under. The render side is the extended Karplus-Strong loop: delay line → one-zero loss filter → first-order tuning allpass → loop gain. Load-bearing: the loop must come out exactly one period long, so the loop filter's own delay (shade, which is its coefficient) is subtracted from the budget before the integer split and the allpass supplies the rest — which is whydampingcannot move the pitch (pinned by a twin pair differing only indamping; the analyticsoundingFrequencyis within 0.01 cents across MIDI 21…105 where rounding the loop would be >40 cents out at the top); the integer part isfloor(so the fraction lands in [0.2, 1.2), the range where a first-order allpass is well behaved (a fraction near zero puts its pole on the unit circle); the excitation is built in a scratch half of the buffer, because the pick-position comb reads the burst it is overwriting, and the comb wraps circularly so its notches land on the harmonics rather than near them; the burst must be written where the first read will reach it (remaining − 0.2) write = count, not 0 — leaving the write head at the start points it at the empty tail and the string is silent, the bug that shipped nothing at all until a probe caught it); velocity multiplies into the excitation's bandwidth as well as its height (playing harder is brighter, the dynamic-level filter's actual musical job); every string's delay line is one allocation taken inSynthRenderer.init(raw memory, theEventRingprecedent) sized bylowestStringFrequency(16 Hz), since the render thread may not allocate, and a note below it plays sharp rather than outrunning the buffer;detunegives a second string, symmetric with the oscillator path.SynthEventstays trivially copyable (PluckedStringis fourDoubles), which is what lets a voice change be sent through the event ring. No pixel snapshot (sound);PluckedStringTests(11, twin-pair based: pick position vs the even harmonics, hardness and velocity vs the spectral centroid measured at the note's own harmonics rather than on a fixed grid, decay vs level at one second, damping measured above 4 kHz because a one-zero loss removes almost nothing near the fundamental) +PhysicalModelAudition.decayis the fundamental's T60 at every pitch (loopLoss, shared with the bow): the loop gain is the per-trip target divided by the one-zero's response at the note, and where the target exceeds what the filter alone allows under the 0.99999 cap, the coefficient is eased to the value whose response is exactly the target (Jaffe and Smith's decay stretching), so the top harmonics there fade closer to together; within 10% from MIDI 33 to 93 on steel, nylon, and harp (SoundInvariantTests), where the uncompensated loop rang a sixth of the steel's 3.6 s at MIDI 93; pitch unmoved (the eased coefficient stays the filter's delay in the budget, within the tuning test's cent). Example.aPluckedStringRingsForItsDecayAtEveryPitch Audio/Strings(click a string where you want to pluck it; the drawn shape is the modal sum that pluck excites, which is the same fact as the comb); Guide Ch 43 § A string worked out sample by sample: the plucked string + PluckedString figure;Docs/.Helpers/ Synthesis .md#physical-models Physical models: the struck shape (
Sources/+OllinAudio/ Synthesis/ ModalBody .swift ModalShape.swift+ModalVoice.swift). Modal synthesis, and the reason it earns its place:StruckShape(measures a drawn outline and_ shape: Shape, modes: resolution: ) body(hands back astruckAt: decay: damping: hardness: ) ModalBody(.drum/.plate/.bar/.bell/.wood/.glass;Voicepresets.drum/.bar/.chime/.glass), so a shape a sketch drew rings at the frequencies its own geometry allows. The frequencies are the Dirichlet eigenvalues of the Laplacian on the shape (a membrane held at its rim), solved by measuring the outline onto a grid then banded Cholesky + subspace iteration with Rayleigh-Ritz + cyclic Jacobi on the small projected problem, all written here (no LAPACK interface). Load-bearing: the model is verified against physics, not itself — a circle returns the Bessel-zero ratios (1, 1.593, 2.136, 2.295…) and a square √((m²+n²)/2) to under 0.5%, which is whatModalBodyTestspins; a symmetric shape returns its tones twice (a pattern that fits at one rotation fits at another) and that is correct, not an artifact, so a gain readback must sum over a degenerate pair (which member takes the strike is arbitrary; the sum is the invariant, and the first test draft failed exactly here);ratioscome out scale-free (the grid spacing cancels), so size never changes the instrument, only the note does;ModalBodystores its modes inSIMD16<Double>pairs, not an array, becauseVoiceis carried inSynthEventthrough the lock-free ring and a heap reference would refcount on the render thread (hencemaxModes = 16, andmodesis a computed view); a tone landing above Nyquist is dropped, never folded (it would arrive as something that was never struck); each resonator's input is scaled by sin(its own angle) so every tone comes out at the gain asked for rather than at whatever its frequency gives, and the strike is divided by the summed gains so sixteen tones are not sixteen times as loud; the excitation is a raised-cosine push whose width ishardness(a wide one reaches only the low tones), divided by its own area so hardness is the color of a strike and never its level: the push is 12 ms of contact at 0 and two samples at 1, and undivided it was its length in samples times too loud, so every preset but.woodsat on the renderer's soft clip at its attack (the bell above 0.95 for 56% of its first second, glass 92%, the drum 6%) and the clip's intermodulation put lines at 1.4 and 3.4 times the note 7 dB under the bell's prime; divided, the bell peaks at 0.58 with those lines over 50 dB down, and the loudness is off the sample rate (within 3% between 44.1 and 48 kHz). The division also showed the presets had been tuned under the clip: at the bell's old hardness 0.6 its octave sat 30 dB under its declared gain and the glass lost its fundamental an octave up, so the presets strike hard (bell and bar 0.9, drum, plate, and the default 0.85, glass 0.8, wood 1), each ringing its declared partials within about 3 dB at MIDI 60 to 72 (the bar's and wood's top partials read lower only because the window outlasts their decay), and the four struckVoicepresets carry gain 1, peaking at 0.46 to 0.57 at velocity 0.8 beside.pluck's 0.67 (aStruckBodyIsASumOfTonesover six presets,aSofterStrikeIsDarkerAndNeverLouder);resolutiondefaults to 40 because accuracy plateaus there (measured: 28 → 1.11% error, 36 → 0.34%, 64 → 0.22%, at 0.9 s / 1.7 s / 8.8 s in a debug build and 0.01…0.07 s in release), and the solver's hot loops run over raw pointers on flat storage for exactly the unoptimized-build reason the point-cloud work documents.StruckShapeexists because striking must be free — it keeps the eigenvectors so a new strike point is a lookup, whereModalBody(shape:)re-measures every call (pinned equal to each other). No pixel snapshot (sound);ModalBodyTests(19) +PhysicalModelAudition. ExampleAudio/StruckShapes; Guide Ch 43 § A shape you can hit: modal synthesis + StruckShapes figure;Docs/.Helpers/ Synthesis .md#physical-models Sampled instruments (
Sources/+OllinAudio/ Synthesis/ SampledInstrument .swift SFZ.swift+SamplerVoice.swift). The one source that is recorded rather than worked out:Synth.instrumentholds aSampledInstrumentandVoice(says how to play it, read from SFZ (the text format free libraries ship in) or fromsampled: Sampler) Recordings in hand. Load-bearing: the recordings live on theSynth, never inside theVoice— aVoiceis carried inSynthEventthrough the lock-free ring and must be copyable a word at a time (the constraint that capsModalBodyat 16 andPatchat 8), and megabytes of heap cannot be carried along, soSamplercarries only numbers (_isPODpinned) and the instrument is set separately; the read head is linearly interpolated (nearest-sample stepping is an audible grainy edge on every note not at its recorded pitch, which is most of them) and moves at2^(, so pitch and length move together like a tape; the nearest recording wins where several cover a note (moving a recording far is the one way a sampler audibly goes wrong and the one thing choosing well avoids), and a note outside every range is stretched from the nearest rather than silent; an unknown SFZ opcode is skipped, not refused (the format has hundreds this does not model, and a library using them should still load), a missing audio file costs that part of the range not the instrument,semitones/ 12) × recordedRate/ playRate <group>/<global>opcodes are inherited, note names read either way round (60orf#3), and Windows backslash paths are turned round; the renderer stops applying velocity to a sampled voice becausevelocitySensitivityis the sampler's own setting and would otherwise be scaled twice (0 = as loud as recorded, for an instrument whose recordings are already its dynamics) — scoped to.sampled, every other source unchanged. The bundled instrument is generated, not sourced (Scripts/, a free-free bar's inharmonic ratios at five pitches, 384 KB,make-sample-instrument .swift .copyresource): Ollin's own, no third-party license, noTHIRD-PARTY-NOTICESentry. Docs list where to get real libraries with their license tiers — CC0 (VCSL, VSCO 2 CE, Iowa) bundlable, Freesound per-clip, and Philharmonia free to make music with but explicitly not redistributable as a sampler instrument. Every loader throws (SampledInstrument(/sfz: in: ) (contentsOf:)andGrainSource(/named: withExtension: in: ) (contentsOf:):AudioError/.resourceNotFound .couldNotDecode/.empty, one vocabulary withAudioPlayer's), where they returnednilbeside a printed note; the bundledbuiltInstays Optional with a developer note, since a framework resource missing is a broken build.SamplerTests(17). ExamplesAudio/Sampler(five recordings against one stretched, which is not a subtle difference) +Audio/OwnSampler(SampledInstrument(over a three-region map and recordings generated beside the sketch, the loop region drawn on each); Guide Ch 43 § An instrument somebody recorded: sampled instruments;sfz: in: ) Docs/.Helpers/ Synthesis .md#sampled-instruments Granular synthesis (
Sources/+OllinAudio/ Synthesis/ GrainCloud .swift GrainVoice.swift). Grains cut out of a sound and piled back up:Synth.grainSourceholds aGrainSource(samples, aSampledInstrument, an audio file, or a drawn.Recording Waveform;.builtInis the bundled struck bar) andVoice(says how to cut it, overgranular: GrainCloud) size/density/position/positionJitter/speed/pitchSpread/panSpread/scatter/shape/seed, with presets.cloud/.smear/.rain. The whole claim is two clocks where every other source has one: the grains are read at the note's pitch (by2^(semitones/12)times the rates' ratio, from the source'srootKey) while the read position travels atspeedalone, so pitch and time are separate (theNotesPitchMovesTheGrainsAndNotTheTravel, verified red by making the travel follow the pitch as a sampler's does) andspeed: 0holds a moment for as long as the note lasts, dragged live bySynth.grainScrub(an atomic read every sample, thepressureshape, in source lengths added to where each note has reached). Load-bearing: the sound lives on theSynth, never inside theVoice(the_isPODconstraint, as for the sampler and the wavetable), and a cloud with none set reads.builtIn, the rule.basickeeps for a wavetable; every grain's state is raw memory the renderer owns (GrainSlot, one block per voice taken ininit) with sounding grains packed at the front so the sample loop walks only what sounds, and the envelope is a table built atGrainVoice.warm()from the renderer's own setup, since astatic lettouched first by the render thread is an allocation there; a note may have 48 grains sounding and drops past that rather than waiting (the event ring's bargain); the sound wraps rather than running out (position 1 is position 0, and a grain reaching the end reads the start, since stopping would cut its envelope and click); onset gaps blend regular to exponential byscatterwith the mean preserved either way, so scatter changes the texture and not the loudness, and at 0 a frozen cloud is periodic at the density, a pitch of its own;.tick/.swellhave their exponential floor taken out so a grain ends at nothing (a hundredth at the end of a grain is still a click, and there are a great many grains);detuneshifts alternate grains rather than running a second cloud.panSpreadis why the renderer gained a second channel (render(): a block with nothing panning takes the one-channel path and writes it to both, and the scaling is spelled out per channel rather than through a shared factor because the two multiplication orders do not give the same bits — pinned byinto: right: frameCount: ) nothingPanningRendersTwoChannelsAsOneover a cloud, a wave, a string and a struck body (verified red), and by the whole 425-test audio suite passing unrecorded; pan is equal power scaled so the middle is unity, a panned cloud needs its own right-channel filter (one filter carries one stream's memory), and a placedSynthis one stream by definition so the spread folds back to the middle. A scrub made while an export's frames go by is written down and replayed (aRecordedControl, with the level and the pressure; the Spatial audio and sound in an export bullet has the rule) or an exported drag comes out frozen (aDragMadeWhileTheFramesWentByIsInTheFile, verified red).GrainShapeand.level( at: ) Synth.grainCountare the read-backs a sketch draws with (Envelopeand.level( at: heldFor: ) activeVoiceCountprecedents). Written from Roads's Microsound and Gabor's acoustic quanta, credited inATTRIBUTION.md.GrainCloudTests(21: one grain the source sample for sample through a plateau's flat middle, RMS as the square root of density, a frozen spectrum against a traveling one, a scrub moving a sounding note, the loop, backward, the two clocks, pitch spread widening the peak, the clocked line, the two-channel rules, the seed) + 2 inSoundExportTests;GrainCloudAuditionwrites a two-channel WAV underOLLIN_AUDITION. ExampleAudio/Grains; Guide Ch 43 § A sound in pieces: grains;Docs/.Helpers/ Synthesis .md#grains Effects as a chain (
Sources/+ the wiring inOllinAudio/ Synthesis/ Effect .swift Synth.swift/SynthExport.swift). The output side of routing-as-a-value, closing the symmetry the patch tier opened:Synthis an ordered chain (.effects: [Effect] .delay/.reverb/.equalizer(/Equalizer) .distortion() replacing the two fixed slots. Load-bearing: order is the feature (a distorted echo and an echo of a distorted sound are different, pinned by exporting both and diffing);Distortion) delay/reverbsurvive as computed views over the chain (read the first of that kind, write replaces in place or appends, nil removes — replacing must not walk an effect down the chain, pinned) so every existing sketch is untouched; the graph rebuilds only when the sequence of kinds changes (wiredKinds), so a setting change never disturbs the wiring; the rebuild happens on the running engine without stopping it, which is a measured decision, not an assumption — probe: reconnecting while running throws nothing and costs 1 sample, stopping first costs the same 1, and a pure parameter change also shows 1, so the "gap" is the test tone's zero crossing and there is no gap at all (this reverses the old "wire once and mix dry, rebuilding a running graph gaps the sound" comment, which was never measured); every unit kind chains at the output format without throwing (probed, since AVFoundation refuses formats by throwing at connect time); the live and placed paths now share onerebuildEffectChain(hanging off) chainHead(the listener once placed, the source otherwise), andOfflineRenderbuilds the same chain from the same list or an export would run different effects from the ones the sketch was heard through (the stage-1 lesson).Delay/ReverbgainedCodableandSynth.configurebecamenonisolatedso anEffectcan be a value. Deliberate cut: the chain is per instrument, not per note.EffectChainTests(13). A built-in room loads as the unit'scurrentPreset, neverloadFactoryPreset, which on macOS 27 names the room and leaves every parameter at the unit's default (the four rooms were one medium hall, live and in an export;theBuiltInRoomsAreFourRoomsdiffs all six pairs). The echo is a line of Ollin's own on the closure unit (Delay.swift,DelayEffect), never the system's delay unit, which held 2 s, landed each repeat a sample late, and clicked when its time was turned (a step of 0.52 on a tone of 0.5, measured 2026-11-11):Delay.timeis held to0...Delay.maxTime(60 s) at init and again where it is read; the read is a whole number of samples behind the write, so a repeat lands on its sample at any length (aRepeatLandsOnItsSample, and through the export inaDelayWaitsAsLongAsItsTimeSays); the loop is the system unit's measured one, one pole atdampinginside the loop (1 - exp(, taken out at 20,000 Hz and above), so an existing echo sounds as it did; a turn of-2 pi f / rate) timecrossfades between two reads over 30 ms; the line's length comes in tiers (2, 4, 8, 16, 32, 64 s, the first that holds the time asked), and a time past the standing line builds a longer one that reads the old line for everything written before it began (previous, adopted on the audio thread, let go from the main thread only after the audio thread has reported the new line full under the lock), so nothing in flight is dropped and nothing is copied or freed on the audio thread.DelayTests(13). The five distortion characters are curves of Ollin's own on the closure unit (Distortion.swift,DistortionEffect,DistortionCurve), never presets of the system's distortion unit, none of which did what its name says (measured 2026-11-11 with a tone:.softClipwas an echo 357 ms behind,.overdrivesounded the octave three times louder than the note,.bitCrushwas a 90 Hz ring with a 28 ms slap,.ringhad no ring in it,.squeezewas the ring): the soft clip istanh(g x) / tanh(g)(odd harmonics only, full scale kept), the overdrive a three-piece hard clip read off center with a DC block after it (even harmonics too, its far side scaled to full scale), the bit crush a mid-tread staircase plus a sample hold (6 dB of drive doubles the step, 12 halve the rate; 6 bits at 11,025 Hz at the default), the ring a 300 Hz sine times the sound held within full scale, the squeeze a band at 1,200 Hz either side of a soft clip. Every curve is memoryless or nearly so: 50 ms after a click all five are silent, and silence in is silence out (the staircase has a step at zero). The gain into a curve is10^(times the character's own factor (2 for the soft clip, 4 for the overdrive and the squeeze, 1 for the ring), so the default drive of -6 dB is a round number in each. At mix 0 the block returns before it touches a sample, so the sound passes to the bit. The curves run at the chain's rate with no oversampling (filed in( drive + 6) / 20) DESIGN-NOTES.md).DistortionTests(15). ExampleAudio/Patching(the finish parameter, whose last two options differ only in order); Guide Ch 43 § After the note: the effects chain;Docs/.Helpers/ Synthesis .md#effects An effect of your own (
Sources/+ theOllinAudio/ Synthesis/ CustomEffect .swift .customcase inEffect.swift). The chain's seam for an effect the sketch wrote itself:Effect(plus the.custom( name) { AudioBlock in } state:form, whose memory comes backinouton every block) goes inSynth.effectsbeside the built-in kinds, anywhere in the order, and reaches the live chain andOfflineRenderalike. Load-bearing: the unit is an in-process registered audio-unit subclass (ClosureAudioUnit, instantiated inline like the built-in units) and the closure is the setting, not the wiring —apply(to:)swaps the runner on the standing unit, so replacing one custom effect with another never rebuilds the graph (a new effect does start with freshstate:); a connection touching the custom unit must name the chain's format outright — both chain builders pass the explicit format there — because left toformat: nilthe engine keeps the unit's declared bus format and silently resamples around it (measured: sample-exact at 1.5e-8 with the format named, worst-sample 0.82 off without); the render block takes the pull buffer'smutableAudioBufferListonce and sizes that same pointer (each property access re-derives sizes from the zero frame length, and the engine refuses a zero-sized pull with -50); the user closure must be@Sendable(so it can never be main-actor-isolated, per the render-thread rule) and runs inside the runner's unfair lock (no reference counting on the render thread; a runner placed twice in one chain serializes on its own state), which is also whystate:is the sanctioned memory — a@Sendableclosure cannot write into a capture; equality is by runner identity, andCodabledecodes to a passthrough that keeps its name (a closure cannot be written down).AudioBlockhands overleft/right(the same channel on mono),frameCount,sampleRate, andtime(rendered frames since allocation, so an export's clock starts at zero).CustomEffectTests(8: per-channel asserted as a relationship, order, block-to-block memory, the 48 kHz rate gate, the passthrough decode, the in-place swap) plus the widenedEffectChainTests. ExampleAudio/Shaping(a wavefolder, astate:crush, atimewobble behind one parameter); Guide Ch 43 § An effect nobody wrote for you: custom effects;Docs/.Helpers/ Synthesis .md#an-effect-of-your-own Convolution reverb (
Sources/+OllinAudio/ Synthesis/ Convolution .swift PartitionedConvolver; the.swift .convolutionkind inEffect.swift).Reverb(plays the instrument through animpulse, mix: , preDelay: ) ImpulseResponse: a recording (.load(path)/.resource(/_: withExtension: in: ) init(contentsOf:), each throwingAudioErroror the system's own error for a file it cannot open andAudioError.emptyfor one with no sound, where they returnednilbeside a printed note until 2026-09-22; the first two channels kept, cut atmaxSeconds= 20), fading noise (.decay(: sixty decibels over the length, a one-pole whose cutoff falls with time for the damping, the filter's own RMS loss undone so the fade is the fade asked for), or a rule (seconds: damping: sampleRate: seed: ) init(, two seededseconds: sampleRate: seed: ) { time, noise in } SplitMix64noise streams so a drawn room has width), plusreversed(). Load-bearing: the reverb uses the existing.reverb(Reverb)case (sosynth.reverbstill reaches it, and aReverbwritten down before rooms existed still decodes) but reads as its ownEffect, since it runs on the.Kind .convolution ClosureAudioUnitrather thanAVAudioUnitReverband the chain is rebuilt by kind; thedelay/reverbviews therefore match by case, not kind (a built-in room set over a drawn one must replace it in place, pinned).Effectcarries the chain's rate (.apply( to: sampleRate: ) Synth, read off the head's format at rebuild; the export passes its own), because a room is prepared for a rate: resampled through.chainSampleRate AVAudioConverterwhen the file's differs (a click lands within two samples of where it should), pre-delayed, capped, and normalized to unit energy across the sides somixmeans one thing for every room. The engine (ConvolutionReverb) is kept on the unit across setting changes (ClosureAudioUnit;.room serves(_:at:)compares impulse, pre-delay, rate) so a mix turn never cuts a sounding tail, the mix crossing to the audio thread as a float under a lock.PartitionedConvolveris uniformly partitioned overlap-save at 256 samples with a direct time-domain head (vDSP_convrun backward over the response) and the tail's partitions in a frequency-delay line; the tail's one-partition buffering delay is exactly the offset its taps carry, so the whole is latency-free and exact at any block size (pinned against the double-precision sum to 1e-5 in blocks of 1 to 4096; the packed DC/Nyquist pair multiplied as reals, the rest throughvDSP_zvmaping-ponged between two accumulators since it is not in-place; the inverse of a product of two forward transforms scales by1/(4N)). A ten-second room measured 2.7% of real time per side in release. The export is pinned to be the dry export convolved with the prepared room, sample for sample.ConvolutionTests(18) +ConvolutionAudition(OLLIN_AUDITION);Examples/;Audio/ Rooms Docs/§ A room of your own; Guide Ch 43 § A room you can draw: convolution reverb.Helpers/ Synthesis .md The four that move (
Sources/; theOllinAudio/ Synthesis/ Modulation .swift .chorus(Chorus)/.flanger(Flanger)/.phaser(Phaser)/.tremolo(Tremolo)cases inEffect.swift, each its ownKind). One slow wave and the thing it moves, written from the textbook definitions: a chorus reads a copy 20 ms behind sliding ±6 ms·depth(the two sides a quarter turn apart, so it is wide by itself); a flanger reads a copy 1 ms to 7 ms·depthbehind withfeedbackwritten into the line, so held still it is the comb0.5 + 0.5·e^{-iωD}; a phaser runsstagesfirst-order all-passes (y = a·x + x₁ − a·y₁,a = () whose corner sweeps from 200 Hz up bytan( πf/ fs) − 1)/ ( tan( πf/ fs) + 1) 20^depthon a log path, withfeedbackfrom the row's output back to its input, so a pair of stages is one notch; a tremolo scales by1 − depth·(,0.5 − 0.5·sin) spreadoffsetting the right side by up to half a turn (1 is a swing from side to side). Load-bearing: all four use theClosureAudioUnitthe custom effect and the convolution reverb use, oneModulationEffectper unit kept across setting changes (setMotion,serves(_:at:)), the settings crossing under a lock and read once per block while the wave's phase, the delay lines, and the stages' memories live on, so a turn of any dial changes the motion in flight and never restarts it; the delay lines are read with linear interpolation, so a click through a chorus lands as two samples and a measurement takes the centroid; a sliding copy arrives when the read reaches it, so its delay is the wave at the arrival, not at the click (0.8 ms off the naive formula at full depth, which is the detune a chorus is for, and the first test run's whole failure); the export path builds the same units throughapply(, so the motion reaches a file.to: sampleRate: ) ModulationTests(12 tests: the tremolo's floor, ceiling, and dip spacing; spread as opposite turns; the still chorus as a 20 ms copy and the sliding one following the wave at the arrival; the still flanger's notch at 1/(2D) and peak at 1/D, feedback standing the peak at0.5 + 0.5/(1 − fb); two stages notching at their corner and four adding notches atf·tan(π/8)andf·tan(3π/8); mix 0 as the plain sound to the bit; a depth turned in flight keeping the wave's phase; the values round-tripping and clamping; the export carrying a tremolo's breathing) +ModulationAudition;Examples/;Audio/ Movement Docs/§ The four that move; Guide Ch 43 § Something that moves: chorus, flanger, phaser, tremolo + the Movement figure.Helpers/ Synthesis .md The three that hold a level (
Sources/; theOllinAudio/ Synthesis/ Dynamics .swift .compressor(/Compressor) .limiter(Limiter)/.gate(Gate)cases inEffect.swift, each its ownKind). What watches how loud the sound is and acts on it, written from the feed-forward design worked out in decibels (Giannoulis, Massberg, and Reiss 2012, credited inATTRIBUTION.md): a compressor measures the level, reads the static curve (a corner atthresholdwith slope1/ratio − 1, and a quadratic knee(across a band1/ R − 1)( x − T + W/ 2)² / 2W kneewide), and smooths the reduction rather than the level, attacking while it grows and releasing while it eases, then applies10^(; a limiter listens( makeup − reduction)/ 20) Limiter.lookahead(5 ms) ahead and rises back toward full overrelease; a gate follows the level, holds the gate openholdseconds past the last crossing, and moves the gain between 1 and1 − depth. Load-bearing: the level is read from both sides at once and one gain is applied to both, or a loud note on one side walks the image (pinned with the loud side on each side in turn, and a left-only detector fails the second); the compressor follows the level from crest to crest (a 10 ms decay under the smoothing) rather than reading each sample, since a per-sample peak eases every time the wave passes through nothing and a tone then lands a decibel short of where its ratio says; the limiter's gain is the mean, over the lastahead + 1samples, ofmin(: the sound leavesthe window's smallest need, the release rising) aheadsamples late, every gain in the mean saw the leaving sample in its window, so none is above its need and the ceiling is a promise instead of a tendency (the release alone can rise past what the sample needs, and did, at 0.5018 against an allowed 0.5012), while the gain comes down along a line over the lookahead, so a full-scale sine through a -6 dB ceiling keeps its THD under 0.3% where taking each sample's need at once flattened every crest (1.2%, 10% of samples on the ceiling); the window's minimum is a monotonic queue and the buffers are memory the object owns, allocated at init;aLimitersCeilingHoldsAndItsDelayIsItsLookahead(bursts 24 dB over, a spike, a step; under the ceiling the sound passes untouched but for the delay) went red under a one-sample delay too long; smoothing in decibels is what makes the attack and release times mean the same thing at every input level; all three use theClosureAudioUnitthe motions use, oneDynamicsEffectper unit kept across setting changes (setDynamics,serves(_:at:)) so a turn continues from the standing gain, and the export path builds the same units. Deliberate cut: no key from another sound (eachSynthowns its engine, so a detector on one has nothing to listen to on another), said in the docs rather than left to be discovered.DynamicsTests(13 tests: a tone under the threshold untouched to the bit; a tone landing at −12/−15/−16.5 for ratios 2/4/8; the attack and release reaching their fractions in the times asked; the knee working a decibel in at the threshold where a corner has nothing to do; makeup lifting by exactly what it says; both sides dropping alike whichever is loud; the ceiling unbroken at three heights over a signal twice full scale; the limiter letting go over its release; the gate open above and silent below; the hold keeping a decaying tail; a threshold lowered in flight walking to the new depth rather than jumping; the values round-tripping and clamping; the export carrying a gate) +DynamicsAudition; the ceiling and the linked detector both verified red by sabotage;Examples/;Audio/ Levels Docs/§ The three that hold a level; Guide Ch 43 § Something that holds a level: compressor, limiter, gate + the Levels figure.Helpers/ Synthesis .md The two that work in the spectrum, and the stretch (
Sources/+OllinAudio/ Synthesis/ PhaseVocoder .swift Spectral.swift; the.pitchShift(/PitchShift) .freeze(Freeze)cases inEffect.swift, each its ownKind;stretched(by:)onSampledInstrumentand.Recording ImpulseResponse). A phase vocoder (Flanagan and Golden 1966, Dolson 1986, and the peak-region form of Laroche and Dolson 1999, credited inATTRIBUTION.md) over the vDSP real FFT: frames of 2048 (4096 above 50 kHz) at a hop of an eighth, the periodic Hann both ways, each bin's true frequency read off its phase advance, the frames written back by overlap-add and divided by the summed window energy.PitchShift(moves the pitch and keeps the length;semitones: mix: ) Freeze(amount:)catches the spectrum of the first frame afteramountrises above 0 and keeps synthesizing it (magnitudes and true frequencies held, phases advancing) until the amount returns to 0;stretched(by:)(0.25...16) is the offline time-scale change on a recording or a room (a stretched room is a bigger room, still cut atmaxSeconds). Load-bearing: peaks own regions (a bin louder than its two neighbors on each side and above a ten-thousandth of the loudest; regions split at the valley between peaks) and a region's bins take the peak's synthesis phase plus their own analysis phase relation (identity phase locking), which is what keeps a partial's main lobe whole; a pitch shift translates each region by a whole number of bins and lets the peak's own advance atratiotimes its frequency absorb the fraction, so there is no resampler, the hop is fixed on both sides, and the latency is exactly one frame (SpectralEffect, 2048 samples), at a worked-out cost under a decibel of level and no ripple (eight windows overlap every sample, and the frames the residual puts out of phase carry almost no weight); the accumulator is reset one advance short (.latency resetAccumulated(, the phase less the frequency times the hop) becauseto: frequency: hop: ) propagateadds the hop before it writes, and resetting to the phase itself shifted every bin by its own frequency times the hop, which read as the output arriving a hop early (worst error 0.66 on the identity invariant); the live path frames from the first hop over a zero-filled ring and discards negative positions, so the first sample out sits under a full stack of windows (framing from the first full frame left the first 29 samples zeroed and the first 256 under one window edge); a shift of nothing is therefore the input itself to 2e-3 from the first sample, and a stretch of one the recording to 1e-4; the dry half of a blend is delayed by the same frame, so a harmonizer's voices land together and a freeze at 0 is bit-exact passthrough; a capture resets the accumulator to the held phases so the first held frame equals the live one, and a release resets the live phases so the passthrough is exact again; the two channels run their own engines; everything is allocated ininit(raw pointers,vvsincosfover the bins) and the per-sample loop touches no heap; both kinds use theClosureAudioUnit(setSpectral,serves(_:at:)by kind and rate), so a turn of the semitones slides rather than restarts, and the export builds the same units. Deliberate cuts: no formant preservation (a voice an octave up is a small voice; said in the docs) and no transient detection (a struck attack softens a little).SpectralTests(15 tests: the values round-tripping and clamping; a shift of nothing the sound itself, sample for sample, over blocks of 512, 100, 3, and 1024; 440 landing at the ratio for 12, -12, 7, 3.5, and -5 semitones within 0.5%; the level within 1.5 dB; a harmonizer keeping both voices and nothing else; the two sides on their own; an octave turned in flight reaching its pitch with no dropout; a freeze holding the tone a second after the input went silent, at its level, and passing the sound bit-exact before; a freeze at 0 bit-exact; a let-go freeze following the sound again; a stretch of one the recording itself; stretches of 2, 0.5, and 3 at the exact length, the pitch within 2 Hz, and the level within 1 dB; a stretched room longer at the same pitch and cut at the limit; both kinds wiring; the export carrying an octave) +SpectralAudition(OLLIN_AUDITION);Examples/;Audio/ Spectral Docs/§ The two that work in the spectrum + § Stretching a recording; Guide Ch 43 § Something that takes the sound apart: pitch shift, freeze, stretch + the Spectral figure.Helpers/ Synthesis .md The patchable graph (
Sources/+OllinAudio/ Synthesis/ Patch .swift PatchVoice.swift). Routing as a value:Patchis an operator graph (.tone(/_: ratio: level: ) .modulated(/by: amount: ) .mixed(with:)/.fedBack(_:)/.level(_:)/.ratio(_:), presets.bell/.brass/.glass/.buzz/.struck), reached asVoiceSource.patch+Voice(patch:)+Voice.fmBell/.fmBrass/.fmBuzz. The bare form is untouched — the presets sit on this the way the bare draw calls sit onDrawer. Load-bearing: the shipped constraint (aVoiceis carried inSynthEventthrough the lock-free ring, which is whyModalBodycaps at 16) is met the same way — a patch is fixed lanes, capped at 8 operators,SIMD8throughout with an output bitmask, so it stays POD (_isPOD(pinned); past the cap it returns the patch unchanged and notes, never silently drops an operator (a patch with a piece missing is a different instrument);Patch/ VoiceSource/ Voice/ SynthEvent) modulated(by:)puts the modulator's lanes FIRST so every modulator sits in an earlier lane than what it pushes and one forward pass evaluates the graph (pinned: everymodulatedByindex < its own lane, at any build depth); an operator'slevelis the mix level where it is heard and the modulation index where it is not, which is the FM convention and why no extra lane is needed; the sum is divided by the number of output operators so mixing does not double the level.PatchVoicekeeps phases inSIMD8lanes, never an array ofOscillator— an array is a reference the voice struct carries and a voice is copied at note start, which would refcount on the render thread.waveformSamplewas extracted fromOscillator.nextso both read the shapes through one function (no drift), andOscillator.nextgained aphaseOffsetdefaulting to 0 that moves where the shape is read without moving the phase — byte-identity pinned byaSingleOperatorPatchIsExactlyAnOscillatoracross four waveforms, plus every non-patch preset still rendering. Deliberate v1 cut: a patch is oscillators only (no per-operator filter/envelope/effect; those stay theVoicearound it).Waveformconforms toParamOptionalongside.PatchTests(16). ExampleAudio/Patching; Guide Ch 43 § Building an instrument instead of choosing one: patches and FM;Docs/.Helpers/ Synthesis .md#patch Wavetables (
Sources/+OllinAudio/ Synthesis/ Wavetable .swift WavetableVoice). A row of single cycles read by position:.swift Wavetable(afinal classholding every frame at eleven band-limited levels, built once from a harmonic spectrum, from drawn cycles resampled and analyzed, or from a(phase, frame)rule;.basic/.pulse/.vowelsbuilt in;frame(_:),frame(,_: harmonicsUpTo: ) cycle(at:)for drawing) set onSynth.wavetable, andWavetableScan(position,sweep,envelope;.at(_:)) carried in the voice asVoiceSource/.wavetable Voice(wavetable:)/Voice.morph. Load-bearing: the table lives on the synth for the sampled instrument's reason (aVoiceis carried in the PODSynthEvent;_isPODpinned for the scan, the source, the voice), and the offline export renderer now copies bothinstrumentandwavetablefrom the synth (the sampled one never was copied, so a sampled note in an export rendered silent); a synth handed a wavetable voice with no table reads.basic(set ininitand thevoicesetter, on the main thread, never on the render thread); the level a note reads is chosen once at note start from its increment (level(, the strongest whose top harmonic stays under half the rate), so a 5 kHz sawtooth keeps four harmonics and folds nothing (pinned against the full-band counterfactual read at the same rate, which folds harmonics 7 and 6 back at 1/7 and 1/6 of the fundamental, and red by sabotage of the level choice); every level of a frame is summed from the same spectrum, each harmonic added exactly once from the weakest level down, and the whole frame scaled by the full level's peak, so the levels agree and moving between them is silent; the spectrum stops one bin short of half the length (the Nyquist bin is not a harmonic; the first build walked one past the array); the read is bilinear over phase and frame; the scan's position is read per note and only itsforIncrement: ) sweepenvelope moves it while the note sounds (a live position,pressure's cousin, is the deliberate v1 cut).WavetableTests(12) +WavetableAudition;OllinAudioTests296 green. ExampleAudio/Wavetable; Guide Ch 43 § A wave you can draw: wavetables with the WavetableFrames figure;Docs/.Helpers/ Synthesis .md#wavetables Driven physical models: the bowed string and the blown tube (
Sources/+OllinAudio/ Synthesis/ DrivenModels .swift DrivenVoice.swift). The other half of the model tier: a pluck and a strike are set going once, a bow and a breath are kept going, so a note has a middle.VoiceSourcegains.bowed(BowedString)/.blown(BlownTube)(+isDriven),Voicegainsbowed:/blown:inits + presets (.violin/.cello/.bowed/.clarinet/.reed/.hollow),Envelope.sustainedis the stay-out-of-the-way gate, andSynth.drive(0…1) is the continuous control: an atomic Double bit pattern likegain, read once per block, shared by every note (one bow, one breath). Both models are digital waveguides over the shipped delay-line machinery; credited inATTRIBUTION.md(Smith's PASP, McIntyre/Schumacher/Woodhouse 1983, Smith 1986), never in.swift. Load-bearing: the bow is the published scattering junction (vΔ = vb − (,fromNut + fromBridge) toBridge = fromNut + ρ(,vΔ)·vΔ toNut = fromBridge + ρ() over two lines whose round trips sum to one period, split at the bow position; the friction curve is flat while stuck then falls as a cube, and bow speed against the slip threshold is the whole regime — below ~1 the string is caught and released once a cycle and the spectrum is the 1/n Helmholtz sawtooth (measured cellovΔ)·vΔ [1.00 0.51 0.34 0.25 0.19 0.10]), above it the string tears loose twice a cycle and jumps to the octave, which is real over-bowing, not a bug (force widens the threshold, so a light bow can be over-driven and a heavy one stays solid);stickingGripis 0.9, deliberately short of a perfect hold (at exactly 1 the stuck bow is a lossless reflector, so the note settles against the threshold and bowing faster changes nothing — even at 0.9 the drive range only spans ~8 dB, so force is the loudness parameter and drive the expression one, pinned at >1.5× rather than at the speed ratio); the tube's round trip is half a period, not a whole one (stopped at the reed, open at the bell), which is the single line that produces odd-harmonics-only (measured[1.00 0.01 0.28 0.01 0.12 0.00]) and puts it an octave and a fifth below an open pipe; the reed reflection is derived from its two physical limits (shut = rigid termination, open = mouthpiece held at breath pressure) which expands exactly to the published form, so nothing was copied; both loops carry the fraction of a sample and only one side may round (the bow's nut side rounds and the bridge side takes the remainder in a tuning allpass, the tube's bore reads its fraction between samples) or the loop is up to half a sample out, which is nothing low down and most of a semitone at the top — pinned <1 cent across MIDI 33…93 at four bow positions and three dampings;pressureis ignored by every non-driven source (byte-identical at drive 0 vs 1, pinned), and both structs stay plain Doubles so they are still carried inSynthEventthrough the lock-free ring. Deliberate cut: no jet-driven tube. A flute jet was built and declined on measurement — it sat at a DC operating point where the cubic's slope is negative, so the loop was far too lossy to oscillate and the output was identical (rms 0.0363) across every jet delay; two attempts, then stopped per the anti-thrash rule rather than keep patching. A lifted bow lets the string ring: the junction's grip is scaled by a contact ofpressure /(0.1, below where any preset speaks, so a sounding note is untouched), so at 0 both waves pass straight through, and the loop's whole loss is taken once a period at the bridge (the nut reflects without loss; taking it on both sides rang a lifted string half itsBowVoice .liftedBelow decay), withloopLoss's compensation; a lifted violin or cello falls under 6 dB in its first 60 ms, rings at its note, and rings for itsdecaywithin 10% at MIDI 48, 69, and 81 (aLiftedBowLetsTheStringRingDown), where the parked bow muted it 25 dB. A glided lift (a note's own 8 ms pressure glide) slows the bow on the string first and loses 7 to 12 dB in that time, filed as measured. Every tube speaks fromTubeVoice(0.3): the breath is reckoned in closing pressures, each note's onset worked out in closed form from the reed's small-signal gain (the reed returns 2x - 1 of a change, x = (m - 2r)/c; the note grows once that times the loop's gain G at the fundamental passes 1; the bore's DC operating point under the loop's DC gain g gives the breath, x² + 2(k - 1)x = 2km with k = (1 + g)/2g), which lands within 0.005 of a breath sweep at five pitches on each preset; the dial rises to that onset over the first 0.3 and on to the old full breath,.speaksFrom 1.1 /(so a full-pressure tone is what it was), and every preset is silent at 0.25 and speaking at 0.5 from MIDI 45 to 69 (closingPressure aBlownTubeSpeaksFromTheSamePressureAtEveryPitch). What a tube radiates is DC-blocked (one pole at 20 Hz on the returned wave, outside the loop, so the oscillation is untouched): no standing offset over 0.005 at pressure 0.2 to 1.0 (aBlownTubeHoldsNoOffset), where it held -0.05 to -0.17. A tube holds its pitch at every pressure, to the top of its range (within 5 cents from MIDI 45 to 96 at every pressure, at 44.1 and 48 kHz,aBlownTubeHoldsItsPitchAtEveryPressure). Until 2026-11-11 the breath pulled it (the clarinet 25 cents sharp at MIDI 95 at full pressure, the reedy tube 36 cents at MIDI 92), which had been read as the note leaving for its twelfth because the line was measured where the note should have been; the note was never lost. Three things hold it, and each alone does not: the bore's round trip takes the same time at every frequency (the loss is three symmetric taps[e, 1 - 2e, e]withe = s(1 - s)/2, one sample of delay at every frequency and the one-zero's loss to first order; the fraction of a sample is a four-point Lagrange read, never an allpass, whose delay differs between the note and its harmonics); at the top of the range the loss has a floor (erises to 1/8 as the half period falls from 80 samples to 40, so a wave's edge stays wider than a sample and has somewhere to sit between two of them); and full pressure blows no more than 0.85 closing pressures there, with the radiated level scaled by what the breath gave up (makeup), so a note is as loud at full pressure as it was (aBlownTubeIsAsLoudAtTheTopAsInTheMiddle, within 1.5 dB). What the holds cost in tone is the top of the spectrum, measured against the old loop: the third and fifth harmonics moved by about a decibel at most from MIDI 57 to 81 on every preset and stay the 1/n odd series within 2 dB (aBlownTubeKeepsItsOddSeries), the ninth and eleventh fall by up to 6 dB at MIDI 76 and 81, at MIDI 88 the harmonics past 8 kHz are 1 to 13 dB down (most at a soft breath), and at MIDI 93 the seventh and above are 10 to 30 dB down at pressure 0.6; the floor is the same for every preset, so above about MIDI 73 at 44.1 kHz the three share one loss. The onset's closed form reads the new loop's gain at the note (the three taps times the read's own). A pitch measured off a slice is scanned at half the width the slice resolves, or a line a few cents off falls between two steps and reads as weak.DrivenModelTests(16, twin pairs) +DrivenModelAudition(9 takes, drive shaped through each). ExampleAudio/Bowing; Guide Ch 43 § A note you keep playing: bowed and blown;Docs/.Helpers/ Synthesis .md#physical-models Spatial audio and sound in an export (
Sources/+OllinAudio/ Synthesis/ Spatial .swift SynthExport.swift+ the core seamSources/).Ollin/ Core/ ExportAudioSource .swift synthputs an instrument in the 3D scene with a.place( at: heardFrom: ) Camera3Das the listener (position/hearingDistance/unplace()), and--export-video/--export-loopcarry the sketch's own music into the file with nothing to switch on. Load-bearing (spatial): placing is a different graph, not a setting, so the firstplacerewires (a source node's channel count is fixed at construction, so the stereo node is replaced by a mono one); the environment node must come first, before the effects (a mono chain throughAVAudioUnitReverbthrows-10868at connect time, probe-verified on the reverb and on the system's delay unit, the stage-1 format lesson again), and the 3D position is set on the source node (AVAudioSourceNodeconforms toAVAudioMixing; the effect units do not). Load-bearing (export): the core cannot depend on a satellite, soExportAudioSourceis apackageseam inOllinthatSketchfinds throughheldObjects(of:)(Sources/) the way it findsOllin/ Core/ HeldObjects .swift FrameAdvancingvalues andTransportMutables: a stored property, and inside a struct, an enum, a tuple, an optional, an array, a set, or a dictionary, or an object of a class the sketch's own module declares, so the Spatial example's three chimes inside structs in an array export and are advanced. Load-bearing (the finder): the direct properties come first in declaration order (a sketch with two instruments mixes exactly as before); each object is found once and never looked into twice; the framework's own half of the sketch (Sketch's stored properties) is read one level deep as it always was and a framework object is never looked into; a collection is read through its first element, and skipped whole when that element holds no object anywhere inside it (a millionVector2s cost under 2 s, a[Post]whose first post holds a synth is read entire; a list plain first and an instrument later is the one shape it misses, and the reference says so); the pending values sit on a list, never the call stack, and the walk stops after 200,000 values (HeldObjectsTests: anEasedinside a struct, an array, a dictionary, and the sketch's own object moves, one held twice moves once, andanInstrumentInsideAnArrayReachesTheExportfinds eight of eight). UnderisRenderingHeadlessaSynth's notes are written down rather than played (emitroutes torecord,start()no-ops) against a clock the sketch sets to the frame's own time throughFrameAdvancingright after each.advance( to: ) advance(by:)step (stepped alone the clock stood one frame past the picture while the frame was drawn, since the sketch advances before it draws, and every note landed a frame late: 736 samples at 60 fps;aNoteAskedForOnAFrameStartsOnThatFrameat frames 0 and 10, within 32 samples), a control moved while the frames go by is written down against that clock and applied at its block (RecordedControl:gain,pressure,grainScrub;RecordedChain: the settings of the effect chain. The live renderer reads each once a block from a word the sketch writes, which leaves nothing for the export's own renderer to read later, so a bow eased off, a fade, and a reverb mixed in each came out held at one value, and a pressure set once before the export played at the full default because the offline renderer was never handed it. A value repeated every frame is written once; the first move also writes the value it replaced at time 0, so the export opens with what it began with whenever its machine is built; the machine copies the three controls as they stand, which covers one set before the export and never moved. A chain of other kinds than the export began with cannot be followed, since the offline engine is wired once: the file keeps its effects and the sketch is told once.SoundExportTests:aBowEasedOffWhileTheFramesWentByIsInTheFile,thePressureAnExportBeginsWithIsTheOneItPlaysAt,aFadeMadeWhileTheFramesWentByIsInTheFile,aChainSettingMovedWhileTheFramesWentByIsInTheFile, each red before its fix),hearingDistancechanges are written down against that clock like a move (RecordedRange; the first change also writes the range it replaced at time 0, so the machine opens with the range the export began with) and applied at their block (aHearingDistanceChangedMidExportIsHeard: the later note at the new range, the earlier note untouched),unplace()switches the source to the mixer's pass-through (.stereoPassThrough, measured at exactly the never-placed level in both ears from any position and switchable while the engine renders;placesets.autoback; sat at the listener's own position instead the pan played it at half level in each ear, 6 dB down for the rest of the piece;anUnplacedSoundIsHeardAtFullLevel, and placed again to the left it pans left), and a note's length is stored in seconds not samples so the file renders at its own rate; the soundtrack replays through the same clock-freeSynthRendererinside anAVAudioEnginein offline manual-rendering mode (which is what lets the delay and reverb render offline too), chunked so a note starts on the exact sample it was asked for. The interleaving trap, which cost a session:AVAssetWriterpaces file-mode inputs in ~1 s chunks and holds every other track until the lagging one delivers its chunk — and this soundtrack cannot lead by a second, because the notes for those frames have not been asked for yet, so the writer held video forever at ~frame 67 and the export looked like a hang (it also hung with zero notes played, since declaring the track is enough). The fix is three parts, all load-bearing: the audio input isexpectsMediaDataInRealTime = true(exempt from chunk gating), audio is pumped before each video frame so it never lags, and the video wait is bounded and fails loudly rather than spinning. Verified: 1200-frame--export-loopcompletes in 19.8 s and two runs decode bit-identically (max sample difference 0.0). Envelope: GIF carries none, and an instrument must be a sketch property to be found.SoundExportTests(8). ExamplesAudio/Spatial+Audio/; Guide Ch 44 §§ Sound from a place in the scene: spatial audio / Putting it together: the music box;SoundInAnExport Docs/+Helpers/ Synthesis .md#placing-a-sound #sound-in-an-export+Docs/. Placing carries into the export (Output/ Export .md#sound RecordedPose/ListenerPoseinSpatial.swift, the environment node inOfflineRender):place(underat: heardFrom: ) isRenderingHeadlesswrites the pose down against the export clock instead of rewiring, and the soundtrack renders through anAVAudioEnvironmentNodein manual rendering mode (probe-verified: it spatializes offline, distance attenuates on the inverse law, and the source→env→delay→reverb chain connects without throwing). Load-bearing: the environment node is built only for an instrument that recorded a pose, so an unplaced export keeps its own chain, and because a chain's shape is fixed when it is built, a pose arriving after that notes loudly rather than silently centering (the one degrade that stays); poses collapse to changes only (a sketch callsplaceevery frame, so a still instrument costs one pose, not one per frame, pinned at 1 vs 600); a note breaks the render block but a pose is applied at the next block boundary (an onset is a transient and must land on its own sample, a position is not, and a block is a fifth of a frame);.autois the algorithm both paths ask for, and with no output device it resolves to a plain left/right rather than the head model (HRTF works offline but needs ~0.5 s to settle, measured, so it would wreck a short export); the hearing range lives on theSynth(placementRange), not the placement, so an export can read it without a live environment node existing. Fixed alongside, a real shipped defect: the offline chain built its source at mono and fed a stereo mixer, so every exported soundtrack was entirely in the left channel with the right at exact digital silence (measured L rms 0.0657 / R rms 0.0 on the shipped code); an unplaced instrument is now built at the output's channel count the way the live path builds it, and the render block writes its one stream into both channels.SpatialExportTests(12, counterfactual twins: left-vs-right, near-vs-far, listener-moved, unplace-recenters, a walk crossing the ears measured as balance rather than level since a voice's own envelope otherwise reads as the crossing) +SpatialAudition. A soundtrack file (SoundtrackFile,Sources/):Ollin/ Export/ SoundtrackFile .swift --export-sequencewritessoundtrack.wavbeside its frames (interleaved stereo 32-bit float at the soundtrack rate, pumped a frame at a time on the sketch's clock like the video track, so frame k begins at sample k × 44100 / fps) and--export-audio FILE/OllinAppwrites the same file alone, driving the sketch with.exportAudio advance+performDrawand no renderer, so no GPU is touched (a sketch whose sound follows a compute step has to render); a skipped stretch is rendered and dropped at the first pump on every route, which the video track did not do before (its sound began at the sketch's zero while the picture began at the skip), and under slow motion every route follows the sketch's own clock, so the track is shorter than the slowed picture.SoundtrackFileTests: the audio export is as long as its frames and begins after the skip, the sequence's file equals the audio export's sample for sample (Metal), and a sketch with no instrument writes none and is refused by name.OSC (
OllinOSCsatellite). OSC 1.0 wire format written from spec (OSCArgument/OSCMessage/OSCBundle/OSCTimeTag/OSCPacket, totalinit?(data:)decode — malformed datagrams returnnil, never trap) over UDP (OSCSender/OSCReceiver). Three read surfaces: latest-value cache (float/int/string/bool), event drain (messages()), and@Parambinding (bind(). A listener's life is one value ("/ addr", to: $param, from: ) ListenerLifecycle,Sources/,Ollin/ Core/ ListenerLifecycle .swift package, shared byOSCReceiver, TUIO over it,DMXReceiver, andEtherDreamFinder:idle/binding/waiting/ready/failed, withportandlastError):isRunning,boundPort, and the newlastErrorread it, and the listener's own state handler writes it. The system refuses a port another program holds a moment afterstart()returns (measured:.failed(EADDRINUSE)then.cancelled, UDP and TCP alike), too late to throw, and the receivers used to read only.readyoff that handler, so a receiver on a taken port stayedisRunningwithboundPortnilfor ever and nothing to say why; nowisRunningturns false,lastErrornames the port instrerror's words, the failed listener is let go so the nextstart()makes a new one, and a cancellation after a failure or a stop is not news (ListenerFailureTests,DMXListenerTests, a port held by the test support'sHeldPort, a plain socket with no reuse flag). ExampleIntegration/;OSCLoopback Docs/.Integration/ OSC .md OSCQuery (
OllinOSCsatellite;OSCQuery.swift). The sketch's@Params published as the namespace a control app browses:extend(serves the tree as JSON over HTTP on TCP and takes values over OSC on UDP at the same port number (9000 by default,OSCQueryServer( port: name: )) 0system-picked), both advertised throughNWListener.Serviceas_oscjson._tcpand_osc._udpunder the sketch's type name (advertisesoff for tests and privacy;OSCReceiveris the receiver's half). A parameter is.serviceName /nameor/Group/name(the group made address-safe bycontainerName, the real name kept in the container'sDESCRIPTION); every leaf carriesFULL_PATH,TYPE,ACCESS3,VALUE,RANGE,DESCRIPTION, the type per kind in the Docs table, and a swatch strip is a container ofrchildren, one per color, so a client that knows nothing about palettes gets a color well per stop.?HOST_INFOnames the server and the OSC port; a query naming one attribute (?VALUE,?RANGE, and the rest) answers it alone (204 when the node lacks it, 400 when the server does not speak it, 404 for no node); noLISTENand no WebSocket, so clients poll. Three layers like the remote surface, and the split is load-bearing: the model (OSCQueryNode/OSCQueryValue/OSCQueryRange/OSCQueryHostInfo, publicCodableunder the protocol's own keys, sorted, slashes unescaped), the wire (OSCQueryWire: the namespace fromParamHandles, a payload from OSC arguments perLeaf,applythrough the control's own write closure so smoothing and clamping match an inspector drag, one response per request target; all pure), and the engine (nonisolatedOSCQueryEngineowning both sockets; the@MainActorextension discovers, rebuilds the tree every 250 ms, and applies the drained queue inbeforeDraw). An incoming message is read on the network queue against aRoute(name + leaf) and never touches the parameter there. Reads are generous (any numeric tag for a number, label or index for a menu,ror a hex string for a color); a short or wrong-kind message is dropped.OSCArgument.color(tagr, four bytes R G B A) joined the codec for this. The HTTP head parser is the core's package-accessHTTPRequestHead, whichRemoteHTTPforwards to (satellites cannot depend on each other). Tests are socket-free but for one UDP loopback datagram (the house no-loopback-TCP rule):.parseHead OSCQueryTests(15). ExampleIntegration/(draws the tree it serves);OSCQuery Docs/; Guide Ch 42 § The sketch that says what it takes: OSCQuery. Failure shape (2026-09-22):Integration/ OSCQuery .md isRunning(the listener is up),unavailableReason(a port another program holds, a bind the system refused, the OSC port that would not open; follows the listener's own state and clears on.ready), andstart()(serves again afterstop(), or tries the port again after a failed start, which drops the failed listener so it can); the failure is also said once on stderr for the terminal, neverprint.OSCQueryTestsholds a plain listening socket on a port the system picked and asks the server for it. A reason per socket:.aPortAlreadyTakenIsSaidAndTriedAgain unavailableReasonreads the OSC port's reason first (itsstart()threw, or the receiver's ownlastErrorafter a bind the system refused) and the HTTP listener's second, where one slot used to be written by both and cleared by the HTTP listener coming up, so an OSC port that would not open was said for a moment and then not at all (ListenerFailureTests);.theQueryServerSaysWhichPortWouldNotOpen isRunningis the namespace's listener alone.TUIO (
Sources/, inside the OSC satellite — a satellite may not depend on another, and TUIO is sent over OSC). A tangible surface (marker table, touch wall, phone app) read as three polled lists:OllinOSC/ TUIO .swift cursors(TUIOCursor),objects(TUIOObject, carrying the marker'ssymbolandangle),blobs(TUIOBlob, carryingsize/area/bounds(in:)), each item holding the tracker's sessionid, apointin the unit square,velocityin surface widths per second, andposition(. TUIO 1.1's three 2D profiles only (in: Rectangle) 2Dcur/2Dobj/2Dblb); the 2.5D/3D profiles, TUIO 2.0 addresses, and non-TUIO messages are ignored rather than half read, and two trackers on one port are not separated (sourceNamereports the last one that named itself). Written from the spec. Load-bearing: the per-profile state machine commits onfseq— sets and the alive list are held aside, so a poll never reads half a frame (one finger moved, another not); a frame numbered below the last is dropped as a datagram that overtook another unless it is more than 1000 below, which is a tracker that restarted its count; frames arrive in the specification's order, alive list first, then the sets, thenfseq, so asetnever closes a frame (closing there commits the alive list beforefseqcan turn a late frame away, and counts every frame twice), while a sets-first frame is still read; a tracker that omitsfseqcommits when the next frame's alive list arrives (one frame late, rather than never); the alive list is the only removal (the protocol has no ended message) and asetfor an id absent from it is not invented. Coordinates are0...1from the top-left, the canvas's own direction, soposition(in:)flips nothing.TUIOReceiverowns anOSCReceiverand uses its new internalobserve(_:)seam (kept internal so the OSC public listing is unchanged, and non-destructive, so a sketch's ownmessages()still sees everything); a shared socket is served instead by feedingreceive(_:), which also takes a wholeOSCPacket. ExampleIntegration/(a stand-in tracker sends real frames toTUIOSurface 127.0.0.1,simulateoff for a real one);TUIOTests(18 tests, the late-frame drop and the alive pruning both sabotage-verified, the wire order's three tests red on the receiver that closed a frame on aset, plus one real UDP round trip);Docs/; Guide Ch 42 § A table you put things on: TUIO with the SurfaceFrame figure.Integration/ TUIO .md TUIOReceiveris its OSC receiver's, so a port another program holds reads.lastError isRunningfalse with the reason (ListenerFailureTests).DMX lighting (
OllinDMXsatellite). Art-Net 4 + sACN (ANSI E1.31-2018) written from spec overNetwork.frameworkUDP, the OSC recipe applied to lighting (the listener's life through the coreListenerLifecycletoo, so a taken port readsisRunningfalse withlastError; the multicast groups are joined before the listener starts, so a join that throws leaves nothing half-started, and a failed bind lets the groups go with the listener,DMXListenerTests): total-decodeArtDmxPacket/SACNDataPacket(golden-byte-pinned against both specs' published tables),DMXUniverse(512 channels, 1-based like every console; out-of-range reads 0 / writes ignored, never a trap) +DMXFixturenamed layouts (.rgb/.rgbw/.drgb/.dimmerpresets + role lists,nextAddresschaining; RGBW takes the min-subtract white split, and a dimmerless fixture scales its color sodimmer:means brightness either way),DMXSender(DMXSender()= sACN multicast to the per-universe239.255.hi.logroup — the zero-config default;sACN:/artNet:unicast forms — Art-Net 4 forbids ArtDmx broadcast) andDMXReceiver(latest-value reads +@Parambinding 0…255 → range; no event drain by design — DMX is levels, not events;start(universes:)joins sACN multicast groups viaNWConnectionGroup). Load-bearing: the wire cadence lives in the pureDMXPacer(send-on-change capped at 44 Hz = a DMX512 gateway's max refresh, the E1.31 three-repeat tail after a change, then ~0.9 s keep-alives — so a sketch just callssendevery frame and the pacer is unit-tested clock-in-hand);close()must wait for its sACN goodbyes (3 stream-terminated packets per universe; canceling theNWConnectionimmediately drops the still-queued sends — a real test-caught bug, fixed with a completion-counted wait); receiver ingest applies the standard's rules (highest priority wins under the 2.5 s source timeout, the signed-8-bit sequence window≤0 ∧ >−20dropped, preview data + alternate START codes ignored, a terminate clears the universe) andhandle(_:)is internal so tests feed crafted datagrams with no sockets; ArtDmx sequence wraps 1…255 skipping 0 (0 = disabled) and its port-address packs Net(7):SubNet(4):Universe(4), valid 1…32767. Envelope (stated in the docs, not faked): streaming tier only — no ArtPoll/ArtPollReply, no sACN discovery/sync packets, no RDM; multicast receive is best-effort until hand-verified against a real console (loopback tests are unicast). The spec-required "Art-Net™ Designed by and Copyright Artistic Licence" credit lives inDocs/+Integration/ DMX .md ATTRIBUTION.md— keep it. LED mapping (LEDMapinOllinDMXover the coreCanvasSamplerseam,Sources/): strips (polyline/ring) / matrices / loose points laid over the canvas, sampled each frame and sent as universes. Load-bearing: sampling is a small GPU compute pass on the rendered-texture extension hook (Ollin/ Renderer/ CanvasSampler .swift wantsRenderedTexture; never the full-frame CPU readback) —CanvasSamplerispackage-access (satellite-seam tier, same package), compiles its kernel from an inline source string outside the segment concatenation (plainfloat4/uchar4buffers, no shared struct to drift), averages each point's box patch in linear light and re-encodes to display (sRGB) bytes (radius 0 round-trips the stored byte exactly; the sRGB-space average is the pinned counterfactual), clamps off-canvas points to the edge texel, and is synchronous (own queue + wait — the Syphon cross-queue hazard rule); universes pack whole LEDs (a straddling LED jumps whole to the next universe's channel 1 — 170 RGB / 128 RGBW per universe, the pixel-controller convention) and a run spans consecutive universes from its start; strip LEDs space by walked length (endpoints included;closed:spaces i/N around the loop, no doubled seam); a matrix defaults to straight rows (pixel controllers are configured with the panel's wiring and own the zigzag —serpentine: trueonly for direct-wired panels); defaultsampleRadius= the patch the LED stands for (half spacing / half of the smaller cell side, banded 1…32); colors land through the fixture path (DMXUniverse), so RGBW white-split and master.set( _: color: dimmer: ) brightnessfollow the shipped rules;Fixtureis the wire readback a drawn preview uses; live-only (headless exports never fire the texture hook, the frame-sharing precedent). Example.address( ofLED: ) Integration/(loopback: strip in wire order + panel lit from received universes);LEDMapping CanvasSamplerTests(Metal-gated) +LEDMapTests; mechanism inARCHITECTURE.md§ The canvas sample pass. ExampleIntegration/(both ends on loopback, the drawn stage lit from received channels);DMXLoopback DMXWireTests/DMXReceiverTests/DMXLoopbackTests.Docs/.Integration/ DMX .md Laser projection (
OllinLasersatellite). Line work fromdraw()scanned by a show laser:LaserFrame(paths in canvas coordinates, one color per path or per point;Contour/Shapeoutlines only — a fill hatches first, the plotter rule),LaserOptimizer→LaserStream(the point list a projector plays, plus what it cost),LaserSafety,LaserProjector(the sketch surface + the arm gate),EtherDreamDAC/EtherDreamFinder(the wire),ILDAFile(format-5 files), anddrawLaserPreview(the beam's own path drawn on screen). Load-bearing: the optimizer works in projector space (ProjectorSpace:-1…1, x right, y up, the canvas fitted so nothing lands outside the field, every point clamped), never canvas pixels, because each distance it sets is a distance the galvos move; segments are subdivided, never resampled end to end (an arc-length resample drops the authored vertices, which is exactly what rounds a corner off — pinned byeveryVertexTheSketchGaveLandsExactlyWhereItPutIt); dwell is held in two places for two reasons (a turn pastcornerAngle, and both ends of every blanked jump — light while the mirrors still move and the beam drags a tail between shapes); the frame's last travel leg returns to the first path's entry, so replaying one frame has no seam (which is what the DAC does betweensends); path order reuses the plotter's greedy tour through the newpackage orderedPathStepsseam (GCodeExport.swift) — the decision is shared, the application is not, since a laser path carries a color per point that must reverse and rotate with it; and nothing is dropped over budget (pointsPerSecond /): the frame plays whole and repeats slower, withrefreshRate isOverBudget/refreshRatesaying so. Safety is API, not documentation: a projector emits only after an explicitarm()(disarmed and stalled both play a dark hold, connection kept),maxBrightnesshalves the drive by default, the stopped-beam guard blanks a lit run that stays insidestationaryRadius(its limit must sit abovecornerDwell, which repeats a position on purpose — both directions pinned), andstallTimeoutblanks a frame the sketch stopped feeding. The DAC pump self-clocks on replies, which is a trap: the buffer figure arrives only on a reply, so a host with no room must ping rather than re-read the number it already holds — a stale re-read deadlocked the stream permanently, caught by the loopback and fixed byaskAgain(after:). The DAC's stop condition is a resting phase, not a lost line, and nothing restarts on its own: a reply with the stop code (the interlock tripped, or an emergency stop sent to it) keeps the socket, moves the pump to.stopped, setslastError, and sends nothing more (hasStopCondition); the rule for an emergency stop is that releasing it never restarts the machine, so the restart isclearStopCondition((the clear, then the handshake again on the same socket), which) LaserProjectorcalls, and.arm( ) send()disarms the projector when it finds the stop, so the beam returns on a deliberatearm()and on nothing else. A clear the DAC refuses (its interlock still open) lands back in.stoppedwithlastErrorsaying so; no retry is scheduled. Read as a failure instead, the socket was dropped and a laser whose interlock tripped once stayed dark until a restart (EtherDreamStopTests, three tests against the stand-in DAC'sraiseEmergencyStop(andholdingInterlock: ) closeInterlock(); the first cut cleared the stop on its own and was corrected the same day). The finder reads its listener through the coreListenerLifecycle(below, under OSC), so a broadcast port another program holds turnsisRunningfalse withlastErrorset (EtherDreamFinderListenerTests). Two more non-obvious facts: the rate-change command byte is 0x74 (the published table names it after a letter that is not that byte; an independent implementation agrees on the byte), and anNWListenerasked for any port reports 0 until ready, which is not somewhere to connect (the test stand-in's own bug). Both formats are golden-byte pinned (ILDA big-endian, 32-byte header, 8-byte records ending B,G,R, blanking bit 6 / last-point bit 7, a null header ending the file; the DAC wire little-endian, 18-byte points, 20-byte status, 22-byte reply, all packed) and a file is read back by a second parser written from the same spec. Envelope (stated in the docs, not faked): no hardware has ever been on the other end — the wire is verified end to end against a stand-in DAC speaking the protocol on loopback, and broadcast discovery is best-effort until it hears a real DAC (only the datagram decode andhandle(_:)are tested, the DMX multicast-receive precedent); one DAC family, no IDN; true-color files only (no indexed palettes); no geometric correction; no point-rate feedback.LaserOptimizer(takes the two numbers a projector is set up by, and the rating stays a number (30K is the vocabulary, the lens-preset ruling), with the ILDA rating table on the Docs page rather than presets in code. ExamplepointsPerSecond: refreshRate: ) Integration/(the optimizer made visible: parameters, the beam's footsteps, the budget readout);LaserPreview LaserOptimizerTests/LaserSafetyTests/LaserWireTests/EtherDreamLoopbackTests(63); no pixel snapshot (the output is a point list). Guide Ch 49 § Drawing with light: a show laser;Docs/.Integration/ Laser .md MIDI (
OllinMIDIsatellite). MIDI 1.0 written from spec (MIDIMessageincl..songPosition, totalinit?(/status: data1: data2: ) init?(umpWord:)) over the modern Core MIDI UMP API (MIDIInput/MIDIOutput, virtual source viaopenVirtual). Read surfaces: control cache, held-note state,messages()drain,@Parambinding. The pitch wheel reads and binds whole-channel beside MPE's per-note bend:pitchBend(channel:)is the wheel as a fraction of its travel (-1/0/1; 0 until a bend arrives; nil channel = the channel that bent last; controller 121 rests it), andbindPitchBend((to: channel: travel: ) Param<Double>andParam<Tempo>,unbindPitchBend) mapstravel(default-1...1) into the range, so rest is exactly the midpoint. Load-bearing: the fraction divides each side by its own count (8,192 below rest, 8,191 above), so both ends reach 1 exactly, andtravel:is on that scale, never raw 14-bit (the label was ruled 2026-10-01 so a reader never writes0...16383there);HeldNote.pitchBendkeeps the specification's /8192 for semitones.MIDIExpressionTests(the wheel, each channel) + loopbackpitchBendDrivesAParamAboutItsMidpoint/pitchBendBindsByChannelAndRange.@Paramsmoothing (.eased/.smoothed) lives on the param, so a softened parameter applies to MIDI, OSC, and inspector drag alike (runs in the per-frame advance pass with@Eased/@Smoothed). Tempo sync —TempoClock(follows MIDI clock into musical time (from: input) tempo/beats/beatCount/phase/beatdecaying pulse /bar/barPhaseover declaredbeatsPerBar/progress(over:), theloopProgresssibling). Load-bearing: position counts ticks (each F8 is exactly 1/24 beat — the grid can't drift); the smoothed interval window (~2 beats, flushed on a >±40% jump or a >0.25 s break) only glidesphasebetween ticks, clamped so position never runs backward;start/continuearm and begin on the next tick (the MIDI convention; song position = sixteenths × 6 ticks, and an SPP jump clears the pulse anchor so the next tick lands on it exactly); a transport-less master (DJ gear) free-runs from its first tick; the math is the pureTempoEnginefed host-time-stamped events throughMIDIInput's internal listener seam (packettimeStamp→ seconds;MIDIOutputstamps sends with real host time so in-process loopback timing is exact), soTempoClockTestspin it deterministically. ExamplesIntegration/,MIDILoopback MIDIMonitor,Tempo(internal-timer loopback: an in-sketch master sends clock through a virtual source; turn it off and real gear drives the same sketch);Docs/. Timecode —Integration/ MIDI .md TimecodeClock(follows MIDI Time Code into a position (from: input) timecode/secondsgliding between frames /frameRate/isPlaying/isReceiving/isReversed) over theTimecodevalue (hours, minutes, seconds, frames at.fps24/.fps25/.fps30Drop/.fps30;frameNumberandtotalSecondsdo the drop-frame arithmetic, 1,798 frames a minute and 17,982 per ten;quarterFrameValue(/piece: ) init(andquarterFrameValues: ) fullFrameSysEx/init(are the two wire forms).fullFrameSysEx: ) TimecodeisComparable, so a cue test is<and a cue window is a range: the order runs ontotalSecondsrather than the frame number, so two rates answer honestly about which moment came first (frame 30 at 30 fps is earlier than frame 30 at 24 fps), and two naming the same moment at different rates are broken apart by rate so<and==never disagree, which is the total order the protocol requires. Four tests inTimecodeTests. Load-bearing: a completed set of eight quarter frames anchors the position at the time it spells plus 1.75 frames (the set took two frames to arrive; backward, minus), every further quarter frame moves the anchor a quarter frame in the direction the pieces run, and the glide between messages is clamped under a quarter frame so a late one never runs the position back; a full-frame exclusive locates and holds; half a second without a quarter frame is stopped. The input walks Universal MIDI Packets by their word count (a 7-bit exclusive is two words, and reading it a word at a time took its data for a message) and assembles exclusives across packets for a module-internaladdSysExListener;MIDIOutputpacks them six bytes a packet and.send( sysEx: ) send(timecode:)sends a full frame.TimecodeTests(13, pure: the drop-frame round trip over two hours at every rate, both wire forms, and the engine's landing, glide, stop, locate, reverse, and restart) + the loopback casetimecodeCrossesTheLink. ExampleIntegration/(an internal deck through a virtual source; real gear drives the same sketch); Guide Ch 47 § Following another timeline: timecode. Per-note expression (MPE) —Timecode heldNotesreads every held note with its bend, pressure, and slide resolved (HeldNote:note/channel/velocity/pitchBendin semitones /pitch/pressure/slide;idis the channel and the note together) overmpeZones(MPEZone/.lower( members: ) .upper(members:), a master channel beside its member channels, the members' bend range 48 semitones and the master's 2 by the specification): a member channel's bend, pressure, and controller 74 are one note's, the master channel's are applied on top (a bend added, a pressure added and clamped, controller 74 as an offset from 64), and a channel outside any zone reads plainly (2 semitones, a key's own pressure per key). Load-bearing: the zone is laid out from the controller's configuration message (registered parameter 6 on channel 1 or 16, assembled per channel from controllers 101/100/6/38; a non-registered selection cancels it; the other zone gives up the channels the new one takes; 0 members takes a zone away), the bend range from registered parameter 0 (semitones plus cents; a member sets the zone's members, the master its own), controllers 120/123 clear a channel's notes and 121 its expression; the math is the pureExpressionEngineunder the input's lock (theTempoEngineshape),slideis nil until told so a note at rest reads exactly 0.5 rather than 64/127, andcontrolValue(74)with no channel is still whichever member moved last.MIDIOutputsendspitchBend/channelPressure/polyPressure/registeredParameter(/_: value: fine: channel: ) send(mpeZone:)(the configuration message plus both bend ranges).MIDIExpressionTests(8, pure) + the loopback caseexpressionReachesOneNote. ExampleAudio/Expression;Docs/§ Per-note expression; Guide Ch 43 § A note under the finger: expression.Integration/ MIDI .md MIDIOutputopens the named destination or nothing (.open( matching: ) MIDIError; the choice is.noDestination MIDIOutputover names, with no fallback to the first device): a name nothing matched used to send to an unrelated device, and no device at all read as open..pick( from: matching: ) Link tempo session (
OllinLinksatellite). The network tier of tempo sync:LinkClockjoins the local network's shared tempo-and-phase session (the Link protocol) — peer discovery over UDP multicast224.76.78.75:20808(_asdp_ALIVE/RESPONSE/BYEBYE + TLV payload), ping/pong clock-offset measurement (_link_, chained until >100 points, median offset, ghost = host + offset, re-measured every 30 s unless founder), and session consensus — implemented independently from published protocol documentation, nothing vendored (ATTRIBUTION.md§ Satellite libraries; the wire format is pinned against a real captured announcement inLinkWireTests). Read surface mirrorsTempoClockon purpose (tempo/beats/beatCount/phase/beatpulse /timeSinceBeat/bar/barPhase/progress(over:)), plus writabletempoandisPlaying,peerCount,start()/stop();beatsPerBardoubles as the session quantum. Load-bearing: the state machine is the pureLinkEngine(host-microseconds in, send-actions out — theTempoEnginediscipline), so priority, arbitration, and the measurement chain are pinned with synthetic clocks; a same-session timeline is adopted only on a strictly larger anchor beat (a local edit outranks by exactly +1 µbeat and arms a 1 s guard against in-flight traffic); arbitration joins the older session — larger ghost time, ties within ±0.5 s to the smaller session id; losing the last peer is a continuity reset (fresh node+session identity, ghost re-anchored at 0, tempo/beat/playing kept, transport stamp 0 so any real change outranks it); the beat grid never stops (transport is advisory, last-writer-wins on a strictly newer ghost stamp) andbeatsis per-participant — the mod-quantum residue (phase encoding) is what aligns, sobarPhaseis the cross-peer read; gateways are per-interface BSD sockets (SO_REUSEADDR+SO_REUSEPORTon0.0.0.0:20808, per-interface membership,IP_MULTICAST_IF+ loop on, loopback interface included so one machine syncs with itself; rescan every 5 s).LinkLoopbackTestsis.serialized— every clock shares the one multicast group, and the fixed port means two overlapping test runs on one machine can disturb each other's peer counts (same class as the Core MIDI loopback names). ExampleIntegration/Tempo(its Link mode; run two copies and they pulse together);LinkWireTests+LinkTimeTests+LinkEngineTests+LinkLoopbackTests(30);Docs/; Guide Ch 42 § One beat for the whole room: Link. Failure shape (2026-09-22):Integration/ Link .md interfaceCount(gateways open, loopback included) andunavailableReason(a sentence only while running with no interface, naming the last socket stage that failed; every interface is retried about every five seconds, so it clears itself), since a running clock that opened nothing read exactly like one alone on the network.LinkLoopbackTestspins the loopback case; a socket that refuses cannot be forced from a test, so the negative is by reading..aRunningClockSaysWhetherItIsOnAnyNetwork Serial (
OllinSerialsatellite;SerialPort.swift+SerialDevice.swift+LineAssembler.swift). The classic physical-computing loop: IOKit discovery (SerialPort, callout.availableDevices( ) /dev/cu.*paths, USB product names searched up the registry, USB devices sorted first) + POSIX termios I/O, nothing vendored. Three read surfaces, the OSC/MIDI recipe: latest-line cache with numeric coercion (latestLine/float/int/bool, the whole trimmed line as one number — the framingbindunderstands too), event drain (lines(), arrival order), and@Parambinding (bind(to:from:), default input 0…1023, the 10-bit analog read); a fourth,bytes(), drains the raw stream for binary protocols and is independent oflines()(two buffers, both capped — 4096 lines / 64 KB, oldest dropped). Load-bearing:open()never throws and never gives up — reconnection is the design center (absent/busy/unplugged retried every 1 s, constant, no backoff: the device is local and coming back fast from a cable bump or a firmware flash is the point), andSerialPort(re-resolves its match on every attempt (a board plugged in later, or re-enumerating under a new number after a replug, is still found — the fixed-path init can't be, so the docs steer atmatching: ) matching); agenerationcounter bumped byopen()/close()invalidates stale retries and stale reads, andattemptre-checks it after storing the descriptor (the close-during-open window). The descriptor opensO_RDWR|O_NOCTTY|O_NONBLOCK+TIOCEXCL(two readers each get half the bytes; consequence:close()before a firmware upload, the reconnect loop handles the reopen) with raw-8N1 termios applied best-effort (pty pairs and some drivers refuse parts; a partly configured port still reads — this is what lets a pty stand in for the device in tests). Reads go through aDispatchSourceReadwhose cancel handler owns theclose()of the fd (no event can fire on a closed descriptor); EOF (read→ 0) = device gone → drop + retry.LineAssemblertolerates LF / CRLF / bare CR (the CR flag survives a chunk boundary), decodes UTF-8 per complete line (a multi-byte char split across reads stays whole), caps a never-terminating line at 4096 bytes, and is replaced on every (re)connection so a partial line never leaks across sessions. Writes go out on the port's queue (bounded EAGAIN grace, ~50 ms, then the rest drops) and bytes sent while the device is away are dropped, not queued — a reconnected board wants current values, not a replay. Whole loop testable headless over a pty pair (the replica opens as a realSerialPort; manager side is the fake device — the same trick theSerialLoopbackexample plays live). ExamplesIntegration/(pty fake device, click writes back and the wave flips) +SerialLoopback Integration/(live device list, auto-opensSerialMonitor matching:, scrolling lines + value bar);"usb" SerialUnitTests+SerialLoopbackTests;Docs/. Firmata over the port (Integration/ Serial .md FirmataBoard,Firmata.swift): StandardFirmata's protocol spoken over aSerialPort(its own at 57600, or one passed in), so a board needs no firmware of the sketch's own.analog(_:)(channel-numbered, scaled 0...1 over the 10-bit reading),digital(_:pullUp:),write(_:_:)for Bool (digital out) and Double (PWM 0...1) andwrite(_:angle:)(servo),setMode,sampleEvery,send(text:),messages()draining every decoded message,bind(analog:to:)onto a@Param,firmwareonce the board answers. Load-bearing: asking a pin is what turns it on (the first read sets the mode and the report, the first write the mode, nothing sent twice), and since an Arduino resets when its port opens the board is queried on every connection and everything asked so far is restated whenever it announces itself (a replug picks up where the sketch is). The parser is a byte state machine that survives any chunk boundary and resynchronizes at the next command byte; a digital port word becomes per-pin changes (all eight the first time). The port grew two internal sinks (byteSinkon the port queue per chunk,connectionSinkper fresh connection) so a protocol layers on without touching the line framing.FirmataTests(12: the codec against the spec's byte tables, the parser, chunk boundaries, resynchronization, and a pty loopback with a fake board for the query, the asks, the writes, the binding, and the restatement); exampleIntegration/Firmata(a real board owes a desk check). Failure shape (2026-09-22):lastErroron the port and the board, the sentenceopen()is waiting on (no device at <path>/no serial device matches "<needle>", the system's own errno text for a port another program holds,the device went away, a read that failed), cleared the moment the port opens;open()retries as it always did. A going-away sentence stands while the retries only confirm the absence (ENOENTat the path, no device matching the needle), and any other retry failure replaces it: the runner's pty path is gone by the first retry where the M2's lingers, so the errno text overwrotethe device went awaythere and nowhere else (2026-09-23).SerialLoopbackTestsand the device-going-away test pin it. The pty suites run one test at a time (.aPathWithNoDeviceSaysSo Pseudoterminals, a serialized parent overSerialLoopbackTestsandFirmataTests): the kernel hands a freed pair's number to the very next pair asked for, so a port retrying its path after its device went away opened a sibling test's fresh pair and read its bytes (two tests red together on the runner, 2026-10-19);aDeviceThatComesBackAtItsPathIsReconnectedpins the reconnect that made it possible.Bluetooth (
OllinBluetoothsatellite;BluetoothDevice+.swift BluetoothScan.swift+BluetoothCatalog+.swift BluetoothUUID.swift+BluetoothBackend+.swift CoreBluetoothBackend). The physical-computing loop with no wire, over CoreBluetooth:.swift BluetoothScanis the room (every device in range, strongest signal first,forgetAfterdropping one that has gone quiet, an optional service filter applied at the radio),BluetoothDeviceis one device found three ways (named:substring /service:/id:/ a scannedBluetoothPeripheral) and read the OSC/MIDI/serial way: latest-value cache (number/int/text/bool/bytes/data/latest, each with adefault:form), event drain (readings(), arrival order, capped at 4096 oldest-first), and@Parambinding (bind(_:to:from:), clamped into the parameter's range), plusread/poll(_:every:)/subscribe/unsubscribeandwrite(_:to:)for text and bytes. The permission is the headline, not a footnote: macOS asks once per app before a program may use Bluetooth, and until that is answered the radio reports.waiting, not off and not refused — measured on this Mac, aswift runbinary sits inCBManagerStatewith.unknown CBManagerfor ever while the screen is locked, because the question cannot be shown there (an embedded.authorization == .notDetermined __info_plistsection + ad-hoc signature gives the process a bundle identifier and changes nothing about this). SoisAvailable/unavailableReason/radioStateare the surface every object carries, the reason is a finished sentence a sketch draws (naming the locked screen, since that state is what reads as a broken sketch), it is repeated once on stderr past a 3 s grace (the haptics precedent), and a headless export reports the radio absent rather than asking for a permission a file cannot use (connect()/start()are@MainActoronly to readisRenderingHeadlessthere and stash it, so the reason stays readable from anywhere). Values carry their own format, because Bluetooth says nothing about what its bytes mean:BluetoothFormat(.raw/.unsigned(/bytes: scale: ) .signed(+ thebytes: scale: ) .uint8….int32shorthands /.float32/.text/.heartRate), least-significant byte first, written from the standard's published layouts;.heartRateis its own case because the first byte's lowest bit decides whether the rate is one byte or two, and more fields may follow (reading two where it said one turns a resting 114 into 626 — the sabotage-verified test, and the only one that separates a right reading from a lucky one is a narrow rate with fields after it). ABluetoothCharacteristicis equal by identifier alone, so a value stored under a discovered characteristic is found by a catalog constant and can be re-read another way at the point of reading (.read(as:));BluetoothUUIDexpands the standard's 16-bit numbers into the 128-bit base so both spellings compare equal, and keeps unparseable text as itself withisWellFormedfalse (a mistyped UUID is a device that never answers, never the wrong value). Catalog:.heartRate/.battery/.environmentalSensing/.deviceInformation/.uartservices with their values,.uartbeing the de facto serial line most maker boards speak. Load-bearing:connect()never fails and never gives up (a 1 s constant retry, the serial precedent),connectingTois tracked besideconnectedTobecause a connection that fails arrives before there is anything connected to compare it against and a check against the connected device alone waits for ever (its own test); a connected device is asked about everything it offers (notify on what announces itself, one read of what it holds) so the first frame that asks usually has a value;CoreBluetoothBackendretains everyCBPeripheralit sees (CoreBluetooth does not, and a released one drops its connection silently) and readsCBUUID.uuidStringthroughBluetoothUUID(it prints short for standard values and long for everything else); the scan asks for repeats and the device hunt does not (without repeats a signal never moves; with them a hunt pays for nothing). The radio sits behind an internalBluetoothBackendseam — the controller satellite's synthetic-pad precedent — which is what makes the whole path testable with nothing switched on:OllinBluetoothTests(46) drive a stand-in radio through the shipped matching, connecting, subscribing, caching, draining, clamped binding, polling, letting go, and coming back. What that does not cover, and only real gear can: CoreBluetooth itself, and this Mac hearing another device. No pixel snapshot (a live radio has nothing deterministic to draw). ExamplesIntegration/(the room by signal strength; needs no gear of your own) +BluetoothRoom Integration/(a name typed into a parameter, everything the device offers as it arrives).BluetoothSensor Docs/; Guide Ch 42 § The same loop, without the wire: Bluetooth + the BytesIntoValues figure. A lost link is readable:Integration/ Bluetooth .md lastErrorcarries why the link dropped or would not come up (the radio's words when it gave any), cleared at the next connection and atdisconnect();nameisnilwhile nothing is connected.MQTT (
OllinMQTTsatellite;MQTTClient.swift+MQTTMessage.swift+MQTTWire.swift). The message bus a building speaks, so a sketch reads a house's sensors and drives its lamps: MQTT 3.1.1 written from the published specification over Network.framework TCP, nothing vendored.MQTTClient(+host: port: clientID: username: password: will: keepAlive: reconnects: ) connect()/disconnect()/isConnected/lastError,publish(for text / a number / a_: _: qos: retains: ) Bool/payload:bytes,subscribe(to:qos:)/unsubscribe(from:)/subscriptions, and the OSC/MIDI/serial read triple: latest cache (message/number/int/text/bool, each with adefault:form, plustopicsandtopics(matching:)), event drain (messages()andmessages(matching:), which takes only its filter's own and leaves the rest so two readers do not steal from each other), and@Parambinding (bind(_:to:from:), mapped and clamped).MQTTMessagereads the three things devices actually write: a decimalnumber/int(whitespace-tolerant), aboolover the words a switch publishes (ON/true/1/yes/open/online/activeand their opposites, any casing), and a JSON object's field throughnumber(named:)/int(named:)/text(named:)/bool(named:)(a field written as a string of digits still reads as a number). Load-bearing:MQTTQoShas no exactly-once case on purpose (the four-packet handshake buys a sketch nothing over the newest reading), so a broker never opens it;.atMostOncepublished while the line is down is gone, not queued (that is what at most once means) while.atLeastOnceis held and resent with the duplicate bit after a reconnection and dropped on its PUBACK, both sabotage-verified; a refusal is an answer, not a dropped line (wasRefusedstops the reconnect and keeps the reason, since the broker closes the socket right behind the CONNACK and a later drop would otherwise overwrite it — the race the stub reproduces); a reconnection resubscribes from the stored filters (clean session is always asked for, so the broker remembers nothing) after a backoff from 0.25 s doubling to 8 s;connect()dials whenever no connection stands, never on whether one was wanted: withreconnects: falsea drop left the wish set andconnect()returned at once, so a sketch doing its own reconnecting could never get the line back (MQTTReconnectTests), and a redial pending on its own backoff finds the connection and stands down; andconnectionCountis what a sketch watches rather than catchingisConnectedbetween frames; the heartbeat goes out at three quarters ofkeepAliveand silence past one and a half of it is a dead line;MQTTTopic.matchescarries the two rules that are easy to get wrong, a trailing#matching its own parent level and no leading wildcard reaching a$topic; a publish to a topic holding a wildcard does nothing (a published topic is exact); the remaining-length field is four bytes at most and a fifth continuation byte is refused; and a partial packet reads as incomplete rather than wrong, since a packet arrives split across reads as often as not. Tests:MQTTWireTests(11: every packet kind round-trips, the CONNECT layout byte for byte against the specification, the reserved0b0010on SUBSCRIBE/UNSUBSCRIBE, the length field at all eight boundaries, every prefix of a packet incomplete, 2,000 random datagrams refused without trapping, the specification's own matching table, and the payload readings) +MQTTSessionTests(14 over the loopback againstMQTTStubBroker, a broker in the test process because mosquitto is not installed on the machine and because a real broker will not cut a socket on request, sit on an acknowledgment, or refuse with a chosen code: connecting, the refusal, the round trip, a retained value handed to a later subscriber, both directions of.atLeastOnce, the two drains, unsubscribing, the parameter binding, the heartbeat, the will firing on a cut socket and not on a goodbye, the reconnection with its resubscribe, and the resend). A real broker at the desk is still owed. No pixel snapshot (the output is values). ExampleIntegration/(every topic heard as a dial, publishing a wave of its own so a bare broker already shows the round trip; media held back for a desk with a broker on it).MQTTRoom Docs/; Guide Ch 49 § What the building already says: MQTT + the TopicsAndFilters figure.Integration/ MQTT .md Remote surface (
OllinRemotesatellite;RemoteInspector+.swift RemoteWire.swift+Resources/). Thesurface .html @Paraminspector served to a phone:extend(starts oneRemoteInspector( )) NWListenerTCP port (default 9330,port: 0for system-picked;url/boundPortreport it, one line printed on ready) whose connections speak hand-rolled HTTP (the page, a.copyresource, served onGET /) and a hand-rolled WebSocket upgrade + frame codec — the whole wire layer (RemoteWire/RemoteHTTP/RemoteWire.Frame) is pure functions over bytes/values, and its tests are socket-free on purpose (the house no-loopback-TCP rule; the accept key is pinned to the RFC 6455 worked example). Values are sent as theCodableParamStoredpayloads the hosts persist, with one deliberate exception: a menu travels by option *index* (.number), because the page knows display labels and their order, never the enum's case names; every other kind applies throughrestore, a menu through its control setter with a bounds check. Phone edits queue and land inbeforeDrawon the main thread — the same frame boundary the host inspector writes at — never on the network queue; the wire snapshot the queue reads (hello descriptors + values + shown) is rebuilt on the main thread each ~250 ms push tick and handed across under a lock. Pushes are diffed (changed values + flippedshow(when:)rows) plus a stats message (fps/clock/frame); the page renders every control family touch-first (whole-row bar sliders, pad, segmented, native color picker), reconnects on close, and ignores echo while a row is mid-touch. Reload safety: a fresh sketch brings a fresh extension;deinitcallsstop()andallowLocalEndpointReusecovers the swap window. Open-network caveat (possession of the address is the key) documented, not gated. ExampleIntegration/(aurora serving all control families, draws its own pairing URL);RemoteSurface OllinRemoteTests/;RemoteWireTests Docs/.Integration/ Remote .md The room (
OllinRoomsatellite;Room.swift+RoomSession.swift+RoomWire.swift+RoomClock.swift+RoomTransport.swift+LocalNetworkTransport). Several machines drawing one piece, with no server and no address:.swift Room(+named: "wall") extend(room)and two Macs on one network find each other over MultipeerConnectivity by that name alone (as:overrides the display name,seat:fixes the slice,passcode:gates the room). Three things travel: values under a key (send(_:_:reliable:)forDouble/Int/String/Bool/Vector2/Color/Data, read the OSC/MIDI three ways — latest cachenumber/int/text/bool/point/color/bytes+ defaults, drainmessages(), andbind(_:to:from:)onto aParam<Double>);@Paramvalues (share(_:)/shareAll(), sent as theParamStoredpayloads the hosts persist); and one clock (room.time,ownsClock,clockError). Plus membership (name/peers/everyone/isAlone/sketchName(of:)/arrivals()/departures()/lastError) and the wall split (seat/seatCount). Load-bearing: the transport is a seam (RoomTransport, three calls over bytes), which is what lets the whole session be tested in memory and the loopback example run two rooms in one process — no socket is opened in any test, the house no-loopback rule; connected membership is kept apart from what greetings say (a hello can arrive before the transport reports the peer that sent it, and reading membership off greetings then makes a machine think it already greeted that peer, so its own hello never goes out and the other end never learns its seat or sketch name — the defect the first run had, caught bytwoRoomsFindEachOtherAndSayWhatTheyAreRunning); only the lower-sorting name invites (both sides see each other, and if both invite, two connections race and one drops, which reads as a peer joining and leaving forever), and the room name is checked twice (in the advertiseddiscoveryInfoand in the invitation) because the service name is capped at 15 characters, withRoomWireprefixing.serviceType( for: ) ollin-and, when it must truncate, hashing the cleaned name rather than the typed one (or "Sala Grande" and "sala grande" would be different rooms); the clock owner is the lowest name (elected locally, no protocol) andRoomClock.offsetsurvives a reset, so an owner leaving re-bases the estimate without room time jumping back to this machine's own clock (measured across a real handover: a 0.1 ms step); the estimate is the published round-trip one with the quickest recent answer believed rather than an average (a slow answer is a delayed one); a parameter carries the room time it was set at, and the later change wins everywhere with the machine name breaking a tie — without it two people setting one parameter at once take each other's value and stay mismatched for good (sabotage-verified red); an arrival re-sends every shared parameter (a machine switched on later would otherwise show its own defaults until somebody touched one, so the join tally is counted, never drained, or the sketch's ownarrivals()would come back empty); incoming parameters apply atbeforeDrawon the main thread (the inspector's own frame boundary) while a bound key applies on arrival (OSC parity); the transport handler closures are built inside the non-isolated session, never in the@MainActorextension, per the render-thread-closure rule;unframecopies theDatainto an array because a network callback hands over a slice whose first index is not zero; the inbox caps at 4096. A headless export never opens the local network (nobody to meet while a file is written, and no permission asked), though a room over a supplied transport still opens. Measured (two sketches on one Mac, real transport): they find each other in about a second, the first clock answer lands within 0.25 s of joining, and the clocks then agree to 0.1 ms (the measurement floor). Local-network permission is the terminal's, as with screen capture. ExamplesIntegration/(a wall as wide as the room has seats, every parameter shared, a readout of seat, company, and clock agreement) +RoomCanvas Integration/(two rooms in one sketch over an in-process transport, space cuts the wire);RoomLoopback OllinRoomTests(53: the codec and its refusals, the service-name rules, the clock arithmetic, and two whole rooms over a memory bus); no pixel snapshot (the output is values). Guide Ch 49 § Several machines, one sketch:Room+ the OneRoom figure.Docs/.Integration/ Room .md Syphon (
OllinSyphonsatellite). Live GPU frame-sharing with other Mac apps over the vendored Syphon Framework (BSD-2,External/CSyphon, Metal portion only — wrapped, off the public surface).SyphonServer/publishSyphon(publishes the rendered texture;name: ) SyphonClient.framedraws an incoming feed asImage(texture:). Brought two core seams (shared with future layered effects): the GPU-texture frame hook (wantsRenderedTexture+frameRendered(, the on-screen frame tone-mapped once more into a canvas-sized texture, no CPU readback) and texture-backed_: texture: ) Image(texture:). Gotchas: publishflipped: true+ client flips back (orientation); hand the server a non-sRGB.bgra8Unormview and read back through a.bgra8Unorm_srgbview (color — both need.pixelFormatViewusage); single-GPU Macs only; and the vendored engine carries no unsafe build flag, because a target holding one cannot be reached through a package depended on by version, which madeimport OllinSyphonunresolvable for every consumer outside this checkout (error:, and note athe target 'CSyphon' in product 'OllinSyphon' contains unsafe build flags branch:dependency does not show it, only a version one does). Upstream's forced prefix header is replaced by one import ofExternal/at the top of eachCSyphon/ OllinSyphonPrefix .h .m, recorded inTHIRD-PARTY-NOTICES. Examples.md Integration/,SyphonLoopback SyphonViewer;Docs/. Failure shape (2026-09-22):Integration/ Syphon .md unavailableReason(no source of that name was available when the client looked, no Metal device, a source that refused the connection, or one that has since gone away, read offisValid),nilwhile the connection stands;SyphonLoopbackTests..aMissingSourceSaysSo stop()is final: the server's life is onePublisherPhase(Core/, public, shared with the virtual camera and the phone screen:PublisherPhase .swift waiting/publishing/unavailable/stopped),wantsRenderedTexturereads it, a frame that still arrives is refused, andphasesays.stopped;isStoppedwas the first spelling andcheck-api-namesrefused it, since a stopped thing reads through its lifecycle word; the next frame used to stand the server back up and turnisPublishingtrue again (SyphonServerStopTests).Haptics (
OllinHapticssatellite;HapticEvent.swift+HapticPattern.swift+TrackpadPlan.swift+HapticHub.swift+DeviceHaptics.swift+Sketch+Haptics). Touch as an output beside the pixels and the sound:.swift HapticPattern(a value holding.tap/.humHapticEvents on its own timeline, built by.tap/.hum/.pulses/.silenceand composed bythen/over/delayed/repeated/scaled/speed/reversed), played throughplayHaptic(_:)/stopHaptics()/hapticStrength(_:)withhapticsAreAvailable/hapticHardware/hapticsUnavailableReasonreporting what is on the other end. The platform fact that shapes the whole design, and it runs the other way from the design note: Core Haptics does not drive a Mac.CHHapticEngineis false on a MacBook Pro with an actuating trackpad, and.capabilitiesForHardware( ) .supportsHaptics CHHapticEngine()init fails-4809(notSupported) — probed on this machine; the Force Touch trackpad is reached through AppKit'sNSHapticFeedbackManagerinstead, which offers three fixed feelings and one strength, and it actuates only while the button is held (felt at the desk 2026-09-01: every knock asked for during a plain pointer move was planned and delivered to nobody, while the same knocks under a held button landed), so a sketch asks for touch inside a drag, never on a hover. So the tier is two back ends behind one seam, and the trackpad one plans before it plays (TrackpadPlan, a pure function, which is what makes the whole translation testable with no hardware): sharpness picks the feeling (thirds), strength becomes density (rate coding, 6…30 knocks a second, and a fade thins the run rather than lowering it, since the hardware has one strength), anything under the 0.05 floor is dropped (so a pattern that fades to nothing ends in silence, not one stray knock), and knocks closer than 20 ms are dropped twice over — inside a pattern by the plan, and across patterns by the hub against the clock, since the plan only ever sees one pattern and a sketch calling every frame is the case it cannot see. Load-bearing details: availability is read from the IOKit registry (.knocks( for: strength: ) AppleMultitouchDevice/ActuationSupported), never from the performer, which is handed back on every Mac and silently does nothing where there is no actuator;stop()resets the spacing clock (nothing is playing, so the next knock waits for nothing) and bumps a generation so scheduled knocks that have not landed are canceled;DeviceHapticsis not@MainActor(the engine's stopped/reset handlers arrive off-thread, the render-thread-closure rule); aHapticEventclamps every number at init and turns a NaN or an infinity into 0 (one infinity in a time is a knock that never arrives, one NaN makes every comparison in the plan false);HapticEventis public so a sketch can draw the envelope the hand is being given, and both the example and the Guide figure do. The.strength( at: ) .enginepath (CHHapticEventtransient/continuous, fades expressed in the system's normalized attack/release adjusters rather than seconds,sustained1) is written and checked as far as it can be without hardware — the system builds a pattern out of events with no device involved, so the tests read the translation straight back off it — and it waits on the phone and pad rather than on this library;makePatternthrowsnothingToPlayon an all-silence pattern (the system itself would accept an empty one and start an engine for it). Felt at the desk 2026-09-01: the three feelings tell apart, and the hum's rate coding reads as a stronger hum toward the right. Rumble on a game controller is the named next leg (theControllerdocs already point here for it). ExampleIntegration/(three strips of ridges knocked under a held-button drag, a hum under the space bar, and the plan drawn along the bottom edge);HapticRidges HapticPatternTests/TrackpadPlanTests/HapticOutputTests(51, the rate coding, the spacing rule, the cross-play guard, and the fade each verified red by sabotage; the hub suite.serializedon the one process-wide hub, with a stand-in performer and a hand-wound clock the stand-in scheduler advances, since firing a whole timeline at one instant would let the spacing rule eat everything after the first knock); no pixel snapshot (the output is touch).Docs/; Guide Ch 42 § Touch as an output: haptics + the FeltPattern figure.Integration/ Haptics .md Game controllers (
OllinControllersatellite;Controller.swift+ControllerButton+.swift ControllerHub.swift+Sketch+Controller). A modern controller read in.swift draw()over GameController:controller(player one) /controller(/_ player: ) connectedControllers/controllerCounthand back aControllervalue snapshot (sticks / dpad / triggers /isDown/wasPressed/wasReleasedover theControllerButtonenum /isConnected+didConnect+didDisconnect/ motion / touchpad / battery /unavailableReason), with the bare settingscontrollersReportMotion(/_: ) controllerDeadzone(/_: ) controllersRunInBackground(/_: ) discoverControllers(. A satellite, not core input, and the reason is the seam, not convenience: mouse / keyboard / pressure are core because they arrive as) NSEvents throughOllinMTKViewand need the AppKit/UIKit seam, where a controller is handed to the process by a system service, touches no view, and is character-identical on macOS and iOS, so core membership would buy the iOS leg nothing and cost every 2D sketch a framework link. Load-bearing: the tier is polled once per frame (sampleIfNeeded(keyed onframe: ) frameCount, so every read within a frame agrees and the hardware is hit once), and that is why it is testable at all — a syntheticGCController(GCController) accepts written values and reads back through the shipped path, but does not fire the system's change handlers and never joins.withExtendedGamepad( ) GCController, so a handler-driven design would be unverifiable with nothing plugged in and the hub takes its list through an injectable.controllers( ) sourceseam; the classicextendedGamepadprofile is the one to build on, notGCControllerLiveInput, whosebuttons/axes/dpadscome back empty on a synthetic controller (probed). Nothing arrives off-thread, so there is no lock and no@unchecked Sendableproducer here, unlike every other satellite. Presses/releases are edges differenced between two samples (ControllerButtonMask, one bit per button,wasDown/downon the slot) with no event drain by design — a press lasts several frames, so unlike MIDI a hand cannot press and release between two of them. Sticks/dpad/touch are y-flipped once into canvas terms (up reads negative, sop += stick * speedmoves up the screen); the deadzone (default 0.1) is radial and rescaled, never a per-axis cut (which jumps at the edge and bends a diagonal hold). Player slots are held, not recomputed (a controller keeps its number while connected, a newcomer takes the lowest free one, so unplugging player 2 cannot renumber player 3), assigned by walking the slot array in order rather than a dictionary (the determinism rule). Motion is opt-in (sensorsActivecosts battery;hasMotionis false both with no sensors and with none asked for) and Xbox hardware has none at all; the touchpad comes fromphysicalInputProfile, never.touchpads[GCInputDualShockTouchpadOne] GCDualShockGamepad, which is typed as a plain direction pad and so cannot tell a finger resting dead center from an untouched surface (only the named element carries.touchpadPrimary touchState). Permission: none — probed, a bareswift runbinary reads a controller with no TCC prompt and no entitlement (unlike the screen); what is real isshouldMonitorBackgroundEvents, NO by default since macOS 11.3, so a sketch behind another window reads centered untilcontrollersRunInBackground(. Headless reads neutral withtrue) unavailableReasonset and a one-time stderr note. Deliberate cuts, each named in the docs rather than dropped: rumble / adaptive triggers / the light bar (outputs, so they belong to the haptics work), Apple Pencil (waits on the iOS leg; its force joins the shippedpressurerather than becoming a second thing), attitude (no public quaternion type yet), racing wheels and spatial accessories. ExampleIntegration/(a pad as a drawing instrument,ControllerInput mapdrawing every input as it is read);ControllerTests(27,.serializedon the one process-wide hub, each invariant verified red by sabotage; the single hardware test is.enabled(if:)so a machine with no pad reports it skipped and says so rather than passing vacuously); no pixel snapshot (live input).Docs/; Guide Ch 42 § Something to hold: game controllers + ReadingAPad figure. A controller with no extended profile takes no slot (filtered inIntegration/ Controller .md ControllerHub): seated, it read as not connected while reporting.sample( ) didConnect, and pushed the readable pad to the next player.Screen and window capture (
OllinScreensatellite;ScreenCapture.swift+ScreenSource.swift). Any display / app / window as a liveFrameSource+VideoFeedover ScreenCaptureKit: the non-cooperative counterpart to Syphon (which needs the other app to publish).ScreenCapture(+_ source: ) start()/stop(), drawn withdrawFrame/frame, GPU-resident (IOSurface →CVMetalTextureCache→Image(texture:), theVideoPlayerpath,.bgra8Unorm_srgbagainstconfig); parameters.colorSpaceName = .sRGB source/excludesOwnWindows/showsCursor/frameRate/scaleare all live (a filter-only change pushes throughupdateConfiguration, a filter-changing one rebinds).ScreenSourceis the nameable value (.mainDisplay/.display(id)/.app(/name-or-bundleID) .window(/matching: app: ) .windowID), withavailableDisplays()/availableWindows()/apps()for discovery — named-in-code is primary and the system picker is a deliberate cut (SCContentSharingPickeris a Control-Center application singleton with an observer protocol, host-app shaped, and a picked filter is a click nobody recorded; enumeration gives the same discovery). Load-bearing: the stream must be retained or it is deallocated and silently stops delivering with no error and no callback (cost a probe to find), and it lives in aStreamHolderso the nonisolateddeinitcan end it; self-exclusion keys on pid, never bundle identifier (aswift runsketch is listed inSCShareableContentwith an empty bundle id, soScreenMatch.appmust reject an empty needle or every such process matches ""); frames arrive on a background queue so theSCStreamOutputis a file-scope non-@MainActorclass (the render-thread rule) handing the buffer over anNSLockbox (aCVPixelBufferis explicitly notSendable, soOSAllocatedUnfairLock's generic form can't hold one); onlySCFrameStatussamples carry pixels (idle/blank ones are also delivered); the captured size is.complete filter(points → backing pixels) times.contentRect * filter .pointPixelScale scale; the CPUCGImageconversion for the tap runs only while a tap is installed; a source naming something absent is a wait, not an error (a 1 s retry loop,isRunning= wanted vsisReceiving= arriving), and a stream the system ends re-binds. The matching rules are extracted as pure functions (ScreenMatch) becauseSCShareableContenthas no public init, so a fake screen cannot be staged; app names match in full (else"Mail"takes MailMate) while window titles match as a substring, ties broken by lowest window id so a run repeats. Permission is the design problem and it is a terminal's, not the sketch's: aswift run/ollin/ OllinLive / gallery binary has no bundle identity, so TCC attributes screen recording to the launching terminal (verified:CGPreflightScreenCaptureAccesstrue and a full stream from a bare binary, with no entry of its own in System Settings), one approval covering every sketch from that terminal; surfaced asisAvailable/unavailableReason/requestAccess()(allnonisolated), a missing permission drawing its reason rather than throwing, and granting it never reaching a running process. Deliberate v1 cuts: system audio (belongs with the audio analyzer surface, not bolted to a video frame source) and the picker. ExampleIntegration/(the display filtered,ScreenCapture Llisting what is capturable as the code line naming it, and the feedback tunnel on a parameter);OllinScreenTests(26; the rules always-on, the end-to-end capture soft-gated on the permission — a consent a machine cannot grant itself); no pixel snapshot (a capture is whatever is on screen).Docs/; Guide Ch 36 § Drawing with the screen: ScreenCapture + ScreenAsMaterial figure. A start that crossed a suspension asks whether it is still wanted (Integration/ ScreenCapture .md attemptBind: stopped or superseded, the stream that came up is ended on the spot, and a called-off attempt writes no reason): otherwisestop()during a start left the system recording for a capture that read as off. The system's half sits behindstartAttempt/hasAccess, whichScreenCaptureLifecycleTestsreplaces.Virtual camera (
Apps/OllinCameraApphost + CMIO system extension, plus theOllinCamerasatellite). Registers a system-wide "Ollin Camera" every webcam app reads;publishVirtualCamera(letterboxes the canvas texture into a 1280×720 IOSurface-backed) CVPixelBufferenqueued on the device's sink stream, with a built-in "no signal" test card while idle. Gotchas: the sink is the direction-0 stream;CMIOStreamCopyBufferQueuereturns a nil queue unless the queue-altered proc is non-nil (pass an empty closure); the extension is an installed, signed, notarized.app(xcodegen, not SwiftPM) with strict activation rules (bundle-id filename,CFBundlePackageType = SYSX, run from/Applications, install withditto --noextattr --norsrc) — see the app README. A build that replaces an installed camera carries a higher build number (CURRENT_PROJECT_VERSIONinproject.yml, the one place it is written; both Info.plists read it): the system offers a replacement only when the version or the build number differs, and takes a rebuild at the same numbers for the extension already there. The Developer ID signature is a certificate the developer account holds and hands over at export time, so an account with an agreement left to accept fails the export asNo signing certificate "Developer ID Application" foundand the notary service with a 403 (the README's When signing is refused). ExampleIntegration/;VirtualCamera Docs/. Failure shape (2026-09-22):Integration/ VirtualCamera .md VirtualCameraErroris internal, since no public call ever produced it;unavailableReasoncarries its sentences and clears when the retry connects.stop()is final (the sharedPublisherPhase, read onphase): the retry ran from every rendered frame, so the frame afterstop()reconnected and published again, and a stopped server now asks for no frame and looks for no camera (VirtualCameraStopTests).Video playback (
OllinVideosatellite).VideoPlayer(@MainActor) plays a file as a live texture-backedImageviaAVPlayerItemVideoOutput→CVMetalTextureCache→drawImage(zero CPU copies);play/pause/seek(to:)/loops/rate/volume,duration/size(async),snapshot()for CPU/vision. All three initializers throwVideoError/.fileNotFound .resourceNotFoundfor a file that is not there (init(url:)used to open in silence, so the same missing clip was an error or a frameless player by door), and a file that opens but is not a movie says so inunavailableReasonwhileframestaysnil, written by the metadata load or the headless reader, whichever finds it (VideoPlayerTests, 2026-09-22). ConformsFrameSource+VideoFeed, so a tracker attaches and analyzes the footage as it plays (via a second video output). ClearingframeTapmeans no more calls, and that takes two things beyond canceling the pump's timer, since canceling stops the next tick and says nothing about the one already holding a pixel buffer: the tick re-reads a cancel flag immediately before it delivers, and the clear drains the pump's serial queue (queue.sync {}) so no delivery survives it, skipping the drain when it is called from that queue, which is a tap clearing itself inside its own callback and would otherwise deadlock. Before that, a tap removed under load could still be handed one late frame, which is what madeframeTapDeliversCPUFramesfail in a batch and pass alone. Headless export is deterministic: underOllinApp(a.isRenderingHeadless packageflag every offline driver sets) the player swaps to a virtual playhead advanced by the sketch's per-frame pass (FrameAdvancing, nowpackageso satellites conform; isolated@MainActorconformance) and decodes by timestamp through a sequentialAVAssetReader(HeadlessVideoReader), so exported framekalways shows the clip atk/fpsafterplay()— create the player by the end ofsetup()or the advance pass never finds it. Aplay()made before the export began counts: an export builds the sketch before it raises the headless flag, so a player started in a property's initializer went to the live player, the virtual playhead never moved, every exported frame was the clip's first, and a tracker reading it was handed nothing (OpticalFlow's published media showed no flow at all, found 2026-10-17).play/pause/stopnow set the virtual playhead's intent in either mode (ExportClockTests)..aVideoStartedBeforeTheExportPlaysOnItsClock snapshot()follows that virtual playhead too, soseek(to:)thensnapshot()is the deterministic way to read one frame's pixels offline, and a still-imagedetect(in:)over a clip works under an export where a live tracker reads nothing (three Chapter 34 figures measure the bundled film that way). Soundtrack tap:audioTap(the coreAudioTapSourceseam) delivers mono PCM off anMTAudioProcessingTap; the tap's C callbacks touch only a storage object the tap itself retains (released infinalize— never reference the player from the callbacks; the tap can outlive it), and OllinAudio'sSoundtrack(of:)runs the analyzer surface over it (rebuilds once at the stream's real sample rate). Gotchas:.bgra8Unorm_srgbtexture; no y-flip (top-down); keep a shortCVMetalTexturering alive;isMuted = truestarves the audio tap (a hard mute stops audio processing) — usevolume = 0; aSoundtrack/vision tracker reads nothing during a headless export (live-clock paths). ExamplesVideo/VideoPlayback,Video/SoundReactive(spectrum bars + beat ring over its own clip's music);Docs/Video/Video.md. A tap's lock holds the closure inHeld, never as its bare state: the bare shape re-wrapped the closure two thunk frames a read and overflowed the tap thread after about twenty minutes of play (2026-10-06);VideoAudioTapTestsandAudioTapRelayTestspin the consumer one call deep on the three-hundredth block, and the rule is inCLAUDE.mdbeside the handoff rule.rateset under an export leaves the real player at rest (the export's own clock readsrate); setting it used to start the player, sound and all.Physics (
OllinPhysicssatellite). OneWorldstepped each frame, hybrid by design: a soft Verlet side (Particle— afinal class, no stored velocity,previous-based;Spring, a positional distance constraint;Worldwith gravity / drag / bounds / bounce / opt-in diskcollisionsbroad-phased through a uniform spatial hash) and a rigid side backed by vendored Box2D (MIT,External/CBox2D) —addBody/Body/Collider(.circle/.box/.capsule/.polygon) /connect/Joint(.revolute/.distance/.weld/.prismatic) /grab(mouse joint), sharing the world's gravity / bounds / bounce / drag, bridged byunitsPerMeter. Gotchas:dragis the share of speed lost per sixtieth of a second, scaled by the step for a particle ((1 - drag)^(60 dt), exactly1 - dragat a 1/60 step so a 60 Hz run is byte-identical) and handed to the rigid engine as the matching exponential rate (-60 ln(1 - drag), on both linear and angular damping), so one number slows a particle and a body alike at any frame rate (a weightless drift field needsdrag = 0; a.kinematicbody gets 0 whatever the world's, and takes it again when switched back); the walls carry restitution 0, so a body's own wins against them under the engine's max-combine, and a body that named none followsworld.restitutionthrough itsdidSet(Body, flipped by.namesRestitution addBody's argument or therestitutionsetter);gravity.didSetwakes every rigid body (the engine never does);allowFastRotationlifts the engine's quarter-turn-a-step spin cap;substepscuts the soft step into pieces, the frame's applied forces re-added each piece and the default 1 byte-identical (the rod's projection loss is first order in the step: a bob on a rod gives back 70% of its height on its first swing at 1, 98% at 16, and holds within 5% for ten seconds at 64; four pieces at 60 Hz and one at 240 Hz agree to the third digit); Box2D's world pool is a non-thread-safe global → every Box2D-touching test in one@Suite(.serialized); spawn aBodyinsidebounds, not above; disk-collision resolution walks particles in index order with a fixed cell scan — never iterate the spatial-hash Dictionary directly (per-process hash order reordered the position-mutating pair resolution, so a seeded pile settled differently on every run; a real Guide-figure flake). Soft bodies from outlines (SoftBody.swift):Worldrings each closed contour of the fill (resolved by a.addSoftBody( from: Shape, mass: spacing: stiffness: bend: pressure: shapeMemory: ) throws -> SoftBody unionwith nothing, islands and holes byseparated(), outer rings wound positive and holes negative) with ordinary particles aboutspacingapart, every corner over 30 degrees kept as a particle of its own; four XPBD families inside the world's passes (λ cleared each step, α̃ = α / h²): edges, links two and three along the ring (never an angle constraint: measured to pump energy when not converged), each ring's own area (one constraint an island let a counter collapse), and shape matching toward a rigid fit; compliances are relative gives against the body's own weight (mass · pull,pull= gravity at build or 980), shape memory's against a drop (a further factor of 100, measured: read against a load the useful dial was 0.9 to 0.99); the walls hold a soft particle by position only (a per-pass reflection re-reflects, a post-solve velocity pass was measured to change nothing) sorestitutiondoes not reach a soft body; contacts per island, the same body's included, walked in insertion order, pluskeepRingsApartand loose particles with a radius whenparticlesCollide; a world with no soft body steps byte-identically;move(by:)keeps the motion. What a soft body meets (SoftBody.swift+SoftRigidContact): friction at every contact (.swift friction, the rigid body's reading and default 0.3; the position-based friction of Macklin, Müller, Chentanez and Kim 2014 inSoftBody.apply,World, and the rigid push: after the normal correction the step's relative slide along the surface comes out,.holdInsideBounds min(per pass, which sums to Coulomb because the passes' gross normal push is the body's weight exactly, internal constraints conserving momentum; two surfaces rub with the geometric mean of theirs, the walls and a loose particle with the body's own; a round body rolls on a rough floor rather than sliding, so a slope or floor test wants a square); rigid bodies two-way (slide, μ · depth) RigidProxy, built per step from the Box2D shapes in points, the body seen at its predicted posecenter + v·h,angle + ω·h; a particle inside a shape takes its mass share of the depth and the body's share is kept as a pending shift and turn the next pass measures against, never re-pushing for a move the body has not made, and handed over as one linear and angular impulse beforeb2World_Step, so momentum crosses whole: a soft disc into a free ball within 2% at both mass ratios; polygon corners are tested the other way round against the soft island so a crate's corner cannot sink between two particles; segments, the walls, are skipped); self-collision opt-in (collidesWithItself, RULED off by default 2026-10-25,thicknesshalf the spacing: every particle at leastthicknessfrom its own ring's edges but those within ⌈thicknessover the ring's shortest rest edge⌉ + 1 particles either way (ringMinRest), found through a grid over the ring with a cell of the longest edge plus the thickness, walked in ring order; a disc with it on steps identically to one without, at a thickness under and over the spacing; a fold closing faster than the thickness a step can still tunnel). The soft passes run before the rigid step and their impulses land in the same frame. Cost on the nine-blob pile with three balls, 702 particles, debug: 73 ms a step against 83 before, the pile settling sooner under friction.SoftBodyTests15 (area within 2% through a drop, rigid at shapeMemory 1 against the default, no sinking past a pixel, one height within 2% at 30/60/120/240 Hz, a counter kept inside at shapeMemory 0), each red under a plant of its own (zero compliance, no area, no step in the compliance, no ring keeping, no contacts);SoftContactTests11 tests / 14 cases (a jelly on a 0.4 rad plank holds under 0.1 px/s at friction 1 and at 0.3 on a plank of 1, slides at 0.3 and twice as fast at 0; the floor stops a pushed cube in the Coulomb distance; a belt carries a cube at its speed; momentum within 2% at two mass ratios; a ball rests in the dent it made; a corner within 1.5 px; a hairpin pressed shut keeps zero crossings with the pass and crosses without; a disc unchanged by the pass; the settings; one run twice), twelve plants each red in its own test (the three rubs, the impulse, the pending pose, the corners, the pass, the skip, the mean, the circle, the default). ExamplesPhysics/Blobs(rewritten over it, 4.3 ms a frame for 556 particles in release) andPhysics/(a cube on a plank whose friction is a parameter, balls dropped on a slab, a rope that folds);SoftBodiesMeet Docs/§ Soft bodies; Guide Ch 11 § A squishy thing from any outline with the SoftShapes figure; ARCHITECTURE § The 2D soft body. ExamplesSimulation/ Physics .md Physics/Packing+Blobs(soft),RigidBodies/Chain(rigid),Joints(all fourJointKindcases off static anchors, each rig grabbable) andForces(applyForce/applyImpulse/applyTorque, a.kinematicsweeper, apin()ned cloth tinted bySpring.strain,unitsPerMeteron a parameter);Docs/. The 3D rigid side (Simulation/ Physics .md World3D.swift/Body3D.swift/Joint3D.swift/Sketch+Physics3D, backed by vendored Jolt Physics — MIT,.swift External/CJolt, C++ behind Ollin's ownextern "C"bridge, the only code that includes Jolt headers, so theJPH_*define-consistency rule holds by construction); the target definesJPH_NO_DEBUG(the library's debug checks are on unless it orNDEBUGis defined, and its asserts compile to a trap, so a full contact buffer, which the library reports and recovers from, stopped a release build; a Chain poster renders pixel-identically without them), the solver reserves sixteen touching pairs a body for both its body pairs and its contact constraints (a packed box touches up to 26 neighbors; one a body overflowed any dense pile; reserved, not touched, so a default world's peak footprint held at 120.8 MB against 120.9), the step's scratch isTempAllocatorImplWithMallocFallback(the plain allocator aborts past its 16 MiB block), and a step's error flags reachWorld3D.lastErroras one sentence, cleared by the next step that keeps every contact (aPileDenserThanOneContactABodySteps, which trapped before, andaPileThatOverflowsSaysSoAndRecovers);maxBodiesreads back what the world was made with, and every body creator throwsPhysicsError.fullpast it (addBody,addStaticBodies,addCharacter, andaddBodies(from:)became throwing calls for it; a vehicle, ragdoll, soft body, or rope that comes back nil with the solver full throws the same; the character askscheckRoom()first because the solver makes its inner body silently; thegroundproperty notes instead;World3DLimitTests):World3D(eager handle,gravityy-up (itsdidSetwakes every body throughcjolt_world_wake_all),groundslab at restitution 0 so a body's own wins against it,bounce(a body that named none follows it,Body3D),.namesRestitution drag(the 2D reading, default1 - exp(-0.05 / 60)so the engine's own 5% a second holds and nothing moves;cjolt_body_set_dampingon every rigid body when it changes; soft bodies, ropes, ragdolls, and vehicles keep their own),maxTimestepclamp,substeps(multiplies the one-pass-per-sixtieth count handed to the solver'sUpdate; the hinge's own loss is first order in the step, a horizontal bar's first apex 7.9% short at 1, 2.1% at 4, 0.6% at 16, so a pendulum scene opts in),unitsPerMeterdefault 1 — scene units ≈ meters, unlike 2D's 100;cjolt_body_createlifts the engine's quarter-turn-a-step spin cap) /addBodywithCollider3D(.sphere/.box/.capsule/.cylinder/.taperedCapsule/.taperedCylinder/.cone/.hull/.mesh/.heightfield(/Heightfield, width: depth: height: ) .compound([Part])— mesh and heightfield colliders are static-only, a dynamic one is pinned with a one-time note) /connectwithJointKind3D(2D's kinds +.ball) /grab, and the sketch sugarwithBody(_:)(pose viawithState+ translate + quat→angle/axisrotate, so replay/export/materials all apply untouched) +body(under:in:)/grabBody(at:in:)/dragGrab(_:to:)— with the polled one-calldragBodies(in:)over them (press grabs, hold drags in the view-parallel plane, release lets go; a press that lands on nothing grabs nothing for that press — the miss is remembered on the world (pointerGrab/pointerGrabAttempted), so a mid-hold sweep over a body never picks it up, and several worlds drag independently) — and the draw sidedrawCollider(_:)/drawBody(_:): everyCollider3Dcase renders (primitives as themselves,.mesh/.heightfieldas their meshes — the heightfield built per call, cache when large —.compoundrecursing,.hullas corner markers, the tapered pair through the packageMesh.frustum), closing the hand-written switch'sdefault: breakhole where an exotic body was silently invisible;drawBody=withBody+drawCollider, byte-identical to the spelled-out loop (PhysicsConvenienceTests, sabotage-verified). (camera ray-pick; drags in the screen-parallel plane at the picked view depth). Load-bearing: never pass&tuple.0across the C boundary — the compiler may materialize a temporary for that one element and silently drop every value the C side writes past it (a real bug: positions read back with y/z stuck at 0 while the sim ran perfectly); all marshaling goes throughCJoltInterop.swift'swithUnsafe(helpers. The grab is the reference drag model and must stay it: a static anchor body created but never added to the world, teleported per move (velocity stays zero), holding the body on a zero-length distance spring (frequency 2, damping 1) — a kinematic anchor driven byMutable)Bytes( of: ) MoveKinematicfeeds its arrival velocity into the constraint and pumps the body into orbit (a real bug). Jolt keeps no global world pool (only an init-once type registry behindcall_once), so the 3D tests run parallel — no.serializedneeded, unlike Box2D's. No pixel snapshots for 3D physics (the artificial-life precedent): determinism is per-binary — the same build replays byte-identically (test-pinned, incl. across thread counts) but a toolchain rebuild may shift ulps and chaotic scenes amplify them; behavioralRigidBody3DTestspin the solver instead, and the Guide's CrateFall figure freezes one collapse. Joint motors, limits & springs (stage 2):.revolute/.prismatictakelimits:(aClosedRangerelative to the connect pose — that pose is 0, so the range must straddle it; hinge clamped to min ∈ [-π, 0] / max ∈ [0, π], the solver's window) and the returnedJoint3Dcarriesdrive(at:strength:)(velocity motor) /drive((spring-servo position motor, upstream defaults 2 Hz / damping 1) /to: frequency: damping: strength: ) stopMotor()/friction/softenLimits(/ thefrequency: damping: ) angle/offsetreadbacks. Load-bearing:cjolt_constraint_set_motorwakes both bodies (a sleeping pair never feels a motor change — a late-engaging door closer would hang open forever); jointfrictionapplies only while unpowered (the solver's contract — one parameter is both stiff-hinge drag and the post-stopMotorcoast-down brake); slider targets/offsets convert byunitsPerMeterwhile angles and the N·m / N effort caps pass through; the motor calls no-op with a one-time note on undrivable kinds (bridge switches onGetSubType, so no Swift downcast can mis-drive).JointMotor3DTestspins every parameter against its counterfactual twin. Compound & world-geometry colliders (stage 3):.compound([Part])fuses shapes into ONE body via.part((part_: at: rotated: axis: density: ) densitymultiplies the body's; parts nest; the Windmill's blade cross is the proof — five shapes, one body, drawn by a recursive part walk inwithBody);.heightfieldtakes aHeightfieldsized exactly like itsmesh(so collider and drawn mesh trace one surface (resampled onto the smallest power-of-two grid covering the source cells, 4…1024 per side, 16-bit samples; beyond the edges is void);width: depth: height: ) addStaticBodies(walksfrom: Scene) Scene.visitWorlds(nowpackage) baking each mesh node's composed world transform into the triangles (scale/shear included) as one static mesh body at identity. Load-bearing:mAllowDynamicOrKinematicmust be false for anyMustBeStatic()shape — allowing the switch makes body creation compute mass properties the shape cannot provide and the library traps (latent stage-1 bug: nothing had ever created a.mesh-collider body until the stage-3 tests); the static pin asks the created shape, never the descriptor type. Shape marshaling goes throughShapeDescArena(arena-owned allocations held withwithExtendedLifetimeacross the create) because compound children make the pinned-buffer count data-dependent — fixedwithUnsafeBufferPointernesting can't express it.Collider3DTestspins the tier (compound mass/balance vs counterfactual twins, part poses, cone = ⅓ cylinder mass, heightfield mappings, scene-collider composition, byte-identical replay). Contact events & sensors (stage 4): every touch that started or stopped during asteplands inworld.contacts(Contact3D:phase/a/b/point/normal/speed+involves/other(than:)), polled indraw()like mouse state, with the per-body viewscontacts/arrivals/departures/touching/isTouching(_:);addBody(makes a detector region that reports overlaps and pushes nothing. Load-bearing: the listener fires on solver worker threads mid-…, isSensor: true) Update, so the bridge's mutex-guardedContactRecorderbuffers flat-POD events the main thread drains aftercjolt_world_stepreturns (never a callback into Swift, the render-thread rule's C cousin); the buffer collapses sub-shape pairs into body pairs by reference count (a crate on terrain reports one landing, not one per triangle) and sorts before draining (worker-thread record order is nondeterministic; the Swifttouchinglists are sorted arrays, neverSets, for the same reason);speedis the pre-solve closing speed(v1 − v2)·n(the manifold normal runs a→b), and anendedevent carries only the pair (OnContactRemovedmay not touch the bodies at all, one may be destroyed) so its point/normal/speed are zero and an event naming a removed body is dropped after its bookkeeping applies; a sensor is kinematic and never sleeps whateverkindwas asked for (a static sensor loses the contact the moment a body settles, which would empty a pressure plate) and lives in its own object layer pairing only with moving bodies, sosensor.touchinganswers standing occupancy where an ordinary settled pile sleeps and stops reporting (Jolt's model, pinned deliberately against its sensor twin); sensors are invisible to ray picking (NonSensorBodyFilter) andBody3D.kindrefuses to change one (noteOnce); thegroundslab is now a registered-but-unlistedworld.groundBody(in the id map so a landing names a body, out ofbodiesso no drawing loop skips a 1000-unit box).Contact3DTestspins it against counterfactual twins (sensor pass-through vs solid deflection, one event per pair vs two loose bodies, √(2gh) impact speed, read-twice-not-drained, no stale touches after a removal, identical replays). Characters (stage 5,Character3D.swift):worldis a walking figure driven from.addCharacter( radius: height: at: ) draw()—move(_:)sets the horizontal velocity it's trying to walk at (held until changed),jump(_:)is granted only if it's on the ground at the next step, andworld.stepsweeps every character along with the bodies (no second update call); readbacks areposition(the feet) /isOnGround/groundState/groundNormal/groundBody/groundVelocity, the parametersstepHeight/maxSlope/pushStrength/mass/facing, and the sketch sugarwithCharacter(_:)(feet + facing,withBody's twin). Load-bearing: aCharacterVirtualis a shape swept by hand, not a body in the world, so it needs its own bridge object (CJoltCharacter) and its own update call — run beforecjolt_world_step(the reference's order) viaExtendedUpdate, the one that does stair-stepping and stick-to-floor (both distances are its arguments, so the wrapper holds them, not the character); the capsule is built bottom-at-origin through aRotatedTranslatedShapesopositionis the feet, andmSupportingVolumeisPlane(up, -radius)so only the lower cap can hold it up (a hand brushing a wall is not ground);isOnGroundreadsGetGroundState, never a normal test. The velocity composition is the library's own recipe and lives in Swift (advance): on the ground it inheritsgroundVelocity(so a moving platform carries it, pinned) and only then may a jump be added, in the air it keeps just its vertical, gravity is added, and the walking velocity is added last and always (air control on, no inertia smoothing — the sketch owns input feel).velocityis intent, not outcome — the library never writes back the achieved velocity, so a character pinned against a wall still reads a full walking pace;actualVelocityis derived from the step's position delta (the reference's "effective velocity") and is what a walk cycle must read. Every character always carries an inner kinematic body (character.body, 0.9× scale,Layers::MOVING): it is what gives the character presence among the ordinary bodies, so the stage-4 contact/sensor surface, ray picking, and tunneling protection all work on it — registered inbodyByIDbut kept out ofworld.bodies(thegroundBodyprecedent, so no drawing loop renders a capsule over the sketch's own figure); characters register in aCharacterVsCharacterCollisionSimpleso they collide with each other.stepHeightis a probe distance, not a hard ceiling (the rounded foot slides up an edge first, so a ledge ~25% taller may still be climbed — test with a margin, don't fake precision);pushStrength(N) vs ground friction decides a shove (4 kg crate moves under the default 100 N, 43 kg does not); a slope just pastmaxSlopereads.onSteepSlopebut a near-vertical face reads.notSupported.Character3DTests(19) pins each parameter against its counterfactual twin (same ramp, onemaxSlope; same ledge, onestepHeight; same crate, onepushStrength), plus platform carry, sensor entry, teleport-rereads-ground, and identical replays. (Fixed alongside:World3D.removeAll()emptiedbodyByIDwhilegroundBodystill pointed at the slab, so floor contacts were dropped and a character'sgroundBodyread nil after a rebuild.) Vehicles (stage 6,Vehicle3D.swift):worldbuilds a driveable machine from a chassis collider plus.addVehicle( _: at: wheels: ) Wheel3Ds (position= the chassis-local mounting point,radius/width,steers/driven/handBrake,suspensionLength/suspensionTravel/suspensionFrequency/suspensionDamping,brakeTorque/handBrakeTorque,grip,casterAngle), driven fromdraw()bythrottle/steering/brake/handBrake(all held until changed,world.stephands them over) with the parametersengineTorque/topSpeed/wheelContact/maxTilt/antiRollStiffnessand the readbacksspeed/forward/up/rpm/gear/isOnGroundplus per-wheelcenter/spin/steerAngle/isOnGround/groundBody/suspensionCompression/slip/slipAngle; the sketch sugarwithWheel(_:)poses a +y-aligned cylinder onto a wheel (withBody's twin), andbalances: truemakes the leaning two-wheeler. Load-bearing: a vehicle is a constraint on a body, not a body — the chassis is an ordinaryBody3Dinworld.bodies(so it collides, reports contacts, and is ray-pickable) and creating one mustAddConstraintandAddStepListener(the wheels are collided and driven inside the step listener; without it the vehicle never moves, upstream's own warning), with the constraint destroyed before its chassis; the chassis takes an explicitmassand a lowered center of mass (defaulting to the mean wheel-mount height) through two newCJoltBodyDescfields, and theOffsetCenterOfMassShapewrap leavesGetPositionat the shape origin so drawing is untouched; axles are derived from geometry, not list order (Vehicle3Dsorts by.axles( of: ) (z, x, index)and clusters within a quarter of the wheelbase, so a two-wheeler gets two single-wheel axles where list-order pairing would fuse front and back), an axle with any driven wheel takes a differential and every full pair an anti-roll bar, and at least one axle must be driven (zero differentials trips the controller's own torque-split assert, so with nothing marked the rear axle takes it); gearing is solved fromtopSpeedin the bridge (top gear at max RPM turns a driven wheel that fast) rather than exposing ratios, and the sample's 10×SetTireMaxImpulseCallbackhack is deliberately not adopted (defaults measured by a torque sweep instead); every wheel setting exceptdrivenis live viacjolt_vehicle_set_wheel_settings(oneapplyWheelDescserves build and retune,const_casting settings the bridge alone owns and the solver re-reads each step; friction curves rebuild from a default tire beforegripscales them) whiledrivenis the gearbox and is refused after construction with a note; the wheels' collision tester filters out the chassis and sensors (overriding the body filter replaces the default self-filter); and a two-wheeler needs a realcasterAngle(~30°) or the balance controller cannot hold a line — note that running dead straight it stays up even unbalanced, so the counterfactual starts it leaned.Vehicle3DTests(19) pins each parameter against its twin (the sharpest: two cars with slick fronts differing only in which axle is driven travel 2× apart), plus suspension sag, braking vs coasting, the hand brake locking only its own wheels, reverse braking through a stop, the gearing ceiling, wheels in the air, axle grouping, a leaned two-wheeler righting itself, and identical replays. (Fixed alongside: aCharacter3D/Vehicle3Da sketch still holds when its world goes now tears down safely — the world marks them destroyed on its way out.) Ragdolls (stage 7,Ragdoll3D.swift+RagdollFit.swift):worldturns a skinned.addRagdoll( from: scene, at: joints: swing: twist: mass: friction: ) Sceneinto a tree of rigid bodies (one per skeleton joint, hung on the new.swingTwist(joint kind) andat: axis: swing: twist: ) scenewrites the simulated pose back onto the skin, the inverse of.apply( ragdoll) apply(_:at:);drive(powers every joint toward the pose a scene is holding (the animation becomes a request),toward: scene, frequency: damping: strength: ) goLimp()cuts it,pose(from:)stands the figure back up,limit(retunes one joint live,_: swing: twist: ) applyImpulse(_:)shoves the whole figure,kindswitches it dynamic/kinematic/static; readbacks arelimbs(name/body/parent/collider/the shape's pose inside the body) +bodies+position+isAwake, and the sketch sugarwithLimb(_:)poses onto a limb's fitted shape (withBody's twin). Built on the library's ownRagdollSettings/RagdollforStabilize()+ constraint priorities +DisableParentChildCollisions(. Load-bearing: a limb's body stands at its joint, not mid-bone (the shape is pushed out along the bone via) RotatedTranslatedShape), which is why the write-back is exact (body transform ≡ joint transform, pinned to 1e-5) and why a motor target is the skeleton's own local rotation; the skeleton seam lives in the core (satellites can't depend on each other) aspackageScene.skeleton()/skinnedVertices()/setJointWorlds(_:)/nodeWorldTransforms(in) 3D/, andSceneSkeleton .swift setJointWorldswalks top-down, keeps each node's scale (a rigid pose has none; dividing it out shrinks the mesh) and re-syncs a TRS animation base to the posed transform (else a rotation-only track next frame drags the node back to its authored translation); shapes are fitted to the mesh, not the bones (vertices assigned to the limb weighting them most, in the joint's frame; axis = covariance's dominant eigenvector by power iteration seeded from the largest-variance axis, radius = 85th percentile of perpendicular distances, ends = 2nd/98th percentiles, so one stray vertex can't decide an arm's thickness) — the bundled figure fits a 0.157 torso against a 0.051 forearm from similar-length bones; mass splits by fitted volume then rebalances throughStabilize()(chain totals preserved); the root has no constraint, so a powered figure holds its shape, not its place (pinlimbs[0]for the puppet-on-a-hook;.body .kind = .kinematic ragdollroutes.kind = .kinematic drive(toward:)toMoveKinematicso it shoves what it walks through); the target scene and the drawn scene must be separate copies (a figure driven toward the scene it was just posed from has nowhere to pull); limbs are ordinary bodies registered inbodyByIDbut kept out ofworld.bodies(thegroundBody/character.bodyprecedent — the sketch draws the mesh), which neededbody(under:in:)to look upbodyByIDinstead ofbodies(also makes a character's stand-in and the ground slab pickable); each figure gets its own collision group, so a limb never fights its parent while two figures collide normally; joints not named injoints:move with the nearest limb above them with their pose and their share of the flesh.Ragdoll3DTests(22) pins it against counterfactual twins — the headline being one drop run twice, shape error 0.48 limp vs 0.034 powered. Asset authored byScripts/(a 16-joint humanoid + a looping wave animation). Soft bodies (stage 8,make-ragdoll-scene .swift SoftBody3D.swift+ thepackageMesh.welded()seam inSources/):Ollin/ 3D/ MeshWeld .swift worldturns any.addSoftBody( from: mesh, at: rotation: axis: mass: stiffness: bend: pressure: damping: friction: bounce: iterations: vertexRadius: twoSided: pinned: ) Meshinto simulated particles (position-based dynamics; cloth that drapes, closed surfaces that hold air), read back assoftBody.mesh(the source mesh with the simulation's positions + derived normals, cached per step) and drawn by the sketch sugardrawSoftBody(_:); per-particle control ispin/unpin/isPinned/move(_:to:)/nearestVertex(to:), the live parameters arepressure/iterations/vertexRadius, and the mouse pair isgrabSoftBody(/at: in: ) dragSoftGrip(_:to:)/releaseSoftGrip(_:)over aSketch.SoftGrip(a pinned particle, since a constraint can't act on a soft body). Bodies live inworld.softBodies, out ofworld.bodies(whose one-pose surface doesn't describe them; thegroundBody/character.body/limb precedent). Load-bearing: welding is a precondition, not a nicety — Ollin's generators emit flat-shaded meshes whose triangles share no vertex index, so an unwelded soft body has no connectivity at all and falls apart into loose triangles;Mesh.welded()merges by position and theremaprepublishes results in the source mesh's order (theMeshReactionDiffusionprecedent), which is what keeps uvs/colors/material intact. Read-back normals follow the source mesh's own normals, not the winding (a one-time area-weighted vote at build time against the rest shape; Ollin's catalog doesn't agree with itself here —Mesh.planecame back lit from underneath, the subdivision-surface lesson again). All three parameters are normalized so one number means the same at any size:stiffnessmaps onto compliance throughscale = meanEdge · √particleCount /(the compliance at which one loaded edge stretches by its own length; a fixed compliance softens a heavy cloth and does nothing to a light one — pinned by( mass · gravity) stiffnessMeansTheSameAtAnyWeight),benddivides that same scale by meanEdge² (a fold constraint measures an angle where a stretch constraint measures a length, so it carries two fewer powers of length; without the correction the whole 0.2…1 range was already rigid), andpressureis the solver'sn R Texpressed as outward acceleration in gravities (a = P·A/(m·V)worked back throughApplyPressure, so1just holds the body's own weight up; refused with a note on an open surface, the closed test being every edge in exactly two faces). Settling takes ~600 steps — a 200-step probe read non-monotone and nearly flat, which is a measurement artifact, not the mapping. The envelope is the library's (not a shortcut): soft bodies collide with rigid bodies but not each other or themselves (a folded sheet passes through its own layers), they are outsideworld.contactsandbody(under:in:), impulses/joints/grabs don't reach one (henceapplyForcefor wind), and there is no tearing (a tear must split a shared vertex and rebuild the constraint set, impossible mid-simulation).SoftBody3DTests(19) pins it against counterfactual twins (pinned vs free, stiff vs slack stretch, bend-held vs limp droop, firm vs limp ball height/volume/shove, pressure inert on a sheet, drape over a sphere, wind, identical replays). Water & buoyancy (stage 9,Water.swift):worldfloats every dynamic body below the surface with no per-body opt-in (the.water = Water( level: density: linearDrag: angularDrag: flow: waves: ) groundDX), plusBody3D.buoyancy(a multiplier on what density alone would do),world/.waterHeight( at: ) waterMesh(/extent: resolution: around: ) waterPhase, andWater. Load-bearing: buoyancy is an impulse the caller applies per body per step, not something the solver works out, so the loop lives in.Waves( amplitude: wavelength: speed: heading: ) World3D.stepbeforecjolt_world_step(the samples'PrePhysicsUpdateslot). The library takes a dimensionless factor (fluid density ÷ body density) rather than a density; the bridge forms it asscale · density · totalVolume /using themass totalVolumeGetSubmergedVolumejust returned, never the shape's own reported volume, so the waterline lands where the displaced volume says (a body of density d settles with fraction d under, pinned to 0.08; the margin is what sleeping costs, freezing the body wherever its last oscillation reached). Ollin's relativedensity: 1already maps to 1000 kg/m³, soWater.densityuses the same scale and a cork/stone falls out of the colliderdensitya sketch already sets. Waves are a per-body tangent plane (the impulse takes a surface point + normal per call, the boat sample's own approach), the surface function lives in Swift with an analytic gradient, sowaterMesh/waterHeightand the surface bodies float on are one source of truth (test-pinned per vertex); the envelope is that a body much larger than its wavelength is approximated. The query (cjolt_world_bodies_in_box, broad-phaseCollideAABoxsorted by handle) filters to dynamic rigid non-sensor bodies: a kinematic body (sensor, character stand-in) would be nudged off its driven path and the library's buoyancy asserts on a soft body (its documented gap, stated not faked). Waking has three modes and needs them (CJoltBuoyancyWake): a settled floater sleeps and holds its waterline exactly (correct, and free); a swell wakes only what its surface passes through (so a sunk stone sleeps on); a changed setting must wake everything afloat wherever it is, because the equilibrium moved (the first draft had only the swell rule and a probe caught it: raising the level 0→3 left a sleeping crate frozen at the old waterline, outside its own bounds, so it never woke). Water is an ocean, not a pool (everything belowlevel, out to the horizon; a harbor is static walls).Buoyancy3DTests(20) pins it against counterfactual twins (cork vs stone vs no water, waterline vs density, brine, drag settles vs bobs forever, sleeper holds its level, tide reaches it, swell carries the top and lets the bottom sleep, current drifts,buoyancyboth ways, sensors/soft bodies untouched, drawn surface == the surface bodies float on, identical replays). World queries (stage 10,Query3D.swift):raycast(from:to:)/raycastAll/sweep(/_: from: to: rotated: axis: ) sweepAll/bodiesOverlapping(/_: at: rotated: axis: ) bodiesContaining(, all taking_: ) ignoring:+includingSensors:and all answering the sharedHit3D(body / point / outward normal / distance along the query) between steps, changing nothing. Load-bearing: the C filter is a struct (CJoltQueryFilter: ignore list +includeSensors+includeSoftBodies) passed by pointer, so collision filtering lands as a field rather than a parameter on every call; what a query is blind to is a decision, not an inheritance — a sensor is transparent (a region to be inside, not a surface to hit; the mouse-pick rule) and a soft body is too (no rigid pose to hand back, matchingcontacts/body(under:in:)), while the ground slab / character stand-ins / ragdoll limbs are visible because hits resolve throughbodyByID, which is what makes a ground probe and a sight check on a walking figure work; the mouse pick is the same call (World3D, the internal ray with.raycast( from: to: ) includeSoftBodieson) so there is one ray implementation, not two that can drift; a ray's normal needs aBodyLockRead(only the body knows which face the sub-shape id names), a sweep's is the negated penetration axis; the bridge returns how many hits it found (not wrote), so Swift sizes a 16-slot buffer and grows exactly once;mesh/heightfieldprobes are refused with a one-time note (MustBeStatic()asked of the created shape, the stage-3 rule). Example3D/;Physics/ Sightlines Query3DTests(24). Collision groups (stage 11,CollisionGroup): a named.swift CollisionGroup(ExpressibleByStringLiteral) on every thing that can be added (addBody/addCharacter/addVehicle/addRagdoll/addSoftBody/addStaticBodies, each also settable live as.group) plus a symmetric world table —ignoreCollisions(/between: and: ) allowCollisions(/between: and: ) collides(/between: and: ) collisionGroups/World3D(64) — and.maxCollisionGroups as:on all six queries (ask as a body of that group would). Load-bearing: the group is stored in the object layer (layer = (, kinds NON_MOVING/MOVING/GHOST/SENSOR), not Jolt's per-bodygroup << 2) | kind CollisionGroup/GroupFilterTable: the layer is the one thing consulted at pair-finding (so the contact listener never hears a filtered touch), in every query'sDefaultObjectLayerFilter, inExtendedUpdate's filters, in aVehicleCollisionTester's constructor, and inSoftBodyCreationSettings, where the narrow-phase group filter reaches none of those, hardcodes "same sub-group never collides", and is already the ragdoll tier's slot (so the two stay orthogonal — a figure keeps its own limb filter and two figures in one Ollin group still collide). Group 0 is numerically today's layer set, so a world that names no group is byte-identical (whole suite unchanged, no re-records). Four hand-honored spots, each a would-be half-applied filter: character-vs-character is outside the broad phase, soGroupedCharacterCollisionrefills a scratch list per call and delegates to the library's own loop (the group travels as theCharacterVirtual's user data); wheel testers take their layer at construction, so a group change rebuilds all three and re-selects the active one, routed throughWorld3Dso setting the chassis body's group works too; buoyancy's.bodyChangedGroup SpecifiedObjectLayerFilter(was an exact-layer match and had to become kind-based or a grouped body silently stops floating (a real trap); and motion changes re-derive the layer from the current group (a body let go from static keeps its group). Queries narrow via aMOVING) groupfield onCJoltQueryFilter(never a new C parameter — the stage-10 rule); past 64 groups the extras stay.defaultwith a note rather than aliasing an in-use group, andcollisionGroupsis what makes a typo (a new group, silently doing nothing) findable. Example3D/Physics/Sieve;CollisionFilter3DTests(22). Per-body motion parameters (stage 12,Freedom3D.swift):freedom(aFreedom3DOptionSetover the six DOFs —.all/.plane(normal:)/.upright/.noTurning/.noMoving/ raw[.moveX, .turnZ]),gravityScale, andchecksPath(continuous collision detection) on everyBody3D, each also anaddBodyparameter. Load-bearing: a restricted DOF lives inside the body's mass properties, socjolt_body_set_freedomre-derives the whole set from the shape and takes the mass as an argument (a travel-locked body reports inverse mass 0 and cannot say what it weighed; Swift passes the explicitmass:a body was created with, else 0 = the shape's own) — which also madecjolt_body_get_massfall back to the shape's mass properties, since a pinned body reporting0reads as weightless when it is the opposite;Freedom3D's raw bits areEAllowedDOFs' (the bridge casts), a zeroed desc field means unrestricted (so every existingCJoltBodyDesc(), the ground slab included, is byte-identical) and an empty mask reads as.all(the library's one invalid case, which would divide by a zero mass);.plane(normal:)rounds to the nearest world axis (only whole axes can be taken away, so there is no tilted plane); CCD stays an explicit opt-in because the solver's own threshold makes it free while slow (two runs byte-identical, pinned) so guessing would only change results for existing fast bodies, and speculative contacts catch far more than the naive estimate (a 0.05 pellet vs a 0.04 wall tunnels at 40 units/s, bounces at 20 — a demo needs genuinely thin plates); aCharacter3Dshape-casts its own path and aVehicle3D's wheels ray-cast the road, so only the chassis would want it. Fixed alongside: the floor slab kept its collision group across aground/unitsPerMeterchange (remembered on the world, sincerebuildGroundbuilds a fresh descriptor). Example3D/;Physics/ Bagatelle Motion3DTests(16); Guide Ch 31 § Taking a direction away: degrees of freedom + Flattened figure. Tracks, ropes, freedoms, and joint-to-joint links (stage 13,JointPath.swift): three moreJointKind3Dcases between two bodies plus a second enumJointLink3Dbetween two joints, through aconnect(overload._ a: Joint3D, _ b: Joint3D, _: ) .path(threads a body onto the smooth curve through a ring of points (through: looping: alignment: ) PathAlignment.free/.rolls/.followsPath/.fixed;drive(at:)= units/s,drive(to:)= a 0…1 fraction,Joint3D.progressreads it back; aContourform lays a plan-view curve on the ground)..pulley(is one rope over two hooks (from: over: and: to: ratio: taut: ) ratio= rope falls on the second side)..allowing(is the general joint written as the_: at: travel: rotation: ) Freedom3Dset it keeps ([]is a weld, the three turns a.ball, one bounded turn a hinge)..gear(ratio:)/.gear(teeth:and:)ties two hinges and.rackAndPinion(a hinge to a slider. Plus the standing gap closed: a standalonetravelPerTurn: ) .swingTwistnow takesdrive(at:)/drive(to:)(the twist only, swing left free) and the newdrive(pointing its bone along a world direction, withtoward: twist: ) Joint3D.twistthe readback. Load-bearing: a link names joints because what it constrains is the motion they allow (bodies, axes, and the drift-correction constraints all fall out of them), and its moving end is the non-static body, or the second one named, matching everyconnectcall's order; the path spline's normals are parallel-transported (a per-point up-minus-along flips on a vertical track) and its points go into body-1 space so a track follows a moving carrier, with progress normalized in the bridge (only it knows the segment count); a gear ratio is forced positive with a note (a negative one leaves the position correction pulling against the velocity rule until the pair detonates); a kinematic pulley end is refused with a note (the library's pulley part guards onIsStaticwhere every other guards onIsDynamic, so it asserts in a checked build and shoves the body in a release one; the vendored source stays pristine); meshed wheels wantignoreCollisions(or plain cylinders jam; a link records all four bodies and both source joints so removing any of them cuts it. Examplebetween: and: ) 3D/;Physics/ Contraption JointKind3DTests(24); Docs §§ Tracks, ropes, and freedoms + Gears and racks; Guide Ch 31 § Machines out of joints: motors, gears, and racks + Machines figure, Ch 31 § More joints: a track, a pulley, a list of freedoms, and cables + TrackAndPulley figure. The soft-body seams (stage 14,Colliding3D.swift): a cloth becomes a member of the world in three ways. Contacts —world.contactscarries soft touches (softBody.touching/contacts/arrivals/departuresmirrorBody3D's), which widened the pair type:Contact3D.a/b,Body3D.touching/entered/exited, andHit3D.bodyare nowany Colliding3D(a tinyAnyObjectprotocol overgroup/isAwake/wake()/userData, conformed byBody3D+SoftBody3D) — every public call site was an identity comparison, so the churn was one cast. Buoyancy —SoftBody3D.density(relative, 1 = water; derived from mass/enclosed volume when closed, else 1) floats a sheet particle by particle. Queries — the deliberate reversal: every query now sees soft bodies (a curtain blocks a sightline), soWorld3D.pickfolded intoraycastandbody(under:in:)/grabSoftBodycast the hit. Load-bearing: the solver'sSoftBodyContactListenerhands over a whole contact set per pass and never reports a parting, so began/ended are diffed byfinishSoftStepafterUpdate(the sameContactRecorder, registered as both listeners), the event's point/normal come from the first reporting particle,speedreadsGetLinearVelocity()during the callback (the arrival velocity — the update averages the new one in afterwards, and the other body's would race), and a sleeping soft body keeps its touches (the solver stops asking, unlike the rigid removal report) — which is also what tells the buoyancy pass a sunk sheet is lying on something; buoyancy takes a ratio (ρ_fluid/ρ_body, since a sheet has no volume to displace) and per-particle surface heights computed in Swift, never one tangent plane (one plane over a 4-unit raft on a 9-unit swell curls it into a bowl — a real fixed defect), ramped over a band of one particle spacing (a flat sheet's particles all cross at once, so a hard test chatters); and a body heavier than the fluid has no equilibrium, so if it is asleep, submerged, and touching nothing it has stalled, not settled, and is woken (cloth's drag holds a sinker below Jolt's sleep threshold; comparing measured lift against 1 fails, since a floating raft balances at ~0.92). Example3D/Physics/Raft;Contact3DTests/Buoyancy3DTests/Query3DTestsgrown; Docs §§ Soft bodies + Water + Queries; Guide Ch 32 § A raft made of cloth: soft bodies that float + Raft figure. Tracked machines (stage 15):addVehicle(builds the third controller on the shipped…, tracked: true) Wheel3Dsurface: the wheels become road wheels split into a left and a right band by which side of the hull they sit on (driver's right is -x; a one-sided machine is refused, never half-built),steeringruns the inside band at1 - 2·|steering|(half lock stops it, full lock reverses it into a pivot on the spot, and it needs throttle since the bands are turned by the engine), and the readbacks areisTracked/trackSpeed(_:)/wheels(on:)over a nestedTrackSide. Load-bearing: the controller'sConstructWheelasserts on the wheel settings type, so a tracked build newsWheelSettingsTV(flat 4.0/2.0 friction coefficients, which is why a band keeps pulling while it slides where a tire's slip curve falls away) andapplyWheelDescsplit into a sharedWheelSettingsbase plus two overloads, withcjolt_vehicle_get_wheelguarding itsWheelWVcast (aWheelTVhas no slip, soslip/slipAngle/steerAngleread 0); every wheel must belong to exactly one band (the controller fills each wheel's track index from the two lists and an unclaimed wheel keeps its-1); neither steering ratio may be exactly zero (the controller divides by them and asserts), so a stopped band is spelled as a very slow one; the axle list is still computed and passed but read only for the anti-roll bars (they live on the constraint, not the controller); track inertia is derived, not exposed (0.08 · mass · radius²at the sprocket, measured across sizes: 0.02…0.15 lands within a few percent, so it stays a constant) and a band's brake is the sum of its wheels'brakeTorque(so the shipped parameter keeps meaning something andhandBrakepulls the same brake). Closed alongside: a wheel'sdrivenis now live (cjolt_vehicle_set_driverebuilds the differentials or the two sprockets and re-solves the gearing against the new driven radius, sotopSpeedis kept), and the rebuild waits for the step rather than the assignment because which wheels drive is set a list at a time and an eager report-back undoes the assignments still to come. Example3D/Physics/Crawler;TrackedVehicle3DTests(20); Docs § Tracks; Guide Ch 32 § Turning without steering: tracks + Crawler figure. Saving a world (stage 16,PhysicsSnapshot):.swift world.snapshot()captures the whole world as aPhysicsSnapshot(aSendable/Equatablevalue wrapping its own bytes, withbodyCount/jointCount,init(data:)/init(contentsOf:)/init(resource:in:)/write(to:)) andrestore(_:)builds it back, over the file pairsave(to:)/load(contentsOf:); it holds the rigid tier (everyBody3Dwith its collider, pose, motion, and everyaddBodyparameter, everyJoint3Dincl. gears and racks, the group table and its rules, andgravity/ground/bounce/maxTimestep/unitsPerMeter/water) plus the tiers above it by value — characters (capsule + parameters + pose + velocity + facing), vehicles (chassis + everyWheel3Dparameter + gearing + the live drivetrain: engine RPM, gear, clutch, per-wheel spin rate and rolled angle), and ragdolls (theRagdollPlanfitting, per-joint limits, and every limb's pose) — and soft bodies once their mesh is named. Naming bulk geometry (PhysicsAsset.swift) is the one referencing seam:Body3D.assetName/SoftBody3D(a serializable sibling of.assetName userData) +restore(/_: resolving: ) load(over acontentsOf: resolving: ) PhysicsAssetResolver((, casesString) -> PhysicsAsset? .mesh/.heightfield) +snapshot.assetNames(what a file will ask for, read without restoring), so the sketch stays the source of truth about where its assets live (theresource:in:rule). Opt-in by design (a self-contained file is what makes an arrangement committable); measured 105 KB held → 1.1 KB named on a 65² terrain + 5k-vertex mesh + 20 crates. Load-bearing: a name is per body, top level only (a mesh nested in a compound is written whole); an unresolved name costs that one body, not the restore (skipped with a note, its joints dropped, and the restored-body list keeps nils in the gaps so saved indices still line up); the fingerprint hashes the geometry (FNV-1a), because counts+bounds is blind to the case that matters most (Heightfieldnormalizes to 0…1, so two seeds give identical counts and bounds), and a mismatch notes and restores anyway (the saved poses are the best answer there is); a soft body needs a name to be saved at all (it is nothing but its mesh) and carries its build parameters + every particle position/velocity + the pinned set via new.diamondSquare cjolt_soft_body_get_velocities/_set_state(write goes through the COM transform mirroring the read, and setsmPreviousPositiontoo; 289 particles back at 1.19e-07). Gotcha: the reader'scount()bounds a length against the bytes left, which is right for an array in the stream and wrong for a fingerprint's piece count (geometry deliberately not there) — reading a 4,225-sample terrain that way threw and refused the whole restore. Load-bearing for the tiers: the taxonomy is the design (sort by what is actually heavy in each: a character and a vehicle hold nothing heavy, a ragdoll splits into a fitting that fits by value and a skinnedScenethat is the sketch's own asset, still loaded and still whatscenewrites onto, so a figure restores in a run that never read the file);.apply( ragdoll) Ragdoll3D's init split into aconveniencescene form over a designated plan form, so a restored figure is built by the same code as a fitted one; a vehicle must carry its drivetrain (without it a car at full throttle falls 6.4 units behind over 2 s, vs 1.5 with it — and the fair comparison is a rigid stack captured mid-collapse, which diverges 2.13, so this is the already-documented in-flight-contact envelope, not a vehicle gap; a parked machine restores at 0); the chassis is written in the vehicle section but still takes a body index after the loose ones (so a joint naming it survives); never write a pose as a position then a rotation — the solver holds a body by its center of mass, so the position is computed against the old orientation and a shape offset inside its body (a ragdoll limb'sRotatedTranslatedShape) lands ~5e-7 out (newcjolt_body_set_poseoverSetPositionAndRotation; invisible for a box/sphere); and the bytes settle after one restore, not on the first capture (integration drifts a quaternion off unit length and the bridge normalizes anything handed back), which is the propertyaWorldOfEveryTierRoundTripsToTheSameBytesstates — reproducing the normalization in Swift was tried and reverted as a half-measure (15 limbs of 16). Load-bearing: the format is Ollin's own, not Jolt'sPhysicsScene, because a snapshot must hand back the Ollin description (a restored Jolt shape cannot become aCollider3Dagain, and the collider is what a sketch draws from), which makes restore a replay of the ordinaryaddBody/connectcalls so a restored world is one a sketch could have built; a joint's zero is the pose its bodies held at connect (Joint3D, recorded at creation), so restore stands them back there, makes the joint, then moves them on (exact for every kind at once: a door saved half open is still half open and still stops where it did, where the naive re-connect reads 0); the desc's three new fields (.connectPoseA/ B linearVelocity/angularVelocity/startAsleep) follow the zero-is-the-old-behavior rule, velocity passed inBodyCreationSettingsbecauseSetLinearVelocitywakes what it moves, andstartAsleepis what makes a settled pile come back settled (0/12 awake vs 12/12 for the same poses built by hand, zero drift over 60 further steps); a vehicle's chassis is inworld.bodiesso capturing filters it out rather than saving a crate that restores wheel-less; the Swift group table is rebuilt in the saved (= solver) order and every pair in the union of old and new counts is reset.PhysicsSnapshotwrapsData(aCollider3Dis neitherSendablenorEquatable), so a snapshot through a file and one in memory are the same value. The payload is LZFSE-packed (system codec, deterministic bytes; conditional on being smaller, which the codec reports by refusing an equal-size destination) behind a header carrying a flag, the unpacked length, and an FNV-1a checksum — load-bearing because LZFSE's decoder returns the full requested length from a truncated stream rather than reporting the truncation, so without it a cut-short packed payload unpacks to rubbish that parses into some world (the checksum is what makes "refused rather than half-read" true by construction, and it catches a corrupted-but-complete file too). Measured 1912 KB → 966 KB on a scenery-heavy world and 10.7 KB → 1.2 KB on a settled heap of primitives; the same measurement rejected narrowing mesh positions toFloat32(saves less, lossy for theMesha sketch reads back frombody.collider, and dominated where it would help most). Round trip is exact (worst pose error 0, a ballistic body stepped on from a restore lands where the uninterrupted one does); the envelope is the solver's in-flight contact bookkeeping (a vehicle's wheel-contact cache included), plus grabs and motors, which a sketch says again. Two bridge getters came with it, surfaced as liveBody3D.friction/.restitution. Example3D/Physics/Yard;PhysicsSnapshotTests(23) +SnapshotTierTests(13) +SnapshotAssetTests(10); Docs § Saving and loading; Guide Ch 31 § Keeping what settled: snapshots + Kept figure. Reading UsdPhysics (3D/in the core +SceneLoaderUSDPhysics .swift OllinPhysics/):UsdPhysics .swift worldpicks up rigid-body / collider / joint annotations authored elsewhere, over the shipped OllinUSD parser — the interchange leg, where lossy-on-the-way-in is the point (writing the format would not be, which is why the snapshot stays Ollin's own). Core reads into.addBodies( from: scene) packageScenePhysics*value types on theScene(the lights/cameras spec precedent), satellite turns them into ordinaryaddBody/connectcalls. Every attribute name was verified againstpxr/, and the schema drove the design: a collider's shape is the prim's own geometry (no shape attribute;usd/ usdPhysics/ schema .usda Cube.sizedefault 2,Capsuleheight = span between cap centers = Ollin's meaning); USD stands Capsule/Cylinder/Cone on z (axis, default"Z") so the turn onto y is baked into the shape's pose; a rigid body owns its whole subtree so several collider prims fuse into one.compound; a collider with no body over it is scenery; and a joint naming one body holds it to the world, which the bridge already supported (resolveBody→Body::sFixedToWorldforCJOLT_BODY_INVALID, documented in the header all along), surfaced as the new publicconnect(_:toWorld:). Load-bearing bug: a collider prim that is its body has an identity local transform, so shape scale must come from the collider's world transform (the body-relative one supplies position/rotation only, measured against the body's rotation+place, not its scale) — taking it from the local transform silently drops every scale, the common case. Out of scope (said, not faked): articulations, drives + limit API, collision groups/filtered pairs;upAxis/metersPerUnitstay unapplied (the scene-import contract). Example3D/Physics/Imported(hand-authoredyard.usda);UsdPhysicsTests(14); Docs § Reading physics from a file; Guide Ch 31 § Scenery and bodies from a file: scenes and USD physics. Cloth a skeleton carries (addSoftBody(+…, skinnedTo: carriedBy: sway: backStop: maxStretch: ) SoftBody3D/.follow( _: ) snap(to:)/ liveswayScale/followsSkin): the solver's skinned constraints turn a hanging sheet into a cape,carriedBy:naming the joint that carries each vertex (mesh-local, thepinned:space) andfollow(_:)handing over this frame's pose. Load-bearing: the bind pose is whatever the figure is standing in at build, so no weights are authored anywhere (invBind = jointWorld_bind⁻¹ · placement) — and sinceplacement · invBind⁻¹is that bind transform back exactly, a restored surface with no scene in sight opens standing in the pose it was hung in rather than collapsed on its origin (only the translation is divided byunitsPerMeter, which is the conjugationS⁻¹[R|t]S, so bind and pose compose in meters as they did in units);pinned:means held by whatever holds it (a joint carries it → held to the figure, none does → held to the world, the shipped meaning); a particle held exactly on the skin (sway0) is made kinematic in the bridge, which is what letsmaxStretch:(the LRA long-range attachments, driven atGeodesicDistance) work from anchors the skin holds — measured: a 6 kg cape hangs 8 cm long on its springs and exactly at rest length capped;sway/backStopare raw world-unit lengths, a deliberate departure from the stage-8 rule (that rule is about compliance; a distance needs no normalization — probed 0.02→0.0202, 0.05→0.0504, 0.1→0.1009, backstop 0.02/0.1/0.4→0.0200/0.1000/0.4005), so watch the sign of a computedsway(negative clamps to 0 and hard-skins that part into a board); the back stop sits behind the normal the solver reads from the winding, so the faces it is handed cross reversed whenever the winding faces the carrying joints (windingFacesCarriers, decided from the rest shape and the inverse binds alone so a restored surface decides the same way with no skeleton present): "behind" is toward the figure whichever way the mesh is wound, and a cape whose sheet faced the figure used to pass straight through it (the plane winding fix of 2026-09-14 turned every written cape that way;theBackStopHoldsWhicheverWayTheSheetIsWoundpins both windings);followrecords andWorld3D.stepapplies (once per step, the interpolation the solver eases across),snap(to:)applies at once (particlePositions/meshare right immediately; the body's owncenterre-centers on the next step); a changed pose is what wakes the body — the skin constraints are solved during the update, so a settled sleeping cape is left behind by a figure that walks away (a real probe-caught defect), and comparing the flat pose against the last applied one is what still lets a still cape sleep; build order is load-bearing (skinned constraints + their inverse-mass zeroing beforeCreateConstraints, which derives the LRAs;CalculateSkinnedConstraintNormalsbeforeOptimize; both no-ops when nothing is carried, so every existing soft body is untouched). The snapshot writes the skin down rather than naming a scene (the closures are a sketch's, thepinnedlist precedent; ~4.7 KB for a 169-particle cape, no newPhysicsAssetcase; format version 3). Envelope: still no self-collision, so a cape passes through its own folds. Ropes (Rope3D.swift):worldbuilds the solver's fifth constraint family, Cosserat rods (Kugelstadt/Schoemer 2016), as a.addRope( through: [Vector3], thickness: sides: mass: stiffness: bend: damping: friction: bounce: iterations: pinned: maxStretch: group: ) Rope3D: SoftBody3Dwhose particles are the polyline's points one for one (identity welding, sopin/move/positions/nearestVertexspeak in point indices) and whosemeshoverride sweeps aMesh.tube, sodrawSoftBodyworks unchanged; the readback issegments(RopeSegment3D:index/start/end/center/direction/length+ arotationthe rod itself carries) posed by the sketch sugarwithSegment(_:)(withBody's twin, local +y along the rope matching Ollin's y-standing primitives, +x the twist), pluspoints/length/restLength/segmentCountand livethickness/sides. Load-bearing: a rope is the first body with no faces, socjolt_soft_body_create'smFaces.empty()guard now asks for faces only when there are no rods, and the rods must go in beforeCreateConstraints(which derives the LRAs by walking vertices, not faces, andCalculateClosestKinematicwalks rods beside edges →maxStretch:works faceless, measured 1.80 → 1.00); the bridge undoes both things the solver does to the rod list (Optimize()reorders,CalculateRodProperties(reverses a rod pointing against its neighbor) via a per-rod remap + flip recorded pre-) Optimize, sosegmentsis in the caller's order and direction (a reversed rod's rotation times a half turn about its own x);bendneeded its own measured scale (a bend constraint holds a rotation, so it carries no length to compare against):compliance ∝ meanRod²/with a measured constant puts( length³·mass·gravity) bend: 0.5at drop/span 0.26…0.33 across 12× length, 2× particle count, and 100× mass, where the naive scale ran from 0.13 to 0.92 over the same lengths — and both sweeps are non-monotone until ~3000 steps (a still-swinging cantilever measures its swing);iterationsis the lever on a long finely-divided rope (40 particles over 6 units: drop/span 0.40 at 5 passes, 0.027 at 20); restoring needs the rod frames or the rope springs (0.361 units of drift one step after an exact restore, vs 0.0014 carrying them), and the way in is thatRodStretchShear:is read exactly once at runtime (: mBishop Initialize, to seed each rod's state) withmLength/mOmega0already computed, so the bridge writes the saved orientations over it afterCalculateRodPropertiesand beforeOptimize; a rope therefore needs noassetNameto be saved (its rest shape is a handful of points, format version 4). Envelope: no self-collision (a coil passes through its own turns), andSoftBodyShapeis face-based so a rope is invisible toraycast/sweep/bodiesOverlapping(pinned deliberately) while still colliding with the rigid world through its particles'vertexRadius—grabSoftBodyfalls back to the nearest particle along the line of sight; one strand only, no branching. Example3D/Physics/Rigging;Rope3DTests(20); Guide Ch 32 § A line that knows how it is turned: ropes + Rope figure. Example3D/Physics/Cape;SkinnedCloth3DTests(15). Examples3D/Physics/Stack/Tumble/Chain/Yard(a truck, a pacing figure, a fallen one, and a named heightfield floor + cloth banner, all kept in one file) /Crawler(a machine on tracks, turning without steering) /Windmill(motors + the compound cross) /Rockslide(heightfield terrain + eroded slope) /Trigger(a scoring hoop = solid bead rim + sensor disc, a sensor tray lit by its load, knock rings scaled by contact speed) /Stroll(a walkable eroded island: stairs to a sensor-lit lookout, shoveable crates,stepHeightas a live@Param) /Joyride(a car over an eroded island: chase camera, live gearing/springs/grip parameters, wheels colored byslip) /Ragdoll(a skinned figure that stands and waves powered, collapses limp, and drags by an arm either way;Bshows the fitted capsules) /Drape(a banner pegged to a washing line flapping in a gusting wind, a sheet thrown over a crate, a deflatable beach ball, all draggable) /Cape(a figure striding with a cape clasped at the neck, carried by the skeleton under the skin; it collapses with the figure and the leash can be cut live) /Rigging(a limp rope, a chain whose links interlock because every other one is rolled a quarter turn about the rope's own axis, and a leafy vine stiff enough to hold a curve, all hanging in the same gusting wind) /Flotsam(crates from cork to nearly waterlogged floating on a swell at their own depths, a stone anchor on the bottom, a current carrying the lot past, all draggable) /Sightlines(a lamp lighting only the crates its rays reach, a drone holding clearance by sweep, a pulse shoving what a sphere overlaps) /Sieve(three colors of bead sorted down one ramp by threeignoreCollisionscalls, the rules withdrawable live) /Bagatelle(a pin table held flat by.plane(), live parameters for freedom / weight / path-checking, and a plunger shot that leaves through a thin rail the moment sweeping is off) /Contraption(a workshop of the machines a hinge cannot make: a gear pair driving a rack off one shaft, a rope trading a tray for a counterweight, a platter allowed only to rise and spin, a cart on a track) /Raft(a cloth raft floating on a swell with cargo aboard, a sounding line that stops at her deck, a gate that reports her sailing through);Docs/; Guide Ch 31 §§ Things with weight:Simulation/ Physics3D .md World3Dand bodies (CrateFall figure) + Machines out of joints: motors, gears, and racks (Windmill figure) + Things that pass through each other: collision groups (Sorted figure) + What hit what: contacts + A region that counts what is inside: sensors (Trigger figure) + What is in the way: rays, sweeps, and overlaps (Sightlines figure) + Taking a direction away: degrees of freedom (Flattened figure) + Water, and what it holds up: buoyancy (Floating figure) + Ground from a landscape: the heightfield collider (Rockslide figure) + Keeping what settled: snapshots (Kept figure); Guide Ch 32 §§ Someone to be in there: the character controller (Walker figure) + Something to drive: the vehicle (Joyride figure) + Letting a figure fall: the ragdoll (Ragdolls figure) + Cloth that finds its own shape: soft bodies (Cloth figure) + A cape on someone's back: cloth a skeleton carries (Cape figure) + A line that knows how it is turned: ropes (Rope figure) + A raft made of cloth: soft bodies that float (Raft figure) + Turning without steering: tracks (Crawler figure). Mechanism:ARCHITECTURE.md§ The 3D physics bridge (+ §§ Cloth a skeleton carries, Saving a world). What stays out is the solver's own gap: soft-body self-collision and cloth-vs-cloth, and tearing it cannot do at all (DESIGN-NOTES.md§ 3D mode). Volume constraints (tetrahedral jelly) are declined on measurement, not absence — built and probed against the shippedpressure, they tie on holding a weight and on dent recovery and lose on recovery from a hard squash, becauseApplyVolumeConstraintsforms its residual from an unsigned volume so an inverted tetrahedron reads as satisfied, where a gas law's push grows without bound as the space shrinks; the win they do have (holding an authored shape with corners) belongs to the interior springs, not the tetrahedra, andbendcloses most of it anyway. Numbers + the two reopeners inARCHITECTURE.md§ Why there is no tetrahedral solid. TheJolt/Physics/Hair/module is likewise declined on measurement (2026-08-06 audit, apparatus reverted): it takes no force of any kind (so it cannot be blown, where every Ollin cloth/rope example gusts viaapplyForce), collides only withConvexHullShape(silently skipping the meshes and capsules Ollin's figures are), and needs an authored groom + skinned scalp where a sketch generates its own geometry. Decisive number: the already-exposed rod family carries 20,000 simulated strands at 12.45 ms/frame in ONE soft body (nothing requires a body's rods to form one chain) against Hair's ~2,500 on its shipped CPU backend, so the Metal path it would need (49 shaders cross-compiled to aJolt.metallibbuild step, Objective-C++ in the C++-only CJolt target, a new draw path for a Jolt-owned buffer) buys a strand countRope3Dalready reaches. If hair is ever wanted, the way in is a multi-strandRope3D, not this module. Reopeners + numbers inARCHITECTURE.md§ Why there is no hair tier. A number the solver cannot hold is refused at the bridge (SolverNumber, one definition for a snapshot's numbers and a sketch's own: finite, within a billion units, a rotation long enough to be made a unit one, an axis of some length): every setter, force, step, and creation argument of both worlds checks there, a setter keeping what it had and a creation argument falling back to its default with a one-time note naming the call (a collider carrying one becomes a unit sphere; a joint with one is handed back inert and is not the world's), the throwing creators (addVehicle,addSoftBody,addRope,addRagdoll,addTensegrity) throwingPhysicsErrornaming it, and.unbuildable .infinitypassing only where a limit means none (a motor's strength). The members the first pass left were ported on 2026-10-20 from an agent's parallel draft of the same work (its own shape, a protocol over the number types with a per-member accept call, was superseded; its coverage was read against main by the note names each guard carries): a body'sbuoyancyScale, a character'sfacing, a rope'sradius, the 2D world'sbounds(SolverNumber), and a ragdoll's.complaint( _ rect: ) pose(from:)/drive(toward:)over a scene whose joint transforms hold one (complaint(, noted as "pose(from:)'s scene"). Ain matrices: ) Rotation3Dnever carries one (its initializer makes a unit rotation of anything else), so that check is a backstop. Before the check, 28 of 37 probed cases stopped a debug build (the 3D solver asserts one step later, in its integrator, sinceJPH_ENABLE_ASSERTSfollowsJPH_DEBUG; Box2D asserts at the call) and poisoned a release build's broad phase;SolverNumberTestsand the two cases inRigidBodyTestspin every family. 2DapplyTorquetakes point units, a force in points times an arm in points, scaled to the engine's newton-meters by the square ofunitsPerMeter, so the numbers that push a body also turn it (RigidBodyTestsagainst the box's own inertia). The disk collision pass (.aTorqueSpinsInPointUnits DiskPass.swift,World): the colliding disks are gathered into one array a pass (springs move particles between passes) and written back after it; the pairs come from a grid of several cell sizes in one hashed table filled by a counting sort, the coarsest cell the largest disk's diameter, each level half the one above, a disk filed once at the finest level whose cell spans it (.solveCollisions level = exponent(, 30 at most). A disk scans the nine cells of its own level for higher indices, then every coarser level that holds anything, there only the cells within its radius plus half a cell. Load-bearing: (1) the order is fixed (disks by index, cells in one scan, a bucket's disks ascending, the lower index first in a pair), and a bucket's entries are checked against the cell and level they were filed under, since two cells share a bucket; that is what makes a seeded pile settle on the same bits in every process. (2) A pile whose disks are all within a factor of two of the largest has one level and is offered a single grid's pairs in its order, so it settles on the bits it always did (largest / radius) DiskPileTestspins two such piles to numbers read from the old pass); a pile of mixed sizes moved once. (3) The own-level scan stays the full nine cells for that reason, and the cells a disk scans come from where it is when its turn comes while the table keeps where every disk was when the pass began. (4) A cell is narrowed with a clamp, so a position that is not a number traps nothing (the old pass trapped). A single grid of the largest disk's width was the old pass; filing a large disk in every cell it covers was read and declined, since one disk of 2,000 px among disks of 2 px is a million entries a pass. Measured in a release build on the M2 at four passes: 9,000 disks at 8 px 37 ms to 8 ms a step, 9,000 at 5 to 80 px 442 ms to 14 ms, 8,999 at 4 px beside one of 600 px 4.5 s to 9 ms.DiskPassTests(every touching pair offered once against a comparison of all pairs over nine mixes, the single grid's order, the cost beside a huge disk, and two levels that share a cell's numbers and a bucket, which only the level in the key tells apart; eleven plants red). Removing many (remove(,_ particles: ) remove(_ springs:)): one scan through a set of identities, the world left as the same removals one at a time leave it (750 of 9,000 with 4,000 springs: 50 ms one at a time, 0.6 ms as a list); the soft bodies leave the list last, since a particle knows its body by a weak reference and the list is what keeps the body alive (BatchRemovalTests, three plants red).Tensegrity (
Sources/+Ollin/ Geometry/ Tensegrity .swift Sources/).OllinPhysics/ Tensegrity3D .swift Tensegrityis the geometry (nodes +Memberstruts +Membercables) with three balanced forms:prism((twist defaults tostruts: radius: height: twist: ) prismTwist(struts:)= π/2 − π/n, Connelly & Terrell's result, independent of height and radius; struts run bottom i → top i+1 with the top turned by +twist, the handedness the node force balance requires),icosahedron((Jessen's icosahedron: the cyclic permutations of (±2, ±1, 0) at strut length 4; struts are the 6 edges of length 4, cables the 24 of length √6; parallel pairs sit L/2 apart, the a = 2b ratio at which equal cable tensions balance),strutLength: ) tower((class-2: prisms on shared polygons, alternating twist).levels: struts: radius: levelHeight: ) imbalanceis a least-squares equilibrium fit (every strut at force density −1, cable densities solved, ridge 1e-9): ~1e-9 for the forms, 0.47 forprism(twist: 0.2). No CPU form-finder ships, on purpose: with equal cable force densities a prism has no finite equilibrium (the radial balance needs q_polygon/q_riser ≈ 0.577 at n = 3, so it shrinks to a needle), and with rest-length springs a wrong-twist prism is an isostatic framework that never moves; asettle()was built, measured, and removed. Physics:World3D→.addTensegrity( _: at: strutRadius: prestress: stiffness: density: friction: group: ) Tensegrity3D: a capsule body per strut (height = L − 2r,r ≤ L/4, local +y from node a to b), a.cablejoint per cable atlength = L × ((default 0.02), a1 − prestress) .ballper shared node;sourceis the geometry as built (zero-length struts, cables to a node no strut reaches, and that node are dropped and the indices renumbered, sosource.cablesaligns withcablesone for one);nodesare read live from the strut poses..cable(is the newfrom: to: length: stiffness: ) JointKind3D: the same solver distance constraint as.distancewithlimitMin = 0(slack belowlength), snapshot tag 9. Measured (2026-09-06): prism, icosahedron, and tower all stand from a 0.3 drop (the top keeps 95%+ past the lift; cables at 1.00…1.03 of rest, none slack; asleep in 0.7 s / 6 s), the same struts without cables collapse to 12%; aprism(twist: 0.2)turns to 0.58 rad (balanced 0.524) as it settles under prestress, so the wrong twist is a demonstration, not a fold; a tall mast dropped on a 0.12 rad lean falls over (set masts down straight, which the example and figure do). Snapshots carry the tier: format 5 appends a tensegrity section (source, strut body indices, cable and shared joint indices, rest lengths, anchors) after the soft bodies; the reader accepts format 4 (oldestReadableVersion) and reads an end-of-payload as "no section";madeJointsis index-aligned with the saved joints (nil for a dropped body) so a tier can name joints.Tensegrity3DTests(12) +TensegrityTests(7, pure). Example3D/;Physics/ Tensegrity Docs/; Guide Ch 31 § Standing on cables: tensegrity + the Tensegrity figure.Generators/ Tensegrity .md Computer vision (
OllinVisionsatellite). ACamera(or anyFrameSource) feedsVisionAnalyzer(drops frames it can't keep up with; the display frame is never dropped) and composable trackers over Apple's modern SwiftVisionAPI. An export reads its detectors on its own clock (ExportClockTests; before it, seven examples exported a different picture each run and most of the rest only matched because neither run had an answer yet: DepthCloud never got past loading, BodyPose showed nobody): a frame offered on the main thread underOllinApp(.isExporting --benchkeeps the live path) is analyzed beforesubmitreturns, every tracker, each one'sprepare(for:)awaited first (the model trackers' loads,ConceptTracker's pending phrase encodings,BodyTracker's one warm-up per process, since the cold model answers with nobody), after any analysis the live path started (theinFlightgroup is entered under the lock that claims an analysis, so the export's first frame either waits for it or comes after it); the main thread parks on a semaphore there, which is sound because it is no cooperative worker and nothing those analyses or loads await runs on the main actor (read per tracker; aDepthTracker-style load throughModelLoaderproved it under the release product); the wait includes a model the system compiles on first use (text recognition's Neural Engine compile held a cold release product about 40 s, and once under media.sh's load past its 300 s limit, so re-run a vision example that fails there warm before suspecting it); a tracker registering during an export reads the source's newest offered frame at once, so alazytracker has its answer on its first draw;StillFramesisFrameAdvancing, publishingratetimes a second of sketch time from the first frame (reached within 1e-9, since fifteen sixtieths sum to just under a quarter) and nothing on a held clock, its thread silenced under the lock it calls the tap in (set bystart(), a tap installed, or the first advance under an export; a window's advance hands it back);VideoPlayerhands its tap each new frame under the virtual playhead, the pump having nothing while the player does not play; a frame source of the sketch's own steps itself fromdraw()underisExporting(TrajectoryTracking);TrajectoryTrackerstamps an export's frames a thirtieth apart (the ratedetect(across:)assumes), starting its request over when the clock changes, and is still not exact, since Vision's trajectory fit varies a few millionths run to run on identical input (held back asNOT_EXACTincheck-determinism);.sh SourceAnalyzersmatches the source itself beside its address, and the still feed's thread holds the feed weakly and ends with it, because that thread kept a dead feed's analyzer alive through its tap and a new feed at the same address was handed it and never tapped. Twenty trackers (the twentieth,MetricDepthTracker, has the bullet after this one):FaceTracker/Face(76-pt landmarks + roll/yaw/pitch),ContourDetector(camera → vectorShape),HandTracker/Hand(21 joints),BodyTracker/Body(2D pose;detect(in:)asks again on an empty answer until this process has seen one pose, at most three times, because Vision loads the 2D body-pose model on the first request that needs it and answers everything arriving meanwhile with no observations at all, so a sketch reading a still was told the picture held nobody. Measured in fresh processes, first call nothing and second all 19 joints, every time, and reproduced later than the first call under a parallel test run; once any picture yields a body an empty answer is believed, at no cost. No other request here does this,BodyTracker3Dincluded, so the retry stays put),RectangleDetector,BarcodeScanner(eachDetectedBarcodecarries a typedSymbology— aRawRepresentablestruct of static constants, so a kind the system learns later still arrives under its own raw value),TextRecognizer(OCR),ObjectTracker(lock + follow;ObjectTrackerTestspin a textured 64-px square moving five pixels a frame within 3 px at the worst of sixty frames and 1.5 on average (measured 2.7 and 1.1), the confidence above 0.85 while it is whole and under 0.1 once it is gone, the box frozen where it was last seen, so the confidence is the sign of a lost patch, and forty re-seeds through the live path each followed;Examples/takes its first lock from aVision/ ObjectTracking FaceTrackerbox on the bundled film),TrajectoryTracker(parabolic arcs, predicted),FlowTracker/MotionField(dense optical flow; the field value lives in the core,Core/, built from a read closure, so the phone's flow stream produces the same type and a source of your own can too),MotionField .swift PersonSegmenter/SubjectSegmenter(matte + cutoutImages),PointSegmenter(whatever you point at, lifted — point-prompted segmentation over a fetched three-part model:pick(at:in:)freezes the frame and encodes once (~0.2 s,.cpuAndGPUby measurement — the Neural Engine spends ~9 s specializing these graphs at load against under a second on the GPU pair, warm speed equal),include/excluderefine against the cached encoding in ~10 ms, three candidate readings with the best score winning; the mask's logits map to a soft rim — byte = 128 + logit·64 — so the upsampled edge lands anti-aliased with alpha 50% on the model's own boundary; prompts and frame are both mapped onto the model's 1024² square squashed, never letterboxed, so a prompt isfraction × 1024on each axis),ImageClassifier,SaliencyTracker(heat-map + regions + point query; the query reads the gray plane the heat map is built from, never the lookup Vision offers on the observation, which reads every row after the first from the wrong place where the map's rows carry padding, 68 wide in rows of 80 on macOS 27, so a marker placed by the query sat beside the glow;SaliencyTrackerTestsasks every cell through the query and compares it with the picture, still and live),BodyTracker3D/Body3D(17 joints in meters; canvas / model / camera space),ModelTracker(any Core ML model — classifier labels / detector boxes / image map / semantic-segmentationClassMask, decoded by observation kind), andConceptTracker(open-vocabulary scoring — typed phrases as parameters:concepts/labels/confidence(of:)softmax shares +similarity(of:)raw cosine + theimageEmbedding/embedding(of:)unit-vector surface, over a fetched contrastive image-text encoder pair), andDepthTracker(depth that holds still: temporally consistent relative depth over anyFrameSource, one frame at a time, from a fetched video depth model whose 32-frame temporal-attention window is kept in Core ML state (eightMLStatecaches of 42 slots, the upstream streaming policy: slot 0 the session's first frame as a permanent anchor, slot 1 an aging second anchor, the last 29 the newest frames), so the tracker feeds one image a frame and reads one map;map/value(at:in:)read0far …1near through a range that follows the scene (range, the 1st and 99th percentiles, out halfway at once and back 2% a frame) so the picture never re-scales frame to frame; a session's first frame is read alone and anchors the depth scale,reset()starts a new one). DepthTracker invariants: the package is built, not downloaded (Scripts/, called by the fetch script, since nobody publishes a Core ML build: the converter traces the upstream streaming step with the cache as model state, a slice assignment being the one in-place form the converter turns into a state update, and refuses to write a package that disagrees with the upstream head's own cached forward pass, measured 1e-5 relative in PyTorch and 1.6% max / 0.1% mean in fp16 Core ML); the frame's state must be opened from a package loaded from disk (an in-memory converted model cannot make state); compute units are pinnedconvert-video-depth .sh .cpuAndGPU, since the Neural Engine fails to build an execution plan for the graph (error -14 at load) and the CPU alone takes twice as long (68 ms a frame on the GPU against 140 ms, M2); the reading settles over the first 31 frames even on a still scene (the first frame's cache comes from a self-only pass and the window then fills with cached-path entries), so a stability test warms up past the window; the analyzer's one-at-a-time frame drive is what keeps the state in order (never run two predictions on one session); the frame is squashed onto the fixed 518×392 input (a fixed shape is what makes the position embedding a constant, resolved once at conversion); relative inverse depth, not meters, so noRGBDFramefrom it (MetricDepthTrackeris the one that fills one); only the Apache-2.0 Small checkpoint is scripted (Base/Large are CC-BY-NC, and the converter takes them only by hand).DepthClipis its other half (the whole clip's depth, read ahead of time): a recording through the model's published inference, the 32-frame window forward pass (VideoDepthAnythingSmallClipF16, the converter's second product, 32 image inputs.mlpackage frame_0…frame_31, one(32, H, W)output, checked against the upstream class's ownforward), scheduled the way the upstreaminfer_video_depthschedules it, kept on disk, and answered by clip time; bound to aVideoPlayerthrough the coreClipPlaybackseam (url+currentTime, the one thing an analysis over a whole file needs from a player)map/value(at:in:)answer for the frame under the playhead andmap(at:)/value(at:in:time:)for any second, and under a headless export the pass runs before the first frame, so exported framekcarries the map of the clip frame it shows, which the live tracker cannot promise (a tracker over a player analyzes nothing headless). DepthClip invariants: the scheduler is the published one to the letter (22 new frames a window; slots 0–9 refilled from the previous window's keyframes[0,12,24…31]; the fit a least-squares scale + shift of slots 0–1 against the clip's first frame and the previous window's keyframe 12; the 8 overlapping frames blended linearly from the older reading to the newer; every aligned value clamped at 0; the clip padded by repeating its last frame so the last window is full, the padding's maps dropped) and it is checked against the upstream pass itself: the converter writesVideoDepthClipReference, the upstream.bin infer_video_depth(fp32,input_sizeset to the package height so its resize is the identity) over a 60-frame clip drawn in whole numbers only (so the Swift test draws the same bytes with no shared random generator), sampled on a 32×24 grid, andthePassMatchesThePublishedInferencecompares the whole Swift pass against it (measured 0.39% max / 0.036% mean of the depth spread, three windows with the fit and the blend between them; the window package itself reproduces the upstreamforwardto 0.00000 in PyTorch and 1.0% max / 0.03% mean in fp16 Core ML, 1.23 s a window on an M2), while the always-on scheduler test drives a distorting stand-in runner (each window read through its own scale and shift) and was verified red by sabotage of the fit (max 2.03 with it removed); the pass runs on a plainThread, never a cooperative worker (minutes of synchronous Core ML), and inline on the main thread underisRenderingHeadless, so create it by the end ofsetup(); its result is a mapped.depthclipfile (a 64-byte header, half-float planes, the frame times at the end) underCaches/, keyed on the clip's and the model's path/mtime/size stamps, staged and atomically renamed, so a clip's second run opens at once (the 28 s bundled clip: a coldOllin/ DepthClips --export-sequenceran 1:34 with the pass, the warm one seconds, and the two runs' frames were pixel-identical, PNG encoder bytes aside); the frame at a time is the last one starting at or before it, the rule the headless player decodes by, so the map and the picture come from one frame; the range is fixed for the whole clip (1st/99th percentiles over a 1-in-7 sample), never followed; a keyframe's converted image input is reused across windows (identity-keyed), so each frame is resized once; compute units.cpuAndGPUlike the streaming package; frames squashed onto the same 518×392, so the pass runs at the tracker's resolution rather than the upstream default's 518 short side (a--width/--heightrebuild is the way up). ConceptTracker invariants: scores are softmax over 100×cosine, relative to the concept set — one phrase alone always reads 1, so contrasts are the intended use; text embeddings cache per lowercased phrase (one encoder run each, drained in background — both inits must queue the initialconceptsintopendingPhrases, the live path published nothing until they did); compute units are pinned.cpuAndNeuralEngine— the GPU graph compiler SIGSEGVs specializing this model family's attention blocks (an MPSGraph attention-fusion pass, crash mid-MLModel.load), and ANE+CPU runs both encoders correctly; the tokenizer (PhraseTokenizer) is Ollin's own byte-pair-encoding implementation, golden-tested token-for-token against the reference (multi-byte UTF-8 + emoji included — merges file line 0 skipped, first 48,894 merges, ids: 256 stand-ins / +</w>forms / merges / start 49406 / end 49407, context 77, truncation re-pins the end marker); the fetched pair is the 2024 permissive-license release — the 2025 follow-up model is research-only and must never be pointed at by the fetch script;ModelTrackerstages its cache copy and atomically renames — two trackers loading the same model concurrently read a half-copied.compiledModelURL .mlmodelcotherwise (hit live: paired encoders always double-load); and every tracker's Core ML load goes through the serializingModelLoader, neverMLModel.loaddirectly — concurrent loads of the same compiled model directory race in the framework's GPU program preparation and some instances come back silently wrong (measured: four concurrent loads of one compiled path, three corrupt masks, nondeterministic; loads serialized with predictions concurrent, all four byte-identical). Each also runs one-shot on a stillImageviadetect(in:); sync contexts (setup(), deterministic figures/exports) run those inline viawaitFor(— the stills are passed as arguments (not captures) becauseimage) { try await …detect( in: $0) } Imageisn't Sendable, it parks the caller (never call it from an async context), and the@Sendableclosure type is what keeps the work off the caller's actor (a plain closure would inherit main-actor isolation and deadlock the parked main thread). Coordinate mapping is the crux:VisionSpace(+ each result'sbounds(in:)/landmarks(_:in:)) maps Vision's normalized lower-left origin → Ollin's pixel top-left canvas (y-flip + rect-scale + amirrored:selfie flag) — map results into the samecamerayou drew the frame into, and use Apple's per-result.fittedRectangle( in: ) *InImagehelpers (never hand-roll the conversion — it over-spreads landmarks). Feeds draw viadrawFrame(. A frame is an_ feed: in: waiting: ) Image, so it goes wherever an image goes:globemaps the feed onto a mesh and.textured( camera .frame) environment(lights by it, with no API of their own; the material is set every frame (each capture is a fresh.feed( camera)) Image) and a freshImagebuilds its texture on first draw, so a feed on a surface costs one upload per new frame and nothing while the frame holds (LiveSurfaceTestspins that the fresh image reaches the surface rather than a stale texture; example.aFeedFrameOnAMeshFollowsTheFeed 3D/; Guide Ch 36 § The room as the surface: textured). Hardware split: classical CV (rectangles / barcodes / contours / object-track / trajectory / optical-flow) and OCR run on any Mac; the neural models (body pose, segmentation, saliency, classification, 3D pose) need Apple silicon — surfaced viaMaterials/ LiveSurface isAvailable/unavailableReason. Gotchas (pinned by probe): trackers bind toany FrameSourcevia the coreFrameSourceseam + a per-source shared analyzer kept alive by the tap closure (formed in a free function — the render-thread rule); point queries on single-channel buffers (value(at:in:)) are clampless nearest-neighbor that trap past the last pixel — clamp to(n−1)/n, and they take top-down fractions so flip y before the lookup;InstanceMaskObservationholds labels, not a soft matte (use.allInstancesMask generateMask); a Core ML model must load from a stable compiled path or it re-specializes (~10 s) every launch;DetectTrajectoriesRequestonly works through timestampedCMSampleBuffers. Model weights download viaScripts/(never committed;fetch-models .sh StyleMirror's is user-trained); a new model example follows the standing delivery rule — weights fetched into the gitignoredModels/, the example shows a run-the-script notice until they exist, provenance inTHIRD-PARTY-NOTICES, real-model tests soft-skip where weights are absent — and the catalog is deliberately bounded: plain ImageNet classifiers duplicate.md ImageClassifier's ~1,300-label vocabulary, and the modern Ultralytics YOLOs (v8/26) are AGPL-3.0, never bundled and never scripted. Examples spanVision/WebcamFeed/FaceTracking/FaceAlign/ContourTrace/HandTracking/BodyPose/RectangleScan/BarcodeReader/TextScan/ObjectTracking/TrajectoryTracking/Lift/PointLift/OpticalFlow/SceneLabels/EyeCatcher/BodyPose3D/DepthRelief/DepthContours/FootageDepth/ObjectDetection/DigitReader/StyleMirror/PaintByClass/TugOfWords.Docs/. Failure shape (2026-09-22): oneVision/ Vision .md VisionError(unavailable, the sentenceunavailableReasonholds, thrown from a call in hand;failed, a run that could not produce its result) replaces the five nestedErrorenums;PersonSegmenterand.detect SaliencyTrackerreturn their value and throw.detect failedon a matte or heat map that will not convert,SubjectSegmenteris.detect nilonly for no subject; the depth tracker's own model failure lands inunavailableReasoninstead of being dropped as a transient.Camera's start under the permission prompt is the same three-phase rule as the microphone's (stop()under the prompt calls the start off; a secondstart()asks nothing; the device opens behindCamera.openDevice, which the tests replace so none turns a camera on). NoCamera.Deviceever opens the Ollin Camera (Camera.choice,CameraChoiceTests): the virtual camera sketches publish to reports itself as an external camera and can be the system's default (found at the desk on 2026-12-04: every camera sketch drew its test card), so the choice reads a candidate list with it marked (its extension's maker and model),.defaultkeeps the system's default unless that is the Ollin Camera and then takes the built-in camera, a kind not connected falls back to that default, and a nearby iPhone counts as.continuitywhen it reports itself as an external camera that is a Continuity Camera (macOS 27 lists it so, and the.continuityCamerakind alone finds nothing).Depth in meters from one camera (
Sources/;OllinVision/ MetricDepthTracker .swift MetricDepthTracker, withPlanarInput,TriangleResize, andFieldOfViewEstimatorbeside it;ModelLoader). A metric video depth model the sketch's author downloads (written against Depth Pro 2's published Core ML packages,.load( functionName: ) apple-amlr, research use only) over anyFrameSource, answeringmeters(at:in:), anRGBDFrame(frame: the crop's color, meters, intrinsics withfx == fyand a centered principal point), andDepthTracker'smap/value(at:in:)/sourceFrame/reset(). Invariants: never fetched, bundled, or needed by an example, and no picture made with it is published (no fetch-script step, no notices entry, since nothing of the model is in the repository; the real-model tests run only whereModels/DepthPro2/was filled by hand); the package is loaded as published: inputframeis float16(1, 3, H, W)RGB in0...1, outputinverse_depthis normalized by focal length over width, so meters arefocal * scale /in the model's own pixels (width / inverse InputGeometry), and zero is the sky, read as.metersScale .infinity; the source is read through its centered crop at the model's shape, never squashed (a squash makesfx != fy), somapis padded back to the source's shape andmetersisniloutside the crop; a package's input sizes are its functions namedres_<W>x<H>, read from the compiled model'sfunctionNamesbefore the load, the smallest by default and one byinputWidth, a width it lacks being anunavailableReasonthat lists the widths it has; compute units are.all: measured on an M2 with 8 GB, the Neural Engine matches the GPU at 640 wide (S about 60 ms a frame on either) and takes half the time for B (123 ms against 267), keeps the GPU for the sketch, and holds about 40 MB in the process against 300 MB to 3.4 GB, while the first load of each size specializes for 8 to 37 s; the three devices agree to about 1% at the median; a session settles over its first 13 frames (a window of four frames at each of four cross-frame stages: 3 + 3 + 3 + 3 + 1), after which a still frame reads bit-identical, so a stability test warms up 13 and compares exactly; a new session is a newMLState(reset()), never a flag input; the lens is the settablefieldOfView(vertical, radians, of the whole source frame) or the estimator package beside the model: the lower median of the vertical angle over a session's first sixteen frames that are not black, the estimate so far used meanwhile, then held and the estimator released (it comes back onreset()orfieldOfView = nil, awaited byprepare(for:)so an export skips no frame); the estimator reads the centered 16:9 crop resized anisotropically to its 896 by 512 input through a triangle filter widened by the reduction (TriangleResize, the antialiased bilinear resize its training used), on.cpuAndGPU; a tracker with no lens and no estimator stops before the load and starts once a lens is stated. Measured against a depth camera (one indoor front-camera clip, true lens stated): B within 3% at the median, S 12% short; the estimated lens was 12% wide there. Tests:MetricDepthTrackerTests(17; ten always on, seven on the real model; twelve planted defects each red).Docs/§ MetricDepthTracker, and § Models to bring yourself for the dated list of eight unfetched models, reread at each release (Vision/ Vision .md CONTRIBUTING.md); Guide Ch 37 § How far, in meters: MetricDepthTracker.The 3D pose model's leftovers (
Sources/+ the C targetOllinVision/ BodyPose3DLeftovers .swift Sources/; macOS only). The system's 3D body pose request leaves one pixel buffer behind on every perform (48 by 2736, one 16-bit float, 0.34 MB, a retain count of exactly 2, person in the picture or not), 9 MB a second at a camera's pace.COllinHeapWalk BodyTracker3Dfinds them in the heap and frees them;BodyTracker3Dturns that off. Every perform of the request goes through.freesLeftoverBuffers = false BodyPose3DLeftovers: the count of analyses is the rule, and a perform outside it makes every look disagree. A buffer is freed only when all of this holds (.counted LeftoverBooks): the shape and format, a surface Core Video made, new at a look that found exactly one new leftover per analysis and nothing gone, still there at the next such look by address and surface id, exactly three owners at that moment (the two that never let go, and the look's), and no perform under way. Anything else frees nothing and is never freed later; eight looks in a row that disagree stop the cleanup for the run, silently where no leftover was ever met and with one stderr line where they do not add up. Never gate it on the system's version: every check is of what is found. A look runs in C under the zone'sforce_lockand takes no memory (generic Swift in a debug build does, and a thread that asks a locked allocator waits on itself); only the default zone is locked. The third owner is taken under the lock by a compare-and-swap on the object's second word, which is what makes asking Core Video about a block safe afterwards: a camera frame another thread is dropping is either held first or never touched. Never call Core Video or Core Foundation on a block the swap did not win. The fingerprint is learned at first use from two buffers made for it (where the count sits, the type bits, the first word, the block's size, the zone); learning fails, and the cleanup stands down, on signed first words, a tagged address, another kind of allocator, or a planted buffer the walk does not find. On macOS 27.3 the second word carries twenty bits that differ per object, so whole words are never compared. Two kinds of look. The allocator's listing visits every block in the heap and the request leaves about thirty small blocks an analysis, so the whole look slows as a run goes on (1.1 ms at a windowed run's start, 9.8 ms at worst ten minutes in, 35 ms on a heap of 670,000 blocks): it is rare, spaced to hold the allocator at most 0.3% of the time, and run about once a minute as the check on the rest. The quick look copies the remembered regions through the kernel and reads the copy (0.31 ms on average, 0.87 ms at worst); one that does not add up concludes nothing, since it sees part of the heap. Remembering addresses instead of regions misses nine looks in ten under a window. Measured on a windowed releaseBodyPose3D, still feed at 30 a second, ten minutes: 297 MB to 342 MB with the cleanup, against 447 MB gained in 52 seconds without it; 520 looks, all agreeing, 12 of them whole. What stays is about 3 KB an analysis of the private framework's own objects. The CI runner's system leaves none (macOS 26 in a virtual machine: 132 analyses, no buffer of the shape, a planted one counted), so the two tests that run the model take either answer inside a virtual machine and still ask for the leftovers on a real Mac, where a walk that stopped seeing them must fail; which of the two differences decides is not known. A test's sweep names its look:sweepNow(, orwhole: true) wholeLooksWait = falsefor sweeps the analyses set off, and it counts the whole looks it got, since a sweep that waits its turn settles nothing and proves nothing.LeftoverBooksTestsandBodyPose3DLeftoverTestscount leftovers alive, never a footprint;OLLIN_POSE3D_LEFTOVERS_REPORTin the environment prints the tally every ten looks.ARCHITECTURE.md§ The 3D pose model's leftovers;Docs/.Vision/ Vision .md A feed with no camera behind it.
StillFrames((core,_ picture: Image, rate: Double = 4) Sources/) publishes one picture as both aOllin/ Core/ StillFrames .swift VideoFeed(sodrawFramedraws it and never waits) and aFrameSource(so any tracker taps it);OllinVision'sCamerapicks a running camera where there is one and a still where there is not, and.orStill( _: rate: ) --phototakes the picture even where a camera would have worked, which is how a still is made of a live sketch; under--photoeveryCamera.start()throws before touching the device, so a sketch that starts aCameraitself never films the room either (four examples started one directly, so under--photothey drew the machine's own camera; they now takeCamera.orStill). It republishes rather than publishing once (4/s by default, far under a camera's rate) becauseVisionAnalyzerdrops frames it cannot keep up with, so a single published frame could be the one dropped; it also hands the picture over synchronously the moment a tap is installed, so an analyzer attached later is not blind for a quarter second. The picture is an@autoclosure, so a machine with a camera never decodes it. On a machine never asked for its camera,orStillhands back aStandInFeed(internal,Sources/): the picture until the camera's first frame and the camera after, with nothing relaunched. It is ONE object throughout, since a tracker finds its analyzer by the identity of the source it was given; its two taps share a lock, so no picture is forwarded after a live frame;OllinVision/ CameraOrStill .swift frameSizefollows whichever feedframelast settled on, so the two agree within a frame for a reader that takesframefirst (drawFramedoes). The prompt goes up at the first read in a window and never underisRenderingHeadless: a sketch's stored properties are built before a headless drive sets that flag, so the ask is put off to the first read instead of being decided where the feed is made. A refusal, at the prompt or from an earlier run, leaves the picture and writes ONE line to stderr (ruled 2026-11-19: the terminal, never the canvas, which may be on a wall) naming System Settings, Privacy & Security, Camera; a camera that could not start for another reason says that instead, and a machine with no camera says nothing. The permission's state, the prompt, and the line's destination are seams (Camera,.authorizationStatus Camera,.requestAccess Camera.note), soCameraOrStillTestsnever touches a device or the screen; aStandInFeedkeeps the destination it was made with, so no test holds a global across a suspension. A headless--exportshows the feed but not the overlay: the export renders frames as fast as it can rather than in real time (measured: frame 60 and frame 900 both take about four seconds, all of it launch), so nothing that needs a background analysis to land has time to. A live window has that time, and a still's one-shot analysis for a figure iswaitFor+ the staticdetect(in:)instead. 14Examples/Visionsketches fall back this way (which photograph each takes follows what it reads);Docs/§ When there is no camera; Guide Ch 36 § When there is no camera: stills and footage.Vision/ Vision .md Camera.or { }is the same choice with a feed of any kind standing in (a film, a screen, a feed of the sketch's own;orStillis sugar over it). The closure builds and starts the stand-in and runs only when it is needed.StandInFeedholdsany FrameSource & VideoFeed, lets the stand-in go at the hand-over (a film stops there), and forwards an export's clock to a stand-in that isFrameAdvancing(advance(by:)andadvance(to:)), so a stand-in the sketch also holds in a property is stepped twice a frame, which the doc comment and the page say; a refusal's line names "its stand-in" whereorStill's names "its picture".VideoFeed.isLive(a core protocol requirement, defaultfalse; ruled 2026-11-23) says which one a frame reads:CameraandRecord3DDeviceanswerisRunning,ScreenCaptureisReceiving,PhoneDevicetrueonly on the cable, and aStandInFeedits stand-in's answer until the live feed has delivered and the live feed's after, changing with the frame that changes and not before (a camera running behind the prompt's answer with no frame yet is not live to the sketch). It is listed inScripts/under lifecycle: it is not the state that followscheck-api-names-allow .txt start(), since a film that is playing is running and not live.ObjectTracking,OpticalFlow, andContourTracetake the film throughCamera.or(their photo-mode exports are pixel-identical before and after);ObjectTrackingmakes its face detector while!feed.isLiveand drops a lock made on the film when the camera takes over, andContourTraceremakes its detector with the contrast footage wants.Found things held steady (
Sources/, core:Ollin/ Math/ Steadied .swift Steadiable,Steadiness,Steady,Steadier,@Steadied;Rectangleconforms in the core,DetectionandDetectedRectangleinOllinVision;Docs/; examplesHelpers/ Steadied .md Vision/,ObjectDetection Vision/;RectangleScan SteadiedTests,SteadiedDetectionTests). A detector answers each frame on its own, so its boxes shake and a thing it is unsure of blinks.@Steadied var objects:takes the findings as found every frame and hands the same things back matched, smoothed, admitted after a moment, and held through a gap; the detector's own property is unchanged. The method is tracking by detection (credited in[Detection] ATTRIBUTION.md). Findings are paired with the things held byMatching.optimal, on the mean of two overlaps: with the thing's last finding, and with that box carried on at the thing's speed. A pair is allowed when EITHER overlap reaches the bar, since a speed read off shaking findings is rough: gating on the carried box alone made real rectangles blink (1 appearance became 4). The carry is what keeps two crossing things themselves; it reaches 0.1 s at most, and speed is taken only from a CHANGED finding, since a sketch reads the same answer two to four frames in a row and a re-read says nothing about speed. Confident findings (minConfidence) are paired first and alone start a thing; faint ones (minKeptConfidence) may only continue one. Time, never frames:appearDelay(0.1 s found without a break; a thing not yet showing that misses a frame is dropped unseen) andholdTime(0.3 s, held where it was), so a detector slower than the sketch costs nothing, andsteady(is called every drawn frame with the same findings again. It takes more to be admitted than to stay, twice: in confidence, and in overlap (_: deltaTime: ) minOverlapbefore a thing shows,minKeptOverlapafter, never counted higher). Each point has aOneEuroFilterof its own, and speed is counted in the thing's own sizes (betaover the mean side of its box), so the settings mean the same in pixels as in shares of the picture (pinned to a thousandth of a pixel). An outline's corners are lined up with the thing's own by the nearest turn before they are smoothed, and handed back in the newest finding's order, since a detector may call any corner the first. A type carries its own settings (static var steadiness, which is the default of every@Steadiedsetting):DetectedRectangleisappearDelay:, because the rectangle detector reports a different rectangle around anything round on EVERY frame at confidence 1.0, and those overlap one another at a median of 0.68 where a real rectangle overlaps itself at 0.98 or more; no loose bar tells them apart, and the looser kept bar is what keeps a real rectangle whose corners the detector varies. The object model's own floor is about 0.48, so its blinks are whole dropouts at high confidence, which only the hold covers. Numbers are given at appearance, things come oldest first,0.25, minOverlap: 0.8, minKeptOverlap: 0.5 valueis the newest finding moved (its label and confidence the newest's),foundis the finding as found, andunseenForis what a sketch fades by. The wrapper isFrameAdvancing, stepped beforedraw(), so a read is one frame late; it is a wrapper on the sketch and not a property of the detectors because alazy varfirst touched indraw()is not among the objects the sketch steps. Measured on recordings of the real detectors (a still photograph under seeded sensor noise, 30 analyses a second for 10 s, drawn at 60;Tests/, written byOllinVisionTests/ Recordings SteadiedRecordingWriterunderOLLIN_WRITE_STEADY_RECORDINGS). Objects: 110 appearances as found against 1, and the three things found on every frame step 0.33 to 0.82 px a frame at the 95th percentile, where the findings step 4 px and more. Rectangles: 288 appearances against 2, none let go, no invented rectangle shown. The film's dancer: one thing, showing on 91% of frames against 69%, a median 16 px behind. The model gives one cup two boxes of different sizes on alternate frames, a 60 px jump that is smoothed and not removed: no smoothing makes two boxes one.SteadiedReportprints these measures for a grid of settings (OLLIN_STEADY_REPORT) and writes the steadied things for a picture (OLLIN_STEADY_DUMP). Not measured on a live camera, and the noise is staged: the look on a camera is a row on the desk list. 25 planted defects, each red. Guide Ch 37 § The same things in the next frame: @Steadied.Geometry & color.
Vector2/Vector3over one sharedVectorprotocol (the constants,lengthSquared/dot, the operators, andwith(x:)/with(y:)are the requirements;length,normalized,distance/distanceSquared,lerp,limited,projected, the scalar-on-the-left*and the four in-place operators are written once in the extension, andCollection.centroidnow takes either element. The extension is@inlinableand must stay that way: a sketch calls these from its own module, where an unspecializable generic body measured +66% on a steering loop (9.19 ms concrete, 15.22 ms plain protocol, 9.37 ms inlined, four-module release A/B); marking the concrete primitives too buys nothing. The move is byte-identical, which is the point:lengthreadslengthSquaredover the same sum, and.squareRoot( ) lerpisself + (, the same three operations in the same order as the old component-wise form. What stays per type is what does not generalize,other - self) * t crossabove all: aDoublein 2D, aVector3in 3D, which is also the whole of the 2D answer sitting in the 3D one'sz;Vector2keepsangle,perpendicular, the signedangle(to:),rotated(by:)and the polar initializer,Vector3keepsunitZ,xy, androtated(.by: Rotation3D) VectorProtocolTests(8) pins the generic reach, an outside type conforming with nothing but the requirements, and the exact arithmetic over 300 awkward triples per invariant, sabotage-verified: the equivalentself * (fails 400 of 600 expectations. The types that are a list of things say so, as1 - t) + other * t RandomAccessCollections besidePaletteandTable:Contourover its points,Shapeover its contours,Grid/HexGrid/TriangleGridover their cells,Polyominoover its squares. Two invariants. A conformance must not quietly redefine a call that already means something else:contour.contains(p)would have become a vertex-membership test besideShape.contains(p)'s geometric one, soContourgained its own geometriccontains(_:)(the concrete member wins over the protocol extension, and removing it turns the test red rather than ambiguous). A grid's element is worked out as it is asked for, so iterating one allocates nothing and its subscript carries its own bounds check (nothing else would trap, andgrid[-1]would otherwise answer for a column left of the grid), andcellsis nowArray(self)so the row-major order has a single definition; that makesArray(tautological, and the order is pinned against a walk written out in the test instead.grid) == grid .cells Contouralso reachesCollection.centroid(the points' mean, which is notShape.centroid's balance point of the filled region; both are documented against each other).CollectionConformanceTests(15), both sabotages red. What was weighed and refused is in DESIGN-NOTES under the idiom track:Path(commands, not points),Rhythm(countwould repeatlength),Ramp(reversedthe property besidereversed()the method), and the documents with several parallel lists. Gotcha, the second time it has cost a build:Sequenceconformance shadows the global two-argumentmin/maxinside the type's own extensions, a hard error at every bare call site.Docs/,Drawing/ Geometry .md Docs/,Drawing/ Tiling .md Docs/),Generators/ Polyominoes .md Box3(an axis-aligned box as one value:min/maxcorners withcenter/size/longestSide/isEmpty/contains(_:),padded(by:)andunion(_:),init(center:size:)and the optionalinit(containing:); whatMesh.bounds,Scene.bounds,Metaballs.bounds,ShadowArt.bounds, and the phone room'sPhoneSceneMesh/PhonePlanesreport and whatisosurface(in:)/shadowArt(in:)march over, in place of the(min:max:)tuple those twelve sites each spelled;Box3Tests),Rotation3D(a turn in space as one value: a unit quaternion read asangle/axis, built from an angle about an axis, the shortest turnfrom:to:, or raw quaternion parts;a * bisbfirst, thena, matrix order;inverse,interpolated(to:_:)along the shortest arc,matrixfortransform(_:),Vector3, and.rotated( by: ) rotate(_:)on the sketch; one form per turn,wkept non-negative so equal turns compare equal however built; it is whatBody3D.rotation/Wheel3D.rotationread and set, with therotationAngle/rotationAxispair andsetRotation(now sugar over it, and what_: axis: ) withBody/withWheelpose through;Rotation3DTests(10),RigidBody3DTestsfor the body),Ray3(the pointing value: an origin plus a direction kept at length 1 in the initializer, so every distance a hit reports is a real distance andpoint(at:)reads as "this far along", withdistance(to:)/distanceAlong(_:)andhit(/sphereAt: radius: ) hit(boxAt:size:)/hit(; only what is in front of the origin counts, a ray starting inside a ball answers the far side rather than handing back something behind the hand, a slab the ray runs parallel to is judged by whether it sits inside it rather than by a division, and a zero direction answersplaneAt: normal: ) nileverywhere instead of NaN —Ray3Tests(11), sabotage-verified; the 2DRay2underenvelopeis a family of lines, not a pointer, and leaves its direction as given),Rectangle(+ theRectangle(letterbox everything shares,fitting: in: ) contains,inset(by:), the normalizedpoint(u:v:)/uv(of:)pair — canvas sugarSketch.uv(_:_:), exampleBasic/),NormalizedCoordinates Circle,Shape/Contour(arc-length walk helpers + evenresampled(spacing:), on both), thePathcurve builder; per-frame transform stack (translate/rotate/scale, scoped viawithState {}; thewithState(/at: rotation: scale: ) withState(forms build the placement in — fixed order translate → rotate → scale, origin at the point, byte-identical to the spelled-out block).at: Vector3) drawSheet(lays labeled_: columns: gutter: _: ) (label, item)pairs into a near-square gallery (label plates on the currenttextFont, state untouched, near-square column count by default) — the layout the filter-family examples each carried a private copy of.Ramp(is the typed twin of the tuple list andstops: [Ramp .Stop]) ramp.reversedmirrors every stop about ½ (built overstops.reversed()so a hard edge keeps its colors in mirrored order;PaletteTests).Heightfieldpaints each sample through a.image( _ ramp: in: ) Ramp(pixels equal the ramp's own colors,Convenience3DTests) andcoloredMesh(...)hands back the terrain mesh with it already applied (build on field change, not per frame).sketchResource(finds a folder-beside-the-sketch file by walking up from the caller's_: in: from: ) #filePath(a free function so astatic letcan call it;nilwhen no folder is found — for bundled resources keepBundle.module). Color reads back ashue/saturation/brightness(public inverse ofinit(hue:...); a gray reads hue 0; exampleColor/Mixing, which labels each band's midpoint that way), mixes as the instancemixed(with:_:in:)beside the staticColor.mix, andColormapwraps by whole laps where.color( cycling: ) color(at:)clamps (aPalettealready wraps; most maps still seam at the lap —CosinePaletteis the seamless ring); exampleMotion/Mandala.Paletteis aRandomAccessCollection(startIndex/endIndexover the existing wrapping subscript, which already answers correctly for every index a collection asks about), so it iterates, maps, and takesrandomElement(; it stays read-only because a wrapping index makes a setter ambiguous. The conformance's one cost is not obvious:using: ) Sequenceputsmin()/max()on the type, which shadows the global two-argumentmin/maxinsidePalette's own extensions, so three call sites inPalette.swift/PaletteExtracthad to become.swift Swift.min/Swift.max(a hard compile error, not a silent one).PaletteTests(2 tests, one pinning that iteration does not inherit the wrap). The generator/technique catalog below is terse invariants + pointers only — mechanism, history, and the example/snapshot/test pointers live inARCHITECTURE.md§ The geometry and generator catalog + § *Color: palettes, dithering, and print separations* (user-facing API in the namedDocs/pages), and new catalog depth routes there, not here. Three catalog-wide rules: determinism is a promise — no rng decision or position-mutating pass ever walks a SwiftSet/Dictionarydirectly (sorted candidates, fixed iteration orders; the WFC rule, shared by mazes / space colonization / boids / the physics resolver); fit a figure by scaling its points, notscale()(the CTM scales stroke width too; the trochoid/Lévy rule); and a geometry cost dial is an artwork parameter, never aRenderQualitytier — geometry is data a sketch reads back and the tiers resolve per-GPU, so a tier would change the piece (and make it machine-dependent), not its rendering fidelity;maxVertices/levels/resolution/ erosion stay explicit numbers, with@Param+--export-sweepthe tuning path (RenderQualitystays GPU-sampling-only; reasoning in ARCHITECTURE.md § Performance and the quality dial). The catalog:Grid— typedcolumns × rowsover aRectangle; indexedpoints/cellselements (indexed cases are a single loop);.center/.spanning;padding/gutterover typedInsets; element-type design history settled, don't re-litigate. Shape booleans & offsets (vendored Clipper2, BSL-1.0) — offset output must beSimplifyPaths'd or cascaded insets balloon; stroke as shapestroked(— the input is not normalized first (that would erase open paths); convex hullwidth: join: cap: ) convexHull(of:)(monotone chain). SVG import —SVG+loadSVG/drawSVG/fitted(in:); control points transform before flattening; initial fill black, initial winding.nonZero(don't "harmonize" with Ollin's.evenOdddefault); unresolvableurl(#…)→ mid-gray, never dropped; unsupported containers skip their whole subtree.Docs/Drawing/SVG.md. Fourier epicycles —Epicycles+drawEpicycles;terms:is a largest-first prefix; deterministic sort tie-break;point(at:)periodic; exact at full terms (EpicyclesTests). Classic curves —phyllotaxis/lissajous/rose(parity-dependent closure span, no retraced doubling) /hypotrochoid/epitrochoid(integer gears, exactlywheel/gcdlaps) /superellipse(Lamé identity pinned per point; uniform-angle sampling,resampled(spacing:)for plotter-even outlines at extremen) /supershape(2D Gielis mirroringMesh.supershape's defaults + its clamp-to-4 radius guard; integermor the curve doesn't close in one turn — a fractionalmleaves a seam, caught in the example) /guilloche+Rosette(rose-engine rings: stacked sinusoid cams over evenly spaced bases, ring k rotated by k·twist — the twist is a pure rotation of the wave and stacked rosettes superpose, both pinned exactly inGuillocheTests; snapshotguilloche, examplePatterns/Guilloche) / the damped-pendulumHarmonograph/spirolateral(the one walk in the set: steps 1, 2, 3 …orderwith a fixedturnafter each, the run repeated until it comes home) / Chaikinsmoothed((open contours keep exact endpoints) / the count-keeping moving averageiterations: ) smoothed((neighbors: weights: ) SmoothingWeights, sigma half the window, or.gaussian .box; one point out per point in, same order; a closed window wraps and stops where it would meet itself,(n - 1) / 2; an open window mirrors through each end point (2 * end - p), so a straight even run is a fixed point and the ends are set back exactly; a 64-point circle shrinks by the kernel's cosine sum at every window, 1.9% box / 0.95% bell at 3 neighbors, pinned per window and both weights inMovingAverageSmoothingTests(8), red under sigma = the whole half-window, a box one point short, and a clamp-to-end boundary); all rng-free; examplesShapes/Superellipse+Shapes/Supershape.Docs/. The spirolateral's closing is arithmetic, decided before a point is placed: one run turns the walker byDrawing/ Curves .md netTurn, so at a turn oftau/kit closes ink / gcd(order, k)runs and never whenkdividesorder(the run then ends facing the way it set off, so every repeat lands further away in the same direction —closesfalse,centernil, drawn open). The whole figure isrunturned aboutcenteronce per repeat, which is the invariant the tests pin (plus the centroid landing oncenter, and the outline measuringrepeats · step · order(). A swept turn angle never closes anything — only an exact fraction of a full turn does — so animate theorder+1)/ 2 orderor thereversedset instead, the gotcha that made the first example draw twelve open walks. ExamplePatterns/; snapshotSpirolateral spirolateral;SpirolateralTests(11, two sabotages verified red). Guide Ch 16 § A walk that comes home: spirolaterals + the Spirolaterals figure. Envelopes & caustics (Geometry/) —Envelope .swift Ray2+envelope((the curve a family of lines leans on, found as the crossings of consecutive members; parallel neighbors never cross, so the answer is a list of runs and a parallel family gives back nothing) +of: closed: ) LightSource(.point/.parallel) +reflectedRays/refractedRays(vector mirror law; Snell in vector form, with total internal reflection dropped rather than faked, so the ray array can be shorter than the curve) +caustic(/off: from: closed: ) caustic(+through: from: ior: closed: ) drawEnvelope/drawCaustic. Surface normals come from each point's two neighbors, so an open curve loses its two ends and a curve wants a few hundred points. The construction arrives rather than lands: the crossing sits outside the true curve by an amount falling with the square of the step, which is the pinned invariant (halve the step, the error quarters) — a fixed tolerance was the wrong test and failed against correct code. Known answers pin the rest: the tangents of a circle envelope that circle, parallel light on a circle draws the nephroid (cusps at r/2, reaching the mirror at r — the first version of this test asserted r/2 for the reach and was simply wrong), a source at the center sends every ray back through it, and a flat mirror has no envelope. Only the lit stretch of a closed curve should be handed in (near and far families lean on different curves), and filtering a ring for it must keep the run contiguous — a wrapped filter puts the arc's two ends side by side and the segments between them are not rays at all (this bit the example and the Guide figure). PlushuygensFront(, the same envelope with circles instead of lines: the new front is where the wavelets lean, and the folded pieces are dropped (a point of the new front is exactlyfrom: advancing: closed: ) distancefrom the old one and no nearer to any part of it), which is what turns an offset into a real wavefront and makes a front tear into a focus once it has traveled the radius the curve bends at. Its reference is the moved point's own two segments, never the distance asked for: a sampled curve is a run of chords sitting a sagitta inside it, so comparing against the radius threw away every point of a front moving into a bend (the first version returned nothing at all for a shrinking ring). The pruning is sabotage-verified by two tests, and the accuracy is one sagitta, which the front test's tolerance states. Cost grows with the square of the point count, so a wall of fronts belongs insetup(). ExamplesPatterns/Caustic+Patterns/Wavefront;EnvelopeTests(9) +HuygensTests(6), sabotage-verified; no snapshot (the geometry is exact).Docs/; Guide Ch 16 § The curve a family of lines leans on: envelopes and caustics + the RaysLeanOnACurve figure. Shape morphing —Drawing/ Envelopes .md ShapeMorph(build once, readshape(at:)) +Shape/Contour: Tweenable+morphed(; orientation mismatch reverses all target contours (never per-pair); spacing derives per outline, not per pair; unmatched contours lerp to their own centroid; originals verbatim at 0/1 (toward: _: spacing: ) ShapeMorphTests).Docs/. Voronoi & Delaunay (Bowyer–Watson + clip toDrawing/ Morphing .md bounds,relaxed()Lloyd; examplesPatterns/Voronoi+Patterns/Delaunay, the dual pair — the triangle side also reading adjacency back throughDelaunay) + power diagrams (.neighbors( of: ) PowerDiagram/WeightedSite/powerDiagram(,of: in: ) Geometry/): a weight subtracted from the squared distance, each cell cut as an intersection of half-planes (the direct construction, not the lifting map — cost grows with the square of the site count, so a few hundred sites, not a few thousand). The cells stay convex and still tile the region exactly, and a site can lose everything (an emptyPowerDiagram .swift Shape, which a plain Voronoi diagram can never produce). Only weight differences matter (lifting every weight leaves the diagram identical — a pinned invariant). Weighting a circle by r² is the case worth having: a circle touching no other lies wholly inside its own cell, where a plain Voronoi boundary cuts through the bigger one. Test-coverage gotcha: the rim test first passed a wrong-sign sabotage, because four similar circles stay inside their cells either way — it only bites once the set holds a lopsided, nearly-touching pair (a big circle beside a small one), which is the case the weighting exists for. ExamplePatterns/; snapshotPowerDiagram power-diagram;PowerDiagramTests(8, sabotage-verified).Docs/§ Power diagrams; Guide Ch 15 § Territories and neighbors: Voronoi and Delaunay + the WeightedTerritories figure. A sheet of facets (Drawing/ Voronoi .md Geometry/):FacetField .swift FacetFieldlifts aDelaunayby a height (init(_:height:),init(,points: height: ) init(_:heights:)), oneFacetper triangle with its cornerheights, a unitnormalby the cross product of the two lifted edges flipped toz > 0(a plane's normal is exactly(-α, -β, 1)normalized,FacetFieldTests),tilt(normal.xy, downhill, as long as the sine of the slope),facing(_:)(the clamped cosine against a light direction;lightDirection(builds one), andangle: elevation: ) bandCoordinate(;angle: shift: ) grid(jitters a lattice anchored at the canvas origin and keyed per node (in: spacing: jitter: seed: height: ) latticePoints, oneSplitMix64stream per node from the seed and its lattice index, so overlapping regions share points and a region's origin never moves them) with one ring past the region so every point inside lies on a facet;crumpled(is the foil filter's default (two octaves ofin: spacing: crinkle: seed: ) NoiseFields(seed:), swingcrinkle × spacing);lifted(by:)keeps the triangulation;edgeslists every crease once;facet(containing:)is a same-side scan. Cuts by a line (Geometry/):ShapeCuts .swift HalfPlane(/point: inward: ) leftOf:/rightOf:(left as the canvas shows it, looking along the direction:inward = (dy, -dx)),Contour(Sutherland-Hodgman against one plane for a closed contour, the inside pieces for an open one),.clipped( to: ) -> [Contour] Shape.clipped(to:)(every contour, winding kept, vanished contours dropped),split((the areas add to the shape's,along: ) -> ( left, right) ShapeCutTests), andclipped(within:of:)(two clips). The Voronoi builder keeps its own private clip.Docs/§ A sheet of facets;Drawing/ Voronoi .md Docs/§ Cut by a line; Guide Ch 15 § Territories and neighbors: Voronoi and Delaunay (a paragraph). + blue noise (BridsonDrawing/ Geometry .md poissonDisk, a public generic over anyRandomNumberGenerator). Low-discrepancy sampling —halton/haltonPoints/sobolPoints: pure index functions (no rng, never touch the sketch'srng);startIndexdefaults 1; Halton bases stay coprime (SamplingTests). Stippling — Secord weighted-Voronoistipple; the ring search may stop before ring r only once the best find is ≤ (r−1)·bucketSide (the r·bucketSide bound was a real lattice-locking bug); zero ink → empty array; density = (1 − linearluminance) · alpha (StippleTests). Random walks —randomWalk/levyFlight(minStep> 0 — the power law diverges at zero) /selfAvoidingWalk(visited-forever marks + parent-link reconstruction); all seeded (WalkTests). Truchet — arcs centered on cell corners, so abutting cells join under any flip; examplePatterns/Truchet(both tiles,.arcsbeside.diagonals). Hitomezashi — one phase bit per grid line (shorter bit arrays cycle; seeded form draws bits atprobability); two faces of one design:stitches(open 2-pointContours, same-line dashes never touch) +parities(the two-coloring, row-major zip withgrid.cells— tone boundaries land exactly on stitches,HitomezashiTestspins the theorem geometrically, sabotage-verified);Docs/, exampleDrawing/ Hitomezashi .md Patterns/, snapshotHitomezashi hitomezashi. Ten print —tenPrint(+in: columns: rows: probability: ) drawTenPrint: one coin per cell choosing between two diagonals (bitsrow-major, a shorter array cycling like Hitomezashi's), two faces of one design:lines(one 2-pointContourper cell, the plain reading) +runs(the same diagonals joined end to end at the corners they share). The corners are a lattice worked out fromgrid.bounds, not from a cell's frame, so agutternever opens a gap two diagonals would fail to meet across. The run walk starts only at a corner that is odd right now (a corner where an odd number of diagonals meet has to end some path), which is the one thing no coverage or length test can see: deleting the rule left all nine other tests green, soaChainWithTwoLooseEndsComesBackAsOneRun(three cells leaning down-up-down must come back as one run, not two) is the test that pins it. Not claimed: minimality, since the leftovers are taken as loops rather than spliced back into the trails running through them. ExamplePatterns/TenPrint; snapshotten-print;TenPrintTests(10, sabotage-verified).Docs/; Guide Ch 7 § The diagonal tile: ten print + the DiagonalMaze figure. De Bruijn sequences (Drawing/ TenPrint .md Math/DeBruijn.swift) —deBruijnSequence(+symbols: window: ) DeBruijnCode(the reader:position(of:)/window(at:)) +lyndonWords(. A cyclic run ofsymbols: maxLength: ) symbols^windowsymbols holding every window of that length exactly once, which is the shortest such run and the reason a glimpse of a few symbols names its own position (encoders, printed rulers, locally-unique tile runs). Built by the Lyndon-word concatenation (write out each necklace whose period divides the window), so the result is the dictionary-least run and therefore always opens withwindowzeros — a fixed answer, not any valid one. The run is a ring: reading wraps, and drawing it as a strip leaves the last windows looking broken.position(of:)is nil for a wrong-length run or an out-of-alphabet symbol (nowhere, not somewhere). The decode table holdssymbols^windowentries, so the window is chosen from what a reader can see, not from a wanted length. Invariants: the count, every window present exactly once (read cyclically), the known small runs symbol for symbol, the sequence equalling its own Lyndon pieces laid end to end, every Lyndon word below its own rotations, the necklace-count formula with the Möbius function computed from its own definition in the test, and the reader round-tripping at every position. Dropping the period rule (write every necklace, not only those dividing the window) is caught by four tests. ExamplePatterns/DeBruijn;DeBruijnTests(8, sabotage-verified); no snapshot (the geometry is exact and the picture is the example's).Docs/; Guide Ch 7 § Every window once: de Bruijn sequences + the EveryWindowOnce figure. Ford circles —Generators/ DeBruijn .md fordCircles(+order: in: interval: ) drawFordCircles(the Sketch facade mirrors the free function's labels exactly — a member shadows a global of the same name inside a sketch, soin:-first would break every call written for the free form; the shadowing rule the CA helpers already carry) over the newfareySequence(and the exactorder: ) Fractiontype (Math/Fraction.swift: reduced, positive denominator,mediant/isNeighbor/determinant, comparison by cross-multiplication so no rounding can change a neighbor into a stranger; a zero denominator reads as one). Every fractionp/qgets a circle of radius1/(2q²)on the line atp/q; the unit interval spansbounds.widthand the radius is scaled by that same width, which is what keeps them touching (scale x and y differently and the whole picture is a lie). The invariant both halves rest on is exact and is what the tests measure over every pair at once:distance² − (, so two circles touch iff |ps−qr| = 1 and are strictly apart otherwise — the never-overlapping half is the one a picture cannot show.r₁+r₂)² = ( ( ps−qr)² − 1)/ ( q²s²) touches(_:)answers on the fractions, never on the distance. The Farey walk is the standard next-term recurrence (cost = the length of the answer, ~3n²/π² terms), pinned against a brute-force build, against the totient-sum count (φ counted from its own definition in the test, not from a shipped helper), againstps−qr == −1for every consecutive pair, and against the mediant being the first fraction to appear between two neighbors, at exactly the order its denominator names. ExamplePatterns/; snapshotFordCircles ford-circles;FordCircleTests(8).Docs/; Guide Ch 15 § A circle for every fraction: Ford circles + the CircleForEveryFraction figure. Ulam spiral —Generators/ FordCircles .md ulamSpiral(+in: size: start: padding: ) drawUlamSpiralover a squareGrid:numbers(row-major, zips withgrid.cells),order(cell per counting step,-1for a step outside an even-sided grid),point(of:)/number(column:row:)/points(where:)/primePoints/path, plus the freeprimes(upTo:)(sieve of Eratosthenes) andisPrime(_:)(6k ± 1 trial division) inMath/Primes.swift. The walk is right, up, left, down with side lengths 1, 1, 2, 2, 3, 3 …, which reads counterclockwise on screen and is what puts the odd squares on one diagonal (offset(n−1)/2both ways from the middle) and the even ones one step off the other (((n−2)/2, n/2)up and left, because their ring turns the corner just before it closes). The invariant that pins why the picture has lines in it is that a quadratic traces a straight line (4n² + 2n + 1steps evenly along one diagonal); turning the walk the other way breaks the square invariants and nothing else.primePointsruns one sieve over the whole square, never a test per cell. ExamplePatterns/UlamSpiral; snapshotulam-spiral;UlamSpiralTests(9, sabotage-verified).Docs/,Generators/ UlamSpiral .md Docs/; Guide Ch 6 § Walking a grid: numbers in a spiral + the NumbersInASpiral figure. Kolam / sona — the mirror-curve walk on a lattice twice as fine as the dots (a dot at odd-odd, the line only ever at points with exactly one even coordinate, one diagonal step per cell); the state is the outgoing direction, not the incoming one (Helpers/ Math .md leaving(filters the start states), or every loop comes back twice, and the walk strikes off the reverse state as it goes for the same reason; a wall asked for on the outside edge is dropped, since the edge already turns the line. Two counting invariants, both tested and neither visible in a picture: a plain field closes into gcd(rows, columns) loops, and the loops always hold 4 × rows × columns segments (four per cell, not two — measured, my first guess was wrong), while any interior wall moves the count by exactly ±1;...) == step KolamTestspins all three.loopsare square-corneredContours (honest geometry;smoothed(is the drawn form, anditerations: ) drawKolamrounds by default);Docs/, exampleDrawing/ Kolam .md Patterns/Kolam, snapshotkolam, Guide Ch 7 § No coins at all: kolam and sona. Celtic knotwork — the sameMirrorCurvewalk (extracted toKolam.swiftand shared, so the two can never disagree) given width and an over/under rule. The rule is one line and it is why the weave holds: the up-right pass goes over wherever the crossing's lattice x is even, which flips at every step and so alternates along every cord, while the two passes through one crossing always run in opposite diagonal senses so exactly one is over. A point the line turns at (edge or wall) is not a crossing — only one pass reaches it — so the dive indices are walk indices, never positions in the filtered crossing list (they do not line up; that mismatch was the first defect).bands(gap:)hands back the pieces already broken at each dive, so stroking them is the weave: no mask, no draw order to get right, and the gap is clamped under the crossing spacing so two dives in a row still leave cord between them. A plain field has 2·rows·columns − rows − columns crossings and each interior wall removes one. The length invariant is the test that caught the real bug (both gap offsets were signed the wrong way, so pieces ran past each crossing instead of stopping short, and the picture still looked woven because the outline pass was covering the overlap): total band length must equal total cord length minus one gap per dive;KnotworkTestspins that, the over/under consistency, and the alternation.Docs/, exampleDrawing/ Knotwork .md Patterns/Knotwork, snapshotknotwork, Guide Ch 7 § The same line, woven: Celtic knotwork. Tiling & layout —HexGrid/TriangleGrid(true-aspect blocks, never stretch; axial math;cell(at:)via cube rounding),Subdivision(the root always splits;chancefrom depth 1),Maze(three carvers, all perfect; collinear walls merged; double-BFSlongestPath()),apollonianGasket(Descartes/Vieta other-root — linear recursion);TilingTests.Docs/. Polyominoes (Drawing/ Tiling .md Geometry/) —Polyomino .swift Polyomino(squares joined edge to edge, always normalized to the origin, so it is a shape and never a place;Polyomino(string form,["XX.", " .XX"]) rotated/mirrored/orientations(,reflections: ) rectangle(, the 12columns: rows: ) pentominoes+pentominoNames+ 5tetrominoes) +outlines((the edges only one cell owns, chained; one contour per boundary loop, so a holed piece hands back the hole wound the other way, and collinear corners are dropped) +cellSize: origin: ) tilePolyominoes(returning_: covering: reuse: reflections: ) [PolyominoPlacement]?(piece/shape/at, since the shape cannot carry its own position). Where a piece sits is swept over the region's whole box, never over its cells — a piece whose own bounding-box corner is empty (the F) sits at offsets that are not region cells at all, and anchoring on cells silently loses those fits (sabotage-verified red); both being normalized is why a negative offset is never needed. The search fills the cell with the fewest remaining ways and keeps those counts incrementally (close/open per option, the dancing-links selection rule over plain arrays): 3x20 pentominoes went 109 s → 8 s against filling cells in order, and a flood-fill island prune that helped the in-order version measured slower once the counts existed (a cell in a dead island already has zero ways), so it was removed. The undo must run the closes in reverse or the counts drift (sabotage-verified red).orientationscounts rather than assumes (F/L/N/P/Y 8, T/U/V/W/Z 4, I 2, X 1, summing 63 — the published table is the test). Invariants: exact cover, each piece once unlessreuse, all four classic pentomino rectangles solvable, the mutilated board refusing dominoes (nil means the whole space was searched), and the seed deciding which fit comes back. Not a per-frame call (~1 s for the 12-pentomino board): solve insetup()and animate the drawing. ExamplePatterns/;Pentominoes PolyominoTests(12, two sabotages verified red); no snapshot (the picture is the example's).Docs/; Guide Ch 7 § Pieces that have to fit: polyominoes + the FittingPieces figure. Aperiodic tilings (Generators/ Polyominoes .md Geometry//Penrose .swift WangTiles.swift/Girih.swift/Spectre.swift) —penroseTiling(P2/P3 by Robinson half-tile deflation from a ten-half wheel, merged into whole tiles; the P2 child orderings encode each half's axis leg — wrong assignments T-junction at depth 2, crack-free-pinned; rhomb outlines lead with the positively-wound half's apex — the intrinsic orientation the arc decoration needs, since C2-symmetric arc placement collapses to midpoint crossings (a solved dead end, not a tuning parameter); arc fractions are solved continuity constants; rng-free);wangTiling(scanline fill honoring west/north edges;WangTilingnever dead-ends, arbitrary sets retry then return nil; weighted picks off the sketch rng);.completeSet girihPattern(Hankin/Kaplan inference: two rays per edge midpoint at the contact angle, paired greedily by summed length with(cost, i, j)tie-breaks; unmatched rays drop;Girihis the exact patch-composition primitive);.Tile .points( onEdge: _: ) spectreTiling(the chiral-monotile paper's 9-metatile / 8-slot substitution; every generation mirrors whole, so leaves at any depth share one handedness — pinned by the cyclic turn-sequence test; gamma carries the 30°-rotatedisOddmystic;curve:bends edges into the strictly chiral spectre, alternation cyclically consistent because 14 is even; rng-free). All four crack-free-tested (AperiodicTilingTests); examplesPatterns/Penrose/WangTiles/Girih/Spectre; snapshotspenrose/wang-tiles/girih/spectre.Docs/. Hyperbolic tiling —Drawing/ AperiodicTilings .md hyperbolicTiling(/sides: meeting: ) HyperbolicTiling, any {p,q} with (p−2)(q−2) > 4 in the Poincaré disk: the central polygon placed at the exact derived vertex radius (cosh = cot(π/p)·cot(π/q)), grown breadth-first by geodesic-circle inversion with center-dedup, pruned by drawn.tiles minEdge; tiles carrydepthand aparitytwo-coloring (checkerboards iffmeetingis even), andviewpointre-seats the tiling before pruning so a pan is a rigid motion (tile count stays ~constant — the test pins panned tiles as exact images of centered ones, the pin that caught a conjugate-sign bug the horizon checks missed). Deterministic, rng-free. ExamplePatterns/; snapshotHyperbolicTiling hyperbolic-tiling;HyperbolicTilingTests(7, the pan pin sabotage-verified red).Docs/. Parquet deformations —Drawing/ HyperbolicTiling .md parquetDeformation(/in: columns: rows: from: to: sweep: ) ParquetDeformation, a tiling whose tile changes shape as it is read across (Huff's design exercise; Kaplan's curve-interpolation reading of it): the geometry lives on the lattice's edges, never on the tiles, so both tiles beside an edge read one stored curve (reversed on the far side) and the sheet is crack-free by construction however far the shape drifts — a tile's outline is the four edges around it, each side dropping its last point, which is the next side's first. An edge is aProfilein its own frame (x along it, y sideways as a fraction of that edge's length, ends pinned to (0,0) and (1,0) so the lattice's corners never move):.straight/.tooth(/depth: width: ) .zigzag(/count: depth: ) .wave(count:depth:)/.bump(depth:)/.custom([Vector2]), each free to double back, with one-argument statics standing in for the common shorthands (an enum case cannot carry a default). The blend is exact rather than sampled: both profiles are reparameterized by normalized arc length and the blend's vertices sit at the union of the two vertex sets, where both inputs are straight and so is their blend — a square tooth therefore keeps square corners at its own end of the run, and there is no resolution parameter to get wrong. The amount is read at each edge's midpoint;Sweep(.horizontal/.vertical/.diagonal/.radial) is sugar over the general closure form (a canvas point in, 0…1 out, clamped rather than extrapolated), which is what lets a run follow noise, an image's tone, or a moving front. Two faces:tiles(row-major, each carryingcolumn/row/amount/center/contour/shape, walked clockwise from its top-left lattice corner) andedges(every lattice edge exactly once, so a translucent stroke never doubles and a plotter makes one pass). The sheet's rim is fringed — the outer tiles carry their deformed outer edges — so a straight border is a boolean intersection, not a setting; the grid'sgutterdoes not apply, since parquet tiles meet along shared edges. Deterministic, rng-free. ExamplePatterns/; snapshotParquetDeformation parquet-deformation;ParquetDeformationTests(9, the shared-edge rule checked point for point with no tolerance, since both sides read one array).Docs/. Circle & shape packing — grow-to-touchDrawing/ ParquetDeformation .md packCircles+ closed-formpackCircles(+around: ) relaxCircles(fixed-axis parting); geometry-awarepackShapesover the statefulContinuousPacking(fits actual outlines); an unboundedmaxRadiusclamps the grid cell and reach to the region size (PackingTests); examplesPatterns/(all three circle routes side by side) +CirclePacking Patterns/. L-systems — 13 verified presets; 2M-symbol expansion cap; oneShapePacking Contourper unbroken turtle run (a branch shares its branch point with the trunk). Parametric L-systems (ParametricLSystem+LSystemExpression/*Parsing/*Turtle/*Presets, ABOP §1.10 + Hanan 1992 ch. 4) — modules carrying reals, rules doing arithmetic; rules are text in the literature's notation (A(). Load-bearing: the match key is (letter, arity) and an unmatched module stands for itself (which is both why turtle symbols need no rules and how a guarded form settles); productions are a source-ordered array and first-match-wins, but first-match and weighted normalization are mutually exclusive policies, so the engine gates on whether any rule declares a weight (weights are shared over the rules that matched, so disjoint guards behave identically either way); Hanan's precedence table is not C's —s) : s > 0.02 -> F( s)[+A( s/ 2)] : weight ^binds above*and groups right, unary binds above^(-2^2 == 4), and getting it wrong is silently wrong rather than a parse error; names resolve to positions at parse time (evaluation touches no dictionary); the word is flat SoA (letters/bounds/values, ASCIIUInt8) since a published derivation runs to millions of modules and a per-module[Double]would spend the expansion in the allocator;==stays exact (the sanctioned idiom is an integer counter guardedd > 0/d == 0) and a NaN condition reads false (NaN != 0is true in IEEE, so a plain zero-test would fire a rule on a division that went wrong); a rule that will not parse is recorded inerrors+ noted once and left out, never thrown or trapped. The turtle is the plain one plus three things: per-symbol parameters (first parameter steers, extras ignored — what letsF(x,t)drawxwhiletcounts down), a width!(w)that[/]save and restore (claimed onto a branch's opening point, so!(w)F(l)is uniform), and%cut. A roll or pitch of a whole number of half-turns is planar — it is a handedness flip (+/-reverse), which is what makes 6 of the published 9-tree rows exactly faithful rather than 2; every other roll/pitch and the polygon/color/surface symbols note once and draw nothing.+follows the shipped 2D turtle's sense (mirrors the book's figures; consistency withLSystembeats matching the page). Widths reach the canvas asStrokeMarks normalized so the widest is 1 (sostrokeWeight= the trunk), vialSystemMarks/drawLSystem(;…, tapered: ) contoursandmarkscome off one walk so they cannot drift.LSystemis shared by both kinds (extracted with identical arithmetic — 185/185 snapshots unmoved). Two turn angles are Ollin's, not the sources' (compound leaves 45°, mesotonic) and say so in the preset docs +.fitTransform ATTRIBUTION.md. Deliberate cut: context-sensitive productions (A < B > C), a clean published boundary — the plainLSystemhas no context either. ExamplePatterns/; snapshotParametricLSystem parametric-l-system;ParametricLSystemTests(49, eight mechanisms each verified red by sabotage). Differential growth — stateful class, order-stable → a fixed-framesnapshot reproduces. WFC — simple-tiled (Gumin); sorted candidates + fixed cell order or the seeded solve flakes. Overlapping WFC (OverlappingWFC+wfc(from:)/wfc(_ model:)) learns its constraints from an exampleImageinstead of declared tiles (patternSize/WFCSymmetry/wrapsSample/tileable), synthesizing a larger texture whose every NxN square is one the sample held; six invariants are load-bearing, each a way it goes wrong rather than slow: propagation runs the four unit offsets only (sound by transitivity through the intervening cell); the support countercompatible[cell][p][d]counts the neighbor OPPOSITEd(so it inits topropagatorCount[opposite[d]][p]— usingdcompiles and is quietly wrong) andbanzeroes all four so nothing bans twice; entropy is Shannon over the weights (a plain survivor count can't tell a 1000:1 cell from a 50:50 one) with an.infinitysentinel; a bounded output's last N-1 columns/rows are outside the solve entirely (never observed, never propagated into — a ban spreading there reads as a false contradiction) and the read-out recovers those pixels from the last covering cell, so an output needs 2N-2 a side; patterns with no legal neighbor in a direction that exists are pre-banned (propagation can never eliminate one, so it survives to be chosen and the output goes quietly illegal, the bounded-sample case); determinism per the catalog rule. Deliberate cuts: no seeding constraints (upstream'sgroundnames a pattern by index, an artifact of extraction order) and no backtracking (restart,attemptstimes). Envelope stated not faked: pixel-art samples only (exact color equality; caps at 256 colors / 1024 patterns), solves fail above ~50px a side (NP-hard), andtileableis unsatisfiable when the sample's period doesn't divide the output size. ExamplePatterns/; snapshotTextureSynthesis texture-synthesis;OverlappingWFCTests. 1D CA & turmites —elementaryCA/totalisticCA(pure functions; the Sketch facade mirrors the full free-function signatures — the shadowing rule) +Turmite(published turn codes, no rng,Presetcatalog;CellularAutomataTests).Docs/. Flow fields —Generators/ CellularAutomata .md FlowField+ Jobard-Leferstreamlines(a batch commits to the occupancy grid only after tracing, so a line never blocks itself); the seeded sugar captures the sketch's noise → transient, don't store the field (it retainsself). Boids & steering —Boids(order-stable force sums → seeded flocks reproduce) +Vehicle(behaviors return forces; onlywanderrolls — a unit roll scaled by jitter; arc-length path follow,closed:wraps;SteeringTests). Pursuit (Pursuit) — everyone-chases-somebody as a stateful stepper (trails/links/web): every runner moves off the pre-step positions (a sequential update sends a ring lopsided within a few steps, and the whole figure rests on it); the ring's four exact invariants are the tests, because a slightly wrong spiral looks exactly as good as the right one — the polygon stays regular, the path holds a constant angle to the center (90 − chasing·180/), a runner coverssides radius /(one side of the square, for a square), and one step takes the ring fromsin( chasing·π/ sides) rto√(; a fixed stride never reaches the middle (hard floorr² − 2dr·sin + d²) d·cos(, the neighbor gap bottoming at one stride atchasing·π/ sides) d/(2·sin)), socatchDistancedefaults to two strides and a runner's own stride floors it (it never runs past what it caught); a runner chasing nobody, itself, or an absent index holds its heading, which is how the straight-line chase is written (the pursuer coversa/(1−k²), never catches at k ≥ 1, and the gap settles ata/2);PursuitTests(16), examplePatterns/Pursuit, snapshotpursuit,Docs/, Guide Ch 12 § Everyone chasing somebody: pursuit curves. Billiards (Generators/ Pursuit .md Geometry/,Billiard .swift Docs/, exampleGenerators/ Billiards .md Patterns/Billiards, snapshotbilliards,BilliardTests12) — one bouncing rule over four rooms (.circle/.ellipse/.polygon/.stadium) plus circularobstacles; the path is[Vector2]of turn points, so it strokes, cuts, and plots like any other geometry. The ellipse solves in squashed coordinates but takes its normal on the ellipse itself (squashing does not carry angles, so a circle normal there is wrong everywhere but the axes). A stadium cap only counts on its own side of the flats, or the far cap catches rays that never reach it. Where a ball is let go is half the picture: a start at the middle of a circle leaves no hole (the caustic radius is the chord distance, conserved from the first run), and the middle of a posted room is inside the post, where the ball is trapped — both caught by looking at the render, andcontains(_:)is the check. The suite's independent invariants are the conserved ones: chord distance from the middle in a circle (hence equal chord lengths, a constant rim advance, and a rational turn closing into a star), and the foci-distance product in an ellipse (which is why an ellipse draws two pictures, sorted by whether a path passes between the foci). Orderly-versus-disorderly is pinned by separation: a hair of angle stays a hair in a circle or a square, and grows past a thousandfold in a stadium or a posted square. Test-coverage gotcha: deleting obstacle handling entirely left every test green until two obstacle-specific tests were added (a ball aimed at a post returns along its own line; a post separates what a bare square keeps together) — a sabotage that passes means the coverage is missing, not that the code is safe.
Drainage (Geometry/, Docs/, example Patterns/Rivers, snapshot drainage, DrainageTests 13) — rivers read off a Heightfield: D8 steepest descent (drop over distance, so a diagonal is divided by root two or every network leans diagonal), flow as the count of everything upstream, the network as reaches above a minFlow threshold, Strahler order, and basins. Hollows are filled first or the network stops dead (filled() / flooded(minDrop:), Priority-Flood: flood inward from the edges lowest-first, raising each reached cell to its flooder plus a hair). Two consequences are visible in the picture and both are load-bearing: a raised cell routes by its flood parent, never by a slope read off the filled surface (the filled surface's gradient is the flood front, so reading it drains a lake as a fan of straight parallel lines — caught by eye in the example, fixed by the parent link, which also leads to the true spill point); and a wide hollow can brim over at more than one place (the flood enters at whichever rim low point it reaches first, so a symmetric bowl has four doors — stated in the tests rather than asserted away). Flow is strictly increasing downstream, which doubles as the topological order Strahler is computed in. A reach is traced once, ends shared at meetings, with the one-cell reach kept (a threshold-crossing cell that leaves the field at once) so the network is covered rather than quietly short. The independent invariant is flowIsTheTotalOfEveryPath: a cell adds 1 to every cell on its way out, so the summed flow equals the total walked path length. Gotcha: Color(hue:) takes 0…1, not degrees (a per-basin hue in degrees renders every basin the same red).
Anamorphosis (Geometry/, Docs/, example Patterns/, snapshot anamorphosis, AnamorphosisTests 16) — the catoptric plate: a picture wrapped on a mirrored cylinder at true size (a picture w wide takes w of arc, so mirrorPoint is the one place the two coordinate systems meet and both directions run through it), each point mapped by one ray run backwards (eye → glass → bounce → page). The wrap runs facingAngle - along /, negated — the other sign is a plate that reads mirror-reversed and looks entirely plausible (theViewersLeftStaysLeft is the only check that sees it). Marks land on the near side (a convex face returns light toward the eye) and always outside the footprint (the bounce is outward, so distance from the axis grows along it); a planted lower edge (lift == 0) does not move, which makes it a degenerate probe: the mark sits under its own bounce, so a reverse-ray test must lift the picture or divide by zero. fits gates on both limits — the tangent arc (widestPicture = 2·acos() and the eye height (a mark level with the eye never comes down; it runs to infinity approaching it). plate(of:) resamples before mapping (the map bends straight lines), returns [Contour] split at what the eye cannot reach, and drops a partly-surviving contour from a Shape rather than opening a region with no boundary. The map back is Alhazen's problem, so it is a search (scan the arc both ends can see, bisect the sign change) and the height then comes free: the bounce keeps the path's fall, so t = eye measured flat, which is the suite's independent second derivation of the forward map.
Clothoid / Euler spiral (Geometry/) — the curve written as a turn rate (start/heading/curvature/curvatureRate/length), the one shape joining a straight to an arc with no jump in bend; curvatureRate == 0 is an arc and curvature == 0 too is a line, ordinary members not special cases, which is what lets clothoidCorners hand back straights, easements, and arcs as one seamless chain. Position is the Fresnel integral, evaluated by composite 8-point Gauss-Legendre at a panel per half-radian of phase sweep, never the Fresnel closed form — the closed form loses precision exactly as the bend rate goes to zero, the arc/line cases a chain hits most (pinned against published C(t)/S(t) to 1e-12 and against 2M-panel Simpson at a 314-radian sweep). The G1 fit Clothoid( follows the Bertolazzi-Frego reduction (3 unknowns → the single zero of g(, Newton from A ≈ 3(φ₀+φ₁), both headings wrapped to ±π against the chord, which is what selects the non-looping answer out of infinitely many); the paper's g'(A) = X₁ − X₂ is sign-flipped — the derivative is X₂ − X₁ (re-derived, pinned against a finite difference, and the flipped sign turns the whole fit red). clothoidCorners scales radius and easement by one factor when a corner will not fit (at a fixed easement share every length in a corner is proportional to its radius, so one step lands exactly rather than iterating), capped at half of each leg so neighbors never collide. points(count:) accumulates span by span, so it costs O(1) per point and the ends land within rounding rather than exactly; a sampled polyline is short of its curve by the square of the step. [Clothoid] reads as one path (length, point(at:), heading(at:), curvature(at:), position(at:), contour(...)), clamped past either end, which is what makes a route drivable at a steady speed. ClothoidTests (23), example Patterns/Clothoid, snapshot clothoid, Docs/, Guide Ch 16 § A corner a car could take: clothoids. Crease patterns (Geometry/) — CreasePattern (a list of Crease: a segment plus .mountain/.valley/.boundary/.cut), MiuraFold, RotatingSquares; the flat sheet a folded or cut thing comes from, emitted as geometry for the draw/hatch/SVG paths. Flat-foldability is measured, never assumed: kawasakiResidual (the alternating sector sum, meaningful only at an even-degree interior vertex), maekawaResidual (M−V, always ±2), isFlatFoldable (both, plus even degree). A .boundary or .cut end marks both its vertices non-interior, which is why a cut-only kirigami sheet reads flat-foldable (it asks for nothing) and why interiorVertices is exactly the (columns−1)×(rows−1) inner lattice. Vertices are matched through a tolerance lattice scaled to the pattern's own bounds (1e-9 of the longer side, looked up over the 3×3 neighborhood, never iterating the dictionary), so fitted(in:) cannot split one; fitted scales uniformly and moves points (angles kept, so the laws are kept). contours(_:) merges same-assignment creases into pen strokes, carrying on through the straightest turn at a junction, so a Miura zigzag column leaves as one stroke and a blade need not stop at every vertex. The Miura folded state is one line plus three constraints: point(, with L² + H² = major², S² + V² = minor², and S·L = major·minor·cos( — that third one is the panel-congruence constraint, and without it the facets stop being the parallelograms they were cut as (planarity is automatic, since the fourth corner is e1 + e2 by construction). fold 0…1 is θ = fold·π/2 through H = major·sinθ·sinγ; poissonRatio = −V²/ (width against length, negative, and the other direction is its reciprocal, so the two multiply to 1). The mountain/valley phase is load-bearing and only the folded geometry pins it: a straight fold (i,j) is a mountain iff (i+j) is even, a zigzag fold at column i iff i is odd — flip either and both laws stay green (Kawasaki and Maekawa cannot see it), so the test that decides is the one deriving each mark from the folded sheet's own dihedral (the facet-centroid lean, perpendicular to the crease: leaning below it means a ridge). RotatingSquares: spacing side·(, turn ±α by (i+j) parity, hinged exactly at a corner point (ν = −1 exactly, measured on the lattice rather than the outline, whose corner overhang is not proportional); cuts are the interior grid edges inset by ligament at both ends, and a ligament of half a side leaves nothing to cut. CreasePatternTests (24), example Patterns/, snapshot crease-pattern, Docs/, Guide Ch 15 § A pattern that folds: creases and cuts. Shape grammars (Geometry/) — ShapeGrammar (start Pieces + label-keyed Rules, generational sweeps, seeded through SplitMix64), rules cut / split / inset / nested / stop / custom; a design is [Piece], so it feeds straight back in as another grammar's start (how a lattice gets its bars). The balanced cut is solved, never searched: a part's area is affine in the far end's edge parameter, so the reachable band is its two ends and the target solves in one step — |A1 − A2| ≤ balance · A holds exactly and balance: 0 halves exactly. n1 + n2 = n + 4 for every cut (the line meets two edges away from their ends), and that one fact derives the whole ice-ray rule table from sides alone: at 3...5 a triangle gives {3,4}, a quadrilateral {3,5} or {4,4}, a pentagon only {4,5}, a hexagon only {5,5}, and 7+ corners is uncuttable at any size — never write those rules out. tries (keep the shortest of N cuts) is what keeps parts compact: a balanced cut down a piece's length leaves two pieces just as long, and the first render without it was slivers. A tight balance band suppresses the corner cut — a square's corner triangle maxes at (1−s)·t·A/2, so under the default 0.2 window/0.2 band a quadrilateral only ever becomes two quadrilaterals; the published triangle+pentagon rule needs a wide band (~0.6). inset pushes every edge along its own normal (a scale about the centroid would not hold bar width), and an over-pushed convex polygon is invisible to an area test — it comes back same-winding with positive area, so the collapse guard is that each inner edge still runs the way its original did. Weight 0 is the fallback idiom (unreachable while any other rule on the label can apply, so a refusing inset falls through to a narrower one); a label no rule names is finished; no piece is left smaller than minArea · (; maxPieces stops a sweep before the design passes it. Built-in rules expect convex and hand back convex; custom may do anything. ShapeGrammarTests (28, five sabotages verified red — and the corner test was blind until it counted its cuts, since a guard … else { continue } loop passes having checked nothing), example Patterns/, snapshot shape-grammar, Docs/, Guide Ch 13 § Rules over shapes, not symbols: shape grammars. Force-directed graph layout (Geometry/) — ForceLayout + drawGraph, the FR spring embedder (repel k²/d all pairs, pull d²/k on edges, temperature-capped moves clamped to bounds, linear cooling); idealDistance is a scale dial, not a promised edge length (a ring's equilibrium spacing sits well under k — measured on-equilibrium, so raise k to open the web, never iterate longer) and a settled layout is frozen (step() early-returns; reheat(_:) is the one path back into motion — the growth/drag idiom); pinned nodes hold, gravity (default 0) centers disconnected pieces, coincident nodes part deterministically; taught in Guide Ch 11. Space colonization — single-closest-node growth; keep killRadius > stepLength; sorted Dictionary iteration + a stall counter (isFinished). DLA — off-lattice walkers; arrival order = index. Dielectric breakdown (DielectricBreakdown) — NPW lattice model: Laplace solved by incremental Gauss-Seidel (a big settle at init, 2 sweeps run with each step), candidates weighed by potential^eta (the same read the public potential(at:) exposes), 4-neighbor adjacency per the paper; branches() decomposes tip-and-fork chain ends so every edge lands in exactly one channel (walking only from tips drops the edge above each fork, a caught bug); pipe-model thicknesses; ground: .border rim vs .points electrodes (rim then insulates via mirrored relax); DielectricBreakdownTests (7) pins determinism, lattice adjacency, the eta regime, arc-to-ground, edge coverage, field read-back; snapshot lichtenberg, example Patterns/, Docs/. Ant colony (AntColony) — Dorigo Ant System: per-ant roulette on pheromone^alpha · (, evaporate-then-deposit with deposits scaled by a greedy-tour yardstick (numbers stay O(1) at any canvas size), elitism = the paper's elitist ants; trails normalizes to the strongest edge and drops sub-0.5% edges (early frames a full haze, late frames the condensed route); best never worsens (pinned), ring convergence pinned within 2%; AntColonyTests (6), snapshot ant-colony, example Patterns/AntColony, Docs/. Crack growth (CrackGrowth) — angle-raster subdivision: a cell within 5° reads as the crack's own line, any other angle stops it (restart perpendicular ±2°, recruit one more, capped at maxCracks); restarts draw from the kept claimed-cell list, never a bounded random probe (goes dormant on a sparse grid, a real bug the tests caught); step() marks carry point + one-sided wash span + random-walk gain, grains lays the sin-eased wash (side pinned, verified red by sabotage); segments feeds the vector exports; example Patterns/Cracks (accumulating, noClear()), snapshot crack-growth, CrackGrowthTests. Meander (Meander) — curvature-driven channel migration (stateful stepper: centerline/oxbows/scars): per-point drift = local curvature at a negative weight + an exponentially decaying upstream average at a larger positive one (the upstream term dominating is what makes bends deepen and slide downstream); the per-step resample is an interpolating spline, never the straight-segment resampled(spacing:) (a linear resample shaves curvature every step, and curvature is the engine); pinch detection skips ( indices along the line so a bend's own flanks never self-cut; the seed line is a few long tapered sine waves, not white noise (point-scale jitter carries no energy at the amplified wavelengths and trips the per-step clamp — a measured stall, sinuosity 1.19 vs 1.84 at step 800); oxbows shrink toward their centroid and die under width/2; scars trim to maxScars in one pass (a one-at-a-time trim never catches up after lowering the ceiling, a caught bug). Example Patterns/Meander, snapshot meander, MeanderTests, Docs/. Strange attractors — StrangeAttractor (RK4) + ChaoticMap (clifford/deJong/henon + gumowskiMira/ikeda/hopalong; Gumowski-Mira is the full damped form and near-conservative, so the long transient is the picture — plot with no settle, the start picks the structure, and its test pins spread-without-escape, the two degenerate failure modes; ikeda defaults u=0.9, 0.918 parks some starts on the coexisting far sink; hopalong's reach grows with count; GPU mirrors ollin_gumowski_mira/ollin_ikeda/ollin_hopalong in the shader lib; example Patterns/, snapshot gumowski-mira); RK4 shared in Math/; the GPU leg is AttractorFlow (its own bullet above). Chaotic 1D maps & bifurcation (Geometry/) — IteratedMap (logistic/sine/tent/gauss families + custom rule, optional analytic derivative): orbit/graph/cobweb + bifurcation points / bifurcationImage density (ink-on-white, ONE global log factor — the flame rule) / lyapunovExponent (exact-value-pinned: ln 2 at logistic r=4, ln r for tent) + drawBifurcation sugar; rng-free throughout. Sweeps sample column centers, never range endpoints (exactly-r=2 tent collapses to 0 in floating point, one doubled bit at a time) and factory starts avoid the critical point (the logistic critical orbit dies in two steps at exactly r=4 — start is 0.3, not 0.5); gauss can hold two attractors at once, so its diagram legitimately depends on start. Example Patterns/ (diagram + Lyapunov trace in a retained batch); snapshot bifurcation; BifurcationTests. Docs/. Percolation (Geometry/): site-percolation clusters over a seeded or caller-supplied boolean grid (criticalProbability 0.592746 as API): one-pass union-find labeling (4-neighbor only, corner contact never joins), clusters largest first (ties by reading order), spanningClusterIndex top-to-bottom, cellRects(of:in:) placement, and outlines(of:in:) closed rectilinear boundary loops (holes included, collinear runs merged, interior on the walker's right, pinch vertices take the tighter turn so loops never self-cross); example Patterns/ (fixed per-cell values + breathing threshold, the flood-not-reroll pattern); snapshot percolation; PercolationTests (10, north-union sabotage-verified red). Docs/. Fractals (Geometry/IFS.swift / InversionFractal / Kleinian.swift, Image/) — IFS (affine Maps + weighted chaos game; presets fern/triangle/carpet, the fern grows +y up so examples flip); FractalFlame (written from the flame paper ONLY — flam3/Apophysis are GPL, never read; variations use θ = atan2(x, y), the y-axis convention, pinned by FractalTests — swapping args is the classic porting bug; ONE log factor from density scales all three channels (independent logs shift hue), gamma at the downfilter; Renderer is the progressive form, deterministic per (flame, size, seed, total samples)); inversionLimitSet (the canonical walk: start OUTSIDE the discs, random circle but never the one just used, no inside/outside test — the pull-inward-only variant collapses tangent arrangements into the tangency points, a real bug); kleinianLimitSet (trace recipe on the Markov minus root; the DFS's cyclic child order + repetend fixed points are jointly what make the output one ordered closed polyline — change either and the curve disconnects); Buddhabrot (Image/, Melinda Green's escaping-orbit density plate: seeds from the whole upper half of the radius-2 disc (a smaller box prints its own edge into the density as a rectangle, a real defect); deposits mirrored about the real axis in the upright framing (imaginary across, real down); one cap = gray, three caps = the false-color RGB split, an orbit outliving every cap plots nothing; cardioid + period-2-bulb closed-form interior skips; develop = per-channel percentile ceiling + gamma, so hot antenna pixels can't dim the plate; Renderer progressive + deterministic like the flame's, slices compose exactly; BuddhabrotTests 7, mirror deposit sabotage-verified red); the public fitted(_:in:) point-cloud placement helper (Rectangle.swift). Examples Patterns/ / FractalFlame / Buddhabrot / InversionFractal / Kleinian; snapshots ifs / fractal-flame / buddhabrot / inversion-fractal / kleinian; FractalTests. Docs/. Schottky circle orbits (Geometry/ + the shared Geometry/, the internal MobiusMap over the public Complex (Math/Complex.swift, once an internal scalar beside it) lifted out of Kleinian.swift — the Kleinian walk is byte-identical after the move) — schottkyCircles / schottkyLimitSet over SchottkyPairing, the circle-emitting sibling of kleinianLimitSet: it renders the disconnected regimes the ordered-curve walk can't, and its [Circle] output means SVG/PDF write true circles (the plotter path, halftone precedent). Load-bearing: a circle's Möbius image is the closed-form Hermitian transform H' = (M⁻¹)†H M⁻¹ (a line image → nil, dropped as a branch, measure-zero for circles clear of the pole), and the map must be unit-determinant for inverse (the adjugate) to be exact; the walk emits w(C_k) for every non-canceling letter and prunes on that same circle's radius (the whole subtree nests inside it, so the radius is the branch's error bound — no second pass); the pairing's twist zero point folds in −u² so two touching circles paired at twist: 0 hold their tangency point fixed and the generator is parabolic, which is the entire reason a picture stays dense (measured: tangent-pair schottkyCuspedPairs 22,660 circles vs cross-ring schottkyNecklace 3,208 at its best twist — no twist rescues the necklace), so lean is the animatable dial (it swings each pair about its own tangency point in opposite senses, keeping both generators parabolic) where twist thins the lace as it grows; overlapping discs make the group non-discrete and a 2M-circle ceiling ends such a walk rather than exhausting memory. Viewing, containing, and the trace bridge: a viewpoint re-seats the whole orbit by conjugating with the involution sending that point to the horizon (walk runs in the viewed plane so minRadius prunes drawn sizes; the disc holding the viewpoint flips to the picture's outer boundary; a viewpoint ON the limit set makes circles above any floor infinite — nudge off it); a pairing disc may be its circle's exterior (fromExterior/toExterior), the containing-circle framing, and the walk's orientation is set by the sign of the Hermitian form's A' (discImage), with exterior discs never radius-pruned (their radius bounds nothing — depth stops them); schottkyCircles( bridges to the grandma-recipe groups via isometric circles as pairing discs (letter k's disc = gens[k]; bases may overlap — nesting is per-map, pruning stays sound; gasket traces (2,2) = the Apollonian-gasket packing, the classic figure; grandma's minus-root makes ±imaginary trace perturbations asymmetric — the example ping-pongs the upper arc only). Example Patterns/Schottky (declares loopDuration); snapshot schottky; SchottkyTests. Spanning-tree line art (Geometry/) — spanningTree(, the branching sibling of singleLine: exact EMST (Kruskal over Delaunay edges, deterministic tie-breaks; collinear input → lexicographic chain, coincident duplicates → nearest-straggler joins), decomposed into the minimal open chains — a walk may start only at a currently-odd vertex (originally-odd starts strand edges into extra chains, a real bug, pinned by SpanningTreeTests). Isolines (Geometry/) — isolines( + levels + image forms, marching squares: oriented case table + cell-average saddle rule; null segments dropped (a contour through an exact grid corner emits them — two-point litter, a real bug); directional stitch → boundary-exiting contours; the levels form marches once: each cell computes its corner range and visits only the levels in it (binary search over the sorted levels, the cell code the final filter), so every level's segments arrive in its own march's order and stitch to the same contours (oneMarchAgreesWithAMarchPerLevel: shuffled and repeated levels, levels on exact corner values, NaN; the range's <= sabotaged red), 28 levels of a cheap 650-wide lookup 22.2 → 8.5 ms in an optimized build beside 2.4 ms of sampling; the stitch computes each endpoint key once and chains a key's segments in order instead of a dictionary of arrays (identical walk); a cell with a non-finite corner holds no contour (a crossing interpolated against NaN or infinity landed on NaN and trapped the quantized key; a hole now leaves the contour open at its edge, aHoleInTheFieldOpensTheRing) come back open; endpoint maps indexed, never iterated; levels share one sampling; image form = linear-luminance-on-white, levels in sRGB tone (the cutoff convention). Examples Images/SpanningTree + Patterns/ContourMap; snapshots spanning-tree / isolines; IsolineTests. Docs/, Docs/. Hulls & medial axis (Geometry/ + MedialAxis.swift; Shape.contains(_:) added alongside, a winding-honoring ray test) — concaveHull( (chi-shape: erode border triangles longest-boundary-edge-first, blocked when the opposite vertex is already on the boundary; hull-notch capping is load-bearing — the substrate's finite super-triangle drops hairline hull slivers, so missing hull edges are capped with sliver fans before erosion, making concavity 0 exactly convexHull (seed-7 regression in HullTests)); alphaShape( (alpha complex, circumradius ≤ alpha; islands + holes as Shapes); medialAxis( (Voronoi subcomplex of a boundary resample — non-ring-neighbor + inside filters; radii are exact clearances; prune collects each round's twigs against the round-start graph and removes them together — mid-round removal turns a junction into a pass-through and the sibling's walk runs past it, a real bug; a whole-component chain never prunes). All three canonically order output by geometry, never triangle order (Bowyer–Watson's Dictionary refan makes triangle order process-varying while the set is stable — loops start at their lex-min vertex, islands and branches sort by points). Examples Shapes/Hulls + Shapes/MedialAxis; snapshots concave-hull / medial-axis; HullTests / MedialAxisTests. Docs/, Docs/. Straight skeleton (Geometry/) — straightSkeleton( (exact shrinking-wavefront skeleton: arcs + one face per boundary edge) + StraightSkeleton (mitered insets cut from the faces as roof planes, the contour-ladder tool; maxInset the vanish depth; Clipper2 offsets stay the rounded/outward tool). Load-bearing: events process in levels clustered by meeting point / shared parent and dispatch as chains (the degenerate-pile-up treatment; naive one-at-a-time is famously wrong); events computed during a level that land back on it are purged as stale echoes, which is why a 2-vertex LAV closes as a bridge (its pair's mutual event always re-lands on the level) and why coincident LAV neighbors must fuse at level end (a ghost corner around a zero-length front otherwise starves its LAV — a real bug, 8% of a spiky blob's area vanished, pinned by facesPartitionSpikyBlobs); output assembles by node identity (each vertex's origin→death arc; faces stitch from their edge's endpoint-role arcs; inset chords match across faces by arc node-pair, no epsilon), and Σ face areas == shape area is the test net. Example Shapes/ (island contour ladder); snapshot straight-skeleton; StraightSkeletonTests. Docs/. Painterly marks (Geometry/ + Watercolor.swift) — Marbling (Jaffer closed-form: area-preserving drop to √(d²+r²), the stylus family tine/comb/tine(around:)/swirl all displacing strength · 2^( along the tool's motion; rng-free, add floats arbitrary shapes holes-intact) + drawMarbling (oldest-first fills); refinement subdivides at pre-transform midpoints while the transformed span exceeds spacing (post-hoc refinement can't recover a fold; depth-capped + source-length floor so a drop centered on an outline can't recurse away); rotational tools preserve radius exactly (MarblingTests). Watercolor (Hobbs recursive midpoint deformation: per-edge variance inherited at 0.4...0.8 with jittered 0.2...1.8 starts; immutable base + further-deformed layers) + drawWatercolor; layers must fill non-zero-wound via layerShape/drawShape (they self-cross: even-odd cuts pinholes, and drawPolygon's convex fan shatters them into radial spokes — both real first-render bugs); the detail floor (edges below it stop subdividing) bounds layer cost regardless of rounds (~40 s → seconds, invisible); painting is setup-shaped (makeBatch or noLoop). Examples Patterns/Marbling + Shapes/Watercolor; snapshots marbling / watercolor; MarblingTests / WatercolorTests. Docs/, Docs/. Chladni figures (Math/Chladni.swift) — chladni(, the center-driven square plate's standing wave in closed form, normalized to −1…1 over plate coordinates 0…1: m == n cancels to zero at the default amplitudes (1, −1) and the diagonal is always nodal (document, don't "fix"); fractional modes morph figures, so animated tours keep m > n at every stop to never cross the degenerate diagonal; mirrored in the shader lib's noise module (chladni() and read by the .chladni Generator (ChladniStyle .sand Gaussian gather + hash speckle re-thrown by phase / .wave signed swing by cos(phase); rawIndex kept in step with ollin_gen_chladni). Nodal lines fall out of isolines( over the field. Examples Patterns/Chladni (mode tour) + Audio/ (modes picked by listening, magnitude(in:) per mode pitch); snapshot chladni; ChladniTests. Docs/. Terrain (Geometry/) — Heightfield (closure/values inits, bilinear value(u:v:), normalized(), heights 0…1 by convention), .diamondSquare (size rounds up to 2^k+1, output normalized, seeded/generic-RNG), eroded(_:seed:) over Erosion.hydraulic (the particle droplet method: inertia-blended bilinear gradient steering, slope·speed·water·capacity carry rule, bilinear-4 deposits, distance-weighted brush erosion; the speed update is the energy form √( — the thesis's printed +Δh·g slows downhill drops and goes imaginary, a known erratum; heights clamp ≥ 0 so border runoff can't dig unbounded drains; mass only decreases, drops carry sediment off-map) and Erosion.thermal (talus relaxation, Jacobi-gathered against the frozen field so it's order-free, deterministic, exactly mass-conserving; transfer halved so a symmetric pair can't overshoot); mesh( emits +y-up terrain (CCW-viewed-from-above winding, central-difference normals, plan-view 0…1 UVs — a height-walked Ramp texture paints altitude bands) and image() the grayscale heightmap. Setup-shaped CPU work (erode once, keep the mesh). Example 3D/Geometry/Terrain (precomputes raw + eroded meshes for the weathered toggle); snapshot terrain-3d; HeightfieldTests. Docs/. Shadow art (Geometry/) — shadowArt( → ShadowArt (occupied / isSolid / count / boxes / mesh over the shipped isosurface, and shadow(from:), what the carved solid really throws). Shape-from-silhouette: a voxel survives only where every supplied silhouette says solid, so the result is the visual hull, and one silhouette alone gives a prism. Bright means solid (inverted flips it), and a picture is sampled at each cell's middle, so a small silhouette stretches rather than losing its right and bottom edges. The shadows thrown are never larger than the ones asked for and can be smaller, because two views share an axis: the front and the side are seen from either end of the same vertical, so a row empty in one empties it in the other. Two come out exact when they are solid in the same rows (the circle-and-square case); three usually fall short. That rule was learned from a failing test rather than assumed — the first version of the doc claimed a pair is always exact, and a lopsided side silhouette reaching rows the front does not have proved otherwise. Test-coverage gotcha, again: reading the side mask along the transposed axis passed every test until the silhouettes stopped being symmetric under transpose (a disc and a square are their own transposes), so the tests now use a bitten disc. Example 3D/; ShadowArtTests (8, sabotage-verified); no snapshot (the marched surface is the isosurface path's, already pinned). Lighting is per-frame state, not per-shape, so noLights() after a drawMesh unlights the mesh already drawn (this cost a Guide figure two renders). Docs/; Guide Ch 28 § One solid, two shadows: shadow art + the TwoShadowsOneSolid figure. Isosurfaces & metaballs (Geometry/ + Metaballs.swift) — isosurface(, marching cubes by default, deliberately mirroring isolines' signature (its 2D sibling), or method: (Geometry/): one vertex per sheet of surface through a cell (the cell's six face contours chained into loops as the march does, each loop its own quadric, so a thin wedge whose two walls meet outside the cell gets two vertices rather than one between them; an ambiguous face is settled by the field at the bilinear saddle, since the bilinear guess reads a thin wedge as a channel) at the least-squares point of the tangent planes through its crossings (each crossing bisected six times onto the true surface, its normal by central differences over a hundredth of a cell, the quadric solved about the mass point with eigenvalues under a hundredth of the largest dropped; an answer outside the cell slides along the crease line or patch plane the data left free to where it enters the cell, and only if that misses does the rank drop), one quad per crossed lattice edge with four cells around it (split on the diagonal whose triangles face the crossing's normal), the normals clustered per sheet at 35° seeded from the crossing normal nearest the quad's, so a block's faces shade flat to the corner (three vertices at one point) while a sphere keeps one per cell; a sheet a crease cut without crossing both sides is bridged onto the chord between its crease-carrying face neighbors. Pinned by DualContouringTests (16): a block's corners land to 1e-6 of a cell where marching cubes stays a tenth of a cell away (the counterfactual), the block shades flat and closes with volume 8, a sphere stays round at resolution 10 and 32, a rim splits its normals, closed by position (a crease's vertices are split on purpose, so closure pairs edges by position), and the default path byte-identical. Known limit: two curved surfaces meeting at a knife edge step by the cell where a cube holds a sliver of one without crossing the other; Metaballs (add( / value(at:) / bounds / mesh(resolution:)) is the headline field, and its curve is public on its own in a sketch's terms: Metaballs (1 at the center, exactly 1/2 at radius, 0 from 2 * radius out; the reach and the u stay inside it, so the polynomial is free to change) and Metaballs (strength times that), of which value(at:) is the plain sum, byte-identical to the loop it replaced. Load-bearing: the convention is inside = field > level (normals −∇f, triangles wound to match, pinned by a positive signedVolume), so an SDF must be negated to mesh; there is no 256-case triangulation table — each cell's surface is built from its six face contours (per face: 0/1/2 directed segments with the enclosed region on its left seen from outside, walked CCW) chained into loops and emitted reversed (the loop faces inward), and the ambiguous 4-crossing face is settled by the asymptotic decider δ = ( over the face's own four corners, which is why it can't crack (both cells read the same four values and the reversed walk swaps starts/ends symmetrically); vertices weld on a flat lattice-edge array keyed (low corner, axis), never a Dictionary (determinism), and normals come from the sampled gradient (central differences, one-sided at walls) so a smooth field costs no extra field calls; a quad loop splits on its shorter diagonal, 5+ fans from an added centroid vertex (cell-interior, so no crack); cells stay cubic (resolution counts across the longest side) and the grid centers its overshoot; Metaballs.radius is the visible radius and reach is 2·radius, because Wyvill's polynomial is exactly 1/2 at u = 1/4 (falloff pinned at its three known values), and mesh() pads the box by 1.5 cells so the surface closes. Cost is cubic in resolution (M2 release, 6 balls at 56: ~2 ms/frame, real-time) and the per-face work is allocation-free (flat faceCorners + caller-owned scratch, worth ~2× over the obvious per-face arrays); no UVs (a blob has no natural parameterization). Deliberate v1 cut: meshing an SDF3D is out — its evaluation lives only in ollin_sdf3d_eval, so a CPU evaluator would be a third hand-synced surface across 15 leaves / 20 combines / 10 transforms. Example 3D/; snapshot metaballs; IsosurfaceTests (watertightness over a saddle-rich field at three resolutions, sphere volume + outward winding, determinism). Docs/. Subdivision surfaces (Geometry/) — mesh refines any Mesh as a control cage: .catmullClark (default, general polygon faces) / .loop (triangle rules with Warren's β, plus a final limit push — γ = 1/(n + 3/(8β)) interior, (3v+b₁+b₂)/5 on rims). Load-bearing: the positional weld tolerance is ~1e-6 of the mesh extent — libtess2 caps come back Float-quantized (~1e-8 relative) against exact-double walls, so a tighter weld leaves every cap rim open (a real bug); quad recovery pairs the consecutive (a,b,c),(a,c,d) triangle pattern gridQuad emits (run before any winding flip — flipping first breaks the pattern); the coplanar face merge (CC only) re-derives whole polygon faces for exactly-flat patches (single simple boundary loop, no interior vertices — a deliberately tessellated flat grid is untouched) because a triangulator's arbitrary cap diagonals give identical corners different valences and an extruded star smooths visibly lopsided (0.2 arm spread → 1.7e-8, the five-fold test); orientation follows the input's normals, not its winding — Mesh.extrude winds inward while shading outward (a find worth knowing), so agreement is area-weighted-summed and a disagreeing mesh's faces flip; no normals → authored winding kept; open/non-manifold edges take the B-spline crease rules, a boundary vertex with one incident face pins (the edge-and-corner convention, so open sheets keep their extent), flat sheets stay exactly flat; deterministic (dictionaries lookup-only, first-come weld ids); 2M-face cap with a printed note; output = smooth area-weighted normals, no uvs, material carried. Example 3D/; snapshot subdivision-surfaces; SubdivisionSurfaceTests (hand-derived mask pins — cube corner 5/18 + edge 3/8, the Loop strip's odd/crease points — plus watertightness, Euler, convex-hull containment). Taught in Guide Ch 28 § Smooth from a cage: subdivision surfaces. Docs/. Mesh growth (Geometry/ + MeshOperators.swift + MeshReactionDiffusion) — MeshGrowth, a stateful stepper that grows a Mesh surface until it folds, over four GrowthDrivers (.uniform / .curvature / .field(closure) / .chemical(); the public MeshReactionDiffusion runs the same Gray-Scott on a fixed mesh (Turk's surface-texture use, displaced(by:) to see it). Load-bearing: forces run along edges only, which lie in the surface, so nothing can inflate the form and every driver folds — the driver picks where and at what scale, not whether (documenting .uniform as "inflates smoothly" was wrong, caught by render, and the buckling is correct); self-avoidance excludes the 2-hop neighborhood, not just the 1-ring (a 2-ring vertex sits ~2·edgeLength off on any smooth surface, so leaving it in makes every vertex shove its own neighborhood and the whole form inflates with growth off — the defect aZeroFieldDoesNotGrow pins), radius default 2·edgeLength, past ~3· it inflates again; stiffness is the fold-size dial (the normal half of the relaxation Laplacian — a sheet with no bending resistance buckles at the triangle scale and reads as crumpled paper, which is the thin-shell term the reference has and the first cut omitted); remeshing is Botsch-Kobbelt isotropic (split >4/3·L, collapse <4/5·L guarded by the link condition + both rings' resulting lengths + no normal flip, flip toward valence 6, tangential relax at 1/5) and growth must stop at maxVertices or the springs stretch triangles the splitter can no longer subdivide; per-vertex channels (the chemicals) interpolate at a split and average at a collapse so a pattern survives the topology churning; the boundary is never collapsed or flipped and a rim vertex relaxes along the rim, so an open sheet keeps its edge. Both types weld first via the shared WeldedMesh — Ollin's generators emit flat-shaded meshes whose triangles share no vertices (an icosphere is degree-2 everywhere), so an unwelded surface cannot diffuse at all and the reaction silently dies; MeshReactionDiffusion simulates on the welded copy and republishes through remap so values still matches mesh.positions by index. The cotangent Laplace-Beltrami operator with mixed areas (Meyer et al.) is the shared substrate (MeshOperators, internal): scaled by mean-edge-length² it is dimensionless and lands at exactly 4 on a regular triangulation, matching a grid's 5-point stencil, which is why the classic Gray-Scott constants (0.16 / 0.08, feed/kill matching Sim) transfer unchanged; a seed patch is u=0.5, v=0.25 floored at 3·edgeLength across (pure reagent has nothing to react with and decays; a patch a vertex or two wide diffuses away before igniting). settleSteps (default 0, .chemical only) runs the opening chemistry all at once at the first step so growth answers a formed pattern — and it must refine the surface to the target edge length first: chemistry settled on the coarse seed cage dies at exactly zero (the patch is a vertex or two wide there, the ignition floor above — a probe-caught bug); it's the ramp fix only, since the pattern covers part of the surface and chemical growth stays a few times slower than .uniform at equal growthRate (rate compensation stays with the sketch). Determinism: edges come from a sorted key array, never a Dictionary walk, and the repulsion hash grid dedupes its 27 slot reads (two cells can share a slot and would otherwise double-count). Cost is real CPU mesh processing (~30 ms/step at 9k vertices on M2 after a 3× pass: ring table built once, flat edge/boundary table, counting-sort grid, allocation-free EdgeFaces), so maxVertices is the interactivity dial. Example 3D/; snapshot mesh-growth; MeshGrowthTests. Docs/. Point-cloud surfacing (Geometry/ + SurfaceReconstruction over the internal PointGrid3 + partialIsosurface) — particleSurface( (the blended union-of-balls skin: field = radius − |p − kernel-weighted local average|, so an isolated point is an exact ball; no normals, always closes) and reconstructSurface( (the faithful path: PCA tangent planes over k-NN, signed distance to the nearest plane, marched by the internal partialIsosurface, whose nil-mask path is byte-identical to isosurface). The fitting: choice (SurfaceFitting, an artwork parameter per the catalog rule, never a RenderQuality tier): .planes default (byte-identical to the shipped path — pinned), .robust( = RIMLS (Öztireli/Guennebaud/Gross 2009, written from the paper — MeshLab's implementation is GPL, never read): IMLS base (kernel-weighted average of plane heights, kernel (1−d²/h²)⁴, per-point h = reach clamped to [1.5, 4]·spacing) iteratively re-weighted by a residual Gaussian (Welsch, σ_r 0.5 in units of h) × a normal-vs-gradient Gaussian (σ_n = 1/sharpness floored at 0.5, where the surface genuinely disconnects); the first pass is unweighted on purpose (a robust start breaks the reconstruction's continuity — the paper's deliberate deviation from textbook IRLS, so iterations: 1 is plain smooth IMLS) and the gradient keeps the kernel-derivative terms (( — the weighted normal average alone is the classic shortcut bug); both fittings share one plane-based validity gate, so holes open identically; the evaluator reuses scratch buffers across the serial march (per-lattice allocation is the debug-build trap) with flat scalar inner loops. Measured on the staged partial-coverage ball (the phantom-fringe scene): mid-air phantom vertices 5,480 → 43, ball-annulus 1,747 → 0, the ball's observed front kept (3,169 vs 3,210 on-ball vertices) — so the fringe envelope below is now .planes-specific. Colors carry: the PointCloud overload transfers the cloud's colors (nearest sample, Mesh.colored(from:)), skipping all-white clouds so bare reconstructions stay colorless; largestComponent remaps colors with positions. Load-bearing: orientation is viewpoints-first, by a distance-weighted vote (1/d⁴) over the (nearest ≤16) viewpoints — never the nearest alone (the nearest camera sees a terminator sample edge-on, dot ≈ 0, sign = noise → flipped planes raise phantom curtains, probe-confirmed; the 1/d⁴ falloff keeps thin walls decided by proximity); the spanning-tree fallback weights edges 1−|nᵢ·nⱼ|, which reads antiparallel as agreement, so it can walk through thin double-sided structure and flip a region (documented limit, not tunable); the field is undefined, never guessed, where the projected foot lands beyond the validity cutoff (nil = per-point k-th-neighbor reach capped at 3.5·spacing — uncapped, the reach inflates exactly where data is missing and phantom bowls grow in occlusion shadows; tighter caps pinhole randomly-sampled clouds, whose local gaps routinely pass 2.5·spacing; .infinity closes everything), which is what keeps scan holes open — and cells touching an undefined sample are skipped whole; partial coverage frays by design under .planes: an open data edge grows a ~gap-wide fringe along its tangent planes just past the samples (four parameter "fixes" probed and refuted — coverage is the fix, so sweep around bodies; .robust suppresses >99% of the fringe, measured, but coverage stays the honest fix; the Docs page says both), and the marching cell must stay under ~2·spacing (a wide-bounds cloud starves the grid and junctions shred — printed note; crop to the region of interest); the near-surface occupancy band short-circuits far cells in one array read but must not run under .infinity (closing legitimately caps far from samples); PointGrid3 ring searches stop on a strict bound only (in-box ring·cell, clamped (ring−1)·cell; a tie at the bound must expand another ring — the stipple stopping rule in 3D) and its queries are flat scalar loops on purpose (per-candidate closures + Vector3 operators ran 8.7× slower in the unoptimized builds examples run under); counting-sort buckets ascend by index → byte-reproducible output. Example 3D/; snapshot surface-from-points; SurfaceReconstructionTests (grid matched against brute force, watertight sphere volume + outward wind, torus Euler 0, a hole stays open, thin-wall viewpoint orientation, byte-determinism both paths). Docs/. Articulated & chaotic motion — IKChain (maxBend enforced inside both FABRIK passes then re-placed at exact segment length, never post-clamped; keep the stall exit), DoublePendulum (fixed ≤1/480 s substeps — reproducible by default), NBody (Barnes-Hut; coincident bodies chain at the depth cap; θ=0 stays the exact all-pairs sum — don't "tighten" NBodyTests' error bound). Docs/. Coupled oscillators (Geometry/) — Kuramoto, the mean-field model: each phase advances at w + K r sin( with (r, psi) the crowd's own order parameter (coherence/meanPhase, one pass per substep, so N is free), criticalCoupling = spread * sqrt( for the seeded normal spread (Kuramoto's 2 / (pi g(0)); a custom frequencies array keeps the made-with value), a range for nearest neighbors on a ring (locks locally and holds a twist, so global r stays low while neighbor pairs agree, the invariant KuramotoTests pins), fixed substeps of 1/240 s with phases wrapped, and a Box-Muller draw of its own over SplitMix64 so a seed replays. Local coupling beyond the ring: Kuramoto( lays the crowd on a Lattice (.square( / .square(.moore) / .hex, range as rings, settable live and the lists rebuilt on change, 0 falling back to the mean field), Kuramoto( couples over any per-site index lists, and the settable neighbors hands any crowd a graph (kept whatever range says, nil returns to what it was made with; a bad index is a precondition at set time). The pull over a list is coupling times the mean of sin(, the same rule the ring used, and the ring, the graph, and the lattice are one code path: a graph handed the ring's own lists steps bit-identically, and a lattice at range 0 steps bit-identically to Kuramoto(count:) under the same seed (both pinned). The hex lattice shares HexGrid's odd-r addressing (row-major, odd rows shifted right), pinned cell by cell against HexGrid.distance for three ranges, so hexGrid( is site i; the hex ball is walked in axial coordinates and turned back into offsets so the stagger is read once; a hex torus is clean only for an even rows (said, not hidden). localCoherence is the per-oscillator order parameter over self plus list (the layer's global r under the mean field, 1 for a loner), computed on read. layers (oscillators per site, index site * layers + layer) copies the neighborhoods per layer with a per-layer mean field, and layerCoupling pulls a site's layers together, averaged over the other layers with no lag; layer 0 of a two-layer crowd steps bit-identically to a one-layer crowd dealt its phases (pinned). rates is every oscillator's rate at the last substep (frequencies until the first advance; pinned as the phases differenced across one 1/240 s substep, unwrapped, on a three-layer hex crowd with a lag), the one number a motion blur or a trail of anything the crowd drives needs. CellNeighborhood gained Hashable for the layout. Asked for in issue #25 by a sketch that had carried its own copy of the rule for a hex field of three plates per dot. Thresholds in KuramotoTests were pinned from a numpy prototype first (r 0.987 at 4 Kc, a peak of 0.08 at Kc/4, N 400 over 20 s); a locked crowd with a lag drifts at w - K sin(lag), the exact invariant the suite reads. Docs/. Crowds (Geometry/) — Crowd, optimal reciprocal collision avoidance (van den Berg, Guy, Lin & Manocha 2011) on the CPU over Crowd.Agent values (position/velocity/goal/radius/maxSpeed/group/isJammed), goals or a preferredVelocity closure, addObstacle (outline or Rectangle) / addWall (polyline or segment), advance(by:), drawCrowd. Each neighbor gives a half-plane through velocity + u/2 (the reciprocal half, pinned exactly: after one step a pair on a collision course has a relative velocity that grazes the truncated cone at the sum of the radii, eachSideTakesHalfAndThePairJustGrazes, red under a quarter share); the new velocity is the incremental 2D linear program's nearest point to the wish inside maxSpeed, and an infeasible program falls to the least-intrusive 3D program with obstacle lines kept hard. Load-bearing: the no-overlap guarantee is conditional on feasibility, as the paper states: a jam (isJammed, the fallback) overlaps by a small part of a radius (≤0.25 r pinned in a packed doorway) while walls hold to 1e-6 even jammed, and a checker built from the authors' reference library (RVO2, Apache-2.0, studied, not ported) showed the same jam overlap and the same circle numbers as the prototype, so never promise "no overlap at all"; the fallback's projection loop runs hardCount ..< max(, empty when the failing line is an obstacle's own (a C loop skips it, a Swift range traps; obstacleLinesThatCannotAllBeMetStillGiveAVelocity, the crash the edge-side sabotage found); an outline is normalized by signed area so either winding is the same obstacle, a wall is the out-and-back degenerate ring (each side faces its own agents, a bend convex on its outer side), and only an edge's outer side sees an agent; edges live in a lazily rebuilt grid and are sorted by (distance, index) after gathering so the dictionary's order never reaches the outcome; every step chooses all velocities from the pre-step snapshot; advance(by:) splits into equal steps ≤1/60 s (a thirtieth equals two sixtieths bitwise). Obstacles never route (the paper's own caveat): a door needs a goal that leads through it. Two defaults were measured, not guessed: timeHorizon 1 s (≈15 radii at the default speed and radius, the reference ring's scale; a dense ring of 96+ at 4 s stalls a third of the way in and never arrives, while 60 arrive at any horizon), and jitter 0.05 of top speed on moving agents (a symmetric knot is a fixed point, since a jammed agent's choice ignores its wish; at 0.005 a small ring of eight arrived in 1 of 5 seeds, at 0.05 in 5 of 5, and under a point a second of wander at 120). Head-on with jitter 0, exactly collinear, and starting near enough that the cutoff circle answers before the legs, a pair only slows and never swerves (that branch has no lateral part; from farther off the legs answer first and the pair swerves, which is the mirror law's setup). Lanes in counterflow (order > 0.9 against a shuffled < 0.65) and door flow rising with width under its geometric bound are emergent invariants. CrowdTests (17, four sabotages verified red: quarter share, no fallback, inner-side edges, inverted convexity), snapshot crowd, example Simulation/Crowd (a translucent sheet over noClear() is what makes lanes visible in a still), Docs/, Guide Ch 12 § A crowd that makes room: Crowd + the MakingRoom figure. Color — CSS Color 4 named set + Color(hex:), HSB (hue wraps), the OKLab family (OKLab / OKLCH / OKHSL, gamut-mapped, written from Ottosson), Color, Color(kelvin:), withAlpha(_:) / perceptual luminance, lighter(by:) / darker(by:) / complement (OKLCH: lightness stepped, hue and chroma held, chroma lost only where the gamut runs out, a gray is its own complement, Palette agrees to the bit), Ramp / Palette (ColorBrewer + harmonies), CosinePalette (iq), Colormap. Palette import — hex / CSV / TSV / JSON / ASE; the three text formats share one parser and .auto sniffs palette-per-line from the file's shape, an explicit format overrides the sniff (palettePerLine:, nil = decide); no comment syntax is promised (#deface is a color); loaders never trap on malformed bytes; ship the loader, not the data (bundled palette data stays license-gated). Palette extraction — weighted k-means++ → Lloyd in OKLab; identical pixels merged and sorted before clustering; output most-used first; deterministic given (image, count, seed). Image dithering — Image.dithered: 8 error-diffusion kernels + centered Bayer + generated .blueNoise; CPU-only by nature; three color spaces, one per family — mixing them is the bug: tone accumulates in linear, .none picks OKLab-nearest, error diffusion picks *linear-nearest (the false-contour rule, pinned by DitherTests on a 1×1 image); threshold maps run the *Yliluoma pair search* (variance-weighted penalty, linear mix fraction, dark→light phase); a fully transparent pixel diffuses no residual. *Measuring color* (Color/, Color/Shades.swift, Image/) — Color: .oklab straight-line (the confusion check's own scale, pinned equal) and .ciede2000 written from Sharma, Wu and Dalal (all *34 published pairs* within 1e-4, symmetric); CIELab is *D50 through Bradford* (white exactly (100, 0, 0), sRGB red 54.2905/80.8049/69.8910), a Lab color outside sRGB mapped back through the OKLab chroma reduction; Palette / nearestIndex(to:) are the brute-force minimum, *ties to the earlier entry, nil when empty. Image returns a Histogram (counts / total / percentile(_:)): **every pixel counts once (total is the region's pixel count, the region averageColor's own pixelSpan), color straight (alpha divided out, clear at 0), bin i of n is [i/n, (i+1)/n) so 256 bins are one byte level each, a texture-backed image empty. Ramp.shades / Palette.shades: OKLCH, the lights turn toward sRGB yellow and stop there, the shadows away (yellow's own toward orange), hueDrift turns at each end and signed, the ends keep half the base's chroma (ShadeWalk.endChroma), and the palette always holds the base exactly. Two equivalent mutants, read rather than chased: CIEDE2000's zero-chroma mean hue never reaches the result (its ΔH is zero with it), and swapping the wrap's +360 and −360 moves the mean a full turn under a T periodic in 360° and a blue rotation near zero there; leaving out the wrap is the real slip, and it reads red. ColorMeasureTests (12), eleven plants red; example Color/Shades; Docs/ § CIELAB, Measuring color, Shades whose hue drifts; Guide Ch 2 § Measuring color, and shades that drift (ShadesThatDrift figure) and Ch 9 § Palettes from a photograph. Palette schemes (Palette over Palette.Scheme .monochrome / .vividAndDark / .vivid / .pastel / .dark, and Color; Color/Palette.swift, gamutCusp/maxChroma in Color/) — a palette built around the key's OKLCH hue alone (a gray reads as hue 0). The most vivid color is the sRGB gamut's cusp at that hue, the same analytic boundary the gamut map uses, pinned against a bisection search over the published OKLab matrices at 24 hues (hue within 1°, chroma within 0.004, lightness within 0.02 of the searched peak), never the key's own lightness; monochrome spreads the rest over lightness 0.22 to 0.96 with the step nearest the cusp replaced by it and moved to the front (yellow's cusp takes the light end), every color within a degree of the key. The vivid colors stand at Ollin's own per-hue typical-lightness table (eight color terms, blended around the wheel so it never jumps: yellow 0.9, blue 0.5, purple 0.46) at the largest chroma there; vivid-and-dark's far half (more than a quarter turn from the key) sits at 0.3, so the halves straddle 0.4 even under full jitter. Jitter is a seeded SplitMix64 of hue (never in monochrome), lightness, and chroma, clamped back inside the gamut; no jitter reads no seed. Inside Palette, min/max must be spelled Swift.min/Swift.max (the collection's own methods shadow them). PaletteSchemeTests (6); figure 02-Color/; example Shapes/PaintedFills; Docs/; Guide Ch 2 § Palettes from one hue: Palette.scheme. Print separations — Image under the translucent-spot-ink overprint model (linear-light mixing, OKLab-judged coverage search; a tie goes to less ink, in the golden section and at the endpoints, since once the inks chosen print solid black every later ink scores flat and the old tie laid solid pink under a black ground, aBlackPixelSeparatesToBlackAlone in either ink order); screening drops coverage under the 2% minimum dot; the sketch declares printInks (NOT inks); --export-separations (registration band around the untouched artwork; recipes carry ExportMetadata.inks). PrintSeparation is public (the darkest ink at 45°, the rest over 15/75/0/30/60, then an even spread; an angle follows its ink, not its slot) and ProcessSeparation is the four-color rosette in plate order (15/75/0/45); both are exactly what the default halftoned uses (pinned byte for byte). Docs/. Print color management — the process-color sibling: ICCProfile (built-ins from CGColorSpace, installed() over the three ColorSync dirs, space/channels/prtr read straight out of the 128-byte header, an FNV fingerprint as the cache key), SoftProof (destination/source/intent/simulatesPaper), Image / gamutMask / outOfGamutFraction, ProcessSeparation (Image, plates in the profile's channel order, peakTotalInk/averageTotalInk, screening shared with the spot path at the conventional CMYK rosette angles), the live Filter.softProof (a proof from: .displayP3 bakes a lattice indexed by P3 components with answers stored on the chain's sRGB primaries, ProofLUT, and the shader carries a pixel into P3 before the lookup; read with sRGB components it put a saturated P3 green's red 18 levels off the CPU proof, PrintColorTests holds it within 2), and Sketch.printProfile + --export-plates / OllinApp (registration band identical to the spot masters; the recipe carries printingCondition). Load-bearing: every transform is ColorSync's (a 2- or 4-step profile chain through ColorSyncTransformCreate, cached per condition behind an OSAllocatedUnfairLock), and the module must be imported @preconcurrency because the SDK spells its CFString keys as mutable globals Swift 6 rejects outright; black point compensation stays off, and simulatesPaper switches the return leg's intent (relative maps white back to white while ink black still lifts; absolute keeps the stock's tint; an .absolute proof always returns absolute); the source is read as a screen (ICCProfile: a v2 display profile's D65 media white rewritten to the D50 connection white, the v4 convention, since ColorSync's absolute intent scales each pair by both profiles' whites and so carried the sRGB white across as a color: white proofed cyan (195, 210, 226) and the paper read (238, 220, 185) against its tag's (224, 223, 216); relative and perceptual proofs are byte-identical either way; anAbsoluteProofOfWhiteShowsTheStocksWarmth, theSimulatedPaperIsThePressProfilesMediaWhite) — measured: rel/rel white 1.005 black 0.055, rel/abs white .934/.864/.726, and BPC on the 4-step chain misbehaves (white drops to .862), which is why it is not a parameter; the gamut check is kColorSyncTransformGamutCheck, which writes one 32-bit float per pixel (1 = out of gamut) whatever depth is requested — asking for kColorSync1BitGamut with a packed buffer overruns and traps; float conversions carry device-encoded values, never linear light. A full-image proof measures ~145 ms at 1080², so the live path bakes a 33³ lattice (~4.4 ms) whose rgb is linear and whose alpha carries the gamut flag, uploaded as an rgba32Float 3D texture keyed by the ProofLUT object identity (the cache hands back the same object per condition, which is what stops a 574 KB upload per frame) and sampled at (i + 0.5)/n through the clamped imageSampler; the fragment encodes with linearToSrgb before the lookup (dropping it is a real picture change, pinned red by sabotage in theLiveProofMatchesTheImageProof). Plates come from .toDevice (1 = full ink; master byte = 255 - ink, the spot-ink convention) and preview() runs .fromDevice from the plates rather than re-proofing the source, which is what makes the CPU and GPU halves cross-check; total ink is honest only on unscreened plates (a screened set reports dot overlap, 400% at a rosette). PrintColorTests (26, incl. three Metal-gated live-filter probes) + the gamut, neutral-gray, and round-trip pins under Physical invariants, snapshot soft-proof, example Color/SoftProof, Guide figure ProofBeforePrint. Docs/. Color lookup tables (looks) (Color/) — ColorLUT reads the Adobe/Resolve .cube text (init(contentsOf:) / init( / init(data:) / init(text:), every one throwing a ReadError that carries the line): both forms (LUT_3D_SIZE → .cube, 2…256 on a side; LUT_1D_SIZE → .curves, 2…16,384 nodes), TITLE, DOMAIN_MIN/DOMAIN_MAX and Resolve's LUT_1D_INPUT_RANGE/LUT_3D_INPUT_RANGE, entries red-fastest; a keyword the format lacks, an entry before the size, a second size (the shaper-plus-cube file is refused rather than half read), an entry that is not three numbers, or a count that does not add up is refused by line. Filter applies it; ColorLUT( builds a cube from a closure, identity(size:) is the control, write(to:) / cubeText write the format back, color(for:) is the CPU read, and .warmPrint is the bundled look (Sources/, written from the four rules its header states). Load-bearing: the table is read on the encoded picture (linearToSrgb in, srgbToLinear out), since that is what a look is authored on; a cube is read tetrahedrally (ollin_fx_lut3d: eight reads at whole coordinates of an rgba32Float 3D texture, the six-tetrahedron case table on the order of the three fractions), so a gray input meets only the cell's gray corners and a table that leaves gray alone does so between nodes, where the sampler's trilinear blend would tint a neutral (grayStaysGrayThroughWildOffDiagonalNodes pins it); the answer is applied as a difference on the encoded axis with a dead zone of 1e-6 (ollin_lut_apply), because the GPU's transfer round trip lands a few float steps off, nothing to the eye but enough to turn a pixel sitting on an eight-bit rounding tie (a channel at 0.9 is 229.5) the other way after the dither: measured, 950 of 36,864 bytes moved a level on a hue sweep, precise::pow read the same, and a thousandfold amplification barely moved the count, so the flips were ties and not error. With the dead zone an identity table of either form and amount: 0 are byte-identical (anIdentityTableChangesNoByte), and a value above white keeps its excess plus what the table does to white, so a tone map still sees the highlight. The 3D texture is cached by the table's FNV fingerprint (colorLUTTextures, bounded to 8), so a look applied every frame uploads once; the curves form is passed through EffectInput.table as a single pass (ollin_fx_lut1d), which is what crosses to the web page (Curved in WebEffectsTests, mean 0.012 against the Mac), while a cube answers nil from singlePass and the export refuses it by name, as the lut filter. GLSL gotcha: arithmetic on a uint index wants a u literal (i0.x + 1u), or the page's compile fails where Metal's passes. ColorLUTTests (17: the reader and its refusal lines, corners exact, an affine table reproduced between nodes, the gray invariant, the domain, the writer's round trip, the bundled look's four rules, and three GPU probes), snapshot color-look, example Color/Look (+ the lut tile in Effects/), Guide figure Look. Docs/; Guide Ch 20 § A look from a colorist's suite: ColorLUT. Gradient paint — Gradient (.linear / .radial / .conic / .alongPath) / Paint on every shape via a baked 256-texel LUT strip (SDF path) + per-vertex evaluation (tessellated path), with native SVG gradient export (a conic, which neither SVG nor PDF can shade, exports as its ramp's midpoint like an along-path fill); the conic (.conic(, the angle from three o'clock turning clockwise like every angle here, -.pi / 2 for twelve) is paint kind 4 in the shape tag, so each paint slot is three bits, 10-12 the fill and 13-15 the stroke (the Metal vertex, the web page's GLSL vertex, and the wire tests all mask & 7; nothing reads the tag above bit 15), its geometry ( relative to the shape center in the color slot like the radial's, and it reads by position, so the merged fields (2D and the raymarched 3D) paint it where they refuse an along-path; on the tessellated path a paint that sweeps around a point (a conic, or an along-path fill) has a seam, the ray from its center at the start angle, and a fill triangle whose corners fall on both sides of it would interpolate backwards through the whole ramp, so Drawer.emitTriangle cuts such a triangle along the seam's line (a corner on the seam takes the ramp end its own piece is on, the two pieces fan from the cut; RoundedCornersTests pins the cut against the exact SDF square at a mean of 3.8 levels against 6.9 uncut, over the whole frame) and every fill site (polygon fans, arc fans, drawShape, outline glyphs) emits through it; shared CPU↔GPU structs live once in the C header (see Shaders). Docs/, Docs/, Docs/, Docs/, Docs/, Docs/, and the per-generator Docs/Generators/* pages. Hobby's spline (Geometry/; the Spline mode in Geometry/Path.swift) — HobbySpline( fits one cubic per gap with every control point solved together, reached from the sugar as spline: .hobby on drawCurve / Contour( / Shape( (.catmullRom stays the default and is byte-identical; Path.curve(to:) runs are untouched). Written from Hobby's 1986 system in the form Knuth programs: the curvature-matching row at each knot (A θ[k-1] + (, re-derived from the cubic's own curvature with uniform tension), the curl ratio at each open end, the velocity function held to 4 chords, and a one-chord open curve with curls at both ends is a straight line by special case (the two curl rows coincide, so the tridiagonal solve returns NaN otherwise, a real failure the first run caught). Closed runs solve the cyclic tridiagonal by a rank-one correction of the open solve (a two-point loop is a dense 2×2). tension is floored at 0.75, curl at 0; consecutive repeats and a closing repeat are dropped. HobbySplineTests (13) pins the invariants: four points on a circle give the classic quarter-circle Béziers (control distance 4/3·tan(π/8) of the radius), the symmetric three-point arch leaves straight up under curl 1 and at 67.5° under curl 0 (both solved by hand), G1 at every knot including the closed seam, mirror and reversal symmetry, tension monotone. Snapshot hobby-spline; Examples/; Docs/; Guide Ch 16 § A curve that reads as drawn: Hobby's spline. Line textures (Geometry/, Geometry/, Geometry/, Geometry/Ikat.swift; Docs/ § Textures drawn as lines, example Patterns/, snapshot line-textures, LineTextureTests 16; Guide Ch 46 § Textures for a pen: wood grain, frost, crackle, and ikat) — four materials as geometry a plotter draws, each repeating from its seed. WoodGrain traces evenly spaced streamlines (the Jobard-Lefer rule: a seed closer to a stroke than 0.75 of its spacing is skipped, a stroke stops at half the spacing from another, every traced stroke seeds the next beside it, the first seeds running across the grain through the region's center) through the ring coordinate across(_:): the distance across the grain + a Gaussian bump height * radius per Knot + two octaves of fbm at 8 rings of wavelength along and 5 across (the wander's slope stays under the grain's own below wobble ≈ 0.5, so the coordinate keeps climbing and no stroke pinches off into an island). Every stroke is a level curve of it: an Euler step then one Newton step back onto its level, the correction capped at a step, so strokes never cross, a stroke circling a knot comes back within 0.6 step of its start and closes (isClosed; rings close above Knot.closingHeight = √e, where the bump's slope passes the grain's), and its tone (cos² of the ring phase, the rings' positions wandered by a 1D noise) is one value along it. The rings show as density too, the separation spacing * (; a seed whose gradient vanishes (a knot's eye) is skipped. Frost (a Contour or a Shape) stands a needle at each point of the outline resampled at spacing, along the outward normal (probed against the contour or the whole shape; an open path's left; side out, in, or both) ± 0.2 rad, its length length * ( where mix blends a slow 1D noise along the outline with a draw per needle by clump, and its barbs under the barb law barbStations( (from barbStart 0.25 of the needle, every spacing, half a spacing short of the tip; a pair per station leaning barbAngle ± 0.17 rad forward; reach min(, the first frost's barbs at 0.34 of the needle crowded the needles into a solid mass). Crackle (a Shape or a Rectangle) seeds area / (2 spacing²) veins, a third on the rim walking in and the rest inside walking both ways, plus one per 0.4 spacing along each crease headed along it ± 0.3 rad, shuffled by the seed; a vein's heading wanders by wobble * 1.3 of a 1D noise plus 0.12 rad of jitter a step (step = 0.12 spacing, ≥ 1.5) and it ends on the rim (bisected to it), on the crossing itself where its next segment would cross a committed segment (an exact segment test over each neighbor's two incident segments, kept as before/after/owner arrays beside the SpatialIndex; the first stop was a proximity test alone, and a segment slipped between two points of another vein), or touching the nearest committed point within 0.8 step (the closing segment tested the same way); a fork's first four steps ignore its parent; a finished vein of ≥ 6 points forks with forkChance * 0.6^order from a station at 0.35…0.65 along it, 0.9…1.4 rad off, up to maxOrder 2. Ikat / stripes(in:count:…): per bundle a shared slip (a shear of skew * bleed end to end + 0.35 bleed of a slow noise) moves both edges, then each edge bleeds on its own, a flare of ± bleed/2 by noise, a spike of 1…2 bleeds out on a spikes share of the bundles (carried into the next at 0.7 with chance 0.35) or an intrusion of 0.5…1 bleed in on an intrusions share, never past 0.4 of the band; leadingEdge/trailingEdge are stairs (two points per bundle, a riser between) and shape the polygon between them. The tests pin: no crossings by brute-force segment pairs (wood grain and crackle), every stroke on one level within 1% of a ring, rings closing with centroids within a radius of the knot, dark gaps against light gaps, the barb law per needle, roots on the outline pointing out, in, or both, veins inside the cell, forks from a parent point at 0.3…0.7 along it, crowding by a crease, the stair per bundle, an unbled stripe equal to its band, the seed on every emitter, and all four back from the SVG a sketch writes (one path per line plus the background).
Spatial queries.
SpatialIndex, the CPU structure that answers what is near a point without reading every point:nearest/kNearest/neighbors(/ the allocation-freeof: within: ) forEachNeighbor/anyNeighbor+hasNeighbor/indices(in:), over two backings picked at build (.grid, a uniform cell grid, the default and the only one that takesinsertcheaply;.tree, a k-d tree for clumped sets, rebuilt on insert). Every answer is an index intopoints, so a sketch keeps its payload in its own array. Theof:overloads take a point index and leave that point out, which is the flocking/relaxation form. Invariants, each pinned by a test: every array-returning query agrees exactly with a brute-force loop, both kinds, ties included (equal distances answer with the lower index, so the ring search may stop only once the best find is strictly inside the ring bound, and the tree visits a far side whose crossing distance is exactly equal); cells are cut on the lattice through the origin, never on the point set's own corner, so a rebuilt index sorts moved points into the same cells and a neighbor walk keeps its order (a drifting order moves the last digits of a force sum, and over enough steps the picture); the first candidate always wins innearest(testing the distance alone answers nothing for a coordinate large enough to square to infinity, sinceinf < infis false); the radius block is measured from the query's true cell rather than a clamped one (a clamped block reads cells that are not within reach, in the wrong order); and every cut to a cell coordinate happens in floating point before theIntconversion, which traps on a value aDoubleholds. Cell count is bounded (fitdoubles the size rather than allocating a million cells for a set lying along a line). Four sims moved onto it and each still renders byte-identically (DifferentialGrowth,Boids,DiffusionLimitedAggregation,FlowField, checked against the committed references at an exact zero difference rather than the mean-diff tolerance); the move also fixed a latent.streamlines Boidsdefect, where cells were keyed from the origin but queried frombounds.origin, so a flock in a non-zero-origin box lost neighbors on one side.PackingandDielectricBreakdownkeep their private grids: their query is a cell block, not a radius. No new snapshot (those four references pin it in pixels). ExampleShapes/Neighbors;SpatialIndexTests(10);Docs/. In space,Drawing/ SpatialIndex .md SpatialIndex3Dis the same index overVector3with aBox3region (Sources/,Ollin/ Geometry/ SpatialIndex3D .swift SpatialKDTree3): cubic cells and a three-axis k-d tree, the same queries and the same exactness rules (every array answer equals a brute-force loop for both kinds, ties to the lower index, the first candidate wins in.swift nearest, cells on the lattice through the origin, every cell coordinate cut in floating point before theInt), and the shell search visits the cells whose largest coordinate offset is exactly the ring (a face-only walk inside the shell on two axes, which is the walk a missed face breaks and the two-way-relation test over 50,000 points catches). The automatic cell holds about one point over the axes the set has extent on (a plane or a line divides by its live axes, never by a zero volume), and the cell count is capped at a million (or four per point) by doubling the size.3D/reads its closest pair off it (two nearest per spot, the first that is not the spot itself, so two trees on one vertex still read 0.000);Geometry/ SurfaceScatter SpatialIndex3DTests(10 tests, 17 cases). Measured in a release build on the M2 over 50,000 points in a 600-unit cube at a 20-unit cell and radius: grid build 2.1 ms and every point's neighbors 26 ms (375,150 found) against about 1,760 ms for the loop; tree build 12 ms and 37 ms; 1,000 nearest 1.5 ms on the grid and 0.7 ms on the tree.Finding boxes.
BoundsIndex(Sources/), a bounding-volume hierarchy overOllin/ Geometry/ BoundsIndex .swift [Rectangle]:indices((which boxes hold a point, ascending, the last one the box drawn last for picking),containing: ) indices((which boxes overlap a rectangle), the twooverlapping: ) forEachIndexclosure walks in a fixed order,overlappingPairs()(every overlapping pair in one set, the lower index first, sorted, the tree walked against itself with the same node visited as the three pairs left-left, right-right, left-right so each box pair is tested once) andoverlappingPairs(across two indexes; every answer equals a loop over every box, with the boundary inside and touching counting to matchwith: ) Rectangle.containsand the newRectangle/.intersects intersection/union(andBox3.intersects). Built by the median of the centers along the axis they spread over most, four boxes a leaf, nodes stored each before its children sorefit(to:)is one reverse walk (leaves from the boxes, parents as unions) that keeps the tree's shape for boxes that drift, exact at any drift and a rebuild on a changed count; a leaf's box is fitted by comparison so a box with a NaN coordinate contributes nothing and never answers, and every walk keeps its pending nodes on an explicit stack.BoundsIndexTests(8 tests: 10,000 boxes' pairs against the loop, refit at three drifts against a fresh index, the shared-edge row, the piled set, the flat boxes, the cross-set pairs both ways);Docs/. Measured in a release build on the M2 over 10,000 boxes of 2 to 24 points on a 2,000-point square: build 2.4 ms, refit 0.04 ms, 1,000 picks 0.47 ms against 577 ms for the loop, every overlapping pair (8,360) 1.1 ms against 62 ms.Drawing/ BoundsIndex .md Optimal matching.
Matching(Sources/):Ollin/ Geometry/ Matching .swift Matchingpairs two arrays of anything at the least total cost by the shortest-augmenting-path assignment (Jonker and Volgenant 1987, in the rectangular form of Crouse 2016: a Dijkstra over the reduced costs per row, the duals moved so the path reads zero, the path flipped), with the.optimal( _: _: cost: ) [Vector2]/[Vector3]forms costing by distance andoptimal(costs:)over a table;pairs(ascending byfirst),partner(of:),totalCost,firstCount/secondCount,reversed(), andMatching.greedyas the comparison. The larger set plays the columns (the solver wants rows ≤ columns) and the pairs are read back the right way round. An infinite or NaN cost forbids the pair (RULED 2026-10-26): a forbidden pair takes a stand-in cost larger than every allowed pair together ((, within a few digits of the real costs so the solver's arithmetic stays exact), which makes the solver maximize the number of allowed pairs before it minds their cost, and the forbidden pairs it still had to make are dropped afterwards, so an element with no allowed partner answers nil and the total counts allowed pairs only;largest + 1) * ( rows + 1) greedyskips forbidden pairs and passes over an element with nothing allowed left; a short row ofoptimal(costs:)forbids the pairs past its end. Among equal totals the answer is fixed (the free column wins a tie, in a fixed column order). Memory is rows × columns doubles. The solver walks raw memory inwhileloops, and the finders are inlinable; both are load-bearing (2026-11-13). With no optimization every array read is a call and every step of aforover a range another, which made 1,600 a side 12 s in a debug build where the raw walk takes 0.84 (and 0.7 of the time optimized). Inlinable, a host's optimized compile of the sketch makes its own copy of the solver, so under a debug host a pairing runs at release speed (1,600 in 0.15 s); the point forms are@inline(__always)besides, since the optimizer left the greedy one a call into the framework (289 ms against 6.5).MatchingTests(11 tests: the total equals every pairing tried up to 8 by 8, square and not, points and tables; never above greedy on 300; no two paths cross under the distance cost while greedy's do; uneven sets, the reverse view, ties, non-finite costs, pairs built by hand; the walk answers a plain-array twin kept in the test, pair for pair, on seven table shapes with ties; and the pairing found from the other side is the same pairs, which a sketch leans on to pass the spread-out set first). ExamplePatterns/(every flight's pairing found once inGatherIntoLetters setup(), a gather and a scatter per word, thegkey the greedy chain);Docs/. Measured through a release host on the M2, random points on a 1,000-point square: 500 a side 8 ms, 1,000 40 ms, 1,600 143 ms, 2,000 252 ms, 3,000 532 ms, the greedy pairing 1.5 to 1.6 times the least total throughout; a build with no optimization, 97 ms, 449 ms, 1.45 s, 2.46 s, 5.3 s. Which set plays the rows moves the cost as much as the count does (the example's six pairings: a cloud to a word 0.35 s, the word back to a cloud 0.70 to 0.92 s as called and 0.45 from the cloud's side), and choosing it in the solver is filed under Technique and algorithm helpers inDrawing/ Matching .md DESIGN-NOTES.md.OllinExamples --cycletestis where a slow solver shows first: it stopped on this example for as long as the pairing ran in the debug framework.Outline questions (
Sources/,Ollin/ Geometry/ ContourQueries .swift Docs/, exampleDrawing/ Geometry .md#contour-questions Shapes/OverUnder, snapshotoutline-questions,ContourQueryTests22, Guide Ch 15 § Asking an outline where it goes: contour questions).Contour/.tangent( at: ) normal(at:)/nearestPoint(to:)/fraction(of:)/distance(to:)/piece(from:to:)/crossings(with:)/crossings()(each aContour.Crossing:point,fraction,otherFraction) /simplified(/tolerance: ) reversed()/rounded(_:)/chamfered(_:), withShape.simplified/rounded/chamferedediting every contour and keepingwinding. Load-bearing: every answer is inpoint(at:)'s own measure (a fraction of the walked length), read off one internalsegments()walk that drops zero-length segments the waypoint(at:)skips them, sopoint(; the tangent at a vertex is the segment arriving (at: fraction( of: p)) == nearestPoint( to: p) point(at:)'s<=); the normal istangent, right of travel on the canvas (inward on a clockwise outline). Each segment owns its start and not its far end (the last of an open walk owns both), so a crossing on a vertex counts once, and.perpendicular settledfolds the rare float double report; a self-crossing skips neighbors and a closed walk's last-with-first, a parallel overlap reports nothing, a touch counts. The broad phase is sweep and prune on x, pinned against a brute-force scan of a seeded 300-step walk.pieceon a closed walk always runs forward (through the seam whenend < start;0to1is the whole loop, returned open with its start repeated), and backward on an open walk is the forward piece reversed.simplifiedis Ramer–Douglas–Peucker against the segment, not the line (the line form drops the turn of a run that doubles back past its end), iterative, a closed loop split at the point farthest from its start; the glyph path's privatesimplifyClosedkeeps the line form and was left alone so no glyph moves.reversed()is a concrete member returningContourand shadows the collection's view; a scratch probe showedArray(c.reversed()),for p in c, and a variable annotated with the collection's own reversed type all still resolve. The corner edits share.reversed( ) trimmingCorners: each edge lends at most half its length to a corner (all of it beside an open end), so an equilateral triangle rounded past its limit is exactly its incircle; arcs flatten to a 0.1-unit chord error, at most 128 steps; a cut that uses up an edge leaves one point, not two. Gotcha: a test that indexeshits[0]after#expect(traps under a sabotage, and every test scheduled after the trap never reports, which made a broken broad phase look green;hits .count == 1) try #requirethe count first. A closed contour's walk wraps (point(at:),tangent(at:)/normal(at:),piece(from:to:)through the one internalwalkFraction; an open one and a non-finite fraction clamp), the ruleCurve3Dwalks by;pieceon a closed contour runs forward at most once round, two fractions a whole number of laps apart giving the whole loop (aClosedWalkWrapsAndAnOpenOneClamps, red under the old clamp).Bending outlines (
Sources/, the corner-keepingOllin/ Geometry/ ContourBending .swift smoothedbeside the plain one inClassicCurves.swift,Path.cubicsandCubicBezierinPath.swift;Docs/, examplesDrawing/ Geometry .md#contour-bending Shapes/andWavyLettering Shapes/, snapshotTraceToCurves bent-outlines,BentOutlineTests16, Guide Ch 15 § Bending an outline: warped, pulled, split, and fitted).Contour/.warped( from: along: spacing: ) pulled(/toward: amount: radius: spacing: ) smoothed(/neighbors: weights: keepingCornersOver: ) split(/atCornersOver: span: ) fitted(tolerance:), each onShapetoo (splitflattens every contour's pieces into one list,fittedreturns onePathper contour, the rest keepwinding);Path.cubicsreads any path asCubicBeziers, andHobbySpline.Segmentis a typealias of that value. Load-bearing: the warp and the pull refine before they move (refined(keeps every vertex and adds points so no straight run is longer thanmaxSegment: ) spacing; 0 keeps the points), so a straight edge bends and corners survive. The warp reads each point against the base through oneWalk(distinct points, cumulative distances, a per-vertex tangent averaged from both segments and lerped along a segment) as(along, across)in the smooth frame at the nearest place, and lands it at the same fraction of the target with the same two offsets: base == target is the identity to 1e-7 for any curve, a point past an open base's end carries on past the target's end, and a target traced from a few points bends what crosses it without a step at each vertex. The pull's weight is the bump(1 - (d/r)²)², times a smoothstep of the walked distance to the nearer end overradiuson an open contour, so the ends never move. A corner is a vertex turning more thananglebetween its two distinct neighbors (cornerIndices(, shared by the smoothing and the split); the corner-keeping smoothing runs the kernel over each run between corners as an open run (ends pinned, mirrored past them), so count and order hold and a square keeps four corners and straight sides; the split measures the turn overover: ) spanback and ahead along the walk, merges candidates withinspanof each other along the walk, never by index (a square's four corners are consecutive indices and must stay four cuts), and folds a run that straddles a closed walk's seam. A jitter larger than the point spacing makes every point a corner (a test and the snapshot scene both hit it): the doc says to simplify first, and a test trace is built with its wobble well under the angle at its spacing. The fit is Schneider's on a pending list, the later half pushed first so the cubics come out in walk order; the error is the squared distance at each point's own parameter, Newton reparameterization runs at most four passes and only when the worst error is within 4× the tolerance, a collapsed or reversed handle falls back to a third of the chord, a closed contour appends its first point and reads the seam tangent as the central difference through it so the loop joins smoothly, and the comparison is<=so a tolerance of 0 still terminates (a two-point piece fits exactly).Path.cubicsconverts a Catmull-Rom span exactly (p1 + (p2 - p0) / 6,p2 - (p3 - p1) / 6, with the run's clamped neighbors as the sampler uses them), a quadratic by degree elevation, a line by thirds, andclose()as the straight run home only when the pen is away; the test pins every sampled contour point onto a cubic to 1e-6 through a ternary search, since a 200-step sampling alone misses by a tenth of a unit. Gotcha:#expect(fails to compile inside the macro ("call can throw"); bind the result to axs .allSatisfy( \ .flag)) letfirst.Curved patches (
Sources/;Ollin/ Geometry/ CoonsPatch .swift Docs/, exampleDrawing/ Geometry .md#coons-patch Shapes/WavingBanner, snapshotcurved-patch,CurvedPatchTests11, Guide Ch 15 § Bending an outline into a patch:CoonsPatch).CoonsPatch(/top: right: bottom: left: ) (/topLeft: topRight: bottomRight: bottomLeft: ) (_ rectangle:),point(u:v:),contour, the oriented sides and the corners;Contourand the.warped( from: into: spacing: ) Shapeform keepingwinding. Load-bearing: the patch is Coons's bilinearly blended form,(less the bilinear surface of the four corners, so four straight sides give exactly the bilinear map (pinned against straight sides given as unevenly spaced polylines) and a patch made from a rectangle is that rectangle for any1-v)T( u) + vB( u) + ( 1-u)L( v) + uR( v) u,v(pinned from -0.5 to 1.5). Each side is read by the fraction walked along it (the internalContour.Walk), never by point index, sopoint(u: 0.5, v: 0)is the top curve's midpoint by length; past 0 or 1 a side carries on straight along its end segment, so a point outside the source rectangle lands outside the patch.topsets the direction and every other side is turned to meet it (left and right start at the end nearer the top's start or end, the bottom at the end nearer the left's end); a corner where two ends miss is their midpoint, an empty side runs straight between its neighbors' corners, and a side of one point pinches the patch. The warp refines before it moves (the sharedrefined(,maxSegment: ) spacingmeasured in the source rectangle), so a straight edge bends with its side.contoursamples each side at its own fractions throughpoint(u:v:), so with matched corners it is exactly the four curves, corners once. Every plant in the suite (index fractions, no corner subtraction, no turning, no refinement, no midpoint) goes red.Packing rectangles (
Sources/;Ollin/ Geometry/ RectanglePacking .swift Docs/, exampleGenerators/ RectanglePacking .md Patterns/, snapshotPackedPhotos packed-rectangles,RectanglePackingTests7, Guide Ch 15 § Packing rectangles:packRectangles).packRectangles((free function, and a_: in: padding: allowsRotation: ) Sketchform defaulting the bin to the canvas) returns aRectanglePacking:placed(Placement:index,rectangle,isRotated) sorted by index,unplacedindices sorted, andoccupancy. Load-bearing: MaxRects (Jylänki 2010) with the best short side fit and the global choice: at every step the snuggest fit over every waiting rectangle and every maximal free rectangle, ties by the long side, then the earlier index, then the higher, further-left place, then upright, so a result is a pure function of the input whatever order the free list is in. The fits are remembered between steps: a placement only removes regions and adds a few, so a rectangle whose best region survived is weighed against the added regions only and one whose region was cut is weighed against all; the prune checks only the new pieces (an untouched region was already inside no other, and none is inside a piece since a piece is inside the region it was cut from).theRememberedFitsPlaceExactlyWhatThePlainSearchPlacesholds the shortcut to a plainly written global search over 24 seeded sets (planting a stale fit, ignored new regions, or an unpruned piece each goes red there). A rectangle with no fit is moved tounplacedat once, since the free space only shrinks. Padding pads every rectangle and the bin on the right and bottom, so neighbors sit a gap apart and the last ones still reach the bin's far edges. Measured optimized (a standalone-Obuild of the file): 300 rectangles 16 to 22 ms, 1,000 about 0.6 s, 3,000 12 to 18 s; about nine in ten waiting rectangles lose their region each step in a dense packing, which is the cost, and the docs state it.Plane curves: segments, arcs, and ellipses as values (
Sources/,Ollin/ Geometry/ PlaneCurve .swift LineSegment.swift,Arc.swift,Ellipse.swift, plusarea/perimeter/point(at:)/nearestPoint(to:)/distance(to:)/contouronCircle,area/perimeter/edgesonRectangle,perimeter/edgesonTriangle;Docs/, exampleDrawing/ Geometry .md#plane-curves Shapes/Crossings, snapshotplane-curves,PlaneCurveTests15, Guide Ch 15 § Shapes that know where they cross: segments, arcs, and ellipses).PlaneCurveis one requirement,var contour:, and one extension method,Contour crossings(;with: some PlaneCurve) -> [Vector2] Contourconforms by returning itself, so a[any PlaneCurve]list asks pair by pair, and the concreteContourkeeps winning for two contours (overload by argument type), so nothing that read fractions moved. Load-bearing: the engine (.crossings( with: Contour) -> [Contour .Crossing] CurveCrossings) reads every curve as one of three forms, a run of straight pieces (segment, rectangle, triangle, contour, and any outside conformer through its contour), a round (circle, arc, and anEllipsewhose radii agree within 1e-12,isCircular), or an oval, and each pair of forms has one method: straights against straights go throughContour(its sweep and vertex ownership), a straight against a round or an oval is the quadratic in the piece's own parameter (the oval carried into its unit-circle frame first, where the parameter survives the affine map and the point is taken on the original piece), a touch is a discriminant within.crossings( with: ) 1e-12 · a · (of zero and gives one root, two rounds are the construction on the center line (coincident or concentric circles report nothing, a touch counts once,|f|² + r²) h² ≤ 0clamps), and an oval against anything round is seeded by the two contours' crossings and polished by Newton's method on the two dimensionless implicit forms (|p−c|²/r² − 1and|toUnit(p)|² − 1, their analytic gradients), a seed that will not settle (parallel gradients, a touch) kept where the outlines put it, then filtered by any arc's sweep. Every answer issettled: sorted along the asked curve in its own measure (a straight form bycontour, a round by the angle from its start or from the right, an oval by the parametric angle), points within.fraction( of: ) 1e-9 · scalefolded into one (a corner found by both edges, a touch split by rounding). An arc with|sweep| ≥ 2πis read as its circle;Arcand the sort share.contains( angle: ) Round.contains/positionwith1e-9slack so an end counts.Circleis the one flattening rule (the 0.1-unit chord error, 8 to 256) and the arc scales it by its sweep (at least 2 pieces), the ellipse takes it at the larger radius (the same maximum sagitta under parametric sampling)..segmentCount( forRadius: ) Ellipse.perimeteris the AGM evaluation ofE(k)(4a · K · (, 40 steps at most, a circle exact and1 − Σ 2^( n−1) c_n²) b = 0giving4a);nearestPoint(to:)is Newton on the parametric angle from the best of 64 samples;boundsis exact under the rotation. The typed draw sugar (drawLine(_:),drawArc(_:mode:),drawEllipse(_:)) forwards to the drawer, a tilted ellipse through push, translate, rotate, pop. Plants: the polish disabled turned the two ellipse tests red at 1e-9 (seven issues); the tests also pin the sort direction both ways along a reversed segment, a corner counted once, a touch counted once, the parametric sort of the ellipse's four crossings, Simpson's rule at 1e-9 and Ramanujan at 4e-4 on five ellipses down to 1000:1, and a rotated pair moving its crossings with it.A turtle driven from code (
Sources/,Ollin/ Geometry/ Turtle .swift Docs/, exampleGenerators/ Turtle .md Patterns/TurtleWalk, in snapshotplane-curves,TurtleTests4, Guide Ch 16 § A pen you drive: the turtle). A value with mutating moves:forward/back,left/rightin degrees (his pick over radians, the L-system's own unit),penUp/penDown/close,move(to:)/home(),pushState/popState(his pick; barepush/popfailcheck-api-names), a settableheadingfrom the positive x-axis clockwise on the canvas (-90up by default, soright(90)from there faces right;leftsubtracts,rightadds, and the spirolateral walker in the framework is the same walk, pinned point for point). Load-bearing:land(at:)is the one place the position changes, appending to the run with the pen down and resetting the run to[position]with it up;flush()always leavesrun = [position];penDownstarts a run where it stands;popStateflushes, restores position, heading, and pen, and starts a new run there (never draws the way back);close()drops a last point within1e-9of the first and keeps a run under three points open; a pop with nothing remembered is a no-op by design;contoursincludes the run in progress once it has two points. Plant:rightsubtracting turned the square and the spirolateral match red.Enclosed regions (
Sources/,Ollin/ Geometry/ Regions .swift Docs/, exampleDrawing/ Geometry .md#regions Shapes/ColoringBook,RegionTests15, Guide Ch 15 § The regions a drawing encloses:regions(, figureenclosedBy: ) EnclosedRegions).regions(/enclosedBy: [Contour]) (returns every face of the planar arrangement of the outlines as aenclosedBy: [Shape]) Shape, withCircle(the count from the radius at a tenth of a unit of chord error, 8 to 256, past which a radius over about 1,300 strays more) and.contour( segments: ) Rectangle.contour(the corners, top left first, clockwise) as the ways in. Load-bearing: every segment is cut at every crossing strictly inside it (the broad phase isContour.sweepover one flat list; two collinear segments cut each other at the other's interior ends, so an overlap is one shared edge), every endpoint snaps to a vertex through a cell grid at 1e-9 of the extent (the two reports of one crossing land on one vertex), duplicate edges fold, bridges are removed first (Tarjan with its pending work on a list, so a hanging stroke, a line joining two loops, and every tree wall nothing off and every kept edge lies on a cycle), then each face is walked as a doubly connected edge list: at the far vertex the edge just clockwise of the one arrived by, which keeps the face on the left, so a bounded face has positive shoelace area and the outside of each connected part negative. A negative cycle becomes a hole in the smallest bounded face of another part that contains its first vertex (parts never touch, so the vertex is strictly inside or outside; a part's own faces are excluded, since its vertices lie on their boundary where the ray test is undefined). Output:.evenOdd, outer and holes wound oppositely, reading order (top of bounds, then left, then area). Pinned: a 5 by 6 grid of lines gives 20 cells of 10,000; the regions tile exactly what the lines wall off, which is the union plus every hole in it (seven circles and a bar ring a 316-unit patch of bare page; the tests fill the union's holes throughseparated()), no two overlap, every vertex and edge midpoint within 1e-6 of an input line, nested circles give disc + ring + band with the right holes, a bowtie its two lobes, lines along each other one edge, a diagonal through two corners and a T onto an edge each once. Test lessons:Shape.areaon a holed shape resolves through the boolean library and rounds at about 1e-4, so the tests measure holed regions by the shoelace and compare against the booleans at 1e-2; lines that may end anywhere inside a box ring islands that are regions and holes at once (the tiling still sums), so the no-hole claim uses chords with both ends on the frame; two in-out slices of one array in the sweep's closure trip exclusivity, so cuts go to locals first. Cost: the sweep plus one walk round every face; a few thousand segments a frame, a few hundred thousand insetup().Hilbert order (
Sources/,Ollin/ Geometry/ HilbertOrder .swift Docs/, figureGenerators/ HilbertOrder .md Docs/, exampleFigures/ HilbertOrder .swift Images/HilbertLine,HilbertOrderTests7, Guide Ch 9 § A picture as one line: stippling,singleLine, andspanningTree).hilbertIndex((a cell's distance along the curve on aof: in: level: ) 2^levelgrid overbounds, the quadrant walk with a reflection and a swap per level;levelheld to 1...30, a non-finite coordinate or an empty axis reads cell 0, outside clamps to the nearest cell),hilbertOrder((indices sorted by that index over the points' own bounds, stretched to the grid, ties by input index so a cell keeps its given order),of: level: ) hilbertSorted(. Load-bearing: the curve starts at the top left of the bounds and ends at the top right (pinned: every cell visited once with every step a grid neighbor at levels 1 to 7, and the classic 4 by 4 sequence); the order is a permutation that repeats and is unchanged by a scale or a shift of the whole set; on 3,000 random points the sorted line is under a fifteenth of the given order's and under 1.5 × side × √n; the Morton order was not taken because it keeps neighbors together less well at its quadrant seams. The figure draws the curve as_: level: ) hilbertSortedof the grid's own cell centers, which is the curve itself, no second routine. The example sorts 3,600 stipple dots on alevelparameter and draws the curve under the line at level 6 or lower, so a coarse order's per-cell scribble is seen; where a stipple has a gap the line crosses it in one step, said on the page.A chain over a grid (
Sources/,Ollin/ Math/ MarkovGrid .swift Docs/, figureGenerators/ MarkovGrid .md Guide/, exampleFigures/ 04-Randomness/ GridReach .swift Patterns/MarkovGrid,MarkovGridTests20, Guide Ch 4 § A roll that remembers the row above too:MarkovGrid).MarkovGrid<Element>learns pictures as rows (learn(_:)whole,learn(_:after:)a row at a time,learn(declared), counts each cell against the settled cells around it, nearest first: before, above, above and before, above and after (_: around: times: ) order, 1 to 4, is how many are read), and writesnextRow(columns:)/nextRows(from a seeded generator of its own;_: columns: ) start(after:),reset(),continuations((forgets as writing does),around: ) count(of:around:)(exact, 0 for an arrangement never shown). Load-bearing, each pinned: the counts are a tree and a cell is counted at every node on its way down, so an unseen arrangement stops at the node that already answers for the cells it kept (the farthest forgotten first, down to the shares); a place off the grid is a code of its own and never a value, and a value the grid never saw instart(after:)matches nothing rather than reading as the edge; a tally keeps its values in vocabulary order and a roll walks them in that order withnext() % total, so a declaredvocabulary:makes what a seed writes depend on the counts alone; the generator isSplitMix64seeded with the seed itself, which is notMarkovChain's one step past it. Those two are what keepRecreations/andHiroshiKawano/ SimulatedColorMosaic Flowcell for cell where they stood when each carried the chain by hand: the suite holds that hand-written chain as its oracle (six seeds, two alphabets, four widths, the counts after every learned row), so a change to the order of the cells, the order of a tally, the roll, or the seeding fails it; both sketches' exports were byte-identical before and after the move (28 files: six seeds each, the data and width variants, a late strip frame, two mid-scan frames). A picture with no cells or with ragged rows throwsMarkovGridErrorand teaches nothing. What is written follows the learned counts within sampling error, pooled one grid a seed (chi-square 40.8 on 43 degrees of freedom over 97,603 cells), and holds no transition the counts give no chance to. 26 plants, all red. Measured on the example's three pictures (a scratch release build, M2): 0.38 µs a cell written and 0.5 µs learned; at order 4 the whole arrangement was never shown for 5 to 8 cells in 100; and a lower order can let one value run away (the town's buildings are 45% of the picture, 77% of what order 2 writes, 48% at order 4), which the page says with its table. The example and the figure draw cells that tile as four-cornered polygons, since stackeddrawRects leave a dot where two halos meet on a contrasting ground.Breaking things (
Sources/+Ollin/ Geometry/ Fracture .swift Fracture3D.swift,convexHullFacesinConvexHull.swift).Shapeand.fractured( into: seed: ) (into:around:seed:)cut a filled region into the Voronoi cells of seeded points and trim each to the shape: the pieces' areas sum to the shape's own, no two overlap, and one seed is one break. A cell straddling a notch comes back as one piece per island (the newShape.separated(), which decides nesting by an edge probe, not by winding, or a ring's outer boundary reads as living inside its own hole), and a hole survives.Mesh.fractured(...)is the same cut in space: the hull is cut out of a starting box once and each cell is that solid minus the other seeds' half-spaces, so volumes sum and every piece is convex, which is exactly whatCollider3Dwants. A non-convex mesh breaks as its convex hull, said in the docs rather than silently. Load-bearing in the clipper: a corner already on the cut plane joins the rim, or several planes meeting at one corner leave the cap short and the solid leaks volume (measured: an icosphere's 80 hull planes converged to 0.14 against its true 0.457, and the same run reads 0.45733902606402 with the corner in); the rim welds at 1e-6 of the extent and is sorted around the plane normal through a basis with.hull( ...) u x v = n, which is a loop only because the cell is convex. Seeds are placed by Mitchell's best-candidate (8 tries), and the crowded form draws its radius asu^1.9from the blow, so the chips there are small and the wedges away from it long.convexHull(is the incremental hull underneath (the horizon is found through a directed-edge set, never a scan over every face, which is the difference between a 500-point cloud costing milliseconds and minutes); fewer than four points, or one plane, encloses nothing and gives an empty mesh.of: [Vector3]) Shape.area/centroidresolve multi-contour shapes through the boolean normalizer first, so a ring authored with a same-wound hole still measures as the difference between its circles. A 2DCollider.polygonis reduced to the solver's eight-corner limit before it is handed over (World, dropping the smallest-eared corner each round): past that limit the solver's own hull builder returns nothing, so the body had no collider, no mass, and never moved, which is what a nine-corner fracture piece hanging in mid-air was (.cornersForPolygon PolygonColliderTests, verified red by sabotage).Worldjoins the 2D physics world to match.remove( _ body: ) World3D.remove(_:)(Box2D takes a body's joints down with it, so the list is pruned byb2Joint_IsValid); a removed body is spent, so read the velocity the pieces inherit before the parent goes (a use-after-destroy here trapped the process with no message).FractureTests(20 tests: the sums, overlap, convexity by each piece's own hull, the crowded break's small chips, seeded repeatability, the hull of a box and of a sphere).Examples/,Physics/ Burst Examples/;3D/ Physics/ Burst Docs/; Guide Ch 11 § Breaking things.Generators/ Fracture .md Cutting solids (
Sources/). The 3D counterpart ofOllin/ 3D/ MeshBoolean .swift Shape's set operations, spelled the same:Mesh.union(_:)/intersection(_:)/subtracting(_:)/symmetricDifference((the last composed of two differences and a union), each returning an ordinary_: ) Meshthat draws, exports, fractures and collides like any other. The cut merges the two solids' binary space partitions (Naylor, Amanatides and Thibault, SIGGRAPH 1990, written from the method and credited inATTRIBUTION.md): a tree of each solid's own face planes sorts any polygon into inside and outside, clipping keeps the half each operation wants, andinvert(which flips planes, winding and vertex normals) is what turns one clip into four operations. Load-bearing, and the defect that hides: a plane-cut surface is geometrically complete and topologically torn, because a corner one face gains from a plane lands in the middle of the neighbor's edge and the neighbor, sorted down another branch, never hears about it. The volumes are then exact while the surface reads as riddled with holes (measured: a box minus a sphere came back with the right volume and 103 unshared edges, a box minus a box with 12), so volume is not a test of closure andprintCheck()is.CSGSeamsews it up: weld every corner that landed in the same place (so coincident corners are bit-identical afterwards and every later merge agrees), drop the faces that collapsed, then find the edges exactly one face uses and cut them at the corners sitting in their middle, fanning from the opposite corner so no piece is a sliver; only an unshared edge can hide a T-junction, which is what keeps the search small. Tolerances are relative to the pair's own bounds and both are load-bearing: the plane thickness isscale * 1e-9and one scale serves both trees (a face landing on opposite sides in the two trees is how a closed surface opens), while the weld isscale * 1e-6, deliberately the same rule the exporter's own bucket weld uses. Two solids whose boxes are clear of each other by more than the weld tolerance take their own branch (both, neither, or the first): planes are unbounded, so a cutter across the room otherwise runs its six planes through everything and hands back a surface carved along seams that were never a cut (2304 triangles in, 2752 out, 4.5 s of work for nothing); solids that merely touch must stay on the cut path, or a shared wall survives on both and the pair reads as a surface meeting itself. The partition plane is chosen by scoring sampled candidates against sampled polygons (8 and 32): a solid with no dividing plane in it, which is every convex one, builds a chain of one node per face, and scoring every candidate against every polygon then costs a pass over the whole surface per face (measured 4x: 5.9 s to 1.6 s on a 2304-triangle cut). Cost is CPU and superlinear in triangle count (debug: 0.19 s at 576 triangles, 1.6 s at 2304, 19.5 s at 9216), so the docs say cut insetup()and keep the mesh. What comes along: the first mesh'smaterialand per-vertex normals always; uvs and colors only when both meshes carry a full set (a partial set is ignored by the renderer, so half of one is worse than none); tangents are dropped (generatingTangents(puts them back). Two honest limits, both documented: a mirrored cutter (a coordinate swap, a negative scale) is wound inside out and takes what it should keep, and a symmetric difference of overlapping solids touches itself along the curve where the two surfaces cross, so it closes with no boundary edge but is not manifold there. An open input gives an open result, by construction.) MeshBooleanTests(18, pure CPU: the volume identities,printCheckon every operation, the stacked twelve-cut block from the example, a solid against itself where every face is coincident, scale from a millimeter to a kilometer, repeatability, and what comes along). Examples3D/(the four operations side by side) +Geometry/ CutAndJoin 3D/Geometry/Carved(a block rounded, bored three ways and bitten at every corner, re-cut only when a parameter moves);Docs/3D/3D.md§ Cutting solids into each other; Guide Ch 28 § Cutting one solid with another: mesh booleans.One mesh from several (
Sources/).Ollin/ 3D/ MeshJoin .swift Mesh.joined(_:)lays parts end to end as one mesh with no boolean (vertices in order, each part's indices offset to its own, a triangle pointing past its part dropped, empty parts skipped), andplaced(_:)bakes aMeshInstanceplacement into a part first: positions throughMeshInstance.matrix, normals through its inverse transpose, tangents through the linear part, a tint multiplied into the vertex colors (a full set of it for a mesh with none). Load-bearing:placedruns the same float arithmetic the per-frame mesh path runs on a mesh under the transform stack (m * float4(p, 1),normalize(nm * n)), which is what makes a joined mesh drawn at the origin render byte-identical to its parts drawn apart undertranslate/rotate/scale(measured 0 on the M2; the test allows one level for a normal re-normalized in double on the identity path). What comes along follows the merged-loader rules: normals wherever any part has them (a missing one is+z, the draw's own default), uvs and tangents only when every part has a full set, colors when any part has one (the rest white, exact under the multiply contract), the first material among the parts.Mesh.textis its glyphs through this join.MeshJoinTests(10) +MeshJoinRenderTests(the A/B).Docs/3D/3D.md#join; Guide Ch 28 § Cutting one solid with another: mesh booleans (closing paragraph).Sweeps and strips (
Sources/,Ollin/ 3D/ Curve3D .swift MeshSweep.swift,Sources/;Ollin/ Math/ Pace .swift Docs/3D/Sweeps.md, figureDocs/, exampleFigures/ Sweeps .swift 3D/,Geometry/ SweptKnot SweepTests).Curve3D: points open or closed (let, since the frames are derived and stored at init),Curve3D(= uniform Catmull-Rom withcurveThrough: closed: segments: ) segmentssteps a span scaled by span length against the mean (1 to 8x), through every anchor;point(at:)/frame(at:)by walked length, clamped open but wrapped closed, the same ruleContourwalks by;frame(at:)slerps the two stations'rotations and returns a station's own frame exactly at a station;resampled(spacing:)keeps an open path's last point (unlikeContour.resampled). Frames are rotation-minimizing by double reflection (Wang, Jüttler, Zheng, and Liu 2008, credited inATTRIBUTION.md): fourth order, measured on a helix at 32/64/256 points a turn at 2.7e-5 / 1.7e-6 / 6.7e-9 rad of twist error a turn against the old rotation transport's 2.3e-2 / 5.7e-3 / 3.6e-4 (second order). Tangents are central differences (one-sided at open ends; a zero one borrows the nearest real one). The first frame stands upright (binormal toward +y, or normal toward +x when the path starts within 0.99 of vertical), so a path along +z lays a shape out exactly asMesh.extrudedoes (aStraightSweepIsAnExtrusion). A closed loop's leftover turn is minus its total torsion, measured by carrying the last frame across the closing segment and spread back by walked length (pinned against Simpson of the trefoil's exact torsion to 1e-4, and the per-point unwinding to 1e-9).Mesh.tube(along:)rides the same frames with its old start normal (tangent x up) so the ring phase holds; NOT byte-identical: rings turn by at most 0.7° (helix) / 1.9° (knot), and the whole snapshot suite (Hopf included) passed unrecorded.Mesh: one ring per path point (sparse paths step, hence.sweep( _: along: scale: twist: capped: ) resampled), the shape's origin on the path, x alongnormaland y alongbinormal,scale/twistread at the walked fraction (twist counterclockwise as the path comes toward you); each closed contour is reversed if the right side of its longest edge is inside the shape (probed withShape.contains, so either winding, holes, and.nonZeroall face out; four windings pinned), open contours make sheets; a vertex turning more than 30° gets two columns (hard edge), else one smoothed; the seam is a duplicated column (u1 where the walk opens and 0 where it closes) and a closed path repeats station 0 atv= 1 withtwist(1)/scale(1);ucounts against the outline's walk (ruled 2026-11-23), because the wall facesacross × alongandvkeeps counting from the path's start, so a picture reads the right way round from outside, hangs from the path's start, and stands upright on a path that runs down (a half turn of the uvs,Vector2(, stands it up on a path that climbs); normals are1 - u, 1 - v) across × alongfrom the built grid (falls back to the outline's own outward direction wherescaleis 0); caps fromtriangulatedFillof the closed contours only, each triangle ordered by its 2D signed area (counterclockwise faces +tangent), uvs from the fill's bounds with the shape's +y as the picture's top and its x running left to right on the far cap and right to left on the near one, so each cap reads upright from outside. A shape wider than the path's bend radius folds on the inside (geometry, not a defect).Mesh(.loft( _: along: at: smoothed: scale: twist: capped: ) LoftTests, snapshotloft, example3D/, figureGeometry/ LoftedVessels Docs/, Guide figureFigures/ Loft .swift LoftedBottle): the sweep IS a loft of one section at station 0 through one builder (SweepBuilder), so sections of one shape are the sweep byte for byte (pinned on an open and a closed path, withscaleandtwist, smoothed or not). Rows are every path point plus a row at each station not within 1e-9 of a point's fraction (path.frame(at:)there), so a section is exact at its station (pinned to 1e-12, corners placed throughscale/twist, between two path points included). Columns, per contour: the union of every section's vertex fractions, each closed outline read from its seam, merged within 1e-9 only across sections (a section's own vertex is exact, the others are read on their segment), so every corner of every section is a column on all of them. The seam of each closed outline after the first is the one of 256 even starts with the least summed squared distance to the outline before, read from its own seam (chained; section 0 keeps its first point, and on a closed path the last joins the first as drawn; a square and the same square a quarter turn round, listed from a different corner, make a straight prism: pinned). Sharp is turning past 30° on ANY section, and the two columns' normals coincide where the other sections round it off. The blend per column:smoothedis a cubic Hermite with the tangent half the chord across a section's neighbors and the whole chord at an open end (so two sections blend straight, and a midway section changes nothing: pinned), written as the start section plus differences so equal sections blend to themselves exactly;smoothed: falseis straight; a row within 1e-9 of a station is that section exactly; before the first or past the last station of an open path the end section holds; a closed path wraps from the last section to the first. Contours are matched in order by kind, as many as the fewest any section has. Caps (SweepProfile): each ring's straight runs are reduced to their ends before the triangulator (libtess2 fills a run of collinear points with slivers of no area, which the sealed-solid test found), each cap edge along a run is split back at the run's points and fanned from the opposite corner (from the centroid when more than one edge splits), and the cap's corners are the ring's own doubles (the triangulator returns single precision;.capTriangles aStraightSweepIsAnExtrusioncompares caps at 1e-6 for that reason). A capped loft or sweep has every directed edge paired by position (pinned), andisClosedis set on sweeps and lofts (closed contours only, and capped or a closed path), which the canvas depth of field reads.atis one station per section, ascending,0...1open and0..<1closed, else a precondition.Mesh: rung.strip( between: and: colors: closed: ) i=first[i]–second[i], quads(a0, a1, b1)(a0, b1, b0), normalsalong × rungper end (front =firstrunning left to right undersecond), a degenerate one falling back to face normals;colorscount must equal the rungs or is dropped;u= rung / (rows - 1),v0 onsecondand 1 onfirst(ruled 2026-11-23: the front facesalong × rung, so the picture's top edge lies on the second rail and a strip handed its lower rail first reads upright from its front); closed repeats rung 0; unequal counts: the longer line sets the rungs and the other is read at the same walked fractions (one point = a fan).Pace(byLengthOf:generic overVector,byAreaBetween:and:;period:wraps and keeps counting,parameter(;at: f + 1) = parameter( at: f) + period over:clamps): the rate atresolution+ 1 nodes and 5 Gauss-Legendre points a stretch, a cubic Hermite per stretch from those, safeguarded Newton (60 steps, bisection bracket) to invert; derivatives by fourth-order differences 0.05 of a stretch apart, one-sided within two steps of anover:range's ends so the curve is never read past them; non-finite rates read as 0; the area rate across a rung is∫|p + vq|in closed form (asinh), with Gauss-Legendre when|q|is under 1% of|p|where the closed form would cancel. Pinned: the cardioid's closed-form length (1e-9), a Lissajous's steps against Simpson of its exact speed (1e-8), the limaçon's polar area (1e-9), a self-twisting strip against a brute-force surface integral (1e-5). Measured-O: a length pace builds in 0.5 ms, an area pace 1.2 ms,parameter(at:)0.1 µs. Five planted defects (one reflection, unwinding by index, a linear stretch, Gauss-Legendre only across a rung, no outline reversal) each went red.Marks built from one gesture (
Sources/;Ollin/ Geometry/ GestureMark .swift Docs/, exampleGenerators/ GestureMarks .md Patterns/, snapshotGestureMarks gesture-marks,GestureMarkTests16 (one over all sixteen families), figure17-MarksAndMedia/, Guide Ch 17 § Clouds, dashes, and feathers from one stroke: GestureMark).GestureMarks GestureMark(from aStrokeMarktimes a width, a contour at one width, or points with widths) has sixteen families returning[GestureMark.Piece](closed contour = fill, open = line;row,index,distance),[Piece].shapethe merged region,hull/blob/figure(_:), andShape.spiked/Shape.wobbled. Sizes are fractions of the local width (the rows' of one row's thickness), RULED 2026-10-21;pixels(cell:)and the two regions are canvas units. Load-bearing, the stability rule: the spine is resampled every 2 units by arc length from the start (GestureSpine.step) and the direction inside step k turns from step k-1's to step k's, never reading ahead, so only the last unfinished step (pastsettled) can change when a point arrives. Station families (cloud, chain, dots, sprouts, pixels) place only at or beforesettled; run families (dashes, strips, spikes, facets, lanes, spiral, strands, wiggle) end each row with one tip piece cut at the length; fragments emit only whole ones, sorted by where they end. Every row draws its own seededSplitMix64stream through its own unit conversion, neverDouble. Pinned a point at a time over 140 appends per family (each row's pieces but the last equal), and a planted.random( in: using: ) settled = lengthturns ten families red.[Piece].shaperesolves each piece alone before the union: a period piece that twists on a tight bend carries a backward-wound lobe that cancels a neighbor's fill under the nonzero rule (white holes in the spiked band). Tips under 90 degrees hold fromsharpness2 (at 1 the flanks are straight); the defaults (spacing0.5,height0.3) keep them under about 65.spiked/wobbledstart each outline halfway along its longest edge so the seam never sits on a corner; the wobble reads noise at the canvas position. Gotcha:Contour(defaults tocurveThrough: ) closed: true, so an open gesture passesclosed: false. In space (GestureMarks3DTests7, figure28-Meshes/, exampleGestureInSpace 3D/, Guide Ch 28 § A gesture in space: tubes and solids from a GestureMark):Geometry/ GestureMarks3D tube(is the gesture as asides: wobble: wavelength: ) Mesh, a ring at every spine station (every 2 units by arc length, plus the end) whose radius is the half width there, in the gesture's own plane as the canvas shows it (x as drawn, the canvas's down as -y, the depth along z, canvas units: theMesh.texthalf turn, the solids' turn about z negated with it), uvsuround the section andvalong the path in widths (so a tiled diagonal stripe is a candy stripe), normals tilted by the taper, andwobblethe center coiled round the path at that many half widths once everywavelengthwidths;solids(returnsspacing: seed: ) [MeshInstance]at the flatchain's stations with its sides and turns (both walk onechainStations, so one seed places both alike), fordrawMesh(over a unit mesh. Both keep the stability rule: rings and solids stand by distance from the start, and only the last ring moves on growth (the test grows a gesture point by point)._: instances: ) Points on a surface (
Sources/).Ollin/ Geometry/ SurfaceSampling .swift surfacePoints(/on: count: ) surfacePoints(scatter a mesh's skin rather than its vertex list (a mesh puts vertices where its shape needs them, so a vertex draw crowds a rounded corner and leaves a flat wall bare), returning aon: spacing: ) SurfaceSampleper point (position, normal, uv, triangle + barycentric weights). A triangle is picked in proportion to area through a running-total table, and the point inside it through the low-distortion square-to-triangle fold (press the square's two halves together across the diagonal: no square root, and an even input stays even where the sqrt map stretches one corner)..blueNoise(the default) draws 5x the count and thins the crowded ones out by weighted elimination over the occupied cells only (BlueNoiseThinning; weight falls to zero at the honeycomb spacing.swift sqrt(and rises as the 8th power, so the nearest neighbor decides who goes, with a floor under very close pairs or the pass spends its budget separating one of them);area / ( 2*sqrt( 3)*count)) .randomis the plain draw. Load-bearing: the points are renumbered cell by cell (cubes the size of the reach in (z, y, x) order, input order within a cube, three stable radix passes) and each occupied cube's nine row runs are found once through a hash and kept, so a neighbor walk is nine ranges and visits exactly what a dense grid's walk visits, in the same order: that order fixes how each weight's sum rounds, so any change to it changes picks; the queue holds one entry per live point (four-ary) and is lazy the safe way (a lighter weight is found out only at the top and goes back in at its true weight; weights only fall, so a true top is the heaviest point there is), and ties break by input index, so the survivors equal the dense-grid pass for every input (BlueNoiseThinningTestsholds that pass verbatim as its reference: every scatter the sampling tests make, a terrain at four counts, ties, one repeated point, a line, a shell, a spread below the cell floor; red under ties reversed, a stale top dropped unchecked, and the rows walked in reverse z, which visits the same neighbors and still changes one terrain count's picks through the sums' rounding). Measured on the valley terrain, release: 400,000 points from 13.4 s to 4.7 s for the whole call (the thinning alone about 12.4 s to 3.7 s; drawing the 2 million candidates is the other second), same points, hash-checked; what is left is memory latency, since drops land in weight order all over the terrain (a radix heap, coordinates packed with their weights, and an indexed decrease-key heap were each measured and none is faster,ARCHITECTURE.md); zero-area triangles are dropped from the table buttrianglestill reports the mesh's own numbering;SurfaceSamplereturns the.alignment( spin: ) Rotation3DaMeshInstancetakes (.aboutY(: the y/z pair already reaches every direction, and nothing is read back into angles), pinned against the matrix the renderer actually builds.swing) * .aboutZ( tilt) * .aboutY( spin) Mesh.surfaceAreais public and is what turns a spacing into a count.SurfaceSamplingTests(14 tests: area shares, the fold's1 - (1 - t)^2, the honeycomb spacing, the alignment matrix; four sabotages verified red).Examples/,3D/ Geometry/ SurfaceScatter Docs/. Points on a sphere (Generators/ SurfaceSampling .md Geometry/):SpherePoints .swift spherePoints(andcount: radius: ) hemispherePoints(are the Fibonacci lattice in closed form, pointcount: radius: ) iofnat height1 - (2i + 1) / nandigolden angles aroundy, top to bottom, the count exact, nothing random, no point on a pole. Load-bearing: the dome is the first half of the sphere of twice the count, bit for bit (one private builder,bandstwice or four times the count), and a nearest neighbor is always a Fibonacci number of places away in the list, which is what lets the test read 100,000 points. Measured from 10 to 100,000: the nearest-neighbor distance varies under 1.15 to 1 (0.871 to 1.0 of the nominal spacing), against 12 to 1 and 150 to 1 for points drawn at random.SpherePointsTests(the shortcut held against a full search to 3,000; four plants red). FigureDocs/.Figures/ SphereLattice .swift Points inside a shape (
Sources/).Ollin/ Geometry/ ShapeSampling .swift randomPoints(scatters ain: count: ) Shape's fill (holes out, every island its share) by drawing from the renderer's own fill triangulation, a triangle by area through a running-total table (ShapeAreaTable) and the point inside it through the same square-to-triangle foldsurfacePointsuses, so a thin or sparse shape costs no more than a compact one;randomPoints(scatters the outline by walked length over every contour with two points (open ones included, a closed one's closing segment counted;along: count: ) OutlineLengthTable);poissonDisk(is Bridson inside the shape. Load-bearing: the blue-noise form seeds from the fill's triangles and restarts from a fresh triangle-drawn seed whenever the active list empties, stopping whenin: radius: candidates: maxCount: ) candidatesfresh seeds in a row find no room, which is what fills a bar thinner than the dart annulus end to end and reaches every island (a single Bridson seed never crosses a gap wider than 2r); each dart still paysShape.contains(a ray test over every edge). Every form takes aRandomNumberGeneratorand theSketchsugar runs onrng.ShapeSamplingTests(10: chi-square by band over a holed frame, a concave L, two islands; the outline by side length and by ring, the closing segment, an open path; the thin bar, the islands, the cap, the seed).Docs/,Drawing/ Geometry .md#shape-points Docs/; Guide Ch 15 § Chance inside an outline: points in a shape.Generators/ BlueNoise .md#shape 3D (camera, depth, point clouds, meshes). Opt-in:
camera(_:)/perspective(...)/ortho(...)overCamera3D(per-frame state) allocates a camera-gateddepth32Floatbuffer (a 2D-only frame allocates none and renders byte-identically). Right-handed, y-up; 3D uses the camera, not the 2D CTM. Point clouds (PointCloud/drawPointCloud, instanced camera-facing splats). 4×4 transform stack (translate(x,y,z)/rotateX/Y/Z/rotate(_:axis:)/scale/transform(, the last composing a whole_ matrix: ) simd_float4x4in one call for transforms that arrive whole — a streamed body anchor, a joint pose — verified pixel-identical to the equivalent TRS calls; a separate stack from the 2D CTM, bakes into geometry CPU-side). Solid primitives — the publicMeshvalue type + a broad generator catalog (drawBox/drawSphere/drawIcosphere/drawCylinder/drawCone/drawCapsule(+drawCapsule(, spanning two 3D points end to end with its round tips on the points — the solid bone/strut) /from: to: radius: ) drawTorus/drawTorusKnot/drawPyramid/drawHelix/ the Platonic set /drawMobius/drawKlein/drawSuperellipsoid/drawSupershape/drawExtrude/drawLathe/drawTube) on a depth-tested mesh pipeline. Type as a solid —drawText3D(sugar) overMesh.text/Mesh.textGlyphsextrudes an outline font's glyphs:sizeis the em in world units (nottextSize's canvas points), the block centers on its own ink,alignonly lines up the rows of a multi-line string, and a space contributes no glyph mesh. Two invariants, both sabotage-verified inMeshTextTests: the glyphs are traced at a fixed reference em of 512 and scaled down, because a glyph's contours are RDP-simplified at a fixed 0.3 tolerance in the size they are asked for, so a one-unit em collapses (a five-letter word falls from 884 faces to 12); and canvas-to-world is a half turn about x, never a y mirror, because a mirror reverses every triangle's winding and leaves all 884 faces inside out while both orientation probes still pass. A non-outline font notes once and draws nothing (no filled outline to raise), and the result carries no UVs, as an extrusion emits none.Examples/,3D/ Geometry/ SolidType Docs/. Generator meshes are consistently wound outward, and their normals agree with that winding — load-bearing because nothing culls back faces and every mesh carries its own normals, so a badly wound surface still draws and the defect hides, while everything reading a mesh as a connected solid (a soft body's springs and its inside, a subdivision cage's orientation, a traced ray's facing) reads the winding:3D/ 3D .md#solid-type Mesh.cylinderwound both cap fans into the solid (which detonated a soft cylinder in half a second),pyramid/roundedBox/extrude/conecarried versions of the same,Mesh.planenamed +y and wound its quads to face -y (an open surface, so the closed-solid probe never saw it; the ink line's hull, which culls the faces toward the eye, drew every floor as a slab of ink, 2026-09-14, and the plane now sits in the normals-agree-with-winding probe; the fix moved three Guide figures, which is the second lesson: the vendored MikkTSpace reads the bitangent sign off the UV triangle's winding, so a mesh wound against its normals draws its parallax and normal maps mirrored along v (the Bench tile), and a soft body built from it takes a different constraint order, so a chaotic scene lands elsewhere (the Raft's crates, re-dropped from lower)), andparametricSurfacederiveddu × dvagainst quads wound the other way (shading superellipsoid/supershape/mobius/klein from the unlit side).MeshTestspins both invariants across the catalog; a supershape's ring beside each pinch is the one allowed exception (its central differences measure nothing there). Per-vertex mesh colors —Mesh.colors(aligned withpositions, theuvsrule) multiply the resolved surface color at thedrawMeshvertex bake (fill × material baseColor × vertex color, the texture contract — white fill shows a scan's colors untouched, fill stays a whole-mesh tint); an emptycolorstakes the constant-color path byte-identically, a wireframe ignores them (edges are the stroke), no shader/stride change (the mesh vertex already carried per-vertex color); painted viaMesh.colored(by:)(position+normal closure) /colored((nearest sample overfrom: PointCloud) PointGrid3), and read from file — glTFCOLOR_0(VEC3/VEC4 × float / normalized u8 / normalized u16, re-encoded linear→sRGB like every glTF factor) + Model I/O'sMDLVertexAttributeColor(PLY per-vertex color, already display values so no re-encode; the two conventions differ and mixing them is the bug); a primitive/mesh without colors fills white (the multiply identity, so a partial set is lossless) and colors survive if any did, unlike the all-or-nothinguvsrule, while a file with none yields emptycolors(the constant-color path stays byte-identical). Model I/O gotcha:vertexAttributeData(returns garbage (the first vertex repeated) when the requested format changes the component count and never returns nil, so read the descriptor's declared format and match its width (low byte offorAttributeNamed: as: ) MDLVertexFormat)..rawValue subdivided(_:)carries colors, refined by the same masks the positions take (mirrored beside the position math, never folded into it — the position path is byte-pinned by the snapshot + the five-fold-symmetry test; the weld keeps the first-claiming vertex's color, and Loop's limit push applies to colors too).MeshColorTests(transforms + Metal-gated multiply/variation probes) +MeshLoaderTests+SubdivisionSurfaceTests. Lights & materials —directionalLight/pointLight/spotLight/ambientLight+Light, Blinn-Phong, auto-lit by default (.auto/.custom/.off,lights()/noLights()); curatedlightingPreset(_:)/LightingPreset; camera-relative lights —Light.frame(.worlddefault /.camera),relativeTo(_:)on a light and on a preset,Light.headlight/headlight((a directional down the view,_: intensity: specular: softness: ) castsShadow: falsesince from the eye every shadow hides behind its caster): resolved in one place,Drawer(.resolvedLights activeLightsfor the packer and the spatial export, the lens flare and the ocean's sun read it too; a kind check may still readlights), throughCamera3D.basis(the view matrix's own right/up/back in doubles, the world axes for a degenerate camera), position offset from the eye and direction/upturned,.camerawith no camera reading as world; a frame with only world lights takes the same array, no arithmetic (byte-identical).CameraLightTests(pixel invariant: a headlit sphere's brightness centroid stays at the disk's center across an orbit while a world light's moves); theinked-solidssnapshot;Docs/, Guide Ch 27 § The cartoon look: outlines, and a light that follows the camera. The ink line —3D/ 3D .md#camera-relative outline(/width: color: ) noOutline()/Material+.outlineWidth outlineColor/outlined(_:color:), an inverted hull:OllinMaterial(rgb linear, w = width in canvas pixels, the gate) drives a second draw of the same vertex run through.outline ollin_mesh_outline_vertex/_fragmentright after the lit draw (PipelineKey), each vertex pushed along its clip-space normal by.meshOutline 2·width/so the width survives the divide as pixels at any distance,viewport · clip .w setFrontFacing(+.counterClockwise) setCullMode(.front)for that draw only (the generator meshes wind CCW seen from outside; the cull goes back to.noneafter, since nothing else in the frame culls), depth-tested and written like the surface. Solid and textured.mesh3Dbatches only (never wireframe/grid/matcap, instanced, field, or the path-traced arm, which composites the traced layer and skips it); a width or color change breaks the batch throughMaterial's equality. A hard-edged mesh opens a notch at each corner (documented, not hidden).MeshOutlineTests(the line rings the silhouette and never the face, which is also the winding check, verified red by culling.back; the run holds its pixel count at twice the distance; a nearer sphere hides a farther one's line, with the near sphere removed as the control; width 0 is the byte-identical frame);Docs/; area lights —3D/ 3D .md#outlines rectLight/diskLight/tubeLight(Light, kinds 3-5): linearly-transformed-cosine shading (rect = the exact horizon-clipped polygon integral, disk = the ellipse eigen + cubic + tabulated clipped-sphere path, tube = the analytic line integral × radius, capless) through the bundled fitted tables (.rect/ .disk/ .tube Resources/LTC/, BSD-3 + notice, float32 from the referenceltc.js) at fragment textures 8/9 on everymeshLitColorcarrier (solid / textured / raymarch / half-res tier), gated byOllinLighting→ byte-identical with no area light;.ltcEnabled intensity×color= the surface's radiance (physical falloff — the punctual kinds keep no-attenuation); load-bearing: the packed frame is right-handed (tangent × bitangent = facing normal— the shader's corner winding and disk front-test depend on it), the cubic/eigen sqrt args clamp at 0 (float dip under exact-math-nonnegative → NaN black speckle where a surface grazes the disk's plane, a real fixed bug), non-PBR materials mapspecularSharpness→ perceptual roughness(2/(s+2))^(1/4)with specular = norm channel ×mat.specular(inert at 0, the finish rule), the RT-reflection hit shade evaluates the exact LTC diffuse per panel (ollin_ltc_diffuse, kept in step withollin_ltc_light's dispatch; only the disk reads a table, so the one amp texture is carried into the trace — bound at texture 9 of the deferred pass, whose lighting must also resolveltcEnabledor panels go dark only in deferred reflections; hit specular stays the traced second bounce, matching the punctual Lambert-only treatment; snapshotarea-reflections(RT-gated) +AreaReflectionRenderProbes), and the SSS back term is the flipped-normal integral (carries the panel's falloff). Area (rect/disk) cast shadows — the caster search appends rect/disk after the punctual kinds (existing scenes keep their caster; tubes never cast — radial emission has no facing axis): the penumbra comes from the panel's real extent (RT device: rays to deterministic points on the actual panel surface — Vogel in a disk's plane, antithetic R2 pairs on a rect, each ray weighted by what its point sends the receiver (cos at both ends over d², visible weight over the whole weight, the ratio estimator, so the factor is the share of the panel's light that arrives: the plain count kept 0.213 under a blocker's edge where the share is 0.091, and a point behind the panel or under the receiver's horizon darkens nothing; under the export's shared passes each pass weighs its own rays against the whole set's weight, geometry alone and no ray, times the pass count, so the passes' mean is the whole set's ratio, where a pass of one ray weighed against itself is its own 0 or 1 and the passes averaged back to the plain count, whichTracedShadowPassTestscaught); else a spot-style map aimed at the camera target, PCSS radius = half-extent in texels capped at 40),shadowSoftnessscales that extent (0 hard / 0.5 default = physical / 1 = 2×), the RT flip overwritesshadowDepthBwith the softness scale (the map path needs the slot for the perspective linearization), and the shadow dims both LTC integrals inside the area branch (atten ondiffI/specI→ every model + SSS dim consistently; no caster multiplies by exactly 1.0, byte-identical). Example3D/(its softbox breathes, the area-shadow exercise); snapshotsLighting/ AreaLights area-lights+area-shadows(RT-gated);LightingTestspacking +AreaLightRenderProbes(one-sided / two-sided / falloff) +AreaShadowRenderProbes(on/off diff isolates the shadow; path-agnostic, so they cover the map fallback too). Mechanism: ARCHITECTURE.md § Area lights + § Shadows. Light shaping (IES profiles + cookies) —IESProfile(LM-63 Type C parser: tokenize all numbers after theTILT=line, real files break the line rules; lateral symmetry keyed to the last horizontal angle 0/90/180/360 + the rare 90→270 case; candela blocks per horizontal angle with vertical fastest; normalized to peak 1;init?never traps — headerInt(Double)overflow guarded) attaches to point + spot viaprofile:(axis:aims a point light, default straight down;roll:spins profile azimuth + cookie together), andLightCookieattaches to spots (resamples anImageonce into its own fixed 512² buffer at init — it exists becauseLightis Equatable/Sendable andImageis neither; GPU-backed images fail to wrap). GPU: profiles bake 256×64r16Floatlayers and cookies sRGB layers into twotexture2d_arrays at fragment textures 10/11 on every carrier (solid / textured / raymarch / half-res + the deferred RT-reflect trace), content-hash-cached with a fresh texture on change (never replaced in place), stand-in a 1×1 array (the 2Dstripis type-invalid for an array slot);iesEnabled/cookieEnabledcopy theltcEnableddiscipline (the same three set-sites, deferred pass included — same pattern-lost-only-in-reflections gotcha) → byte-identical featureless frames (whole suite un-recorded); layer indices are packed into the newOllinLight.shapingfloat4, deduped bymakeLightingintoDrawer/.usedIESProfiles usedLightCookies(rebuilt every call, so repeated per-frame calls agree). Shaping applies on the light's local copy (Ltint → every shading model and.color/ .specular *= ollin_rt_directpick it up);ollin_light_frameis the projector convention (right = axis × ref— the cross(ref, axis) order mirrors the projected image, a caught bug); cookie edges land at the outer cone (the [0,1]² square contains the cone circle, so the edge clamp is invisible); a profile is dark outside its measured range, so a 90°-capped file sends nothing above the fixture's horizon — a wallwasher tilts its axis at the wall (the example's lesson). Example3D/(authoredLighting/ LightShaping .iesresources, never manufacturer data); snapshotlight-shaping;IESProfileTests(parse / symmetry folds / ordering / bake / packing) +LightShapingRenderProbes(ring profile / cookie orientation / roll). Atmosphere (fog + aerial perspective + volumetric light) —fog(/_: density: heightFalloff: ) noFog()(exact closed-form distance/height transmittance per fragment) +aerialPerspective(/density: haziness: heightFalloff: sun: ) noAerialPerspective((the Hoffman-Preetham wavelength split: per-channel extinction over the same optical depth + closed-form sun in-scatter, Rayleigh + HG phases) +) volumetricLight(/_: anisotropy: ) noVolumetricLight()(the Toth-Umenhoffer single-scatter march: directional + spot beams shaped by cone/IES/cookie, shafts carved by the 2D-map caster's shadow) +volumetricQuality/volumetricSteps(the fourthRenderQualityparameter, 16/32/64 by tier, both lighting-resolution sites). Load-bearing: the constants are stored in threeOllinLightingtail fields gated byfogColor.w(0 → byte-identical, suite-verified) and pack before the.offearly return (unlit scenes fog); surfaces fog themselves to their own depth and the air is a fullscreen skybox-slot draw (.fogAir, premultiplied(inscatter, 1−T)) so call-ordered compositing needs no stored scene depth (splats/particles composite over the beam-painted backdrop, 2D never fogs, a batch-less frame skips the air draw); the march's ray∩cone span bounding (thin beams otherwise dissolve into a woven lattice or vanish un-jittered), light-leg extinction (the integral is otherwise unbounded along a cone; beams-only mode substitutes a 0.05 reference density for σs and that leg), and per-step re-read jitter (a single shared offset reprints the jitter pattern as a lattice) are each a fixed real defect — don't simplify any away; jitter is a pure function of (pixel, step) so exports reproduce with no temporal history; the RT hit shade applies the analytic leg inside the shared trace (inline + deferred agree; env-miss sky stays clear, documented). Aerial invariants: it is mode 2 on the fog gate (fogColor.w0/1/2, so every existing> 0gate stays armed and one compare picks the model) with two appendedOllinLightingtail fields;ollin_apply_fogstays verbatim and aerial is a twin beside it (ollin_apply_aerial— the GI fast-math codegen rule; classic fog pinned pixel-identical by a clean-HEAD-worktree double record of all 182 refs);OLLIN_AERIAL_RAYLEIGHmirrorsDrawerby hand (the.aerialRayleighRatios ollin_sdf_distancerule); the sun resolves explicit → the.skyenv through its rotation (world sun = R_y(−rotation)·(0, sin e, cos e), sign confirmed against the drawn disc) → first directional light negated → a default elevation, and its radiance is airmass-reddened white (a horizon sun feeds the veil sunset color, no parameter); a nil density derives as 0.35/eye-to-target (the contact-shadow default rule); the air veil steps aside behind a skybox (renderer-setfogParams2.z; the sky already is this scattering at infinity — beams still add), and with no backdrop the air paints the implied horizon glow; long paths saturate toward the sky tone by design (the closed form's equilibrium — a milky frame means density too high for the framing, not a defect). Examples3D/(fog + aerial on one colonnade) +Effects/ Atmosphere 3D/; snapshotsLighting/ VolumetricLight fog+volumetric-light+aerial-perspective;VolumetricTests(packing + the ordering/shaft/beams-only probes) +AerialPerspectiveTests(packing/sun-resolution/reset + the blue-veil/sunward/haziness/sky-byte-hold probes, sabotage-verified). Mechanism:ARCHITECTURE.md§ Atmosphere.Docs/. the stylized3D/ Atmosphere .md material(_:)/Materiallibrary (toon / gooch + specular / Fresnel-rim / subsurface / iridescent / sparkle-flake finishes over a per-batch uniform; the fake-subsurface bleed is the distorted-lobe translucency approximation plus an always-on ambient floor weighted thinner-at-the-silhouette, so.jade/.waxread under a front-lit rig, not only backlit (ollin_sss_translucency, shared by both mesh fragments); the library's everyday-finish roster was retuned by eye in the material explorer (clay/rubber sheen made visible, beetle's bands deepened,frostedGlassroughness 0.2 so blurred structure survives) and gained fixed.clearGlass+.gummyentries (a built-in preset keeps every field it touches within the explorer's parameter set — no color-carrying presets, so the menu's snap reproduces each one exactly and the "(tweaked)" caption stays honest); a finish writes itself back as source —Material(.swiftSource 3D/) is the expression that rebuilds it, a curated preset as its dotted roster name, otherwise aMaterialSource .swift Material(...)call in the initializer's order carrying only the fields whose formatted text (four decimals, shortestColorform) differs fromMaterial()'s, so parameter float dust never prints and a default change never drifts (the diff reads the live defaults, the reason this emitter lives in the core rather than beside the project emitters, which depend on nothing); the explorer's C key copies it (any other key still steps the roster), andMaterialSourceTestspins the roster names, the order, the dust rule, and — through aswiftc -typecheckgate over a kitchen-sink expression with every field changed, sabotage-verified red on a misspelled label — that every printed label is one the initializer takes; sparkle cells sized byOllinLightingso the default works at any scene scale; soap-film mode —.sceneScale iridescenceFlow/iridescencePhase/iridescenceFlowSizeturn the iridescent rim sheen into a thickness-driven film: drainage via the normal's y (quadratic, so interference bands crowd toward the bottom) + a domain-warped 3D-fbm swirl (fbm displaced by a vector of two more fbm reads — single-octave noise only makes blobs, the warp+octaves make the sheared marble wisps;fbm(float3)added to OllinShaderLib mirroring the CPU name) in sceneScale-sized cells scaled byflowSize(the sparkle-size rule — a small bubble under a far camera needs ~0.3-0.45 or the swirl is near-constant across it), colored by per-RGB-wavelength two-beam interference (rates 1/1.2146/1.4513 — zero thickness goes dark, the black-film cap; aexp(-0.18·d)broadband rolloff washes thick film pale), phase is the sketch-driven clock (no hidden time), flow 0 keeps the plain-sheen expression verbatim (byte-identical, suite-verified); example3D/composes it on thinMaterials/ ThinFilm .glass()for its floating bubbles — the merged host also callssceneThroughGlass(), so overlapping bubbles ease back to the environment per the one-piece-of-glass rule; snapshotsoap-film); the physically-based metallic-roughness finish (Material+.physicallyBased .metal(roughness:)/.dielectric(+ the brushed/polished/plastic built-ins) — Cook-Torrance GGX (glTF 2.0 / Filament forms, reimplemented from the math), surface color staysroughness: ) fill; it'sshadingModel 3, so every non-PBR material stays byte-identical. Glass (transmission & refraction) —Material/.glass( roughness: ior: thickness: attenuationColor: attenuationDistance: dispersion: ) .frostedGlass: the KHR-transmission/volume/ior model built on the PBR finish (no new shading model), the transmitted lobe replacing the diffuse one (mixbytransmission·(in the IBL ambient; punctual + LTC diffuse scale by the same1−metallic) diffKeep). Dispersion (Material.dispersion, 0…1 on thecaustics(scale: red and blue refract atdispersion: ) ior·(around green,1 ∓ 0.03·dispersion) ollin_channel_iorsinShader3D.metal, so a body's fringe and its caustic agree): every transmission read splits per channel where it is on:ollin_env_refraction(three cube reads),ollin_scene_refraction(one march per channel; the green read's coverage decides the pixel and a refused side channel reads where green did, so a fringe never punches a hole), the tracedollin_rt_refraction(one walk per channel through its trailingiorparameter, which sits after thebodyExitpair with no#ifbetween them), and the path tracer (a path draws one wavelength at its first dispersive solid vertex and keeps it, taking the caustics photon tint so the ensemble sums to white; dispersion-free glass draws nothing, so its random stream and its frame are untouched). Byte-identical at 0: each path tests the gate before it does anything (the 247-reference snapshot suite and the traced reference pin it). Shows only on a solid body (a thin wall leaves every color parallel). Probes:SceneThroughGlassProbes(3: the scene read, the refracted environment, the traced walk, each measuring how differently red and blue moved between the clear and the dispersive render inside the ball while the pixels nothing transmits stay byte-identical; a change that moves the channels together reads zero, and all three are red by sabotage of the split) +PathTraceTests(red by sabotage of the index shift; the tint alone reads 0.2 against the 3 the bar asks) +.dispersionSplitsATracedPathByWavelength MaterialTests. Example.dispersionDefaultsOffClampsAndPacks 3D/(the fifth body); Guide Ch 29 § Glass with theMaterials/ SeeThrough Prismfigure. Load-bearing: F0 now comes CPU-packed asmat.f0, the exact literal 0.04 at ior 1.5 (the computed form rounds to a different float —MaterialTestspins it) so pre-glass frames stay bit-identical; transmission is inert without an environment (nothing to transmit → shades as the plain dielectric, probe-pinned byte-equal) and inert at 0; the base path is env refraction (analytic interior span, curvature-blended exit normal, blur lod fading as ior→1, Beer-Lambertpow(with channels floored 1e-4 — a zero channel NaNsatt .rgb, span/ att .w) pow(0,0)under fast math);rayTracedReflections(upgrades glass too (one opt-in for mirrors + glass): the traced walk reads raw hit facing — a back face is the solid's real exit (refract out, trace on, traced span feeds Beer-Lambert), a front face inside is an embedded object, a thin wall hops its own shell's back faces (≤4), TIR carries straight on — and hits shade via) ollin_rt_hit_radiance, extracted from the reflection trace so mirror and glass can't drift; refraction traces inline even in deferred frames (refracted content is minified; revisit on shimmer). A raymarched field owns no triangles, so it hands the walk its own exit: the accel structure holds.mesh3Dbatches only, so the interior leg can never hit the body and would otherwise take whatever stands behind the field for the far interface and absorb over the run to it (a green 0.95 sphere read G137 as a field against the mesh's G189, and followed the slab behind it) — the raymarch fragment sphere-traces the inside of its own field (ollin_sdf3d_interior_exit) and passes the exit + inward normal throughollin_pbr_ibl_ambienttoollin_rt_refraction, which uses it only while it is nearer than any traced hit (an embedded mesh still shows through the entry interface); the mesh path passes zero and is byte-identical, and the env path was always in step (its span is analytic). That march starts on the surface, where the interior distance is ~0, so it needs a floor under every step (else it crawls) and must latch on having really been inside before counting the exit (else the sub-epsilon residual the outward march leaves — which bands radially — decides it, printing the body in fine concentric rings); it returns a distance, never a failure, since the caller's fallback is the defect itself. The rings were invisible to a patch mean (the center matched to 0.6/255 through them), so the probe compares the two bodies pixel by pixel over a disc that stops a few pixels short of the rim — a square's corners reach the silhouette, where the outermost pixels legitimately differ (the AA models disagree, multisampled vs analytic, and the field's single inline reflection ray meets the rim-compressed mirror image a mesh's supersampled deferred layer averages); the rim's own shading agreement has its own probe,aFieldRimShadesLikeAMeshRim, above. v1 envelope: opaque shadows, opaque seen in mirrors / through other glass; what lies behind a glass field still comes from the mesh scene, so a second field is not visible through it. Example3D/Materials/Glass; snapshotsglass-materials+rt-refraction-3d(RT-gated);GlassRenderProbes(env-inert byte-equality / absorption-vs-span / traced-wall-through-pane / field-absorbs-like-mesh) +MaterialTestspacking. Mechanism: ARCHITECTURE.md § Glass: transmission and refraction.Docs/3D/3D.md#glass. Anisotropic specular (the brushed streak) —Material.anisotropy(−1…1) +anisotropyRotation(radians, packed as cos/sin CPU-side): the Kulla at/ab split (at = α(1+a), ab = α(1−a)) over the anisotropic GGX distribution + height-correlated anisotropic Smith visibility on the punctual lobe in both lit twins, and the bent-reflection-vector environment gather (RT reflections trace the bent direction for free; coat + sheen keep the plain mirror directionRmirror; LTC area lights stay isotropic, the fitted tables having no anisotropic form). The isotropic helpers stay the strength-0 path (the gate keeps every non-anisotropic frame byte-identical, suite-verified). The tangent frame is the real per-vertex basis on the nm/surface-mapped pipelines (orthonormalized against the shading normal), else the stable world fallback (ollin_ltc_any_tangent), which reads as a lathe finish on primitives (poles pinch by design);.brushedMetalcarries the finish. Example3D/; snapshotMaterials/ BrushedMetal anisotropy-materials;AnisotropyPackingTests+AnisotropyRenderProbes(streak-extent probes: extents and peaks, not region means).Docs/. Clearcoat & sheen (layered PBR lobes) —3D/ 3D .md#anisotropy clearcoat/clearcoatRoughness+sheen/sheenColor/sheenRoughnesson the PBR finish (presets.carPaint(/roughness: ) .lacquer/.satin/.felt): the coat is a second GGX lobe (Kelemen visibility, fixed 0.04 Schlick) with the base dimmed by (1−Fc) and its F0 remapped for the coat interface — the remap sends the default 0.04 to exactly 0 (the interface vanishes), so a coated base legitimately loses its broad spec and a probe must compare peaks, not region means (the first probe draft failed on this); sheen is the Charlie sine NDF + cloth visibility, no Fresnel, base scaled by 1−max(tint)·E. Load-bearing: E is the sheen LUT (ollin_ibl_sheen_lut, r16Float 64², baked lazily byensureSheenLUTbeside the threeresolveIBLcall sites when a frame's batches carry sheen — environment-independent but needed under plain lights, so it triggers off materials, not the env bake; fragment texture 12 on everymeshLitColorcarrier, stand-in otherwise); both lobes branch on their packed fields → byte-identical at zero (suite-verified, no re-records); under LTC area lights the coat runs a second LTC fetch at the coat roughness and sheen takes E·diffI (the broad-lobe treatment); under RT reflections the coat reuses the traced radiance (same mirror direction, no second trace) while sheen keeps the prefiltered env; a surface seen in a mirror shades without the lobes (the glass-in-glass envelope);OllinMaterialgrew 176→192 (clearcoatfills the old offset-124 hole,clearcoatRoughnessthe 172 tail pad,sheenColorappended, strength premultiplied into its rgb with roughness in w). Example3D/; snapshotMaterials/ CoatAndCloth coat-sheen;CoatSheenRenderProbes(point / panel / env coat peaks + the sheen rim) +MaterialTests. Mechanism: ARCHITECTURE.md § Clearcoat and sheen.Docs/. Thin film (interference color) —3D/ 3D .md#clearcoat-sheen thinFilm(0…1) +thinFilmThickness(nanometers, the one parameter in the material that is not in world units) +thinFilmIoron the PBR finish (presets.anodized/.oilOnWater/.nacre/.soapFilm(): light reflecting off both faces of a clear film meets itself out of step, so the color is interference rather than pigment (soap bubble, anodized metal, oil on a road, nacre). Written from the published technique and credited inthickness: ) ATTRIBUTION.md; it lives asthinFilm/thinFilmF0in the shared shader library's.colormodule, so a user shader can call it too. Two ways in, and the split is load-bearing: a term that traces one direction takes the film's reflectance in place of its Fresnel (ollin_pbr_film_F, the punctual lobes in both lit twins and the path tracer's BSDF), while a term that integrates a whole lobe at once (an LTC area light, the IBL split-sum) takes the straight-on stand-in (ollin_pbr_film_f0, the Schlick inverse at NoV) — feeding it the raw reflectance applies the angular response twice. A thickness of 0 ships strength 0 from the CPU (so the shader gate is one compare, and the model is never asked for a color it has no basis for) → byte-identical at zero, the whole snapshot suite passed unrecorded. The base F0 is the film's second face, so the same film over a conductor and over a dielectric are different colors. The sensitive dial is the optical path difference; the second interference order is worth about 1% at these interfaces, so a probe that drops it reads inert and proves nothing. Envelope: a body seen inside a traced reflection shades from the compact RT finish record, which carries no film (the coat's limit). Example3D/; snapshotMaterials/ ThinFilm thin-film-materials;ThinFilmMaterialTests(clamps, packing, the zero-thickness gate) +ThinFilmRenderProbes(inert-at-zero byte-equality, the color spread, the walk with thickness and with the angle, the base's part in it, path-traced parity, and the fidelity check against an independent Swift reading of the model across 220–820 nm, sabotage-verified: a 15% error in the path difference fails it at many thicknesses).Docs/. The hologram (a grating's rainbow) —3D/ 3D .md#thin-film hologram(0…1, the gate) +gratingSpacing(nanometers, about 1,000 for a sticker, 1,600 for a disc) +gratingRotation(the groove direction in the surface plane, likeanisotropyRotation) on the PBR finish (preset.hologram): Stam's diffraction lobe (credited inATTRIBUTION.md), the half-vector sum's component along the groovesu = |(L + V) · T|picking the wavelength each order sends this way by the grating equationλ = d u / n, orders 1 to 3 summed at shares 1 / 0.3 / 0.1, each a Gaussian in wavelength whose width grows with the roughness (σ_u = 0.02 + 0.25 rough², floored at the tap spacing) and is summed over the 15 spectral taps the lighting uniform carries (OllinLighting/.spectralTaps spectralToRGB, cooked from the same block the.thinFilmand.diffractionfilters read, written every frame bymakeLighting, read only while a batch'sgrating.xis above zero). The unit is load-bearing: the taps' own XYZ-to-RGB inverse maps the sum of the taps to white, so a one-tap lobe at luminance 1 lands several times too bright and clips to the primaries; the lobe is scaled by the taps' white luminance over their brightest tap (packed inspectralToRGB[0].w), then by 0.5 for the share a real embossed grating diffracts, times the surface's own Fresnel and the light, faded in over the first 0.15 of N·L. The groove frame isollin_surface_frame(the anisotropy's frame builder, generalized to a cos/sin pair;ollin_aniso_frameforwards to it, byte-identical), re-orthonormalized against the shading normal, which is what turns the grooves per facet under a normal map (holographic foil in 3D; aFacetFieldwritten out as a green-up normal map is the sheet the 2D filter reads). The lobe answers the punctual loop only (no area panel, no IBL); the path tracer shades it as the plain metal (Docs/lists it); a raymarched field with it is refused by the web page (Output/ PathTraced .md WebGraph.refusal). Strength 0 or spacing 0 shipsgrating.x0 from the CPU, the whole snapshot suite passed unrecorded. Example3D/; snapshotMaterials/ Hologram hologram-material;HologramMaterialTests(clamps, packing, the zero-spacing gate, the preset, the source writer) +HologramRenderProbes(inert-at-zero byte-equality; the three tilts the grating equation puts at 450 / 550 / 650 nm reading blue / green / red; the hue walking one way across 430 to 650 nm; a quarter turn of the grooves taking the rainbow out of the light's plane; a crumpled map breaking it into facets).Docs/; Guide Ch 29 § A rainbow from grooves: the hologram. Real subsurface scattering (the separable diffusion) —3D/ 3D .md#hologram Material.scattering(0…1) /scatteringRadius(world units, the one scene-dependent number) /scatteringColor(per-channel falloff ratios, default the warm skin set) +.skin(radius:)/.marble(radius:): a screen-space diffusion, twoollin_sss_blurpasses over the linear pre-tonemap resolve inserted between the geometry resolve and the frame filters on every render path (live / headless / benchmark; accumulation + texture-handoff keep their no-deferred-pass envelope), fed by a dedicated scatter-mask mesh re-encode with its own depth (occluders suppress hidden skin; matcaps occlude but never scatter). Load-bearing: the mask pipeline (isScatterMask) runs blending off — its alpha carries the profile index, which.normalblending would multiply into the color; the kernel is CPU-built and pure (25 importance-placed taps over the published sum-of-Gaussians skin profile stretched per channel by the falloff, normalized then strength-folded into the center tap, so strength 0 is exactly the identity; cached by profile, ≤8 distinct profiles/frame, extras reuse the last + note); the depth-gap guard measures against the scattering radius (tap fully cut at four radii, un-projecting the mask's step via2·step·wFactor/P11) — never a fixed screen-space constant, which is proportional to radius and saturates on the surface's own curvature the moment the radius is a visible fraction of the object, silently disabling the whole blur (a real first-render bug); unmarked pixels pass through bit-exact and a no-scattering frame skips the stage byte-identical (whole suite unchanged, no re-records);OllinMaterialgrew 192→224 (scatterfloat4: raw falloff ratios floored 0.001 + radius in w,scatterStrength+ explicit pads); the lit fragments read those fields only inside the transmittance branch (gated onscatterStrength > 0), so every non-scattering shading path is untouched. Transmittance (the translucency half) — under acastShadows()caster the same material transmits through thin backlit geometry: thickness from the caster's own depth (2D map via the newOllinLighting[2][2]/[3][2] constants — the PCSS ratio needs only [2][2], an absolute distance both — with the receiver shrunk 2 map texels along its normal, each tap a per-corner-linearized manual bilinear read (blending perspective depths first bends the ramp; a nearest tap terraces), gathered over the diffusion's entry footprint (.shadowLinearize transmitGather2D: a world-anchored-rotated 13-tap spiral sized by the scattering radius in world units — never map texels — per-Gaussian-normalized so a constant-thickness slab reduces exactly to the slab form; a single-tap read re-exposes the caster mesh's own tessellation at grazing light, the audit's terminator stripes, and the fix is red-first-pinned bygrazingLightLeavesTheTerminatorSmooth); cube via its stored linear distance; RT point via one closest-hit ray,meshRTThicknessOne, traced by the solid/textured fragments under the same material gate);ollin_sss_transmitis the closed-form slab integral of the same Gaussian tablescatterKerneluses (w·e^(−s²/2v), hand-synced — theollin_sdf_distancerule), thickness entering in kernel units (×3/radius); irradiance is the reversed-normal 0.3-wrap. The term reads the pre-shadow attenuation (a backlit face sits in its own body's shadow — dimming by it erases exactly the transported light) while still applying the cone gate + shaped light copy, and lands before the blur (diffused with the reflectance, the published treatment); only the casting light transmits, area panels don't, and every blur gate (strength 0 / no caster / field carriers) leaves the term byte-identical. The transmitted rim on a deep body is a tight bright feature, so an overdriven radius prints the blur's tap comb around it exactly as around a tight highlight (honest radii can't show it — measured, ARCHITECTURE.md). Envelope: solid/textured meshes on the main canvas (a target's mesh and a raymarched field note once and keep plain shading; specular blurs with the diffuse, the single-buffer form). Example3D/(space = bare comparison; castShadows on, so the swinging key transmits when behind); snapshotsMaterials/ Subsurface subsurface-scattering+subsurface-transmittance;ScatterKernelTests+ScatteringRenderProbes(terminator carry / red-outruns-blue / radius scaling / occlusion byte-identity / off-surface bit-exactness / reproducibility — verified red by sabotage) +TransmittanceRenderProbes(thin-vs-thick per caster kind / red-through-body / no-caster + strength-0 gates / reproducibility — the spot probe isolates the linearization, all verified red by sabotage). Mechanism: ARCHITECTURE.md § Subsurface scattering.Docs/. Image-based lighting (IBL) —3D/ 3D .md#subsurface-scattering environment(_:)/Environmentlights the PBR materials from a surrounding HDRI via the split-sum bake (Karis; equirect→cube / irradiance / GGX-prefiltered mips / BRDF LUT, baked once per source and cached). The decode keeps a sun past half range: an HDRI is drawn into a single-precision context and packed to half bypackEquirectwith oneprescalethat brings its brightest component to 65,504, whichIBLMapsdivides back out (the cache blob's header is version 3 and carries it; the procedural sky's readback keeps its own half path);.normalization anEnvironmentsSunReachesTheSceneholds at 200,000. The specular lobe keeps its energy: every physically-based path (punctual, area-light, IBL, path-traced) carries multiple-scattering energy compensation priced from that LUT's directional albedo (ollin_pbr_ess/ollin_pbr_energy_comp; single-scatter alone kept 36% of a white furnace at roughness 1). Three invariants: the LUT bakes with the same height-correlated Smith term the lobes shade with (a mismatched bake prices the lobe low and over-fills it — the k=α/2 form read 104.5% in the path-traced furnace); the LUT bakes for any frame carrying a physically-based finish, environment or not (ensureBRDFLUT(for:), the sheen-LUT trigger shape — without it a no-environment PBR frame reads the stand-in strip as its albedo); and the IBL form returns the dropped share through the irradiance, not the mirror gather (exact in a uniform surround;Favg = F0 + (). The matte body keeps one minus the lobe's directional albedo at the view direction, for every light: the image-based ambient by1-F0)/ 21 1 - (in both twins (FssEss + FmsEms) ollin_pbr_ibl_ambientand_mapped), every lamp, panel, caustic receiver, trace, and bounce byollin_pbr_lobe_albedo(the split-sumF0·A + Btimes itsollin_pbr_energy_comp), so a white dielectric returns a uniform field at every angle and roughness. One minus the Fresnel at the view angle (the old ambient) kept 90.3% at grazing at roughness 0.5, and one minus the Fresnel at the half vector (the old lamps) 135% at grazing at roughness 0.2, since most of what a grazing view sees sits far from the mirror direction. A panel's diffuse takes the same weight (it once took none). White-furnace pins:EnergyConservationTests(raster, three roughnesses, bounded both sides) +theMetalFurnaceKeepsItsEnergy(traced). HDRI sources: 8 CC0 HDRIs bundled at 1K (instant, offline, CI-safe) + 12 download-on-demand (Poly Haven), user.hdri(path:)/.hdri(downloadURL:)/.remote(,url: fallbackResource: ) highRes(backdrop upgrades (the lighting never needs >1K) — a remote source downloads through.twoK/ .fourK/ .eightK) EnvironmentCache, whose blocking form is for the export path's main thread only (downloadBlockingparks the caller until a worker's task lands the file; from anythingasync, a test body included, it parks a pool worker, the other parked thread in every 2026-09-06 CI wedge sample), so anasynccaller usesdownload(_:), which suspends, andScripts/refuses the blocking call underpreflight .sh Tests/— and the procedural.sky(— a zero-asset Hosek-Wilkie dome (vendoredturbidity: sunElevation: groundAlbedo: ) External/, BSD-3) generated with no CPU read-back (the read-back was the 3-fps bug), re-baked per frame at a reduced budget when animated (the HDRI path stays byte-identical),CHosekWilkie rotated(_:)spinning the sun for free; a neutral.sky()is the default placeholder while a download lands. A sun-lit sky's ground is a matte ground the sun lights (ruled and measured 2026-10-26): whileskySunLit, both generators leave the lower hemisphere black andollin_ibl_sky_ground_reduce(one threadgroup over the baked upper half, cosine and solid-angle weighted, so a cloudy sky's ground is lit by the cloudy sky) plusollin_ibl_sky_ground_fillpaint it with one radiance, the albedo times the level irradiance of sky and beam over pi (SkySunis the CPU twin, for the exposure;.groundRadiance SkySunholds the model's own numbers within 0.03%), so a face turned down reads the sunlit ground (about four times the mirror under a clear sky at albedo 0.3) and the backdrop below the horizon is that flat ground; a sky whose sun is not a light keeps the dimmed mirror byte-identical. The sun's share follows the clouds the backdrop shows:.levelIrradiance ollin_ibl_sky_sun_transmittancemarches the shell along the sun's direction with the view march's own extinction (so the share is the disc's own dimming) into 32 bytes of shared memory beside the ground,IBLMaps.sunReadback;syncSkySunTransmittancehands it toDrawerbefore anything packs the frame's lights, a frame late in a window (the bake's completion handler lands it) and exact in a headless frame (which bakes on its own command buffer and waits, so one.skySunTransmittance image(of:)and an export's first frame already have it), andskySunLight()scales the beam by it in place of 1 minus the coverage while the exposure keeps the expected share (a passing cloud darkens the scene, never swings the exposure).LightingInvariantTestshold the ground to the CPU model within 3%, to a traced white plane within 5%, a face turned down to the trace's own ratio within 10% and to the matte floor's 0.3, the contrast of a sphere to the model's 4.76 (8.59 over the mirror), and the share to 1 in a gap, under 0.2 behind a cloud, and within 0.05 of the backdrop's disc. A live feed lights the scene —Environment(the.feed( _ feed: VideoFeed) .feed(id:)source + the weak main-actorFeedEnvironmentsregistry,EnvironmentFeed): the feed's latest frame wraps into a GPU equirect (.swift ollin_ibl_feed_gen— front hemisphere direct about +Z, back its horizontal mirror, pinched to the picture's center column at the poles, so the wrap is seamless) and runs the reduced-budget sky bake on the frame's command buffer (no CPU read-back). Load-bearing: the bake key carries a per-feed generation (IBLKey, 0 for every other source) bumped on a new frame — newness is Image identity, and.feedGeneration FeedBakeStateholds the compared frame so a freed frame's recycled address can never read as "unchanged"; a GPU-backed frame (a live texture updated in place) re-bakes every resolve, the animated sky's own cost, and stale generations evict (the animated-sky discipline);bakeReady's HDRI/sky path is textually untouched (the feed branches out first; the whole suite passed unrecorded); auto-exposure is exactly 1 (a camera exposes itself; a real average would read every frame back); the factory setsshowsBackgroundfalse (the wrap is for lighting, not viewing — draw the frame yourself); no frame yet / a deallocated feed → the neutral placeholder sky (the remote-download discipline). Example3D/;Environments/ LiveEnvironment FeedEnvironmentTests(5, the color probe sabotage-verified); no pixel snapshot (the input is live).Docs/. Volumetric clouds are part of the sky bake (3D/ 3D .md#live-environment Environment, the.clouds( _: ) Cloudsvalue: coverage/density/scale/tallness/phase, presets.fair/.scattered/.broken/.overcast) — the Schneider/Nubis recipe marched inside the sky generation so backdrop + IBL + reflections see one weather and an overcast dims the scene by construction; load-bearing:ollin_ibl_sky_genstays verbatim with the clouds twin beside it (the GI codegen rule), the bake cache keys onIBLKey(source + clouds; clouds nil for non-sky sources so a stray value can't fragment an HDRI's slot — the cache-key sabotage is red without it), the weather field thresholds fbm into hard-cored blobs (a soft field reads as veil everywhere), the tiling noise volumes are a fixed lattice baked once per process (ollin_cloud_noise_*, deterministic on any machine), the march jitter keys on the fragment's own pixel position (a hardcoded texel scale printed stripe combs when the cloudy bake doubled to 2048), the skybox auto soft-focus turns off only when the source is really.skywith clouds (keying on the clouds value alone changed an HDRI's backdrop, a probe-caught live defect), andphaseis the deterministic wind clock (a still sky bakes once and costs nothing per frame). Example3D/; snapshotEnvironments/ Cloudscape sky-clouds;CloudTests. Mechanism:ARCHITECTURE.md§ The procedural sky. Terse invariants (mechanism, caches, and downloads inARCHITECTURE.md§ 3D lighting and environments): mip the equirect before the equirect→cube pass (else the cube reads empty → black IBL, a real bug); the bundled set is PIZ half-float (ImageIO won't decode dwab); per-environment auto-exposure (the set ranges ~800× in brightness) so any HDRI just works; non-PBR materials take the diffuse irradiance as their ambient (Gooch keeps its own ramp) so one environment lights every material — all gated oniblEnabled→ byte-identical with no environment; export blocks on downloads (full-res art) while live shows a placeholder; the decoded equirect is blob-cached (<hash>) and read off the render thread; the in-memory bake cache is LRU-bounded (.equirectf16 IBLCacheTests). The environment draws as a skybox backdrop by default (bicubic-reconstructed, resolution-awarebackgroundBlur;.lightingOnly()opts out). The irradiance bake reads each sample at the level its footprint asks for (log2 of the step over the env cube's texel angle), never the derivative's: the tangent frame flips where |n.y| crosses 0.999, the middle of the up and down faces, and the quad there read the coarsest level, so every floor under a structured environment lost light (14% of a hazy sky, 3 to 8% of a clear one;aFloorGathersTheWholeSkyholds a plain floor to the model's level irradiance within 3% clear and 8% hazy, the hazy sky's sharp glow reading 2 to 6% high through the cube's box-filtered levels). The sky's sun (Environment,.sunlight( _: ) .automatic/.always/.off): the model's own solar radiance function (vendored with its solar and limb-darkening tables, the disc integrated by four Gauss-Legendre nodes in the limb cosine, exact for its quintic, against a 20,000-ring integral to 1e-7) through the CIE 1931 observer into linear sRGB, the sky's own unit (the RGB dataset is the XYZ one through the sRGB matrix within a few percent, and the observer reproduces the spectral Y within 1%), joinsactiveLights(in:)after a set's own lamps as one more directional light, so the shadow pass, the shafts, the traced export, the GI probes, the light grid, the ocean's sparkle, the flare, and the caustics' gate see it..automaticjoins a set with no directional light of its own (a sketch's key stands in as the sun, so preset-lit sky scenes keep their look); the frame's own set decides the bake (Drawer.skySunLit→IBLKey.sunLit). One function feeds both sides:SkySun(CPU) gives the beam, the sky's coarse average, and the horizon, and the bake's exposure and the light's scale both come fromSkySun.exposure, so the light lands in the backdrop's unit to the last bit. While lit, the beam joins the exposure's average as its luminance over 4π (a photographed sun's pixels count the same way in a loaded map), the clear sky's 25× stand-in disc leaves the bake (radius 0 insky[10].w) and the skybox draws the disc at the sun's true size (half of 0.51°) at its mean radiance, area-conserving below a pixel; a cloudy sky keeps its baked disc, dimmed by the clouds, and the beam keeps 1 − coverage. An unlit sky (.off, or a sketch's own sun) bakes byte-identically to before. Facing-to-away 8.66 against the model's 8.59, a sunlit floor against its shadow 3.48 and 1.90 against 3.45 and 1.89 at turbidity 2 and 8 (a separate program over the full upstream source;aClearerSkyCastsHarderLight). The aerial air under a.skyis the sky's horizon averaged over 64 compass directions, over the phase mix averaged the same way, at the backdrop's exposure and intensity (Drawer), so the far veil averages to the backdrop's horizon and the haze's halo still leans it sunward (.aerialAirLight theFarAirIsTheSkysHorizonwithin 4% of the model at 60, 120, and 180 degrees from the sun, read at the frame's middle since a wider read crosses compass directions the halo leans differently); without a sky the first directional light's linear color times intensity scales the old fixed sunlight, so the frame is linear in its light. (Environmentis the bare public name, so Ollin's SwiftUI files qualify@SwiftUI, as they already do for.Environment Image.)matcap(_:)/Matcap(view-normal sphere-texture shading, 26 bundled CC0 looks + a CPU generator). Meshes from file —loadMesh/Mesh(contentsOf:): Ollin's own OBJ + glTF readers beside Model I/O (.usdz/.usdc/.usda/.stl/.ply/.abc), carrying base-color material + texture + UVs;bounds/center/normalized(scale:)to recenter+fit. Textured meshes (Mesh.uvs/MeshMaterial/mesh.textured(_:)). A picture reads the right way round from the side the normals face (uto the viewer's right,vdown the image):Mesh.spherecarries the picture's middle on its front (+z),u0.25 on -x and 0.75 on +x, the side edges meeting at -z, and the point a uv stands for is(, which a map baked for the ball goes through too (the planet's-sin 2πu · sin πv, cos πv, -cos 2πu · sin πv) planet_direction). The plane, a terrain, and a gesture's tube read right as well, and so do a sweep, a loft, a strip, and both of a sweep's caps, each by one coordinate turned (the Sweeps and strips bullet says which);MeshPictureDirectionTestsreads every one off its triangles (readingShare) and off a frame. Two things in the ball's generator are load-bearing: its columns start at the back, because the join needs a column of points there, and its quads are listed from +x round by the front as they always were, because nothing culls back faces and a see-through ball blends its faces in listed order. So a ball of fourfold segments is triangle for triangle the solid it was, and any other count is that ball a quarter turn round. The basis a normal map is read in is generated from the uvs, so it follows the picture with no code of its own, and the surroundings, a picture seen from inside, keep their own lookup (ollin_ibl_equirect_uv, middle on +x).MeshPictureDirectionTestsreads the rule twice, off the triangles with no GPU (readingShare) and off a frame, with a ball built from +x kept beside it as the twin its solid is held against.Docs/.3D/ 3D .md#which-way-round-a-picture-sits TextureWrapdecides what every one of a material's maps does outside the 0…1 square (.clampthe default /.tile/.mirror, ontextured(and_: baseColor: wrap: ) MeshMaterial.wrap). Load-bearing: a sampler is a compile-time object in MSL, so the mode is a select between threeconstexprsamplers in each mesh fragment (and in the tracer's hit reads, for parity) keyed onOllinMaterial, never sampler state carried with a batch — the branch is uniform per draw, clamp is the zero, and the bound sampler is the clamp case, so an unstated material samples through exactly the path it always did. The three modes agree strictly inside the square and differ within half a texel of the edge (the filter reaches across), which is what makes turning tiling on safe for a mesh whose uvs stay in range; triplanar and the detail pair repeat regardless (no uv tile of their own). One mode covers the whole map set, including the parallax march's height reads, since a surface that repeats its color repeats its relief. A loaded model brings the file's own answer, and each format states it differently: glTF reads the texture's sampler and defaults to repeat when none is declared (the case that decides whether an authored tiling floor tiles),.uvWrap .mtltiles unlessmap_Kd -clamp on, USD readsinputs:wrapS, Model I/O reports its ownsWrapMode, and a file that says nothing gets clamp; the USD writer now writes the material's mode rather than a hardcodedrepeat, so a round trip holds.TextureWrapTestspins it by predicate rather than a snapshot (four screen quarters over a plane whose uvs run 0…2: the third quarter is white clamped, black tiled, and white-then-black mirrored), plus a traced-export parity probe, byte-equality inside the square, and the four loader readings. Example3D/(its floor tiles four across). Texture filtering — every decoded picture carries a mip chain (Geometry/ TexturedMesh .generateMipmapson both the color and the value/data loads; the hand-built sRGB fallback fills its own levels by blit), and the samplers are trilinear plus 16× anisotropic on the surface path only, with all threeconstexprsamplers written into the mesh fragment carrying both settings too — the tile/mirror wrap pair, the triplanar projection, and the detail pair (miss one and that read alone keeps crawling: a projected floor read 150.8/sd 103.2 and a decoded picture there was byte-identical to a one-level one, the reading that says the chain was never reached; a detail pair read 59.3/sd 46.9 the same way). The two-sampler split is load-bearing:imageSampler(the chain, the image quads, the glyph atlas, the gradient strip) stays at 1 tap because a screen-space pass reads one texel to one pixel — there is no footprint to resolve, and asking for one makes the sampler read a derivative that a pass returning early per pixel (the scatter blur's mark test, the sandpile's open edge, a disoccluded pixel in the temporal resolve) has no whole quad to form; that undefined read is what made a plain lit box render differently on every run on a scene with no picture in it (~450 bytes at up to 12/255). Those passes now namelevel(0), and onlysurfaceSampler, bound by the textured-mesh draws, resolves a footprint. A parallax read is the one uv the sampler must not derive from (the march steps it per pixel): its maps read throughgradient2dof the geometric uv, or the silhouette moves 3px against its flat control. Load-bearing: generating levels on an_srgbformat averages in linear light — a black-beside-white checker's level 1 reads 188, not 128 — which is the light the renderer blends in, so a picture holds its tone as it shrinks instead of darkening: a plane tiled 40× across 256px reads mean 127.5 / sd 127.4 at one level against 187.9 / sd 0.51 filtered. Only minified pixels move; the near half of a receding floor is byte-identical. The per-frame pixel-upload paths keep one level on purpose (Image(and a subscript write re-upload on every frame a pixel changes, and the chain there costs ~0.7 ms/frame at canvas size to smooth a read a full-size picture never makes), as do the pass-through GPU-backed images (camera frame, effects layer) — so a hand-authored texture on a mesh still aliases, by choice. A grazing floor's far band goes from sd 0.51 to sd 8.20 with the taps on, tone held at 187.3 (the counterfactual is the same band of the same frame both ways). The traced export needed no work: its per-hit ray-conewidth: height: premultipliedRGBA: ) ollin_pt_map_lodalready picked a level and had none to read (16 spp: sd 18.2 → 0.51).TextureFilteringTests(11; the reproducibility probes are the ones that caught the global sampler,ParallaxTeststhe parallax footprint; the projected and detail probes each read the decoded picture against the one-level one, which is the only way to see a sampler that reaches no level at all)..parallaxNeverMovesTheSilhouette Docs/3D/3D.md§ When it lands on fewer pixels,Docs/. Wireframe (Drawing/ Images .md wireframe(_:)). Normal maps —Mesh/.normalMapped( _: scale: ) MeshMaterial+.normalTexture normalScale/Mesh.tangents(MeshTangent, aligned withpositions; generated by vendored MikkTSpace,External/, zlib — the glTF-named standard, bundled because matching its exact basis is the point). Load-bearing: the normal-mapped mesh is the textured path's twin pipeline (CMikkTSpace ollin_mesh_nm_vertex/_fragment, anormalMappedPipelineKey variant — never a branch in the shipped textured fragment, the verbatim-plus-twin codegen rule, so unmapped frames are byte-identical by construction); the tangent packs as half4 inOllinMeshVertex's 8-byte tail pad (OllinHalf4: Metalhalf4/ CPUsimd_ushort4bit patterns — stride stays 64), world-space via the model's linear part (a surface direction, not the normal's inverse-transpose; skins pose it with the blended joint matrix); stored handedness is glTF's sign = −fSign — measured, raw MikkTSpace makesfSign·cross(N,T)point along +∂p/∂v (image-down) on every surface while the spec's maps are green-up (image-up), so the ecosystem stores the negation — verified against the Khronos NormalTangentTest/MirrorTest oracles (authoredTANGENTs pass through unchanged); a winding-vs-normals-inconsistent mesh flips fSign (never build a convention probe on one), and a "missing terminator" between spheres at ±x is perspective parallax, not a bug (both cost real debugging); the map samples as data, never color (Image, the raw-bytes twin cache slot — an sRGB decode bends every stored direction);.linearTexture( for: ) finish.normalScale(a claimedOllinMaterialtail pad) is set per batch only after uvs and tangents verify aligned, doubling as the encode and shader gate, with 0 routed down the plain textured pipeline byte-identically (probe-pinned) and a missing basis degrading honestly (geometric normals + noteOnce); shading uses the bent normal everywhere, the geometric normal keeps driving ray/shadow/transmittance offsets; glTF readsnormalTexture(+scale) and authoredTANGENTon both merge paths, generating per spec when absent — but a generation that would split vertices (a mirrored-UV seam) is refused on skinned/morph/part-aligned meshes (their arrays follow the vertex order); mesh rebuilds (welded,subdivided) drop tangents andgeneratingTangents(re-attaches. Example) 3D/(maps authored from height functions); snapshotMaterials/ NormalMaps normal-maps;MeshTangentTests(12: basis pins + the green-direction/transform-bake/scale-0 render probes). Mechanism + the sign-convention record:ARCHITECTURE.md§ Normal mapping.Docs/. Surface maps (the PBR map set) —3D/ 3D .md#normal-maps Mesh/ the.surfaceMapped( metallicRoughness: occlusion: occlusionStrength: emissive: emissiveColor: ) MeshMaterialmap fields: a packed metallic-roughness map (glTF layout: roughness g, metallic b), an occlusion map (r), and an emissive map ×emissiveFactor, all through one pipeline (ollin_mesh_maps_fragmentover the shared nm vertex, the normal-map bend folded in behind its own gate). Load-bearing: per-pixel metallic/roughness reach the shading tail throughmeshLitColorMapped/ollin_pbr_ibl_ambient_mapped, mechanical substitution copies of the shipped tails KEPT IN SYNC BY HAND (the biggest such twin; edit the original, re-copy, re-substitutemat.metallic→pxMetal/clamp(→( float)mat .roughness clamp(pxRough+ thepxAOambient scales — never grow the shipped originals, whose codegen every unmapped frame depends on); the sampled channels multiply (finish × the mesh material's factors × map — the drawer folds the mesh factors in only undermrGate, somaterial(, the new factory, shows a file's maps as authored); occlusion dims indirect light only (flat ambient in the twin, IBL/GI/flat-IBL at the fragment; direct untouched, pinned by a byte-equality counterfactual); emissive adds after lighting, before the atmosphere (a factor with no map routes down the same pipeline against a white stand-in; a black factor with a map emits nothing, the glTF default); mr/occlusion sample as data (.physicallyBased( metallic: 1, roughness: 1)) linearTexture), emissive as color; gates are stored in the finish (mrGate/occlusionStrength/anemissivefloat4, claiming the lastOllinMaterialpads + one appended row) so unmapped frames keep their exact codegen by construction. glTF reads the maps + factors/strength; USD reads connectedmetallic/roughness/occlusion/emissiveColor/normalinputs (an ORM-layout tap reuses the image —USDAssetStorecaches decodes by path so taps compare===— else channels repack at load, untapped = white; factors are carried in tapscale, occlusion strength scale s / bias 1−s, normal strength scale (2s,2s,2,1) / bias (−s,−s,−1,0), each exact; USD normal maps generate tangents post-skinning under glTF's vertex-split guard); the spatial exporter writes every encoding back (reader's stated inverse;usdchecker --arkitaccepts a mapped package, test-pinned). Envelope: primary surface only (reflection hits keep the per-vertex w-slot values; matcap/wireframe ignore the set). A surface glowing in its own color —MeshMaterial(.emissiveIntensity Mesh.glowing(_:)sets it on a copy): the surface-mapped fragment addsintensity × base(the resolved base: fill, base color, vertex color, texture, detail, decals) beside the constant factor, so a vertex-colored mesh keeps each vertex's hue whereemissiveColoris one color a mesh; the gate is stored in the finish (OllinMaterial, a row after.emissiveIntensity emissive;usesSurfaceMapsand the drawer'ssurfaceMappedrouting read it under the constant factor's own uv rule), zero leaves the sum untouched (intensity 0 is byte-identical to no glow, probe-pinned). The tracer addsintensity × albedoafter the base map at every hit as a separateselfEmissiveterm credited whole (the mesh-light table weighs the factor alone, so no next-event strategy competes for this share; unbiased, the copy rule). The USD writer has one emissive slot, so it writesfactor + intensity × baseColorin linear (a material with no intensity writes the factor to the digit) and connects the slot to thevertexColorprimvar reader for a vertex-colored mesh with no other emission.SurfaceMapTestspins the red/blue vertex-colored quad glowing in each hue against a dark control, the zero-intensity byte identity, and the writer's color and connection;PathTraceTeststraces the same quad. Example3D/; snapshotMaterials/ SurfaceMaps surface-maps;SurfaceMapTests(13: loaders/round-trip/validator + the metallic-split, roughness-spread, indirect-only-AO, unlit-emissive, factor-multiply and gate byte-identity probes — the shader sabotages each verified red). Mechanism:ARCHITECTURE.md§ The PBR map set.Docs/. Height maps (parallax occlusion + CPU displacement) —3D/ 3D .md#surface-maps MeshMaterial/.heightTexture heightScale+Mesh/.parallaxMapped( _: scale: ) Mesh: one height map (r channel, data; white = the authored surface, darker carves in — the shared datum, so the shading fake and the real geometry agree) read as per-pixel parallax (linear search + one secant step in the maps fragment — slice-2 code exempt from the verbatim rule, gated on the packed.displaced( by: scale: ) parallaxfinish field so mapless frames keep their codegen; the shifted uv feeds every map sample; height at texture 21,usesSurfaceMapsroutes it) or as real geometry (weld-aware: one averaged normal + height per welded position group, so the flat-shaded generators' coincident corners move together and a uv seam can't tear; smooth normals recomputed over the welded displaced surface, tangents regenerated). Load-bearing: the uv step per unit depth isscale/— the v sign is opposite u's because the stored-handedness bitangent points image-up while v grows down (the slice-1 green-up fact; probe-pinned per axis, sign-flip sabotage fails each independently); march samples use explicite .z · ( −e .x, +e .y) level(0)(the loop's exit is divergent, implicit derivatives undefined); the1/e.zstretch floors at 0.1 (grazing views smear boundedly — the documented silhouette envelope); parallax is shading only — depth, silhouette, shadow rays, and reflections keep the flat surface (coverage-mask-equality-pinned, the teaching contrast withdisplaced); a white map is the exact null (byte-pinned on the same pipeline) andheightScale0 routes down the plain textured path byte-identically; needs uvs + tangents like the normal map (parallaxMappedgenerates them; honest degrade with a note). glTF has no height-map slot (core or ratified extensions) so the map is Ollin-authored API there; USD round-trips it via the preview surface'sdisplacementinput (writer: a tap at scale s / bias −s, the exact spelling of s·(h−1); reader recoversheightScalefrom the channel scale, generates tangents for a displacement connection, and ignores a constant unconnected displacement — no relief in it;usdchecker --arkit-validated). Example3D/(one crater map: parallax / displaced / bare, depth as a live parameter); snapshotMaterials/ Parallax parallax-relief;ParallaxTests(12: direction per axis, silhouette hold, both nulls, weld/datum/seam, USD round trip — sabotage-verified red). Mechanism:ARCHITECTURE.md§ Height maps: parallax occlusion and displacement.Docs/; Guide Ch 28 § Depth from a picture: height maps + HeightRelief figure. Triplanar projection (texture with no uvs) —3D/ 3D .md#height-maps Mesh/.triplanarTextured( _: normal: scale: normalScale: baseColor: ) MeshMaterial(world units per tile; 0 = uv mapping): the base texture (and a normal map) project flat along the three world axes and blend by the surface normal, for the meshes that carry no uvs at all (isosurface/metaballs, growth, subdivision, reconstruction) — no uvs, no tangents, none generated. Runs in the surface-mapped fragment behind a.triplanarScale mat.triplanargate (tiles per world unit in the tail pad parallax left, stride unchanged; the slice-2 branch-freely exemption re-verified empirically: full snapshot suite unrecorded + guide-figures zero churn). Load-bearing: the sampling space is world space, decided (the drawer bakes the model matrix CPU-side; the envelope stated everywhere: abutting meshes continue one pattern, a transform-animated mesh slides through it, pinned bytheProjectionIsAnchoredToTheWorldNotTheMesh; aspace:param can widen later); each axis's u flips with the normal's side so the picture reads unmirrored from either direction (keyed on the normal, not the viewer — the back of a single-sided quad legitimately mirrors, a probe-caught lesson), v runs down the image, each frame right-handed so the normal map keeps its green-up decode; weights are |n|⁴ renormalized; the per-plane normal combine adds the tangent-plane push onto the geometric normal expressed in the plane's frame and multiplies the heights (a flat map returns exactly the geometric normal); samples through its own repeat constexpr sampler (the mesh sampler clamps). v1 carries base color + normal only — MR/occlusion/emissive/height stay uv-mapped (noteOnce), parallax is the technique-level cut (one uv-space march can't follow three projections); constant emissive +material(_:)finish compose. Neither glTF nor USD has a triplanar slot → Ollin-authored API only; the spatial recorder notes and strips the projected maps. Example3D/; snapshotMaterials/ Triplanar triplanar;TriplanarTests(9, the u-flip / hard-pick / top-v / green-direction sabotages verified red). Mechanism:ARCHITECTURE.md§ Triplanar projection.Docs/; Guide Ch 28 § A picture from three sides: triplanar + TriplanarSkin figure. Detail maps —3D/ 3D .md#triplanar Mesh/.detailMapped( _: normal: scale: amount: ) MeshMaterial+.detailTexture detailNormalTexture+detailScale+detailAmount: a finer texture pair tileddetailScaletimes across the base uv in the surface-mapped fragment (the branch-freely exemption again; textures 22/23, both data reads through a repeat sampler). Load-bearing: the color map's neutral is byte 128 in a data read (the sample ×2 multiplies; an sRGB read would put the neutral at ~188, which no author would guess) so a flat-128 map is near-identity andstrength: 0is the exact off switch (the drawer never raises the gates → plain-pipeline byte-identity, probe-pinned); the detail normal blends by Reoriented Normal Mapping (a flat detail hands back exactly the base normal — the identity an overwrite blend fails, probe-pinned) and its branch recomputes the bent normal from scratch (one redundant base sample only when detail is on) so the shipped base-normal resolve stays textually untouched;OllinMaterialgrew 256→272 (detailScale/detailAmountclaimed the tail pads + adetailGatesrow) and theusesSurfaceMapsunion gate isdetailScale > 0, packed only for a verified uv-mapped mesh (never with triplanar; the detail-normal half needs tangents like a normal map, each half degrading honestly alone); no mips like the whole mesh texture path, so extreme tile counts shimmer (documented envelope); no glTF/USD slot → Ollin-authored only, the exporter notes-and-strips. Example3D/Materials/Detail; snapshotdetail-maps;DetailMapTests(sabotage-verified). Mechanism:ARCHITECTURE.md§ Detail maps.Docs/. Decals —3D/ 3D .md#detail-maps Decal(theLightCookieconstruction + keptaspect) + the per-framedrawDecal(: a picture stamped through an oriented box onto every lit mesh surface inside it, composited over albedo before lighting (the stamp takes the surface's own finish), capped at_: at: direction: width: height: depth: roll: opacity: ) OLLIN_MAX_DECALS(8), repeated placements sharing a texture layer, later decals compositing over earlier in call order. Load-bearing: the decal loop lives only in the surface-mapped fragment, and a frame with placed decals routes every lit mesh batch through that pipeline at encode time (wireframe/matcap/grid keep their own) — no shipped fragment grows, so a no-decal frame is byte-identical by construction (a decal-carrying frame shading plain meshes through the maps fragment is the feature's own envelope); solid meshes use the nm vertex safely becauseOllinMeshVertex()zero-fills; the CPU builds each world→unit-box transform once (Drawer.placeDecal, the cookie projector-frame convention, +y in box space = the image's top); the composite is premultiplied with one scale on both halves (fades can't fringe the edge), a facing fade melts the stamp off edge-on surfaces instead of smearing it, and a depth-end fade keeps the box's far planes from hard-clipping; the list is carried in its ownOllinDecalsuniform (fragment buffer 2, count-gated) beside a content-hash-cached sRGBtexture2d_arrayat texture 24 (shapingStandIn()when empty); reflections show the undecaled base, fields/particles/point clouds sit outside by design, and the spatial exporter notes placed decals stayed behind. Example3D/Materials/Decals(declaresloopDuration); snapshotdecals;DecalTests(placement pinned against a drawn marker at the same world position; sabotage-verified). Mechanism:ARCHITECTURE.md§ Projected decals.Docs/. Cast shadows —3D/ 3D .md#decals castShadows()/noShadows(): directional/spot via a 2D shadow map; point ray-traced on an RT GPU (inlineintersection_querybehindOLLIN_RT_SHADOWS), else a mid-point cube; rect/disk area panels ray-traced on an RT GPU, else a spot-style 2D map (the Area cast shadows rules above);shadowQuality(_:)maps hardware-relative ray counts.castShadows()alone is the whole ask for an area caster too:AreaShadowTests(2) reads the floor under three spheres against the same set unshadowed and finds the panel's shadow at the default count as deep and as wide as at 48 rays a pixel (mean 62 against 122 unshadowed on the M2, within 2 levels for every count from 2 to 48, and only a single ray reads deeper, having no penumbra); an explicitshadowSamplesis for a picture that must match across machines, which is why the Guide's softbox figures name one, never for the shadow to show (a figure had read as needing it when its panel was throwing onto floor the camera could not see). More than one caster per frame —OllinLighting+.shadowCasters[4] shadowCasterCount(theOllinShadowCasterstruct, stride 112) beside the single-caster fields, which mirror slot 0, so a one-caster frame is byte-identical. Every dependent system follows the whole list, each paying only for the casters a frame declares: the fog march taps each 2D caster's own layer, the contact pass marches once per caster and writes each factor into the mask channel its slot names (the mesh fragments then read channelcs), the SSS transmittance reads each caster's own layer / cube / traced thickness (meshRTThicknessAll, themeshRTShadowAllshape), the marched fields cast a channel per point/RT caster (meshFieldShadowFactorreturns afloat4, and the half-res pre-pass carries all four), a field carrier marches its self-shadow toward every caster and receives each one's map, cube, or trace, and the GI probe pass traces occlusion for each. Two exceptions, both deliberate: caustics emit from the primary alone (a frame's photon budget is fixed, so splitting it between lights only makes each pattern noisier), and the path-traced export reads no caster list at all, since it shadows every light physically (which also means acastsShadow: falsefill does throw there — an open question, seeDESIGN-NOTES.md). Pinned byEveryCasterRenderProbes(6 probes, each verified red with its own fix removed). Slot 0 is the primary caster and keeps the old priority (directional → spot → point → rect/disk); the rest fill slots 1+ in declaration order. A 2D caster's map layer is its slot index, so the shadow map is adepth2d_array(allocated at exactly the frame's caster count, a fresh texture when it must grow) and layer 0 is a constant for whatever still reads the primary; a cube/RT primary just leaves layer 0 cleared. One pass per 2D caster (depthAttachment), each with its own.slice lightViewProjection— the marched fields render into every one. A point light casts from any slot. The cubes are atexturecube_arraywith one cube per point caster (OllinShadowCaster, ranked in slot order, so a cube primary is always cube 0), all rendered in one layered pass whose vertex adds a per-caster.cubeIndex cubeBase(vertex buffer 3) to its face; the array is sized to the frame's cube count, never the caster cap, because a cube costs 50 MB at the shipped 1024 resolution. A ray-tracing device instead traces every point caster against the frame's one acceleration structure:meshRTShadowAllreturns afloat4of per-slot factors and the shading tail readsrtShadow[cs](slot 0's value and its ray count are the single-caster fields, so a one-caster frame is byte-identical). Two consequences that are easy to get wrong: the structure is now bound whenever any caster traces, so both sites that flipshadowKindto 2 must ask whether the primary is a tracing kind (shadowKind == 1 || casterGPUKind >= 3), or a directional key beside a traced point light loses its own 2D map; and one structure serves them all, so an area primary beside a point caster takes the built one rather than building a second.finalizeShadowCastersdrops any extra caster whose own resource (map layer, cube, structure) was not produced. A tube never casts; the cap is 4. The rasterized mid-point cube is the fallback a GPU without render-stage ray tracing takes, and it is the one 3D path an Apple-silicon machine never runs, so it has to be forced to be seen:OLLIN_NO_RAY_TRACING=1answers "this device cannot trace" (MetalRenderer, read by both the renderer init and the shader compile that sets.rayTracingAvailable( on: ) OLLIN_RT_SHADOWS), andCubeShadowTestsruns its probes under it (also unasked on a GPU that genuinely cannot trace). A pass that traces its shadows alone leaves the reflection paths out (PipelineKey;.tracesShadowsOnly kOllinReflects, function constant 18, read inollin_rt_reflectsbesidekOllinTraces): the traced reflection and refraction paths are most of what the software traversal costs a lit fragment, used or not (a point light's traced shadow at four rays, 1080 squared, on an M2: 153.5 ms with them compiled in, 11.3 ms without; one ray, 73.2 against 6.6), so a pass with a structure to cast against and none to reflect in (reflectAccel == nilinencode,lightingin the field's own pass) builds its lit fragments without them. Same picture to within one level in a few pixels (two compiles of one arithmetic). A field beside a traced shadow costs 1.07 times a mapped one, and twenty times only in a frame that traces reflections..rtReflections == 0 UntracedPipelineTestsreads which build each pass picks and compares the pictures;aBuildThatTracesShadowsAloneReachesFewerRayQueriescompiles both builds offline and fails when a reflection path skips the helper. The live window keeps tracing on an M1 or M2 (ruled 2026-11-17, at 11 ms a frame against a map's 2.8).Scripts/is the number to read again before a default is decided on a cost: it had read 88 frames a second in June, and nothing ran it until it read 6. A pass that traces nothing draws through pipelines that cannot (benchmark .sh shadows PipelineKey;.untraced kOllinTraces, function constant 16 inOllinShaderLib;.metal ollin_rt_reflectsinShader3D.metal): a GPU that traces in software has the traversal compiled into every fragment that can trace, and that fragment pays on every pixel whether a ray is traced or not, so the five lit fragments (PipelineKey: the four mesh fragments and the field's) are built a second time with the constant false, where every traced path folds away, and a pass handed no acceleration structure (.tracingFragments traceAccel == nilinencodeand inencodeRaymarchHalfRes) draws its lit kinds through that build; a pass with a traced caster or traced reflections keeps the traced one and its cost, for every lit kind in it (a field beside a mesh under a casting point light or panel still pays the twentyfold and can still run into the hang check; a field alone under a point caster builds no structure and takes the untraced build,aFieldAloneUnderAPointCasterTracesNothing), and a device that cannot trace has one build and never sets the flag. Measured on the M2 (November 2026): a lit mesh filling 1080² 43 ms to 3.9 ms (57 to 5.2 physically based under an environment), a 15-node field at 270×480 170.8 ms to 8.9 ms, and the 31-node field whose one draw the GPU reported as a hang 27 ms; the GPU's offline translator writes 2.3 MB and 3.7 MB of code for the two fragments with the traversal and 0.18 MB and 0.43 MB without. The rules that keep it: every read ofrtReflectionsin a lit fragment goes throughollin_rt_reflects;meshRTShadowOneandmeshRTThicknessAllreturn before tracing when the constant is false; and only the lit fragments and helpers reached from them alone name the constant, since a function that names a function constant builds only throughfragmentFunction. A traced path that does not ask the constant puts the traversal back in the untraced build and no picture changes to say so, which is whatUntracedShaderTestsis for (the gates read off the sources, and the library compiled to LLVM text by the Metal front end with the constant false, where no lit fragment may reach a ray-query call through anything it calls while the five passes that trace on purpose still do; skipped without the Metal toolchain). Code size is not the measure: a traced shadow left in adds 48 KB.UntracedPipelineTests: which build each pass picks (the reduced march's own pass included), the same pixels from both builds, and Metal's binding list (the untraced build uses no acceleration structure). What the GPU refuses is too much work in one tile of a pass, not a slow frame: a 64-capsule field at 1080×1920 drew twenty frames at 1.42 s each, while the frame that hung was about half a second over 135 tiles; by a CPU count of the march priced at each run's rate, the busiest tile that has drawn clean carried about 8.5 ms and the one that hung about 16 ms, and a tile's work is its pixels × steps × nodes whatever the resolution, so a field near the node limit under a shadow is still past what has drawn clean and was not run (the bounded passes are ahead,DESIGN-NOTES.md§ 3D mode). One ray query to a fragment (OllinRayQueryinShader3D.metal): every tracing helper (the shadow factors, the thickness walk, the reflection trace and its bounce chain, the refraction walk) takes its caller's query, resets it for its own ray, and reads what it needs out of it before anything traces again, and only a fragment makes one. A helper that made its own added a query to every function it is compiled into, once per call site, so the four lit mesh fragments held 41 queries each and the field march 40, and a GPU that traces in software locks on such a fragment as soon as one of them runs, where the passes holding one to ten traced the same scene (found on the M2, November 2026: every frame with a traced shadow restarted the GPU; with one query the same frames render, and the reflection and refraction figures are pixel-identical before and after).RayQueryCountTestsreads the shader sources and fails when a helper makes a query (verified red by planting one); the compiled count is read offline by compiling the composed library to LLVM text with the Metal compiler and counting the calls that allocate an intersection query, per entry point, through the call graph. Traced shadows alone switch off on a device that traces:OLLIN_NO_TRACED_SHADOWS=1(MetalRenderer, read once at init) sends each point and area caster through its rasterized map while reflections, global illumination, caustics, and the traced export go on tracing; it is for a machine whose GPU cannot be trusted with traced shadows. Each frame cast that way is counted (.tracesShadows OllinApp), which is how a drive that needs the traced picture learns it did not get it: under the switch the figure runner skips a figure whose source casts such a shadow before it renders (.tracedShadowFallbacks sourceCastsTracedShadow), and one the count catches afterwards, by name, leaving its image and its cache entry alone and counting it neither rendered nor failed nor moved;Scripts/test.shgoes further and turns ray tracing off for the run, so every test gated onSnapshotreports as skipped. Both say so at the top of the run, so a green run is never read as covering the traced paths..hasRaytracing TracedShadowSwitchTests(2, the switch off on a renderer of its own, so nothing in it traces a shadow). Three invariants, each found broken and each verified red by sabotage: the face projection's y row is negated — the six face views use the standard cube-face basis, written for a bottom-left framebuffer origin, while Metal's is top-left and a cube face is addressed top-left in both, so rendering them unchanged stores every face upside down and mirrors every shadow to the wrong side of its light (ualready agrees, so only that one row moves); the far plane is fitted to what the light reaches, in the renderer, not to the camera's framing radius (pointCasterFartakes the farthest corner from the light ofpointCasterBounds, +2%, carried to the fragment byMetalRenderer, keyed per casting light, and applied in.pointShadowFars finalizeShadowCasters; the scan runs once a frame and is shared by every point caster) — the packing's camera-derived guess clips a caster further from the light than the camera is straight out of the cube, so it lights up and throws nothing. Every caster kind is in that bound, including the ones with no vertices to scan: a plain mesh contributes its own vertices, an instanced batch carries its base mesh's local bounding sphere through each placement matrix, and aMeshFieldanswers with its cachedlocalBounds()(each copy's sphere through its own matrix, stretched by the matrix'slargestColumnScale— the conservative world sphere the cull kernel takes, so a copy is bounded here exactly as it is bounded there) transformed by the draw-time matrix. A frame drawn entirely from copies therefore fits like any other, where before it had nothing to fit to and every copy past the guess threw nothing. The one caster that still leaves the guess as a floor is a compute-written placement buffer, whose matrices never come back to the CPU by design (CasterBoundsreports it); the offset, bias, and tap spread are worked out at the receiver (.complete 2·d/, the resolution now in the shared header for exactly this), with the depth bias scaled by the tangent of the incidence angle, capped at 12, and sized for the whole 3-texel tap spread — a flat bias measured where the camera looks leaves a grazed floor combing itself with rings, while a surface square on to the light has a tangent of zero and the figure it always had (the normal offset stays flat on purpose: moving the sample is what notches a box's bottom corners). Past the far plane a receiver reads lit, the same envelope the 2D casters state for a receiver outside their fitted frustum. On the M2 the whole cube path is inert, so all of it is snapshot- and figure-neutral (2201 tests, 49 probe figures unmoved); measured against the traced picture of the same scene, the fixed cube path sits at a mean 0.34–0.40 per channel where the old one was visibly wrong. Per-light opt-outOLLIN_POINT_SHADOW_RESOLUTION Light.castsShadow/castingShadow(_:)/ thecastsShadow:argument on every factory and bare call — the curatedLightingPresetrigs set it false on every fill and rim, which is what keeps.standard/.studio/.threePointscenes rendering exactly as before (the Guide's 26 3D figures and 209 snapshots pin it). The lit mesh loop resolves a light's slot by scanningshadowCasters, andcs == 0gates the primary-only terms (rtShadow,fieldShadow,meshFieldShadow); a field carrier takes the primary alone (it is in no map). Renderer-side facts settled aftermakeLighting(the traced flip, ray/tap counts, whether a map was produced) are carried back byfinalizeShadowCasters. Example3D/;Lighting/ ManyCasters MultipleCasterRenderProbes(3 probes, sabotage-verified red) + 10 packing tests inLightingTests;PointCasterSlotTests(3 probes reading the same band with and against the caster, so they run on the traced path and underOLLIN_NO_RAY_TRACING=1alike; the two feature probes verified red by sabotage, which read exactly equal both ways, the signature of a light that throws nothing); Guide Ch 27 § Two lights, two shadows. Soft (PCSS) shadows —shadowSoftness(_:)(0 hard → the legacy 3×3, byte-identical; 0.5 default contact-hardening; 1 very soft): blocker search → penumbra estimate → Vogel-disk PCF (shadowFactorPCSS, the Fernando/NVIDIA technique); the penumbra ratio must be formed in light-linear depth (a spot map linearizes via the projection's[2][2]term — details in ARCHITECTURE.md); the one parameter also drives the RT point caster's area radius (the 0.5 default reproduces the old look,point-shadowsbyte-identical); 2D taps viaresolveShadowTaps2D(export →.detail); soft-by-default measured sub-tolerance, so no snapshot re-records (the SSAO silhouette-AA precedent). Contact shadows —contactShadows(/length: ) noContactShadows(), per-frame state refining whichever castercastShadows()resolved (every caster kind, any Metal GPU): a depth pre-pass re-renders the solid canvas meshes from the camera (the.meshShadowpipeline fed the camera's jittered VP, the scatter-mask filter), then a fullscreen march (ollin_contact_shadow, ShaderCombine) walks each pixel's projected (uv, z) segment toward the caster and the mesh carriers sample the mask (fragment texture 16) into the samemeshFieldShadowmultiplier the marched fields use, someshLitColoris untouched. Load-bearing, each a probed defect or a production-reference rule: the ray start is pulled 0.002 of the eye distance toward the camera (the no-normals self-occlusion guard; without it a static speckled crescent forms along every lit silhouette) and the occlusion test is a band around a threshold derived from a same-length view-axis ray's own device-z span scaled bymax(0.07, 1/steps)(slope- and density-aware, so a thin edge can't streak); a first-hit binary verdict + static interleaved-gradient-noise start dither (the dither rule; the production reference's own TAA-off configuration) + a clip-space vignette fade;lengthis world units, nil = 2.5% of the eye-to-target distance (packed inmakeLighting's framing block; the renderer zeroes the gate when the pass didn't run, so off / no-caster / targets / accumulation are byte-identical, suite-verified); steps = 8/16/32 byeffectiveQuality((the TAA no-per-feature-parameter rule; measured M2 release 1080²: the whole term ~1.0 ms GPU); the envelope is the screen (off-screen geometry casts nothing, a curved surface picks up a little extra shading inside its silhouette, only the casting light dims; fields and target-drawn meshes sit outside the march by design). Example.default) 3D/; snapshotEffects/ ContactShadows contact-shadows;ContactShadowRenderProbes(sabotage-verified) + theLightingTestspacking trio.Docs/; Guide Ch 27 § The seam under a resting thing: contact shadows + Seated figure. Ray-traced reflections (3D/ 3D .md#contact-shadows rayTracedReflections() — a physically-based metal reflects the actual scene (off-screen geometry included, no SSR contact-streaks), the hybrid-rendering approach written from the technique (Apple's WWDC21 session + Metal sample). It integrates into the IBL specular, not a post-process (the traced hit replaces the prefiltered env sample; a miss shows the sky), with two-bounce, metalness-aware hit shading — the second trace is load-bearing for mirror corners: an unoccluded env sample at the first hit pipes the HDRI's bright floor through as a razor-thin streak no AA can remove (a real fixed bug; dead ends recorded in ARCHITECTURE.md) — and grazing-widened env lobes () ollin_rt_env_lobe), into which a rough hit fades its own traced bounce (smoothstep(, the primary surface's rule, so a matte floor reads matte in a mirror and through glass instead of turning into a second mirror; the miss branch already is that lobe, and a hit below the ramp is untouched, so the near-mirror snapshots didn't move). It reuses the shadow-caster accel (per-geometry offsets buffer;0.12, 0.55, s1 .rough) encodeShadowPassdecoupled so the accel builds when shadows or reflections are active), gated byOllinLighting→ byte-identical when off; every solid mesh is reflectable; needs an environment + an RT GPU, off-by-default, non-RT → no-op. Reflection AA is deferred + stochastic: live temporally accumulates (an.rtReflections SSRHistorySlottwin,statefulEncodeIsRepeat-guarded); headless/export instead averages N deterministic in-frame rays (4/8/16 by tier — historyless, so no warmup and video exports can't flicker; snapshotrt-reflections-3dre-recorded once, supersampled). Load-bearing: render targets + the raymarched fields keep the inline single-ray trace (a thin wrapper over the shared hit shade, so the paths can't drift), and no roughness-cone jitter without a spatial denoise stage (a stochastic cone reads as sparkle on brushed metals). Chain length is a parameter (reflectionBounces(, persistent, clamped 2…8, packed as_: ) OllinLighting): 2 is the shipped nested pair and stays byte-identical (the branch is.rtReflectionBounces > 2, so a default frame runs the prior instructions — the 52 figure probes and the three RT figures re-render identical), and past it a separate forward walk (ollin_rt_specular_tail) carries a throughput rather than nesting, since Metal has no recursion. The pair keeps its nested form on purpose: forward accumulation has to distribute itsmix(intodeeper, lobe, blend) blend·lobeadded now plus1 - blendcarried down, which is the same number in exact arithmetic and not the same order of operations. Each step is one more closest-hit ray per reflected pixel; the walk ends at the env lobe when the budget runs out (a truncated chain reads as a dimmer image, never a hole), and the refraction walk shares the shade, so traced glass gets the same depth. A rough surface's reflection is a traced lobe rather than a mirror ray (glossyReflections(), persistent, off by default, packed asOllinLighting= the 0.75 roughness ceiling; 0 = the shipped mirror path, verified byte-identical by a clean-HEAD counterfactual on two RT scenes): each ray leaves along a microfacet drawn from the visible-normal distribution (Heitz's routine,.rtReflectionGloss alpha = rough²), the trace writes the ray beside its radiance on a second attachment (direction + hit distance, so the pass is MRT either way and one fragment serves both paths), and a resolve gathers its own ray plus 7 neighbors on a 1.25-texel ring, each weightedD_local(and normalized by the summed weights, not the count (the ratio estimator: unbiased under differing roughness/normals, and it absorbs any constant). Two properties fall out of the weight rather than a rule: a mirror gives an off-lobe neighbor ~0 weight and stays sharp, and a rough pixel spreads over the whole neighborhood. Path roughness regularization is load-bearing and it is applied at every surface along the chain (H)·NoL / pdf_neighbor minRoughthreaded throughollin_rt_reflection_trace→ollin_rt_hit_radiance→ollin_rt_specular_tail, defaulted 0 so the mirror path folds it away): a ray from a rough surface stands for a cone, so a satin floor looking at a mirror ball otherwise reads its pinpoint light back many times brighter than the ray beside it — white speckle. It travels at full width; a fraction was measured and leaves the speckle in (example floor grain 1.53 → 0.82). Lobe truncation was tried and rejected (the published answer to tail noise): measured against a 256-ray reference it is quieter and less right (2.4% error unbiased vs 4.5% at bias 0.4, where the feature off is 7.0%) — that trade was made for a one-ray budget, and this path spends more. Live = 1 ray/frame → resolve → the temporal EMA, whose history guard is a variance-clipping box, never a min/max clamp (mean ± γσ over a 5×5 window, γ and the blend set by the pixel's own reprojected motion, clip on the color channels only: a min/max box holds the live floor at single-frame speckle forever, a 3×3 window reads σ 0 between the sparse fireflies and crushes the history to a point, and alpha's near-constant channel would drag the rest through the clip's shared scale); export = the trace+resolve pair run 4× the mirror tier's rays (16/32/64) accumulated in-frame by ping-ponged targets, since the ray layer holds one ray and cannot describe an inner loop's N. The G-buffer's roughness ceiling widens from 0.55 to the gloss ceiling (aconstant floaton the G-buffer fragment) and the composite fades over[0.8·ceiling,instead ofceiling] [0.12, 0.55]; both gates protect the hand-back, so a test only reads red with both removed. Example3D/(its satin row), snapshotEffects/ RayTracedReflections glossy-reflections,GlossyReflectionTests(6, each verified red),Docs/, Guide Ch 34. A hit is shaded in its own finish (3D/ 3D .md#glossy-reflections OllinRTFinish, stride 208, one record per geometry then one per copy slot): the stylized shading models (toon cel bands, the Gooch warm-cool ramp, which replaces the ambient as the primary path does) plus the two light-independent layers that apply on top of any model (the Fresnel rim, the fake-subsurface wrap), so a surface reads in a mirror the way it reads head on, where before every finish reflected as the plain diffuse body underneath it. Load-bearing: the records are stored in the hit table's own buffer past a four-word-aligned base named in its two-word header (no tracing entry point gains an argument — the rule the hit records already follow), and the block is written guarded by that base rather than by the flag that set it (a block written at offset 0 lands on the header it is reached through, which is how the first sabotage read as a run-break artifact); a compact record is also the run-breaking key, so a geometry is finish-uniform without two batches breaking over something the trace ignores, and a frame with nothing stylized to say writes no table, no extra break, and the shade it always ran (zero base = the gate). A surface's picture rides in the same record (base, the texture's GPU resource ID, with the gate and the wrap incool.w): a mesh drawn with a picture writes the table and breaks its run on picture identity and wrap; every record names a picture (the white stand-in when it has none, since a handle is read whole even behind a closed gate); a hit multiplies its albedo by the picture at its interpolated uv, at full size for a walk that passes no cone and at the footprint's level for one that does (below). A layer's picture is drawn after the traced scene is built, so its record keeps the gate down in the table every earlier pass reads, and the main passes read a blit copy with the handle filled in (tracedPictureTable, right afterencodeEffectTargetsin all three render paths; a blit because the hit records of copies a kernel places are written on the GPU earlier in the frame), so no pass reads a texture it was not made resident for (useTracedScenemarksrtMapTextures) or one not yet drawn. Copies and triplanar pictures carry none, and the path-traced build never raises a gate (the picture's or any other map's) (its kernel calls the same fetch and then applies every map from its own table, so a raised gate multiplied the picture twice and read a triplanar one by uv, whichPathTraceTestscaught)..aTriplanarMeshKeepsItsProjectionThroughTheTrace TexturedReflectionTests(a layer's and a loaded picture against the same floor filled in the picture's colors, within 2 levels; five plants red: no multiply, one corner's uv, the layer copy skipped, the loaded stamp skipped, no run break). A reflected or refracted hit reads the surface's other maps and its glow, each at the ray's footprint (ollin_rt_fetch_surface(,..., cone) ollin_rt_cone,ollin_rt_sample_mapinShader3D.metal). The record carries the gates (maps: the normal map's strength, the metallic-roughness gate, the occlusion strength, and the address mode they share), the composed factors a metallic-roughness map multiplies (factors.xy: the vertex slots hold only the drawing-state half), the emissive factor (glow) withemissiveIntensityinfactors.z, and three more handles; the emissive map and its gate were already there for the probe trace (coat.z), and are written whether or not the frame bounces light. The three value maps are bound through the picture's linear view (linearTexture(for:), the raster encode's own split): through the color view a normal map decodes bent, whichaNormalMapsReliefShowsInAMirrorcaught on its first run. A gate whose texture does not resolve when the table is written comes back down, a layer drawn as one among them. A cone opts a walk in:float2(-1)(the default) is the fetch as it was, the picture alone at level 0, which the shadow tint, the probe trace, the caustics trace, and the path tracer keep; the reflection trace, its second surface, the tail, and the three refraction walks passollin_rt_cone(a pixel's width at the ray's origin, widening by the pixel's angle and by4 x roughness squaredfor the lobe a glossy ray was drawn from) and carry its width on down the chain. The pixel's angle isOllinLighting(above zero an angle, below zero minus an orthographic pixel's width, zero unknown and full size), measured from the projection matrix in.cameraPosition .w encodeLightCull, the one call every render path makes with its render size ahead of everything that shades, and held on the drawer (tracedPixelCone) because the drawer has no render size of its own. The level is the path tracer's formula: half the log of the triangle's uv area over its world area, plus the log of the footprint over the arrival cosine, plus half the log of the map's own size; no curvature term. A bent normal that faces away from the ray is refused (the hit keeps the triangle's own), since it would shade the surface's far side. The glow is display-linear and takes the divide by the exposure the direct terms take (ollin_rt_glow), added under the layered lobes at the first surface, at the second, and down the tail; occlusion multipliesollin_rt_ambient. A frame with none of it writes zeros (or no table) and shades as before: the reflection, glass, bounce, and stylized-hit suites pass unrecorded. Measured (one-texel checks, a loaded 512-pixel picture on a floor seen in a mirror at 256 px): read at full size the mirror's image spread 3.25 levels and changed 4.34 levels a pixel for a 0.004 move of the camera; at its footprint 0.51 (the dither's floor) and no change. A picture authored pixel by pixel has one level, so its read lands on full size whatever the footprint.TracedHitMapTests(6: the relief against the floor's own tones, the finish map against the same floor by factor, occlusion, the three glows, the shimmer, determinism; seven plants red on their own statements).Docs/,3D/ Combining .md Docs/. The two layered physically-based lobes are carried in the same record (3D/ 3D .md#rt-reflections ollin_rt_layer_lobes, applied at the first hit and at the pair's second surface, in the primary shade's own layering order): the sheen keeps the environment sample (its lobe is wide enough that the prefiltered environment is the honest integral) while the coat reuses the radiance the trace already found along that surface's mirror direction, the single-trace tradeoffollin_pbr_ibl_ambienttakes; the sheen's directional albedo comes from the same LUT the primary reads, so the trace carriers bind it at texture 12, the slot everymeshLitColorcarrier already uses. Out of the trace, and it is one rule not a list: a traced hit computes no light highlight at all, so the standard model's Blinn-Phong, the coat's own hotspot and the sheen's, and a panel's stylized highlight and subsurface wrap all stay with the direct view; iridescence and sparkle need their own fields; the deeper surfaces of a bounce chain keep the tail's plain shade; andMaterial.scattering's diffusion cannot reach a mirror at all (a screen-space pass over the primary buffer).StylizedReflectionTests(7: the mirror-holds-the-sphere control plus toon / Gooch / rim / subsurface / coat / sheen, each against the same material minus its stylized part so the reading cannot come from the roughness a non-PBR batch bakes from its specularSharpness, and each verified red by the feature-off sabotage at a residual of exactly 0.0); the measured band must clear the object's own raster entirely (a difference map against the control is what finds where it ends).ReflectionBounceTests(4, each verified red by its own sabotage: the tail disabled, a default of 3, the clamp dropped) over a two-mirror corridor probe; no snapshot (the default may not move).Docs/. Mechanism:3D/ 3D .md#rt-reflections ARCHITECTURE.md§ 3D lighting and environments + § Deferred ray-traced reflection AA. Global illumination (globalIllumination(/_: intensity: ) noGlobalIllumination(/) globalIlluminationQuality() — real-time diffuse bounce via a re-traced probe field (the DDGI papers, written independently;_: ) ShaderGI.metal+encodeGIPass): a probe grid auto-fitted to the mesh geometry's AABB (per-axis counts adapt to the fitted volume's aspect under a fixed 512 budget, axes clamped 2…16, derived at fit time bygiAxisCounts' smallest-isotropic-spacing search and held with the volume — a cube keeps 8×8×8, a flat scene spends 16×2×16; the grid is laid so the scene's bounding faces sit half a cell inside the outer probe planes (giFitVolume: on an axis with three probes or more the raw extent spans two cells fewer than there are probes, so no face sits on or a hair off a plane, which put a ragged dark seam on a room's open end, a row of probes at the walls' front edges flipping in and out of the visibility test; a two-probe axis keeps the 15% pad;GlobalIlluminationTests); atlases allocate once at budget capacity so a refit never reallocates; the bounds fold over the same batch walk as the accel, target-drawn meshes included, so a scene drawn entirely inside a render target still gets a field), each probe an 8×8 octahedral irradiance tile + 16×16 distance-moments tile (1-texel gutters recomputed in-pass by octahedral wrap), traced per update with a rotated spherical-Fibonacci fan against the shared accel and sampled by every lit carrier (textures 13/14/15) through trilinear × soft-backface × Chebyshev weights from a self-shadow-biased point. Load-bearing: under an environment the probe sample replaces the IBL diffuse irradiance (probes integrate the same sky, occlusion included) and specular is untouched; probes store E/π in perceptual gamma 5 (sample = pow 2.5 per probe, square after the blend, the irradiance-cube-compatible convention); hit shading traces one visibility ray to the casting light (else bounce leaks through the wall whose shadow the direct pass draws) and adds the previous update's field (multi-bounce by recursion, packed at intensity 1 so the artistic dial can't compound); never.theFittedGridPutsEveryFaceMidCell mixtoward an unread history (0·NaN poisoned the whole field, a real first-render bug), visibility moments cap at 1.5× spacing (uncapped far geometry collapses near-surface variance into hard dark blobs), and probe relocation is not optional (wall-slab rooms park whole probe rows inside the slabs; the relocate pass walks them out via backface statistics, the sign of a surfel's stored depth); relocation statistics read the fixed, never-rotated fan (the surfel texture's first 32 columns, distance-only; the blends skip them — fed the rotated radiance fan instead, its thresholds flicker and a probe near one oscillates between positions, visibly pulsing every surface its cage touches, a real live defect isolated by freezing relocation) and a comfortable probe drifts back toward its grid anchor with proposals committing only inside the 0.45-of-spacing ellipsoid; the live irradiance blend's temporal-response pair is asymmetric and live-only (a darkening past 0.25 cuts hysteresis by 0.75, a brightening past 0.10 luminance is rate-limited to a quarter step — with a sun disc in the fan a bright spike is estimator variance to absorb, not news to trust, and un-limited it pulses a sky-lit scene's whole field; headless skips the pair so its iterations converge an unbiased progressive mean — both live stabilizers are verified by live frame-diff measurement, not tests, the artificial-life honesty rule); live = one hysteresis-0.97 update/frame into ping-ponged atlases (statefulEncodeIsRepeat-guarded, volume held until bounds escape it;beginStatefulEncoderuns the frame-scoped reset ahead of the GI pass, which precedes the effect-target encode), headless/export = per-frame refit + whole iterations in two phases, a burn-in whose updates replace the field so the recursion reaches its depth, then averaged updates under a progressive-mean hysteresis (6+6 / 10+8 / 16+12 by tier; a mean from the first update weighed the shallow first fields with the deep ones for good, and a light room read 0.77 of a 64-deep trace), with iteration-indexed seeds → byte-deterministic; an exact tie is settled by a fixed order, in every walk (ollin_rt_query, the one closest-hit query: the reflection's two bounces and its tail, the refraction walk, the probe traces, the caustic photons, the path tracer. Two faces at one distance, a ray through the edge where a solid's side meets its top, a ray leaving one piece of a cut solid and entering the next, two solids in one place, were committed in whichever order the traversal reached them, which changed from render to render: a lit face a level apart in 12 of 35 frames of a peer's fractured cube, and under a traced reflection six pictures in six runs of a glass block cut into touching pieces, 7,396 pixels up to 177 levels apart. Every candidate is reported, the strictly nearer kept, a tie to the back face and then to the surface drawn later (the higher instance, geometry, and primitive, which is the one the rasterized view shows at equal depth, so a mirror shows what the eye sees), and a ray with no tie commits what an opaque traversal did. Cost on the M2 at 1080 squared: a frame's queries 2.4 ms to 3.7 of 53 with eighteen solids over a mirror, about 16 ms to about 30 of 127 with four hundred and ten; a second short query around the first one's distance was measured no cheaper. A new walk traces throughollin_rt_query; the subsurface thickness keeps a traversal of its own because it reads the distance alone, andTracedTieTestsfails on any other..everyClosestHitWalkSharesTheOneQuery TracedTieTests,.ofTwoSolidsInOnePlaceAMirrorShowsTheOneTheEyeSees LightingInvariantTests, and the.touchingPiecesBounceTheSameLightEveryTime Touching,CutGlass, andDoubledcases ofcheck-determinism, each red with the opaque traversal planted back; the mechanism and the measurements are in.sh --selftest ARCHITECTURE.md); rays/probe and the headless iteration count resolve through the persistentglobalIlluminationQuality(tier (the_: ) shadowQualityshape; the probe grid deliberately never follows the tier — a tier-driven grid would move the probes and light an export differently from live); traced mirror interiors and render targets gather too: the shared hit shade (ollin_rt_hit_radiance) swaps its irradiance-cube diffuse for a field sample at the hit, pre-divided by the IBL exposure (the whole traced radiance re-scales by it on composite), atlases bound into the deferred trace pass and threaded throughollin_pbr_ibl_ambientinline, and targets take the field viaencodeEffectTargets(— distinct from the flat-pastel-blobs dead end, which was about the specular secondary; RT devices only (no-op otherwise), byte-identical when off (suite-verified;gi: ) gi-3dre-recorded once for the adaptive grid); what a hit gives to the bounce follows its finish (ollin_gi_shade_hit): its glow (the emissive factor plus its color timesemissiveIntensity, read off a per-slotOllinGIGeotable the accel build fills beside the caustic one, indexed by the hit record's slot, the build breaking a run where the record changes), the direct light and the previous field through its lobes by the path tracer's parity rule (a physically based finish through the microfacet BRDF, the body over π weighted by what the lobe leaves over and the GGX lobe with its multiple-scattering share from the split-sum table, which the pass bakes when no environment has; every other finish the un-normalized Lambert the raster draws it with), so a metal throws its own color along its lobe and a physically based wall bounces what it is lit with (it bounced π times its share before); an emissive map glows by its map (ollin_gi_glow_map: the handle rides in the RT finish record's second texture slot, gated bycoat.z=uvWrap + 1, the record written whenever a GI frame draws a uv-mapped glow map, the accel run broken where the map changes; a triplanar mesh, a copy, and a same-frame layer keep the factor;LightingInvariantTests, a half-black map at 0.5 of the white panel's bounce in the field as in the trace); a lobe narrower than an irradiance texel is widened to it at a probe hit (.anEmissiveMapGlowsByItsPatternInTheBounce OLLIN_GI_MIN_LOBE_ROUGHNESS0.5, path regularization: a polished copper floor threw 0.085 of the trace's copper onto the ceiling, its lamp spike slipping between the rays and the encoded blend crushing the rare hits, 0.84 after with the rest spread onto the walls;aMetalFloorThrowsItsOwnColorIntoTheBounce(); a surface's read is carried back to the surface (roughness: 0.1) ollin_gi_sample_volume): the weights stand a read at the row inside, up to a cell in front of a wall, ceiling, or floor (a ceiling read 1.12 to 1.21 of a 64-deep trace), so the irradiance blend stores each texel's dimming slope in the atlas's alpha (ollin_gi_probe_slope, a second read of the previous field a cell along the texel's direction, in reciprocal light, dimming only, trusted while the probe's stored distance along that direction reaches the second read and every probe around it sees it) and the read divides by 1 plus the normal's share of the offset times the weighted slope, at most halving (0.99 to 1.03 after; the room's mean error by region 15 to 17% to 4 to 8%, the sphere's underside and the floor under a table at 1.26 to 1.35, occlusion finer than the grid, a little better than before). The second read is never per pixel: taken per fragment it cost 7 ms a frame in a 1080 room (12.4 to 19.5), baked in the blend about 1 ms; remaining envelope: point clouds / particles don't gather, a metal gathers nothing from the field (its reflection of the room is the traced one), and a surface reads the field from the probe row nearest it, a third of a cell inside the room, so a converged field reads 1.12 to 1.21 of a deep path trace at a ceiling over a lamp's pool (the grid's resolution, filed inDESIGN-NOTES.md). Camera-anchored probe cascades give a vast scene a near field: past the coarseness threshold (fitted spacing > half the eye-to-target distance — calibrated so a room with the camera inside stays single-volume, and it must)giCascadeLadderadds up to 3 windows halving the scene spacing toward a quarter of the working distance, stacked one 512-probe atlas slot each (same widths, soollin_gi_atlas_uvand the carriers' bindings are untouched); axes whose span covers the scene slab pin (a terrain's cascades never scroll vertically); live they scroll in whole probe planes (phys = (grid + phase) mod counts, one-plane truncation dead zone) with a scroll pass invalidating exactly the scrolled-in planes via the offsets texture's w validity, which the blends read per probe (fresh at full weight, the refit rule per probe); headless refits ladder + volumes per frame (pure function of the frame, no scroll machinery); sampling takes the finest covering cascade, fading over its outermost cell into the next coarser, scene volume the fallback. Codegen rule:ollin_gi_sampleandollin_gi_tracestay verbatim as the single-volume paths with cascaded twins beside them (fast-math re-contracts unchanged expressions when a function's control flow grows, and the ulp is a byte off every dithered frame) — the no-cascade path is byte-identical (pixel-exact reference scenes + a 180-file snapshot re-record matching a clean-HEAD re-record byte-for-byte). Example3D/(intensity + the quality tier as live parameters —Lighting/ GlobalIllumination RenderQualityconforms toParamOption, so any quality dial can be a segmented@Param); snapshotgi-3d(RT-gated);GlobalIlluminationTests(11: counterfactual probes incl. mirror-interior + render-target + the parameter's export-tier bytes + the exact count derivation, sabotage-verified red). Mechanism:ARCHITECTURE.md§ Global illumination.Docs/. Depth-aware compositing —3D/ 3D .md#global-illumination depth(at:)/noDepth()/project(_:)/withBillboard(put 2D drawing inside the 3D depth buffer —at: ){} cameraRay(through:)isproject's public inverse (origin + unit direction; perspective rays share the eye, ortho rays are parallel from the view plane;nilfor the intrinsics projection — the physics pickers use it),drawText(is the projected one-call label (skipped behind the camera), and_: at: Vector3, size: color: align: ) drawGround(is the floor slab as one call (top surface atsize: at: thickness: color: material: ) y, style scoped to the slab), or composite against a depth feed viadrawDepthScene(/ the metriccolor: depth: …) drawDepthScene(+_ frame: RGBDFrame) Camera3D(a drawn cloud, a depth feed, and a placed object share one metric space). Wired depth-correct through live + headless.fromIntrinsics image(of:); accumulation / texture-handoff render 3D without depth sorting (documented limitation), and gradient paint isn't supported on the 3D path (solid color only). Building 3D drove thePipelineenum →Hashable PipelineKeymigration.Docs/3D/3D.md,Docs/; examples the3D/ DepthCompositing .md 3D/*set (PointCloud / DepthCloud / Transforms / Solids / Lighting / LoadedMesh / Shadows / RayTracedReflections / Materials / PhysicalMaterials / ImageBasedLighting / EnvironmentGallery / ProceduralSky / Matcap / DepthCompositing / DepthOcclusion (its metric mode) / …); snapshotssparkle-materials/pbr-materials/pbr-ibl/procedural-sky/rt-reflections-3d(RT-gated viaSnapshot, so it records/runs only on a ray-tracing GPU). Fog as one value (.hasRaytracing Sources/):Ollin/ 3D/ Fog .swift fog(_ fog: Fog)takes a color, aveil(the share of a surface at the camera's target distance that is fog, clamped under 1) and apooling(the height falloff in target distances);Drawer.fogValueis resolved at pack time fromcamera3D's eye-to-target distance (the aerial default's own rule) into the world-unit density (-ln() and falloff, so it draws byte-identical to the bare call it means there (1 - veil) / distance FogTestspins it on a fogged colonnade) and a preset reads alike at any scene scale; presets.haze/.mist/.thick/.groundMist/.night,tinted(_:), and aParamChoicesconformance that puts them on the inspector's menu (3D/behind its haze switch). The bare world-unit call is unchanged and the last call in a frame wins. A traced point light's softness belongs to the light and the scene: its area radius isMaterials/ Explorer 0.06 * shadowSoftnesstimes the light's distance to the center of the frame's drawn meshes (Drawer, walked once per frame on first use; the camera's target only while the frame holds no mesh), and the caster's.meshBoundsCenter texelWorld, which the traced ray offsets its origin by and the cube path takes as a floor, is measured at the same distance, so the penumbra no longer changes with where the camera aims (192 levels between two aims along one sight line, 92 of them from the texel size alone) or breathes through a camera move; the cube map's far plane keeps the camera's framing, since it has to reach past what the camera frames (aShadowIgnoresWhereTheCameraAimsholds). An OBJ'svtis flipped to the top-left origin at read (1 - v: the format counts from the bottom of the picture, the surface samples from the top, the USD reader converts the same way, and glTF is top-left by its spec;objFlipsTextureCoordinatesToTheTopLeftOriginpins it, found by a Polycam scan whose charts landed scattered). The Model I/O path (STL, PLY) still hands a texture over at that importer's origin, a noted limitation nothing has measured. The OBJ reader welds corners by their (v, vt, vn) index triple, so a scan that writes onevtper corner arrives with one vertex per corner; welding by value is filed inDESIGN-NOTES.md. The camera's matrices are public (viewMatrix,projectionMatrix(,aspect: ) viewProjectionMatrix(,aspect: ) matrices(aspect:)as the sharedOllinCameraMatrices), so a kernel or a shader of your own projects through the sketch's camera; the look-at and projection builders stay internal.Lines in 3D (
drawLine(_:_:)/drawLine(/_: _: _: _: _: _: ) drawPolyline(/_: closed: ) drawPolyline(over_: colors: closed: ) Vector3,strokeWeight(_:in:)+StrokeUnits,drawAxes(length:),drawGrid(,size: divisions: ) strokeDash(_:in:);Sources/,Ollin/ Core/ Drawer+Lines3D .swift ollin_line_vertex/ollin_line_depth_fragmentinRenderer/,Shader3D .metal OllinLineVertexin the shared header;Docs/3D/Lines.md, figureDocs/, figureFigures/ Lines3D .swift Docs/, examplesFigures/ Lines3DStrokes .swift 3D/andGeometry/ FieldLines 3D/Geometry/Orrery,Lines3DTests,Lines3DStrokeTests, snapshotlines-3d). The points go through the model matrix and the camera at draw time (a camera set earlier in the frame, asdrawMeshneeds; none = nothing drawn + a note), what lies behind the near plane is cut in clip space (a closed loop crossing it is opened at a point behind and comes out as one run), and the projected run goes throughStrokeExpander's indexed form, which hands each emitted vertex the path point it was laid around (every cross-section, join, and cap is built at one; the plain form wraps it, so the 2D path and the web player are unchanged: the snapshot suite passed unrecorded). A vertex stores that world point plus its canvas-point offset, and the vertex shader projects the point through the pass's own.expand Uniforms3Dand adds the offset times w, so a stereo eye and a TAA jitter move it correctly (offsets are the draw-time camera's). Kind.lines3Dwith explicit core/fringe ranges (lineCoreVertices/lineFringeVertices, one upload, core then fringe): a triangle with all three coverages at 1 is core and tests + writes depth, the rest is fringe and tests only, so a solid drawn later behind a line fills the soft edge instead of leaving a background rim (aLineHidesWhatLiesBehindItWhicheverIsDrawnFirst). The fragment writes the depth ([[depth(any)]]; a plain fragment where the pass has no depth attachment): the centerline's view depth (perspective-correct, exact on the planar ribbon) pulled toward the eye by0.0005 + min(of the distance. The offset term is what a floor's depth does across a line's width; the +0.5 is the MSAA footprint (one fragment depth serves all samples while the floor is tested per sample; without it pale flecks inside solid ink and 91% of the ink on a grazing floor); per-vertex pulled depth was wrong too (a long receding segment is a sliver whose ends differ in distance). Measured: lines on a floor keep 100% of their ink from about 7° up and 91% from 7° to 3°; the cost is a line within a few percent of its distance behind a surface showing through (a fork of the two edges a few points before the exit).|offset| + 0.5, 2) · unitsPerPoint · 10 .worldwidth =weight/per point; the unit is stated with every weight (2 · averageScale( model) · P11·viewport .y/ 2 / w strokeWeight(_:in:), default.screen) because a persistent mode outlived its number in the first example and drew the grid a world unit wide. SVG records the projected polyline (2D transform held off; world width = mean projected width; each dash a path of its own, a profiled piece as its outline throughsvgRecordStroke, a brushed line as its stamps far to near;aVectorExportCarriesTheProjectedLine,aVectorExportCarriesTheDashesTheProfileAndTheStamps);makeBatchrefuses (no camera), spatial export skips with a note, the web page refuses by name;strokeMediumand a picture for a brush's tip note once (the line draws without the one, and discs for the other). Overload trap:drawLine((two implicit members) resolves to the 3D overload, which notes once without a camera. Measured.zero, .unitX) -Oon an M2 with round joins: 2.96 ms for 5,232 points and 10.8 for 19,152, against 3.16 and 11.1 for the 2D strokes through the projected points (about half a microsecond a point; the projection is noise). Six planted defects (no sample reach, fringe writing depth, no near clip, world width ignoring distance, no depth state, the 2D transform left on the SVG) each went red. A dash, a width or opacity profile, and a brush are worked out on the projection and carried back to the line: a point a fractionuacross a projected segment is the fractionu·wa /along it in space (( u·wa + ( 1 − u)·wb) LineFrame, the two ends' clip w), so a dash's end, a profile's sample, and a stamp each take the depth of their own point (.between( _: _: onScreen: ) aDashEndStandsAtThePointOfTheLineItCuts,aWallCutsADashWhereTheLinePassesThroughIt). Every point carriesalong, its length in world units from the line's first point (a loop opened at the near plane counts on past the seam, a lap added), which the profile, an.alongPathgradient, and a dash in world units all read, so none starts over where the near plane cuts the line. The dash's unit is stated with the pattern (strokeDash(_:in:), saved with it bywithState, reset bynoStrokeDash):.screen, the default, is the 2D dash on the projection vertex for vertex (aDashedLineIsTheTwoDimensionalDashOnItsProjection) and, head-on, within a level in every pixel (aDashedLineSeenHeadOnIsTheTwoDimensionalDashInPixels);.worldis lengths along the line in space timesaverageScale(model), the pattern anchored at the line's first point even behind the camera. Measured over one turn of a camera about a line 4.7 units long: a dash end in canvas points slides along most of the line, 1.2 points a frame at 600 frames a turn, and one in world units does not move, its length on the picture running 48 points to 0.8. Both cuts walkStrokeDash, lifted out of the 2D.spans( along: closed: ) cutwith its arithmetic unchanged, so every 2D dash is the bytes it was. A profile splits a segment past 12 canvas points, as the 2D stroke does, each new point carried back through the clip w. A brush goes through the line's own pipeline, in the line's batch: its stamps follow the weight's unit (.screen=Brush.stampson the projection, the 2D brush;.world= laid along a straight line the piece's world length, in hundredths of the weight so the brush's size floor does not depend on the scene's units, then carried to the line), are recorded the farthest first (ties keep the path's order, so head-on it is the 2D brush's order), and carryposition.w = 2, at whichollin_line_vertexhands the fragment the whole depth reach: a stamp's face is pulled as one, or at one depth a later stamp's middle fails against an earlier stamp's outer part and translucent stamps show holes (stampsAtOneDepthBuildUpAsTheTwoDimensionalBrushDoes; clear of the stamps' edges the 3D and 2D brushes agree within 2 levels, and on the edges they part by up to 34, since a stamp here is the round cap's polygon, within a tenth of a point of the circle, and the 2D brush's is the exact disc). A disc is laid out directly (appendDisc, the round cap's rings); a square goes through the expander, about two and a half times a disc's cost (87 ms against 34 for the same stamps in a debug build); a shape for a tip is its fill triangulated once and placed per stamp, all core, its edge the multisample mask's. Every lookup along the line halves (LineWalk.place): the first form scanned from the start for each stamp, and a brush on a 5,000-point line took 800 ms in a debug build against 34. In that build the same line dashed in either unit takes what the line whole takes (63 to 67 ms against 68). A line with no dash, profile, or brush records the bytes the code before recorded, hashed over 118 cases (three cameras, every join and cap, open and closed, both units, colors per point, gradients, a model matrix, the grid and the axes) and its SVG; the one case meant to move is an.alongPathgradient on a loop the near plane cuts. Seventeen planted defects each went red.Hidden-line solids (
featureEdges(/creaseAngle: ) noFeatureEdges();Sources/(Ollin/ Core/ Drawer+FeatureEdges .swift FeatureEdgeSet,FeatureEdgeTopology,FeatureEdgeCache),ollin_edge_vertex/ollin_edge_core_fragment/ollin_edge_fringe_fragment/ollin_edge_fragmentinRenderer/,Shader3D .metal OllinMeshEdge+OllinEdgeStylein the shared header;Docs/, figure3D/ HiddenLines .md Docs/, exampleFigures/ HiddenLines .swift 3D/,Geometry/ HiddenLines FeatureEdgesTests). A mesh's faces draw as always and its feature edges draw over them in the stroke: an edge set found once per mesh on the CPU (corners welded byLineDrawing.weld; a face whose welded corners are fewer than three is skipped, which is what keeps a UV sphere's south pole, a hair apart in float, from reading as 32 branching creases), each edge its two ends in mesh space and its two face normals, kind boundary / crease (past the angle, or a third face) / smooth; kept in an immutableFeatureEdgeSetthat makes its GPU buffer once (no per-frame edge upload; the edges sit in page-aligned memory the buffer wraps withbytesNoCopy, the memory held by the buffer's deallocator so a frame in flight keeps it) behind a 16-entry cache that keys on the mesh's own position and index arrays (==answers at once on the same storage). A mesh whose positions move while its index buffer holds keeps its faces: the search is split into aFeatureEdgeTopology(the weld, the kept faces, each edge once with its two faces, the closed flag: all the hashing, about 98% of a search) and the crease pass over new positions (face normals, edge kinds, rows), whichedges(redoes alone after checking the positions meet as the searched ones did: every welded corner still in its representative's weld cell (at: creaseAngle: validating: ) LineDrawing.weldKeyunder the new extent's grain), no edge's two ends in one cell, every kept face still with area past 1e-20 and every flat one still without; any failure is a search from scratch. What it does not check is two parts of the surface coming to touch away from a shared face, which a fresh search would weld (documented on the type). The moving mesh takes its entry over (one entry, not a cache filled with frames past: before, a 1.2-million-vertex mesh rebuilt each frame held up to 16 entries of ~260 MB), and a second mesh over the same index buffer drawn in the same frame gets an entry of its own sharing the topology (FeatureEdgeCache, from.beginFrame( ) Drawer.beginFrame). Each pass of the crease test splits across the cores past 65,536 items. Measured (M2, release, a 12,000-ring tube of 100 vertices, 1.2 M vertices, 2.4 M triangles, 3.6 M edges, positions moved every frame): the edges cost 798 ms of CPU a frame before and 16 ms after (2% of the search), end to end +31 ms of which ~13 ms is drawing the edges. Pins:aMeshThatMovesIsSearchedOnceAndFindsTheSameEdges(box, sphere, plane, and a sphere past the parallel threshold, byte for byte against the one-pass search kept in the tests asReferenceEdgeSearch, one search over six frames, one entry),cornersThatPartAreSearchedAgain,endsThatMeetAreSearchedAgain,aFlatFaceThatOpensIsSearchedAgain,twoMeshesOverOneIndexBufferKeepAnEntryEach,aMovingMeshInksAsTheMeshSearchedWhereItStops(the pixels). A draw records a.lines3Dbatch carryingedgeSetright after the solid (so every.lines3Drule, depth, peel, DOF scissor, applies) that rides the solid draw's own copies: its run ofmeshInstances(a singledrawMeshappends its model matrix there) or the compute buffer. The vertex shader decides per copy: boundary always; crease unless both faces turn away on a closed mesh (the mesh's front hides it, and drawing it lets the pull leak it through a thin solid's front:aCreaseThatTurnsAwayOnAClosedMeshIsLeftOut); smooth only where its faces face opposite ways (the silhouette); normals by the model's adjugate with the determinant's sign. Each edge is a round-capped capsule on the canvas whose coverage is the 2D fringe's ramp computed per pixel from the distance to the segment (anEdgeIsTheLinesStrokeat weights 1, 2, 3: within one level ofdrawLinealong the same segment) and whose depth is the line path's pulled depth at the segment's nearest point (inverse view depth linear on screen, so caps take the end's depth). Two rules found by the probes: (1) the pass is multisampled, and a fragment's color reaches only the samples its quad covers, so the core quad reaches past the core by more than half a pixel's diagonal (a core quad cut to the core drew a 2-point edge on a pixel boundary as a gray hairline: 137 levels off); (2) a curved surface's silhouette is set outside the contour by its half width, the side chosen by the screen projection of its two face normals, and the quad's corners move with it (moving only the ends moved the coverage frame too and cancelled: a 20-point shift changed nothing): a silhouette centered on the edge beads, because the face beside it is seen nearly edge on and its depth outruns any pull (65 of 720 rays across a sphere's outline found no ink;aSpheresOutlineIsUnbroken). Core then fringe as for lines; a weight of a point or less in screen units skips the core pass (its ramp never reaches whole coverage). Order: copies in one call draw every face before any edge; meshes drawn one call each draw in call order, so where two solids nearly touch (within the ~1% pull) the first one's edge can show through the second's face (documented; the identity test keeps copies apart on the canvas). Off underwireframe()andnoStroke(); a gradient stroke takes its ramp's middle color, with a note; a mesh field draws faces only, with a note. Measured (M2, release, 1080 square, 10,648 boxes): GPU 4.2 ms solids alone, 8.3 ms with 1-point edges, 11.5 ms with 2-point, CPU unchanged at ~5.4 ms; the same edges asdrawLinecalls cost ~216 ms of CPU. Technique: feature edges classified in the vertex shader from an edge buffer of face normals (McGuire and Hughes, Hardware-Determined Feature Edges, NPAR 2004).Many lights (
reach:on every positioned light kind +Light.reach/Light.reaching(_:);ollin_light_cull+ollin_light_setinRenderer/,Shader3D .metal MetalRenderer+Lights). Tile-based forward: the frame's lights are culled per screen tile and still shaded forward, so the 8-light ceiling lifts without deferred's cost to draw-order compositing, blending, or the float-MSAA path. Two halves, and the first is what makes the second possible..swift reachis the world-space distance past which a light contributes exactly nothing, stored in the freeOllinLightlane (0 = unbounded, so a reachless light packs and shades byte-identically); the window is.position .w (1 - d/reach)², which is 1 at the source, 0.25 halfway, and exactly 0 at the edge (an inverse square with both ends made usable), applied on the light's local copy (L, the light-shaping rule) inside a.color .rgb *= within position.w > 0branch so a frame with no reach never enters it. A light with no reach cannot be bounded and stays in every tile: the reach is what buys the cull. The grid engages pastOLLIN_MAX_LIGHTS(the inline array stays 8 and is still what fog, GI, the traced export, and every non-mesh path read), caps atOLLIN_MAX_SCENE_LIGHTS= 256 with a one-time note (the decal-cap rule), and is one compute dispatch of one thread perOLLIN_LIGHT_TILE_SIZE= 16 px tile: the tile's six planes are row combinations of the view-projection (the left plane at NDC x0 isrowX - x0·rowW), so no per-tile matrix multiply and both projections work; the rect grows one pixel so temporal jitter and multisample positions cannot land a fragment in a tile built without them. Light bounds: a point/area kind is a ball, a spot is the smallest sphere of its spherical sector (apex-and-rim below a 45° half-angle, the cap alone above it, the whole ball past a quarter turn), a directional or reachless light returns "cannot be bounded" and every tile keeps it. Load-bearing: the grid decides only which lights a tile lists, never how one shades, andcullingIsTheSamePictureAsShadingEveryLamprenders the same 64-lamp frame culled and unculled and compares the bytes (the internalDrawerfills every tile with every light; sabotage-verified with a 0.85× radius);.cullsLightTiles anEightLightSceneIsByteForByteWhatItWasdiffs the committedmesh-lightingreference at exactly 0 (sabotage-verified). The renderer, not the drawer, ownssceneLightCount/lightTileGrid/lightTileStride, set only where the two buffers are bound (fragment 8/9, stand-ins otherwise), so every other pass reads the inline array; a pass takes the grid only when its attachment is the size the grid was culled over, which is why the live geometry pass names its ownrenderSize:(a temporal upscale renders smaller than the drawable) and why a full-canvas render target is tiled while one of another size falls back to eight. The half-res raymarch carrier divides its position byraymarchScaleto land on the same tile. One portability rule came out of the runner:ollin_light_atpicks between a light indevicememory and one inconstantmemory with two returns, never a ternary, which a Metal compiler one version back reads as ambiguous (each side converts to the other), and a shader that fails to compile takes the whole renderer down rather than one pass. Measured on an M2 at 1080²: 64 lamps 16.89 ms culled against 42.65 ms brute force (60% saved), 128 lamps 31.10 against 81.24; 16 culled lamps (6.75 ms) beat 8 inline ones (8.39), since the inline path culls nothing.Scripts/is the sweep. Examplebenchmark .sh lights 3D/;Lighting/ ManyLights ManyLightsTests(14) +ManyLightsBenchmarkTests; snapshotmany-lights;Docs/3D/3D.md#reach, Guide Ch 30 § A courtyard of lamps: many lights. The bounce trace (ShaderGI.metal, both trace bodies) and the path tracer's direct light (ollin_pt_direct) read the reach as the raster does, throughollin_light_reach, so a lamp lights and bounces nothing past it anywhere (aLampAddsNoBounceBeyondItsReach,aLampLightsNothingPastItsReach).The scene through glass (
sceneThroughGlass()/noSceneThroughGlass(;) ollin_scene_refractioninRenderer/+Shader3D .metal encodeSceneBehindPassinMetalRenderer+Targets). Screen-space transmission on any Metal GPU: the frame is drawn a second time with every transmissive run left out (.swift GeometryBatch+.isTransmissive encode(, so what the layer holds is the picture with the glass removed, which is what keeps a body from finding itself), and a transmissive PBR fragment reads it along its own refracted exit ray; the read is finished light, so it is divided byskippingTransmissive: ) iblIntensitybefore it replaces the refracted environment (the ambient it lands in is multiplied by that on the way out, as the traced walk's direct light is pre-divided): clear glass passes 1 − F of the light behind it at any environment intensity (clearGlassPassesTheLightBehindItAtAnyEnvironmentIntensity: 0.960 at intensity 0.4 and 1.0, a gray wall minus a black one so the pane's reflection cancels; 0.199 and 0.498 without the divide) (the color at fragment texture 27, its resolved depth at texture 28, the walk's skip table at texture 30, each pixel's span and way onto its surface at texture 31,sceneBehind+sceneViewProjection+sceneInverseViewProjectionon theOllinLightingtail, the ltcEnabled stand-in discipline → byte-identical off, pinned at the pixel byaFrameWithNoGlassIsUntouched; the depth slot wants a depth-format texture even unsampled, so the stand-in is a cleared 1x1depth32Float,ensureDummyDepth). The walk isollin_env_refraction's, step for step (same entry refract, same analytic interior span, same IOR-remapped roughness fade), so a body reads the same shape whichever backdrop it lands on; then it differs: a thin wall (thickness 0) samples the exit point's projection and touches no depth (byte-identical to the read before the lens); a solid body is a lens: it refracts out through the curvature-blended exit normal and walks that exiting ray across the layer's depth (ollin_scene_march: the ray's screen path runs from the exit pixel to the vanishing point of its direction,VP * float4(dir, 0), and one over the depth is linear along it, so the walk is perspective-exact and works in 1/depth throughout, dividing nothing), which is what turns what stands past the ball's focus over rather than shifting it (the image-space refraction of nearby geometry, credited inATTRIBUTION.md). The walk tests every pixel on the path, one step a pixel along the longer axis, against the span of depth the ray covers across that pixel (leaving in front of the pixel's nearest point: still in the open; leaving behind it, having entered no deeper than the pixel's own surface runs: a surface met; entering deeper than that, where the surface carries on from the pixel before, its far end within 2% of that pixel's depth: met too; entering deeper than all of that: a silhouette the ray passed behind, and it carries on, meeting nothing, until a pixel finds it in front again). A pixel's depth is one number, the nearest sample, and at an outline the walk needs three things it does not hold (ollin_scene_depth_spans, one pass over the pre-pass's own multisample depth into anrg16Floatlayer; found 2026-11-25): how deep the pixel's surface runs (the samples sorted from the nearest, each within 2% of the one before being the same surface, plus one sample's step: nothing for a face seen square on, 3% a pixel for the side of a box a pixel and a half wide in the layer), whether the surface covers the pixel at all, and which neighbor lies further onto it (from the middle of the samples off the surface to the middle of those on it, one of eight ways). A walk that takes the nearest sample for the whole pixel turns a steep face down as a silhouette: the side of a block seen through a ball was missing (its picture ten pixels narrower than a three times finer layer draws it, 4 and 21 uneven rows of 155) and is now within two pixels of that layer on every row and even. The span's reach is one sample's step and no more: carried on by its own length it drew the side four to six pixels too wide wherever a pixel's last sample stood at the face's far edge. The 2% continuity rule is the seam between two pixels' spans, not a test of nearest against nearest: without it a dotted line of misses runs down a steep face (6 and 42 holes), and with any depth allowed nothing is ever passed behind. The read keeps to one surface (ollin_scene_meeting_read): a pixel the surface partly covers is a blend with what stands behind (a fringe of 32 and 43 levels of the block's color against the face's own 53 and 63), so the read moves to the neighbor further on; a point whose four pixels are not one surface (one partly covered, or 2% off in depth: two gathers) would tint the floor beside an outline, a dotted line of 14 pixels in the probe, so it takes its own pixel's middle; anywhere else it is the point between the pixels, which is what keeps a seam seen large through a ball a smooth run. The depth samples are kept only in a frame with a solid body (.storeAndMultisampleResolveon a.privateattachment, the table's two passes and the span pass gated with it: a frame of thin walls draws three passes fewer,onlyASolidBodyPaysForTheWalk). Never sample the path at a stride: the walk it replaced stepped up to 1/40 of the frame (27 px at 1080) and bisected the first crossing, so a ray that met a face just inside its edge was behind it for a few pixels only, some rays' samples landed there and their neighbors' did not, and every edge seen through a lens came out in uneven steps (onSeeThroughat frame 240 the red block's edge in the second ball jumped more than a pixel on 6 of 84 rows, 3 px at worst, and sat 4 px short; now on none, and it is where the every-pixel walk puts it). A table lets the walk pass over what it cannot meet (OLLIN_SCENE_BLOCK8 px blocks andOLLIN_SCENE_REGION64 px regions in onergba32Floattexture, the regions' rows under the blocks'; each texel a planea x + b y + cin 1/depth that no pixel of its cell is nearer than, and the cell's farthest pixel): a ray in the open is in front of every pixel for as long as it is in front of that plane, both are straight lines along the path, so one read says how many steps to pass over (all of the cell, or the ones before the ray reaches the plane), and a ray behind something passes over a cell it enters farther than everything in it, when nothing in the cell stands in front of the glass. Over a floor or a wall the plane is the surface itself, which is what makes the table worth having: with the nearest depth alone a ray over a floor read 17 to 32 times, and 84% of the glass pixels of a ball filling the frame now read 16 times or fewer. The table only saves reads: the walk with it leaves the bytes the walk without it leaves (MetalRenderer, a test's switch carried in.skipsSceneBlocks sceneBehind.w;passingOverBlocksLeavesTheSameBytesover six scenes), the comparisons lean 1e-5 toward looking closer, and a plane is raised by half a pixel of its slope since it is read anywhere in a pixel. The table is written in two passes, and that is load-bearing for cost (ollin_scene_depth_blocksreads the pixels into the blocks, the tilt from three corners and the plane raised to clear every pixel;ollin_scene_depth_boundscopies the blocks and builds each region from its 64 blocks' planes): built from its 4,096 pixels, the regions' part alone cost 3 ms a frame, a long loop in a few hundred fragments being work the GPU cannot spread out, against 0.2 ms for both passes now. The far plane is a surface like any other (a ray reaching it reads the frame's own backdrop, the way a thin wall does). A ray that ends hidden reads the last pixel it stood in front of, at that pixel's center (a point off the center on a silhouette mixes the occluder in by a fraction that follows the pixel grid, and neighboring rays then stripe; measured in the snapshot scene's clear sphere). Two refusals return the environment (coverage 0): a pixel on the path nearer than the glass fragment (so a foreground object never prints inside the body) and a ray leaving the frame; something between the surface and the exit (a snow-globe figure) reads at the exit pixel; an orthographic or cross-view ray (rate ≤ 1e-4) keeps the exit-point read.OLLIN_SCENE_WALK_READS(192) bounds what one ray reads, the table and the pixels together, and a ray that spends it reads the last pixel it stood in front of. Cost, accepted (ruled 2026-11-23), measured old against new in one process with the GPU kept busy (M2, 1080 square): about 3 ms more a frame wherever solid glass is on screen. A solid ball filling the whole frame draws in 11.4 ms against 8.5 (the walk 5.4 ms against 2.6, the table 0.2); the example's own row of five bodies spends 4.4 ms on its walks against 1.3, though they cover a tenth of the frame, because the GPU shades neighboring pixels together and a group runs as long as its longest walk (a tenth of the glass pixels there read more than 32 times, along the gaps between the blocks' images). That second figure is invisible to a plain frame time in a debug build, whose CPU sets the pace at 7.5 ms there and read old and new alike: it was read by giving both walks four rays a pixel and then eight and dividing the difference. A lower bound on the reads is not the remedy (48 moves 6,752 pixels of that frame, 96 saves a tenth of a millisecond). A thin wall adds nothing, and a body withdispersionwalks three times (the glass entry above). The spans cost about 1.2 ms more a frame, accepted (ruled 2026-11-26; same harness): a walk 5.6 ms against 5.3 with a ball filling the frame and 4.9 against 4.4 in the example's arrangement, and 0.6 ms for keeping the samples and reading them. The meeting's check of its four pixels is two gathers for that reason: as six single reads a walk cost 6.5 and 6.0. Load-bearing: the pre-pass mirrors the main geometry pass exactly (same size, sample count, depth format, clear, and shadow/environment/probe inputs), which is what lets it share every pipeline already built and what makes the two pictures line up pixel for pixel; its depth resolves with the main pass's.minfilter; it resolves into a mipmapped texture and the mip chain is the roughness blur (rough * (, generated by a blit after the resolve, so frosting softens the scene the way the prefiltered cube softens the sky); the read carries a coverage that eases to 0 across a 2% border band and drops at once behind the camera (mipCount - 1) clip.w <= 0), so a lookup leaving the frame dissolves back into the refracted environment rather than smearing the edge pixel; the pass is encoded once, unjittered, outside any TAA sample loop and returns the matrix it was drawn with (the deferred-reflection rule; the projection cannot disagree with the layer);rayTracedReflections(wins and the pass is skipped entirely when a reflect accel exists (the trace has none of the limits, so asking for both costs nothing, pinned byte-identical by) tracingTakesOverUnchanged). Same envelope as the other pre-passes: main canvas, camera +environment(_:)required (transmission needs one either way, and the ambient's own gate gets there first), targets / accumulation / texture handoff excluded. Documented v1 limits, each a consequence of reading the screen: only what the camera drew can show through, one piece of glass does not appear inside another, 2D chrome drawn after the glass is in the layer too (the rule is the whole frame minus the glass, not what is behind it), and the layer is one surface deep, so where a foreground object hides what a lens ray would reach, the visible side of that silhouette stands in (the traced walk has the geometry). Cost: the scene draws twice. Example3D/(hold-space compare); snapshotMaterials/ SeeThrough scene-through-glass;SceneThroughGlassProbes(14: a block seen through a lens keeping an even edge on all four sides (aBlockSeenThroughALensKeepsAnEvenEdge, red on the stride walk at 6 and 11 rows), its side whole and where a three times finer layer puts it, with the face's own color up to its edge and nothing of it on the floor beside (theSideOfABlockSeenThroughALensIsWholeAndInPlace), a seam seen large running smoothly, only a solid body paying for the walk (ten planted faults in the meeting rule, the spans, and the read each turn one of those red, the continuity rule in both directions among them), the table changing no byte over six scenes (eleven planted faults in the walk and the table red; the rounding guard at a cell's wall is reached by no scene), the wall arriving inside the glass, the no-glass byte-identity, a pane staying out of a bottle, a solid body reading past a seam a thin one does not, a solid body turning a far bar and post over where a thin wall shows them upright (red by sabotage of the march), a foreground post refused rather than printed inside the rim (red by sabotage of the refusal; the post must stand where the exit reads land, or the march never meets it), frosting flattening a striped wall, the traced takeover, and anOllinLighting-fits-a-fragment-push guard).Docs/.3D/ 3D .md#scene-through-glass Light sets (
withLights(/_: ambient: _: ) withLights(/_ preset: _: ) withoutLights(_:)/addLight(_:);Drawer.LightState,GeometryBatch,.lightSet GeometryKind). Lighting is per batch, not per frame: the lamps, the ambient, and the on/off mode are drawing state on the state stack beside the blend mode and the surface finish, so the set in force when a mesh is drawn is the set that shades it and one frame mixes rigs (a lit stage beside an unlit hologram, two rooms each with its lamps). A batch carries a.readsLighting lightSetindex and breaks when it changes, like a blend or a finish; the renderer packs oneOllinLightingper set and binds the batch's throughbindLitMeshFragment(, the raymarched field, the strand field and the ocean each taking the same index. Load-bearing, and the reason every committed 3D reference still matches at 0: set 0 is the frame's own, resolved at the end of_: set: ) draw(), so a lamp added after a mesh still lights it exactly as the per-frame model always did, and a frame that scopes nothing records no set at all (lightSets.isEmpty, every batch at 0, wholeSnapshotTestssuite green unrecorded including the 8 RT cases). Only a scoped set is a snapshot, taken when the batch opens; the base isstateStack, which is what keeps the frame's rig accumulating whatever a block does to its own. A set is a value, so two blocks under identical lamps share one entry rather than appending, and the lit kinds are the only ones that ask (.first? .lightState ?? lightState readsLighting), so a 2D frame inside awithStateblock never builds one. The two questions the design note asked, answered. A caster's own depth pass per set: casting stays with set 0 and a scoped set names no caster at all (makeLightingguards the whole caster block onset == 0), because a caster is a depth pass into its own map-array layer, a cube of the cube array, and a far plane the renderer files under the caster's index in its own light list, all three keyed by a light's place in the set that holds it; a slot pointing into another set's list would sample a projection that has nothing to do with it. A second tile cull per list: implemented.encodeLightCullloops the sets and culls each one that outrunsOLLIN_MAX_LIGHTSinto its own pair of ring buffers (MetalRendererkeys the ring by slot and set, since an in-flight frame may still be reading either),.gridKey( frame: set: ) currentLightGridsholds them by set, andapplyLightGrid/bindLightGridtake the set; a set on the inline path builds no grid, byte-identically. The environment, the atmosphere and the flare stay per frame (properties of the world, not of a rig), though an.offset turns its own IBL off with everything else, which is what makeswithoutLightsflat under an HDRI. The IES/cookie layer lists became a frame-wide union cleared inbeginFramerather than rebuilt permakeLightingcall, so two sets' profiles share one baked texture array and repeated calls still agree. Cap: the frame's own plusDrawer= 15, past which the extras draw under the frame's with a one-time note. Cost, measured in one process alternating (M2, 1080²): splitting costs a batch per set and saves shading, so 8 rooms of 8 lamps run 2.33 ms as 8 sets against 13.34 ms as one 64-lamp set, and 8 rooms of 2 lamps about 1.2 against 4.0, while 2 rooms of 4 lamps in all lands inside the run-to-run noise (two idle runs read +5% and -10%, which is why only the large cases are quoted);.maxScopedLightSets Scripts/. Examplebenchmark .sh lightsets 3D/;Lighting/ LightSets LightSetTests(19 CPU tests) +LightSetRenderProbes(3, the leak test rendering the pair and each set alone and demanding the shared pixels equal the solo ones) +LightSetCullTests(3) +LightSetBenchmarkTests; no pixel snapshot (the claim is a relation between renders, which no one reference image states).Docs/with the LightSets figure, pointed from Guide Ch 27 § Light: presets and the kinds of light.3D/ 3D .md#light-sets Caustics (
caustics(/intensity: dispersion: ) noCaustics()/causticsQuality(_:);Renderer/+ShaderCaustics .metal MetalRenderer+Caustics). Photon-traced focused light: emit a budget of photons from the caster light, walk each through transmissive (.swift Material.glass) and mirror-polished-metal surfaces with photon differentials (the emission cell's u/v perturbations chain-ruled through every reflect/refract, including the interpolated normal's own triangle-plane derivative, which is what makes curved glass focus), deposit on the first rough opaque hit, splat each as an anisotropic elliptical footprint into a screen-space layer the four lit mesh carriers add by screen position (fragment texture 25,causticsEnabled/causticsScaleon theOllinLightingtail, the ltcEnabled discipline → byte-identical off, whole suite unrecorded). Adaptive emission per the published technique: a light-space density map → per-texel perfect-square leaf counts → cumulative-uint4 quadtree (node = running child sums in traversal order r=(0,0), g=+(1,0), b=+(0,1), w=total; the walk's final level read is guarded off) hands every GPU thread its emission cell; deposited photons atomically feed back projected screen area and temporal variance (the live temporal resolve writes variance into the layer's alpha, which next frame's photons sample — the loop closes through it), density updates as d·clamp(aAvg/aTarget) + v·gain with a 3×3 spatial blend and a probe floor; the density total resets every frame in the args-reset kernel (left accumulating it splits the budget over every frame ever rendered and the whole map starves within a second, a real fixed defect: rays fell 65k -> 427 -> 3) and the adaptive leaf counts round stochastically per texel per frame (floor alone zeroes every texel wanting under one ray, which at seed density is the whole map; the uniform/export branch keeps the exact floor, so exports are untouched), and a texel planned below one ray emits on that share of frames, so its photon carries the inverse share (leafWeights, written by the leaf pass, read by the trace): without it the first adaptive frame fell 17% short of the uniform plan's light and the settling frames 5 to 14%, now every frame within 2%. Three rules keep that plan honest, each one measured as a lens's spot going out and staying out: the promotion is solved in rays, not in k (a texel emits k² rays, so promoting on k's fraction asks for ~23% more rays than the budget, the trace dispatches exactly the budget, and the quadtree hands out tasks in traversal order, so the overflow is always the same corner of the map and whatever caustic sits there dies); the plan's running total is ×256 and rounds (×16 truncation counted every texel under 1/16 of a ray as zero, under-reporting the divisor and inflating every texel's plan by a sixth); and the density bounds are shares of the uniform plan, not absolutes — live floor 0.5·d0, idle floor 0.05·d0, ceiling 32·d0, the last being the windup guard (the area target is unreachable where a photon lands at a grazing angle, since the footprint is the receiving surface's doing; unbounded, those texels multiply ×4 a frame to the old 4096 ceiling and take the whole normalized budget within 30 frames, while the sharpest caustic in the scene — small footprints, which the same rule reads as over-sampling — starves first and never recovers). The guard is Ollin's, not the published technique's. Load-bearing: photon flux is the beam cross-section — first-hit footprint area × |cos incidence| (area alone over-weights grazing silhouette rays into a skirt of bright spikes, a fixed real defect); a footprint past the max screen extent is CULLED, never clamped (the min-width clamp would widen a meters-thin streak into a visible hairline combing the floor — the second fixed defect; min-width itself stays area-conserving; the extent is in screen pixels, so the cull takes a little more at a larger canvas: a ball's deposit was 0.837 of its beam at 192 px and 0.829 at 1080); deposit requires ≥ 1 specular bounce (a straight light-to-surface path is the direct lighting the scene already shades — caustics never double it) and drops paths still inside a solid; the accel build breaks its coalesced runs where the caustic materials change and fills the parallel per-geometryOllinCausticGeobuffer (transmission/ior/thin/attenuation; metal/rough/albedo are stored in the baked vertex slots), only while caustics are on; glass = refract-only lineage (Fresnel-weighted, Schlick read at the angle on the lower-index side, the incident one going in and the refracted one coming out: read at the inside angle the exit reflected too little and a ball passed 0.878 of its beam against the full Fresnel equations' 0.836, now 0.848; albedo tint at entry, Beer-Lambert over the traced interior span, TIR bounces inside), polished metal (metallic > 0.5, roughness < 0.25) = reflect, F0-tinted; a point or spot caster has no distance falloff, so a photon carries its cone's light at the length of the path it took (the first-hit cross-section × (path / first-hit distance)², the distance to a mirror's virtual source) and its reach thins it at that length (params.z): at the first-hit cross-section a lamp's ball gave back 0.35 of its shadow and, with a reach, 4.8 times; a mirror's caustic now equals its virtual light within 1% for both kinds; one caster light by the shadow system's priority (shadowLight if punctual, else directional → spot → point; directional = ortho patch fitted to the specular casters' AABB, spot = its own cone, point = the cone subtending that AABB); splat shading uses the caustics G-buffer's own attributes (normal/metal-rough/albedo MRT + depth — the reflection G-buffer's recipe plus albedo, pipeline.causticsGBuffer, with the batch's shading model and F0 in the material target's freez/w) and shades a footprint exactly as the receiver shades a direct light: a physically based receiver takes Lambert over pi kept by one minus the lobe's directional albedo at the view and faded by metalness, plus the shared GGX/Smith/Schlick lobe with its multiple-scattering compensation (the BRDF table bound at texture 4); every other model takesalbedo × E, no pi and no lobe; and never× NdotLagain, since flux over the footprint (which lies on the receiver) is already the surface irradiance with its cosine in it. Measured before the rule: a physically based floor took its caustic at pi times the light, the cosine counted twice, so a slab's caustic gave back 2.73 of the light its shadow took (0.904 on a Lambert floor, 0.82 under a 0.5 rad light); after, 0.9216, the slab's 0.96², on both models and both angles. A manual slope-adaptive depth compare clips footprints to the geometry they lit; the layer isrgba32Float: additive half floats stall where a pixel reaches a power of two (a focused spot flat-topped at exactly 1.0, 2.0, 4.0, its peak 20 once lifted) and shaved 4% off a flat caustic; every trace thread owns photon slottid(a thread that deposits nothing leaves it at zero power, which the splat culls) and the splat draws all slots in thread order, never through an append cursor: the cursor handed out slots in arrival order, and the additive splat rounds each order differently (85 pixels of the example at frame 480, run to run, when the layer was half float); export/headless = uniform emission at the detail budget, no history touched, and the jitter seed held at 0 (a frame is a pure function of itself, and every exported frame traces the same photons, so a still caustic holds still across a sequence where a per-frame seed re-rolled its sparks ±5% a frame;anExportedCausticHoldsStillFromFrameToFrame; live = jittered emission + EMA resolve on anSSRHistorySlottwin behindstatefulEncodeIsRepeat, the resolve reining history with 5×5 variance clipping, motion-scaled exactly like the reflection temporal, never a min/max clamp, which on the sparse splat layer crushes history wherever a frame lands no photon and holds the flicker forever); dispersion = per-photon IOR perturbation (±3% × the parameter) with energy-preserving RGB weights that sum to white. The kernels live in the main shader library (libraryComputePipeline(, its cache cleared on live shader reload); segment order: after ShaderGI (needs Shader3D's_: ) ollin_rt_query/ollin_rt_fetch_surfaceand ShaderEffects'PresentOut), everything traced inside#if OLLIN_RT_SHADOWS; non-RT devices no-op (causticsWantedgates onrayTracedShadows). Documented v1 envelope: screen-space apply (no caustics seen in mirrors/through glass), roughness never widens differentials (sharp caustics from frosted glass), no area-light photons (the soft-caustics covariance extension is the follow-up), a glass surface's own specular spawns no second photon family. Example3D/(lens spot inside its own shadow + chrome-torus fans, hold-space compare); snapshotLighting/ Caustics caustics(RT-gated);CausticRenderProbes(inert-without-casters byte-equality, lens-brightens-its-shadow on/off diff, green-glass tint) +CausticsLiveTemporalProbes(the headless live-path net: drivesencodeCausticsPass(frame after frame — a static camera asserting the layer stays fed and converges toward its settled reference, and 150 frames of the example's own cast asserting that the lens's focused spot keeps its energy, that the whole layer keeps its light, and that the plan never asks for more rays than the trace runs; the profile every export-path test is structurally blind to).supersample: false) CausticEnergyTestswalks the energy chain stage by stage against values the chain does not compute (a slab's deposit againstI × area × 0.96²within 0.5%, a ball's against the Fresnel band, a slab against its own shadow on both receiver models and two angles, a mirror against its virtual light, every live frame against the uniform plan), each red under a planted copy of the defect it guards; the two-sided lens invariant is under Physical invariants.Docs/3D/Caustics.md.Volumes (
Volume+Volume.noise(...)+MediuminSources//Ollin/ 3D/ Volume .swift Medium.swift;ComputeTexture3D+PingPongTexture3DinCompute/;ComputeTexture3D .swift drawVolume(/_: size: medium: ) drawVolume(over a_: width: height: depth: medium: ) Volumeor aComputeTexture3D, recorded byDrawer+Volume.swift(aVolumeSource) intodrawer.volumeDraws;Renderer/+ShaderVolume .metal MetalRenderer+Volume; the shared.swift OllinVolumeDrawandOllinVolumeShadowinOllinShaderTypes.h). A density grid drawn as a participating medium: Max's emission-absorption model (1995) with scattering of the scene's lights, each step integrated exactly under its sample (Hillaire 2015'sS·(1−e^(−σΔ))/σ), so a uniform medium is exact at any step count. The light the medium bounces to itself is Wrenninge's octave sum (Medium.bounce, 0…1, on by default, ruled 2026-10-28):OLLIN_VOLUME_OCTAVES(8) octaves per lit light, the k-th through the medium's own shadow thinned to 2^−k of the optical depth, at b^k of the share (b = 0.43 · bounce, packed inglow.w), and with the phase's g halved each time; b stays under the thinning factor (Hillaire 2016's energy rule) and is calibrated to the exact half-space solution, which is the thick limit only: a thick white, evenly scattering slab lit and seen along its normal reads H(1)²/8 = 1.057 of a white matte surface (Chandrasekhar's H function for conservative isotropic scattering, H(1) = 2.9078), and Σ 0.43^k/(1 + 2^−k) = 1.061 lands there, where the paper's b = ½ gives 1.257 and 0.4 gives 0.991 (a side agent's catch: both were look choices); the single scattering under it is 4× the physical one by the fog's normalization (phase isotropic = 1 against the light's color), which is why the first octave is 0.5 of the whole rather than physics' 0.12 and why a thin medium reads brighter than nature beside the same surfaces (left alone on purpose: the fog pictures stand on it), so that slab reads the closed form 1.061 at full thickness against 0.5 lit once (aLitSlabReturnsItsOctaveSum,aThickCloudBouncesMoreLightAndNeverPastTheLight); a solid's shadow blocks every octave (the bounce thins only the medium), a light past the four grids takes one octave, the ambient takes none, and b = 0 ends the loop after one octave (single scattering, the closed form unchanged). The light grid holds optical depth, not transmittance (ollin_volume_light_kernelwritesdensity · τ; both readers, the march's self-shadow and the solids'ollin_resolve_volume_shadow, takeexp(−read)), since a deep octave (1/128 of τ) still finds light whereexp(−τ)is under a half float (aDeepOctaveFindsLightThroughAThickSlab: a back-lit slab at τ 25 reads the closed form 0.053 where transmittance storage reads black). Every lit step works its light out in full; lighting at a coarser rate was measured and refused (2026-10-28, the saturated test-build harness at 1080², three rounds, the plume example and a dense 64³ cloud, each at one light per step against one per two lit steps, interpolated between the two ends of a lit run and then simply held: interpolated 10.98 → 11.92 ms plume and 10.38 → 11.17 dense, held 10.59 → 10.63 and 9.94 → 9.84, so the light is not where the march's cost is and the bookkeeping costs more than it saves; the bounce's eight octaves add 0.3 ms on the plume and nothing measurable on the dense cloud). The lattice-rate idea stays inDESIGN-NOTES.mdwith those numbers. Fog veils a volume as it veils a solid: after the march the result is fogged (ollin_apply_fog/ollin_apply_aerial) at the coverage-weighted mean depth along the ray, the medium's light dimmed and the air's light added over the alpha; a glow with no thickness is only dimmed at its light-weighted depth; a dense glowing slab under fog reads within a level of a white solid one extinction length behind its face (fogVeilsAVolumeAsItVeilsASolid, under a gray fog and under a black one at twice the density, where a veil read at the face instead is two levels off). Six planted defects each red in their own test: the octave's share never shrinking, the shadow never thinning, the grid holding transmittance under readers that exponentiate, the veil at the face, the solids reading the depth as a transmittance, and the share at the paper's ½. Load-bearing: volumes are NOT batches. The geometry pass cannot read its own depth attachment, so every volume composites after its pass ends (canvas: right afterapplySubsurfaceScattering, before TAA/upscaler/DOF/blur/flare/filters/overlay; a geometry layer: right after its pass, inencodeEffectTargets), over the resolved color with premultiplied source-over, reading the pass's resolved depth (mainDepthResolve/ the export'ssceneDepthResolve/ the layer's resolve; every depth-resolve gate includesdrawer), so the march ends at the first solid and call order does not matter (.hasVolumes( for: ) aVolumeDrawnFirstStillEndsAtALaterSolid). Several volumes sort farthest first by box center (two that interpenetrate order as wholes); equal distances keep call order, the later draw on top, so an absorbing medium drawn after a glow over the same box dims it and drawn before it dims only what is behind both (twoVolumesOnOneBoxCompositeInCallOrder; a glow-only medium adds in any order). The pass's lighting, shadow map, and jitteredUniforms3Dare stashed byencode(keepVolumeLight, not from the hidden layer, the overlay, or the scene-behind pass), andencodeno longer returns early on an empty batch list when the pass holds a volume. Two sources, one march: aVolume's lattice samples run corner to corner (ollin_volume_uvw), r16Float 3D textures uploaded once perVolumeStorage(copy-on-write; a write after upload copies first, a newcontentID); aComputeTexture3Dis the same lattice kept on the GPU, written by a sketch's kernel throughcompute(_:writing:)(a 3DRecordedDispatch,gridDepth, threadgroupstew × 4 × budget/), its red channel the density, each side at least 2, zeroed on first bind, and its cache identity is its( tew·4) idplus awriteCountevery recorded write bumps (VolumeSource), so a rewritten grid reads new and a still one stays cached; a kernel-written uniform slab draws byte-identically to the CPU slab (.contentGeneration aKernelWrittenGridDrawsAsTheCPUGridToTheByte). Resolved ahead of every pass:prepareVolumesruns right afterencodeComputein each drive (so a kernel-written grid is read as written), realizes each grid, and computes its light-transmittance grid per lit light (ollin_volume_light_kernel, Behrens and Ratering 1998, one step per sample spacing whatever the view tier) for the first four lit lights, when the medium has density and the lights are on, for scattering or whenevercastsShadows; cached on (content, generation, model, density, light ray), recomputed into another texture on any change, a texture unused eight frames going to a pool a grid of its size is taken from, so a cloud rewritten every frame allocates nothing.encodeVolumesreads the prepared table per target and sets each draw's phase. The cloud's shadow on solids, undercastShadows()only:volumeShadowTablepacks per pass target up toOLLIN_MAX_VOLUME_SHADOWS(4)OllinVolumeShadowentries (the inverse model plus, per caster, the transmittance grid toward that caster's light as agpuResourceIDhandle, the never-sampled stand-in behind a 0castslane) into a small buffer bound at the lit mesh fragments' buffer 11 (one zero entry otherwise, so the argument is always bound;useResourcesfor residency),lightinggates the read (0 is byte-identical), and.volumeShadowCount ollin_resolve_volume_shadowsamples each caster's grid where the surface's ray toward the light enters the box (a surface inside reads at itself), which is the transmittance of the whole column beyond, folded into the same per-caster dimmer the marched fields and contact shadows use, so the caster's strength scales it, any caster kind takes it (a grid read, not a map), only set 0 shades under it (a scoped set resolves no casters), and the raymarched fields take none. The overlay pass binds none; the hidden layer and the pass behind the glass take it.ollin_volume_boxkeeps a ray running along a face inside that axis's slab (before, a lattice point on a face parallel to the light read no medium ahead of it: a bright skin on the grid's faces, a shadow fading short of the box's edge). The view march's step followsvolumetricQuality(volumeStepsPerSample: 1 at.performance, 1.5 at the live default, 2 at.detail, which every export and test runs at, so the closed-form tests and the snapshots are unchanged; avolumetricStepscount is the beams' and leaves 2). The composite scatters the first eight inline lights (directional, point, spot with cone/IES/cookie; area kinds scatter nothing), phase normalized isotropic = 1 like the fog, the flat ambient plus the environment's irradiance averaged over six axes; the self-shadow reads the same transmittance grids; solids' shadows through 2D-map casters (ollin_fog_shadow_tapwith the caster's strength); point (cube) and traced casters do not shadow the medium. Per-step start offsets (ollin_ignat pixel + step × 5.588, the fog's rule: one shared offset printed streaks along a sharp shadow edge) shifted per temporal sample byvolumeJitterPhase(golden-ratio steps), so TAA averages the grain away. Refused by name on the web page (drawVolume); skipped under SVG, the spatial recorder,makeBatch, andwithOverlay. Not carried: reflections and glass do not show the medium, DOF and motion blur read the solid behind it, and the medium casts onto meshes alone (not into fog, not onto a marched field).VolumeTests(16, against closed forms in linear light: Beer by row 0.00045, the emission integral at three densities, the depth probe, single scattering at g 0 and 0.5 per channel withbounce: 0, the octave sum at g 0 and 0.5 per channel, the thick slab on the half-space reading and its silver lining, the deep octave through a slab at τ 25, the fog veil against a solid within a level under a gray fog and a black one, call order against a solid and between two volumes on one box, a solid's shadow inside, a layer, temporal samples, the kernel-written slab to the byte, an empty volume byte-identical, the skip to the byte) +CloudShadowTests(3: the floor under a slab of growing thickness keeps exp(−σ·d·value) per column within 3% for a CPU and a kernel grid, nothing changes untilcastShadows(), both sources shadow to the byte) +ComputeTexture3DTests(3) +VolumeValueTests(4); snapshotsvolume-plume(re-recorded: the plume shadows its floor) +volume-glow. Measured (M2, a saturated headless frame ring at 1080², the full plume scene with TAA and a spot caster): the kernel fill alone 0.1 ms at 64³, 0.5 at 96×144×96, 0.8 at 128³ (a constant fill 0.07), whereVolume.noise64³ costs 4.9 ms of CPU; the whole frame 2.7 ms with no volume, 7.3 with a 64×96×64 plume, 11.0 with 96×144×96 (9.3 at.performance), 12.1 with 128³, and at an 1800² drawable 18.3 / 24.6 (20.4 at.performance) / 24.9, so the march, which paid per pixel per step through a box mostly empty around a plume, was the cost at a fine grid in a big window (see the skip below); a file-loaded kernel used to add 2.7 ms of CPU a dispatch in a debug build by composing and hashing the 200 KB of library source every frame, and now hashes its own text from the library's hash state. The march skips what reads zero, and only that (VolumeOccupancy,ollin_volume_occupancy_kernel/ollin_volume_coarse_occupancy_kernel/ollin_volume_bounds_reset_kernel,ollin_volume_empty_exit,ollin_volume_tight_box): per source, cached on (content, generation) like the light grids and rewritten in place on the GPU when a kernel rewrites the grid, an r8Uint fine occupancy ofOLLIN_VOLUME_BLOCK(4) lattice cells a block, a coarse one of 4 fine blocks, and a six-UInt32tight box (the lowest and the complement of the highest held fine block per axis, folded by atomic minimums), all worked out in the compute encoder ahead of the light kernel. A block counts every sample a trilinear read inside it can reach, its own plus one more on each side, so a block of 0 reads exactly zero anywhere in it, a rounding step past a face or the filter's neighboring texel included; the coarse block is the OR of its fine ones, whose margins cover it. The march keeps the whole box's step lattice (the samet0,dt, step count, and per-step jitter) and only changes which steps it takes: it runs from the first step whose sample may fall inside the tight box to the last, discards a ray that misses that box (which emitted (0, 0, 0, 0) and blended to the same bytes), and where a sample reads zero it asks the occupancy for the empty block around it, coarse first, and jumps to the first step whose sample may land past the block's exit. Every skipped step would have read zero andcontinued, so every volume draws the same bytes, not only the uniform slab: the plume example's frames 0, 40, and 133 in smoke and frame 70 in cloud and fire were byte-identical to the committed march, andskippingTheEmptyBlocksLeavesTheSameBytes(a lumpy puff with a hollow, a spot through its own and the solids' shadows, a CPU and a kernel grid) pins it againstMetalRenderer, the test toggle that binds the held-everywhere stand-ins; a threshold of 0.3 in the occupancy and a tight box one block short both turn it red. The march also reads the light in place (.skipsEmptyVolumeBlocks = false ollin_light_shaping_tintover aconstant OllinLight &, not a copy of the light per step). Measured (M2, releaseOllinLive --bench 60 --gpu, the plume scene, the committed and the new shader swapped in one build): 1080² 9.65 → 7.27 ms at the live default and 11.46 → 8.33 at.detail, 1800² 23.9 → 18.1; the scene without the march is 4.1 ms, and of the march's 3.2 left, 0.6 is the empty space before the cloud, 0.6 stepping inside it, and 2.0 lighting its steps (the solids' shadow tap 0.55 of that), so what remains is the medium's own light, which the skip leaves exact. Example3D/Effects/Volumes(the plume a kernel writes,Plume.metal);Docs/3D/Volumes.md; Guide Ch 29 § A cloud in the scene: volumes.Reflection resolution tier (
reflectionQuality(;_: ) resolveReflectionScaleinMetalRenderer+Targets, the.swift deferredReflection:triple through( texture: guide: scale: ) encode). Trades ray-traced-reflection resolution for frame rate:.performancerenders the deferred reflection layer at half the drawable in each axis (a quarter of the trace) and the lit fragments read it scaled;.detail/.defaultkeep it full size. The fragments read the layer asposition(.xy · scale / texture size rtReflectionScalewas reserved inOllinShaderTypes.h), so the tier itself is Swift-only; what the shaders carry is the surface-guided read below. A persistent setting likeshadowQuality; an export resolves.defaultup to.detail, so every snapshot stays byte-identical unless a sketch asks for.performanceoutright. Measured (M2, the reflections example at 1080²,--bench 200 --gpu): GPU 22.19 → 14.02 ms, 45 → 71 fps (37%). The cost is reflected detail, and only that: one traced ray serves four screen pixels facing different ways, so a curved mirror quantizes and fine detail inside a mirror image softens. It does not cost the mirror its strength. What was documented as "~15% weaker at half size" was a trace defect the coarse layer only magnified:ollin_rt_reflect_tracebuilt its jittered sub-pixel sample by unprojecting at the pixel's own depth, which lands on the plane of constant depth rather than on the surface, so on any oblique surface about half the jittered origins fell under the mirror and their rays struck its underside a hair away. Meeting the tangent plane instead (P = eye + dir · (; the direction, and sodot( P0 - eye, n) / dot( dir, n)) R, is unchanged) repairs it at every resolution: the probe's mirrored band goes from 81% to 97% of the full-size signal at half size, and thearea-reflectionsreference lost the salt-and-pepper speckle it had been carrying across its whole mirror floor (re-recorded withrt-reflections-3d; the other 13 references that recording rewrote move identically on a clean HEAD, so they are toolchain drift and were restored). The upsample is surface-guided (ollin_rt_reflection_read,Shader3D.metal): below full size the four taps are weighted by the reflection G-buffer's own coverage and normal (the joint-bilateral shape), so a mirror at an edge keeps its own reflection instead of taking a share of what its neighbor reflects — over the pixels where the filter has a choice to make, a flat blend measured 11% brighter than the full-size picture it stands in for. The guide is the normal rather than the depth on purpose: a relative depth test reads a floor running away from the camera as a discontinuity at every step, which turns the whole grazing half of a mirror floor blocky. The G-buffer normal's alpha now means "a traced reflection stands behind this texel" (a surface is here and it is under 0.55 roughness), which is exactly the trace's own two-part early-out, so one flag serves both readers. Full size stays byte-identical (the read early-outs to the same single linear tap above scale 0.999), and so does the common case below it (all four weighted taps agreeing takes the hardware bilinear and leaves three reads unmade), which is what keeps the guide's cost at ~0.5 ms and the tangent-plane meet's at ~0.35 ms.filter::nearestreads closer to full size on a per-pixel metric and was rejected on the look: it is blocky where the guided read is smooth. Two benchmark-harness defects had to be fixed before any tier number was measurable at all, and both were hiding a third of the frame:--benchnever applied--render-quality(so no tier reached the render at all), andbenchmarkGPUMillisecondsencoded no deferred reflection pre-pass and re-encoded one sketch frame per iteration, which every stateful pass reads as a repeat and skips (lastStatefulEncodeis now cleared per iteration) — so the GPU column had been leaving out the reflection trace, the photons, and the probe update.ReflectionResolutionTierTests(3: the mirrored band keeps ≥90% of its signal at half size, a two-faced mirror box keeps each face's own reflection at the joint, and an instanced copy still mirrors at the lower tier; the first two verified red by sabotage).Docs/.3D/ 3D .md#rt-reflections Temporal anti-aliasing (
temporalAntialiasing(/) noTemporalAntialiasing(;) ollin_fx_taa_resolveinRenderer/+ShaderCombine .metal applyTemporalAAinMetalRenderer+Targets). Sub-pixel projection jitter accumulated across frames (live) or averaged within the frame (export), refining 3D edges past MSAA and absorbing the screen-space/traced effects' residual shimmer. Per-frame state like.swift rayTracedReflections(; main canvas + active 3D camera only (2D no-op with a note;) withTargetlayers and the accumulation surface keep plain MSAA); any Metal GPU. The jitter is one NDC translate premultiplied onto the projection (MetalRenderer— exact for perspective/ortho/intrinsic where the add-to-[2][0] trick is perspective-only; z/w untouched, so.jittered( _: by: ) depth(at:)and every depth test are unchanged; zero jitter early-outs, so the off path is byte-identical by construction — whole snapshot suite + a zero-churnguide-figures.shrun verified it at the byte level), threaded as onetaaJitterparam through every main-canvas 3D pass (encode'smakeUniforms3D, the reflect G-buffer, the scatter mask, both half-res field pre-passes; targets pass zero). Load-bearing, each a measured live defect first: both reprojection matrices are unjittered (the published remove-the-jitter velocity rule — reconstructing through the jittered inverse resamples the history at a different sub-pixel offset every frame and its content random-walks with variance Var(jitter)/(1−feedback²): px-scale oscillation on every hairline edge; the RT-reflect temporal takes the same rule now that its G-buffer carries the frame's jitter); the rectification box is velocity-adaptive (γ 2.5 at rest easing to 0.75 by 15 px/frame — at fixed γ=1 the μ±σ box itself oscillates with the jitter phase and drags a converged hairline edge, the clamp-sawtooth failure); adaptive feedback keys on how far the clip moved the history (untouched → 0.97, dragged → 0.88), never on the instantaneous jittered sample, which permanently distrusts exactly the pixels needing the longest memory. Live accumulates into anSSRHistorySlottwin (taaHistory) behindstatefulEncodeIsRepeat, fed by a.minmain-depth resolve (attached only when TAA runs) and a Catmull-Rom history resample, in linear light, held to the range of the 2×2 texels under it (the lobes ring on a step, and a step in linear light can be the sun, a thousand times its sky: unclamped, the sky's turn resampled a disc into a halo of 118 and 199 beside it and a pit of 115 inside it, and before the clamp a bright mover under a turning camera, a glowing sphere as much as the sun, came out a dim smear lagging 0.74 px; a still pixel's fetch lands on one texel, where the clamp is inert, so the converged still frame is untouched; the compressed-space resample was measured twice and left out: with every tap compressed before it is weighted it follows the disc's true place more closely and wraps the whole disc in a soft skirt, 1.41 to 1.83 times the plain area held to the footprint and 1.78 to 2.07 unheld; in linear light a pixel the disc covers by any fraction is still many times its sky, so the resolved disc is every pixel the true disc touches, one pixel longer along the turn, 1.12 to 1.55 times the plain area against 1.16 with the camera still, and its centroid is off the computed place by half a pixel minus the turn's fraction of one, +0.33 to -0.47 px over sixteen rates and -0.04 on average, where the plain frame's own snap is +0.18 to -0.35, so the half-pixel lead first pinned at one rate was one phase of a snap (ruled 2026-11-05: the crisp disc stays, and the extra pixel is filed);theSkyFollowsATurningCameraInTheLiveResolvereads the disc off the live loop in 2D at eight rates from a quarter of a pixel a frame to six, against the sun's computed place: within 0.6 px at each and a quarter of a pixel on average, area at most 1.65×, interior white, the still camera within a tenth of a pixel, red under the far plane at the identity, the unclamped history, and each compressed form); the resolve reconstructs the current sample only where the 3×3 holds a depth under 1 (a pixel of pure backdrop keeps its own sample, so still 2D in a 3D canvas passes through exactly: the 3×3 Gaussian over every pixel had read a still hairline as 85, 219, 111 across three columns where the plain frame reads 0, 255, 0,stillTwoDPassesThroughTheLiveResolveoff the live loop), and the far backdrop takes the camera's turn under an environment (backdropTurnsWithCamera:showsBackgroundand a baked skybox;ollin_backdrop_motioncarries each far pixel's direction from this frame's eye to last frame's, kept on the slot aspreviousEye, so a turn moves the sky by exactly what it moves a floor at the horizon and a travel moves it by nothing; over a plain clear color the identity stays exact, so 2D over a colored ground never softens; the one helper serves the resolve, the blur's fill, and the platform effects' fill); headless/export renders N deterministic jittered geometry passes averaged in linear light (4/8/16 by tier; export's automatic tier is.detail= 16) with the pre-passes (shadows, GI, layers, sims, the deferred reflection) outside the loop — byte-stable snapshots, flicker-free video. A traced shadow shares one sample set across those passes (encode'staaPassargument setsOllinLighting/.shadowPass shadowPassCount, which fill the struct's tail padding so the stride is unchanged;shareTracedShadowsdivides each traced caster's rays by the pass count, rounded up, at least one; a.detailtier, which is what every export resolves to, takesexportDetailShadowSamples, 64, as the set, four rays a pass, where the live 16 showed a wide penumbra as sixteen bands once the passes shared one set, and an absoluteshadowSamples(_:)passes through; pass p traces samples p, p + P, … of therays·PVogel disk or antithetic R2 set, so the passes together trace each point once):.detailon the M2 traces 16 points in all where it traced 16 per pass (1,000 spheres under a point light at 1080×1920: 25.3 s to 2.3 s a frame, the same 16-step penumbra, 24.0 dB against a 64-point render where the old frame read 24.8 for pairing every point with every jitter offset). One pass (every frame outside that loop, the live path included) is byte-identical by construction.TracedShadowPassTests: the shared penumbra within 4 levels of the whole set traced in one pass (1.2 to 2.2 measured, 0.9 to 1.6 for the old every-pass trace, 41 to 88 for a collapsed set), and a budget of 1 drawing what 16 draws under 16 passes; both red under plants. The live stabilizers carry no test (the artificial-life honesty rule; every deterministic probe restarts the loop): verification is the frame-diff record in ARCHITECTURE.md (TAA-off control exactly 0.0; converged hairline-rod crop p99 3–11/255, down from 14–33).TAATestspins the deterministic half — the kernel-discrimination probe (the export average must match its own analytic construction, built by box-reducing an 8× reference at each declared offset in linear light; a plain box-filtered ground truth is not the export's limit, its kernel is box ⊗ jitter set, and judging AA in gamma space is the classic trap), flat-interior energy conservation, on-then-off byte-equality, two-render determinism, the 2D gate, and the exact-pixel-shift unit — discrimination + conservation verified red by sabotage. Per-object motion vectors —withMotion { }/withMotion(declares the block's meshes one world-space mover, and scopes the drawing state like"name") { } withState(the Sketch forms wrap the body; unscoped, atranslateper block in a loop accumulated and a 10 by 10 grid drew 2 boxes,VelocityBufferTests): the drawer remembers each draw's model matrix across frames under call site + occurrence + draw index (the.aBlockKeepsItsTransformInside SSRSlotKeyrule, never a frame-wide ordinal; history prunes when a key skips a frame, and a first sighting records nothing) and recordsprevModel·inverse(per vertex range;curModel) encodeVelocityPasswrites an rg16Float velocity texture — previous − current, pixels, y-down, both view·projections unjittered (the MetalFX motion contract verbatim; one buffer designed for TAA + the temporal upscaler + motion blur, each now a shipped consumer) with a sentinel clear (OLLIN_VELOCITY_NONE; a NaN from a degenerate transform reads unwritten), in two phases: non-movers depth-only first (nil fragment + empty color mask — a hidden mover must lose the depth test; wireframes skip both phases) then the mover ranges, multisampled at the geometry pass's count and resolved by the nearest sample (ollin_mesh_velocity_resolveover the stored per-sample pair invelocityCache, the readable-MSAA shape of the mesh-normal pass: a pixel a mover covers at all carries the mover's motion, as the.mindepth resolve already carries its depth, so the blur's depth and velocity agree at every edge; single-sample, a pixel whose center missed the mover kept the background's motion and its share of the mover stayed sharp, about 1% of a 24 px box's light on its leading side); the resolve samples at its dilated closest-depth neighbor (closest-fetch) and a written texel replaces the matrix fallback, which stays verbatim — population is sparse movers-only by design (every no-mover pixel keeps the shipped live-measured path, byte-identical by construction); a stationary mover writes the camera's own motion (the total-motion contract, probe-pinned). Live-only for TAA (export supersamples within the frame and never reprojects, so under TAA alonewithMotioncosts an export nothing; the motion-blur chain re-encodes the same pass headless when it needs velocities).VelocityBufferTests(13: registry rules + velocity-texture readback probes over a 1:1 ortho scene + a crafted-texture resolve-branch probe; the velocity-sign / occluder-drop / resolve-sign sabotages each verified red); the live perceptual A/B is measured (static-camera probe, 30-capture bursts per mode: mover edge raggedness 0.006 with exact motion vs 0.048 without, 3–10× at every matched bar length, control rod identical, no ghost either way — record in ARCHITECTURE.md). Example3D/(the orbiting bar'sEffects/ TemporalAA exactMotionparameter); snapshottaa. A mesh that changes shape —drawMesh(hands last frame's vertex positions (same count and order; a mismatch notes once and falls back to the transform-only form), and the drawer expands them in the mesh's index order like the vertices, bakes them through last frame's model matrix when the key has one, else this frame's (a mover that also moved whole writes the sum), and records the range with_: previous: ) previousStartinto the per-framemoverPreviousPositions(previousOfCurrentleft the identity; a first sighting records, since the sketch said where the vertices were); the velocity pass uploads those positions itself into a ring of 2 ×maxFramesInFlightslots advanced per encode (the pass runs at most twice a frame: the TAA resolve, then the blur or the upscaler) and draws such ranges throughollin_mesh_velocity_deform_vertex(previous world positions at vertex buffer 4,.meshVelocityDeformingbeside.meshVelocity, same fragment), switching pipelines only where the kind changes. Outside awithMotionblock the Sketch call opens an implicit block keyed by its call site (hasOpenMotionBlockdecides), inside one it joins the block's identity. Deforming and transform forms of one displacement write the same field (probe-pinned, no texel differs past 0.05 px);VelocityBufferTestspins the first-sighting record, the per-vertex previous place, the mismatch fallback and its note, the block's placement applied to the previous positions, the per-frame reset, and the readback probes (the displacement, the two forms agreeing, the still mesh). Mechanism:ARCHITECTURE.md§ Temporal anti-aliasing.Docs/.3D/ 3D .md#temporal-antialiasing Specular anti-aliasing (
specularAntialiasing(/_: strength: ) noSpecularAntialiasing(;) ollin_ndf_filter_kernel+ollin_ndf_filteredinRenderer/,Shader3D .metal specularFilteronOllinLighting). The shading half of anti-aliasing, beside temporal AA's geometric half: MSAA takes many samples of the shape and one of the shading, so a highlight narrower than its pixel is a speck the single sample lands on or misses, and fine shiny detail crawls with sparkle as it turns. Each lit mesh fragment measures the spread of shading normals its own pixel covers (the two screen-space derivatives of the world-space normal) and adds it to the squared GGX roughness, which turns the missed speck into a slightly broader highlight that holds still. Per-frame state liketemporalAntialiasing(; any Metal GPU; two derivatives and no extra pass. Load-bearing: the kernel is the published less conservative isotropic form (the average of the covariance eigenvalues) at strength 1 rather than the conservative one, since a sketch that asked for polished metal should still get polished metal, and strength 2 reaches the conservative form; the math happens in α² units (α = perceptual roughness squared, so the filtered value is the fourth root of α⁴ + kernel) and is applied at the definition of every local roughness, which is what carries it through the direct-light, LTC area-light, clearcoat, and environment reads in one edit each; zero is the gate at both ends () sigma2 <= 0skips the derivatives,widen <= 0returns the roughness untouched rather than through two roots), so an unfiltered frame is byte-identical by construction rather than by tolerance; the derivatives are taken at the top level of each fragment, never where the normal was last written (the maps path writesNinside detail-map and decal branches, and a derivative asks for control flow every pixel of the quad reaches); the parameter cannot be namedkernelin MSL (a reserved word); and the widening is capped (the published 0.18 in α²), which is what stops a silhouette quad straddling two surfaces from turning matte. Reaches all four lit fragments (solid, textured, normal-mapped, map-driven) and themeshLitColor/meshLitColorMapped+ollin_pbr_ibl_ambient/_mappedhand-synced pairs, always as a trailing defaulted argument, so every other carrier (the raymarched fields, the traced hit shades, which have no derivatives) passes nothing and is unchanged. Envelope, stated rather than silent: it fixes a highlight that is in range, and a highlight already clipped to white is flat, so widening it spreads that flat area and reads brighter rather than steadier (measured: against a converged reference the filtered frame is further from the truth once the light clips); and the estimate comes from one quad, so detail far below a pixel is guessed rather than measured.SpecularAntialiasTests(8: the strength-to-variance packing and the three ways of saying no, the per-frame reset, and four render probes — the crawl of a sub-pixel surface measured against the converged sequence of the same frames (truth 0.039, unfiltered 0.148, filtered 0.112, so a third of the excess goes; both crawl probes verified red by sabotage), the parameter still buying at strength 2, and three exactness probes: a flat sheet, an off frame, and an unlit frame all byte-identical). Example3D/(a bed of small polished balls with the toggle, the strength, the ball size, and the polish on parameters, and a flat plate behind them as the counterfactual in the same frame); snapshotEffects/ SpecularAntialias specular-antialias. Mechanism (the measurement record and the envelope):ARCHITECTURE.md§ Specular anti-aliasing.Docs/; Guide Ch 34 § Highlights that hold still: specular anti-aliasing.3D/ 3D .md#specular-antialiasing Motion blur (
motionBlur(/shutter: ) noMotionBlur();ollin_mb_*inRenderer/+ShaderCombine .metal applyMotionBlurinMetalRenderer+Targets). The published velocity-buffer reconstruction filter (credited in.swift ATTRIBUTION.md): a full-screen velocity fill (thewithMotionmover texture composited over depth-reprojected camera motion per pixel — the temporal upscaler consumes the same field through its own unscaled variant, the blur's copy being half-shutter-scaled and magnitude-clamped to the published[0.5px, k]), the TileMax → NeighborMax dominant-velocity pyramid (k = clamp(height/36, 16, 64), the published 20 px at 720 tall made resolution-relative), and the scatter-as-you-gather reconstruction (a depth compare whose two halves sum to one, a spread compare from each side, (S − 1)/2 tap pairs either side of the pixel with S = 9/15/27 byeffectiveQuality(— the TAA no-per-feature-parameter rule; the gather jitter is a pure function of pixel position, the dither's rule). Load-bearing: the weights are never renormalized — their mean over the taps is the streak's share of the pixel and the pixel's own color fills the rest, so every result is a convex combination (never outshines) and a mover keeps its light (the renormalized three-case gather it replaced 2026-10-08 kept a mover's interior whole and gained 5%/25% at shutters 0.5/1; measured against.default) --subframes, the region error fell from ~20% to under 2% of the box's value); the published mirrored background reconstruction is left out on measurement (it smeared a still column beside a fast sphere and moved the streak further from the subframe reference); a half-covered mover edge pixel streaks with the mover (the mover pass multisampled and resolved by the nearest sample; the region invariant holds with the box's edges on pixel centers, where the single-sample pass had lost ~1% of the box's light on the leading side); and 2D drawing over the 3D scene, or over a sky, takes the motion of what is under it (captions belong inwithOverlay). Per-frame state like TAA; same envelope (main canvas + active 3D camera only, 2D no-op with a note, targets/accumulation/texture-handoff excluded); any Metal GPU; runs after the TAA resolve, before the frame filters (linear pre-tonemap, so bloom reads the streaks). Load-bearing: the cross-frame camera lives on the Drawer (previousCamera3D, kept inbeginFrame), so live, same-frame repeats, and headless export all read the same previous matrix — the TAA slot's copy is the identical value on a live frame, and on a repeat the slot has already advanced, which is exactly why the blur re-encodes the mover pass itself through the sharedencodeMoverVelocitycore (the TAAencodeVelocityPassgates are untouched, so the shipped TAA path stays byte-identical); export works because the headless drive already runsperformDraw()for every warmup frame, so the mover registry and previous camera populate with no extra machinery, and frame 0 (no previous camera) renders unblurred by definition; a still frame skips on the CPU (previous view-projection float-equal + no mover ranges → byte-identical), and a still mover passes through the GPU early-out byte-identically; the backdrop (depth exactly 1) takes the sky's turn under an environment and holds still otherwise (backdropTurnsWithCamera+ollin_backdrop_motion, the TAA background rule shared with the platform effects' fill: the environment's picture sits at infinity, so a turn streaks it by what it streaks a floor at the horizon and a travel by nothing; over a plain clear color the 2D drawing and the clear never smear;theSkyStreaksUnderATurningCamerareads the procedural sun's run on its row); soft-depth extent = 1% of the eye→targetsceneScaleproxy (a screen-space constant would hide a scale assumption, the SSS lesson); the depth resolve reuses the TAA.minattachment, gate widened totaaActive || blurActive(export allocates its own). Shutter 0.5 = the 180-degree film standard; the fill stores current − previous × half-shutter (the paper's half-spread, sign-exact). Point clouds/particles take camera blur only (no per-particle velocity). Example3D/; snapshotEffects/ MotionBlur motion-blur(frame 2 — a mover + camera pan, any Metal GPU);MotionBlurTests(12: streak-direction twins, tile-pyramid reach, shutter scaling, camera-only blur, the still/frame-0/2D byte-identity gates, determinism — the neighbor-max skip, velocity-axis swap, and mover-drop sabotages each verified red). Mechanism:ARCHITECTURE.md§ Motion blur. The conservation and region invariants are under Physical invariants; the reference is Motion blur from subframes.Docs/.3D/ 3D .md#motion-blur Depth of field on the canvas (
depthOfField(/focusRange: maxBlur: quality: ) noDepthOfField();ollin_fx_lens_*+ollin_lens_gatherinRenderer/,ShaderCombine .metal applyDepthOfFieldinMetalRenderer+DepthOfField). The finished 3D frame blurred by its own depth through the camera's thin lens:.swift Camera3D.aperture(radius, world units),focusDistance(from the eye, along the view axis; the target's distance when nil),apertureBlades. Per-frame state like motion blur; main canvas + perspective camera + aperture > 0 only (a note otherwise;withTargetlayers and the accumulation surface stay sharp,.defocusis the layer route). Order: after the TAA resolve, before motion blur on all three chains (live, both export chains, the benchmark), since the gather is a fixed pattern the history need not clean and a moving defocused shape should streak as one soft shape; the depth resolve is allocated when it runs. Five passes: a prepass (blur size R·F·|1/s - 1/d| px with F = P11·H/2, distance read nearest from the resolved depth, the backdrop at depth 1 read as the far plane, which keeps a far highlight's light in balance: held sharp it doubled), a k×k tile pass (widest blur, widest blur in front of the focus, and the tile's color spread), a 3×3 neighbor max, the gather, and a 3×3 median (the nine-input exchange network) blended in by the pixel's own blur so nothing in focus is touched. A pixel gathers only to max(its own blur, the widest near-field blur nearby) (a farther tap is held to the pixel's blur and a nearer one behind the focus is less blurred), and a neighborhood of one flat color returns the pixel (exact: any weighting of one color is itself); k covers the gather's whole reach including a bladed iris's corners. The gather is a scatter written as a gather: each tap is a disc of light with density 1/(pi c²) times the area it stands for, which keeps a highlight's light as it opens and a sharp line's weight against a blurred background (an average of the taps that reach gives both away). Taps read whole pixels (a filtered read invented a blur size and threw a sharp line's color 10 px), distances run between pixel centers and a tap on the pixel itself is skipped (its light ishere), and the spiral places tap j at r² = start + 2s(j + 1/2) (stepping r by s/r overshoots the first ring: a thin line kept 95% of its light at a quarter-pixel step), in two zones when a wide near-field blur sets the reach past the pixel's own (half the taps to its own blur, so a small source is found; one zone left the bokeh grainy). The whole spiral is moved per pixel by up to half a tap spacing (interleaved gradient noise of the pixel position,kDofJitter, so exports stay identical): unmoved, the taps finding a small source shift slowly across pixels and leave smooth blotches the median cannot see; moved, the grain is a pixel across and the median takes it. The smallest sources leave the gather (ollin_lens_sprites_collect,ollin_lens_sprites_vertex/_fragment,encodeLensSpriteCollect/encodeLensSprites,PipelineKey): a pixel blurred by 3 px or more, brighter than three times the dim mean of a ring 4 px out with at most two bright samples on it and never an opposite pair (a dot of five pixels passes whole, a line fails, a dot of seven gathers), keeps the ring's dim mean in a flattened copy of the frame the gather reads and hands the rest to its 2x2 block's sprite (one slot per block in block order, never an append cursor: an additive draw rounds by its order and the frame must repeat); the sprite is a quad at the light-weighted center with the light-weighted blur and distance, drawn after the median at the gather's density.lensSprites 1/(pi r^2)through the same iris, its edge softened bysqrt 2times the radius of gyration of what it took, and covered by a nearer surface by the share of a ring at that surface's own blur whose samples are nearer (all deep inside an occluder, half at its edge, all for a sharp one). The ring's mean is of its dim samples only (a bright one is the source's own far side; counting it left a tenth of the light to gather as blotches). A one-pixel lamp kept 0.2% of its light gathered at.performanceand 64% at.default; it keeps 100% as a sprite, and a five-pixel highlight's disc interior is flat within 2%. The pass costs nothing measurable: 400 lamps at 1080 by 1080 on an M2 read 0.3 to 1 ms faster with it at both tiers, within the run-to-run spread (the flattened frame short-circuits more of the gather than the collect and the draw cost)..defocusruns the same collect and draw under its ramp law and iris. A traced export stands the canvas pass down (pathTraced != nilin the headless chain): the traced frame came through the lens already, and the pass over it blurred twice (disc grain std/mean at the export tier 0.104-0.136 with neither, 0.054-0.078 median alone, 0.043-0.061 both; the median costs a highlight 1-3% of its light). A bilateral prefilter before the gather was tried and measured no gain. Three layers by distance against the pixel's own (within 1% is the same surface): taps nearer and in front of the focus are a veil (densities summed as coverage, composited over the rest); the pixel's own surface, when it is itself in front of the focus, covers the pixel by its share of the disc nothing in front takes, own area against the holes the scene behind shows within its blur (one minus the holes counted the surface's nearer part twice, once in the veil and once here, and drew an outline inside a blurred ball's edge: its cover stepped 0.198 a pixel where a 22 px blur allows 0.029; as a share the veil's X and the surface's Y/(1-X) add to X+Y, and a density sum comes out short once the disc is smaller than the taps), else it joins what stands behind, normalized; a farther tap is held to the pixel's own blur. A farther tap counts as another surface only when its blur differs too, compared as the lens's own blur beforemaxBlurcaps it (a ball's edge turning away left a light rim otherwise, and a capped near bar matched its backdrop), and behind a foreground the scene beyond the tap's own blur stands in at a quarter weight (kDofRevealWeight; the inside of a blurred bar matches the pixels beside it, RMS 0.035 against a layered thin-lens reference, 0.042 at full weight). Split at the focal plane alone a subject in focus counts as foreground behind a blurred bar; a veil on both sides of the focus was tried and refused (it kept every light but ringed a sharp subject over a layered far field with blocks, since what hides a far source is usually sharp and must be filled from what shows), and so was folding the own surface into the veil (as close to the traced lens on a floor scene, but a bar over a ball covered it 0.22 where the lens gives 0.30). The published two-layer forms were implemented and measured too: sorting by the tile's closest distance (the 2014 course) sorts a ball behind the floor in front of it as background, since with no scene scale a depth range cannot both hold one object together and split two (its blur stopped spreading: a sharp edge), and sorting by the sample's own near-field blur (the 2013 shader, one averaged layer behind) let a sharp surface behind a slightly blurred one outweigh it forty to one by density (a crescent of the red ball through the yellow). Measured against the thin lens (study, 512 px): radius within 0.5 px at eight depths near and far, light 97 to 100% (behind the focus a bar a tenth as blurred as its backdrop keeps 98.5%, the share model's; averaged by density it kept 92.7%), highlights even discs (peak over mean 1.5), no rim at an in-focus silhouette (1.000;.defocus1.099 with its earlier gather, 1.001 with this one), a near bar's cover 0.77/0.51/0.30 against 0.76/0.50/0.30, and, on a floor scene with a ball in front of the focus, 0.0064 RMS against an accumulation-buffer lens (512 pinhole renders of the same raster, the eye moved over the aperture throughCamera3D.intrinsicwith the principal point shifted so the focal plane holds: the reference that shares the raster's shading, 0.0076 before the share fix) and 0.024 against the path-traced lens (its shadows differ). The hidden layer (encodeHiddenLayerPass,hiddenLayerExtent,OllinPeelin the shared header,kOllinPeel+ollin_peel_rejectsinOllinShaderLib,.metal PipelineKey.peel): what a blurred foreground hides is read from the 3D scene drawn a second time keeping only what lies behind the first layer, the hidden image of Lee, Kim, and Choi's per-pixel-layer splatting (2008), drawn as a depth peel against the main pass's resolved depth (.min) under the main pass's own jitter, into cached MSAA color + depth resolved like the main pass, throughencode(itspeelargument) with the same shading inputs. The peel is a function-constant variant of every 3D fragment (kOllinPeelSet, index 15, set byfragmentFunction(; the lit mesh family incl. textured/normal-mapped/surface-mapped/matcap, points, lines, the ocean, the depth scene), the first layer's depth at fragment texture 29 and the rule at buffer 10: a fragment stays out when it is no farther behind the first layer than 1% of its distance plus how far its own slope carries its depth across 1.5 px (a surface seen nearly edge-on changes depth by many pixels' worth inside one pixel and the nearest sample sits anywhere in it; without the slope term a sphere's own rim joined the layer), and a face turned away from the eye stays out when the kind says so (a closed mesh or copy, a field: a closed shape's inside; blades, splats, lines, water, a depth scene have none). A mesh says whether it is closed (named: peel: using: ) Mesh.isClosed, internal: the generators set it,falsefor a plane, a strip, an open-ended tube, a parametric surface that does not wrap both ways;nil, the loaded or hand-built case, reads as closed), carried per batch asGeometryBatch(a change opens a fresh batch, like a finish change), so an open surface seen from its back joins the layer (.meshClosed anOpenSurfaceSeenFromItsBackJoinsTheHiddenLayer) while a sphere's inside still stays out. A function that names a function constant at all, even only throughis_function_constant_defined, cannot be built the plain way (Metal refuses the pipeline), so every geometry fragment is now made throughmakeFunction(with no value set. A raymarched field peels too (name: constantValues: ) ollin_raymarch_fragmentunderkOllinPeel): the march starts behind the first layer's distance at the pixel, past the same tolerance (a hundredth plus the slope term, the slope from the field's own gradient there), and where that point lies inside the field's body (the field is the first layer) it first walks out by the field's own distance, then runs clearing until the face it left is a pixel's footprint away, recording no near-miss before (clearinginollin_raymarch_fragment; without it the face just left read as a grazing hairline over the whole first layer), and only then looks for the next entry, so a solid's inside never joins; with a peel every field marches at full size through its variant, since the reduced-size pre-pass holds the first layer. A replayed batch, a wireframe, and the ink line draw into the layer unpeeled or not at all; the live grid stays out. Drawn only when and where the near field is (hiddenLayerDrawnLastFrame/hiddenLayerExtentLastFrame):GeometryBatch(a mesh batch's union of each mesh's box through its matrix, a list-placed instanced batch's bounding spheres) gives each batch's nearest view-axis distance against the distance where the lens blurs half a pixel in front of the focus, and the near batches' projected corners (two pixels of margin) scissor the pass, cleared whole first so outside it the layer is the backdrop; a kind with no box (GPU-placed copies, fields, strands, water, points, lines, a marched field, a depth scene, a replay holding a point cloud) counts as near and everywhere. The gather reads it under a near-field pixel (textures 3 and 4, the layer and its own prepass; params[3].x says whether one ran, else the frame stands in for it and every hidden tap reads as unknown, which keeps a frame without the pass on the shipped math): a hidden tap is known when it lies behind its tap's own surface by over 1% (the backdrop is known to hide nothing), and a known tap turns the quarter-weight stand-in off; it lands only for a pixel in front of the focus and only under a tap in front of the pixel or under the pixel's own surface, sorted by distance with no turning-away rule; under the pixel's own surface it is behind that surface whatever its distance says (under a floor of boards the layer holds the next boards' lit sides, within a percent of the top, and sorted as the surface itself they darkened the floor 2%), so it goes to a separate back sum that joins the holes' light only when its mean inverse distance stands in front of the holes' own (a ball's top against the backdrop with the floor hidden behind it: yes; a gap between boards showing the next board's side, with the backdrop under the boards never reached: no; soft-edged at ±10%); a known hole's stand-in (the quarter weight past its own) is kept aside and fills whatever share of the holes' light the layer does not, so a pixel never falls back to its own color where the layer is known but not what the holes show (a near ball behind a nearer one kept a hard dark notch inside the nearer one's rim without it); behind the focus the layer is read only under a veil tap, since what a near ball hides scatters past its rim onto the scene beside it (the lens shows the floor behind a ball's top on the backdrop above), and never under a tap behind the focus (a nearer surface there blocks the rays that would reach what it hides; added anyway it diluted a far bar's light to 93%). Behind the focus the same share model holds (.worldBounds mid, the second veil): the pixel's own surface against the holes that show what stands behind it (farther taps, held to the pixel's own blur), a nearer surface at or behind the focus over that by its cover, the near field's veil over everything, with the plane-continuity test on this side too so a receding far floor is not sorted into veils and holes against itself; averaged by density instead, a bar a tenth as blurred as the backdrop behind it kept 92.7% of its light (98.5% now) and a highlight there 94.1% (98.1%), and the near bar over the subject reads 0.0222 RMS against the layered reference (0.0271). Measured on the lens figure's own scene (880 by 420, the accumulation lens again): the halo over the ball's top +0.0049 green over red, the 30 px band around the ball 0.0097 RMS with 0.0020 in its high-frequency part, and the edge profile never steeper than 0.018 a pixel against the lens's 0.024; what remains is a band outside the ball's upper-left rim over the floor behind the focus, 0.020 RMS, darker than the lens by a floor-colored amount (DESIGN-NOTES). A tap at another distance is another surface only when its lens blur lands off the line the pixel's own surface draws across the screen: the signed uncapped blur is affine in inverse distance, so a plane extrapolates exactly, the slope taken as the gentler one-sided difference per axis; before, a floor running toward the eye read its own farther taps as holes (harmless while the stand-in was the same floor, a dark smear once the layer filled them). Measured against the accumulation-buffer lens on the floor scene: the green cast where the ball's top meets the horizon +0.0137 to +0.0036, the halo's RMS 0.0273 to 0.0170, the band around the ball's edge 0.0143 to 0.0108, its high-frequency part 0.0042 to 0.0037, the whole frame 0.0064 to 0.0050 (the near floor's gap lines read a touch darker, 0.0034 to 0.0042, where the undiluted holes show the gather's taps). Cost at 1080² on the M2, a bead sphere: +10.6 ms.performance, +14.8.default, up to +34.detailwide open for the gather; the second drawing plus the gather's two extra reads per tap, the figure scene wide open at 1080² with the near field across most of the frame: 33.8 to 38.7 ms at.default, 73.7 to 82.3 at.detail(the frame without the lens 4.6). The live window and an export match byte for byte at the same tier.DepthOfFieldTests(16: thin-lens radius and light incl. a line a hair behind the focus against the far-plane backdrop, an even highlight disc, a small highlight even and whole at the lowest tier (the sprite's 99.5% against the gather's 94.5%), a sharp bar cutting a far highlight's disc, the in-focus edge, the near veil against the analytic disc-strip cover, no outline across a blurred ball's edge (went red on one minus the holes), the floor hidden behind a blurred ball's top showing through it while nothing shows above the ball, the layer drawn only with something in the near field and only over its pixels (and never for a pinhole), the band and the cap, beside TAA and motion blur, the window equal to the export, pinhole and orthographic untouched with their notes, determinism; the hidden-surface clamp, the own-surface veil, the near and far split, count-not-area weights, the stepped spiral, the near-plane focus, and the export skip each went red, and the window test caught the live skip). Snapshotdepth-of-field-3d; Docs figureDepthOfField3D.Docs/. The Jacobian of the blur's slope (ruled by measurement 2026-10-05): a tap's density 1/(pi c²) is exact only where its surface's blur is flat; where c varies across a surface the map from a lens point to the image is stretched, and the exact density carries3D/ 3D .md#depth-of-field 1 + ((q the pixel, u the tap, grad c the blur's slope along the tap's own surface).q - u) · grad c / c ollin_fx_lens_dof_slopewrites that slope per pixel beside each blur map (the gentler one-sided difference per axis of the capped blur, zero where the two disagree in sign, so a one-pixel line or a step between surfaces never stands for a surface's slope), the gather reads it once per tap (textures 5 and 6, the hidden layer's too) and holds the factor to 0...2, with 1 where the pixel clamped the tap's spread;offsetruns from the pixel to the tap, so the code's sign is minus (the first cut had it plus and doubled the error, which is the signature to look for). And a near surface's share of its own pixel is its light density, not an area:ownWeight /, whereflat / ( 1 - X) flatis what a flat surface at the pixel's own blur returns through the same taps (one on a flat field by construction, under one at a sub-pixel blur where whole-pixel taps cover their footprints only in part; without it an in-focus ball read a quarter transparent, 0.084 RMS on a 20-px block), so the share reduces to the area form on a flat surface and follows the lens on a curved one. Why: to a thin lens a ball is a disc at its center's depth (a ray meets it when it passes within the radius of the center), while the gather spread each rim point by its own wider blur. Measured on the lens figure's scene against the accumulation lens with the near ball flat white on a flat black world (the harness's cover-only switch): the canvas covered +0.02 to +0.035 more than the lens over 0...25 px outside the rim in every direction and 0.04 to 0.06 less inside, +0.63 to +0.83 px of cover integrated outside; the ideal scatter without the factor reproduces that to the hundredth (+0.91 px) and with it closes three quarters (+0.21), light conserved; the canvas after: +0.07 to +0.17 px outside, every ring within 0.01 inside and out. On the lit scene the band outside the upper-left rim (the 0.020 RMS item) reads 0.0109 outside-only from 0.0128 with its teal cast gone (mean rgb error -0.0085, +0.0035, +0.0042 → -0.0044, +0.0002, +0.0008), the top halo's green-over-red bias +0.0049 → +0.0014 (the ~10% item), the top edge's steepest step equals the lens's (0.0127 vs 0.0126, from 0.0094), the right and bottom bands 0.0093 → 0.0039 and 0.0025 → 0.0008, the whole frame 0.0071 → 0.0066 per channel; the red ball at the focus, the horizon rows, and the near floor within 0.0003 of before.aBlurredBallsEdgeFollowsTheLenspins the edge within 0.02 of the thin lens's exact sphere cover (thinLensSphereCover, 4096 lens points, nothing of the gather in it) at every 2 px from 30 inside to a blur outside, 0.017 at its worst and 0.072 on the old gather; every other DOF claim and the snapshot suite held. Open, measured: just inside the top rim the canvas reads 0.02 dark (the sphere's own limb, culled from the peel as back faces), and the dotted gap lines barely move with the tap count (0.0012 → 0.0010 high-frequency error, default → detail tier), both in DESIGN-NOTES.The overlay (
withOverlay(_:)onSketch,Drawer.withOverlay,GeometryBatch,.overlay applyOverlayinMetalRenderer+Overlay,.swift ollin_fx_copyinRenderer/). A block drawn over the finished frame after every pass (the temporal resolve or upscale, the depth of field, the motion blur, the lens flare, theShaderEffects .metal postProcessfilters), before the frame interpolation, the extra displays, the frame grab, and the linear capture, so a caption or a readout stays sharp and untinted. The block records into the frame's own batch list and is flagged when the outermost block closes (overlayon every run from the block's start, clamped against abackgroundinside it that dropped the start), so the geometry rides the frame's ring slot: the canvas pass and every layer pass skip flagged runs (theoverlayargument ofencode), the overlay pass draws nothing else, and the web page writes the canvas's flagged runs last (WebGraph) while a vector export holds the block's commands aside (.items( for: ) SVGRecorder) and writes them after the rest. The pass is a multisampled geometry pass at the finished frame's size and format that starts by writing that frame into every sample and draws nothing but the flagged runs (the environment's backdrop, which.overlayCommands encodelays under a frame's geometry, is gated off the overlay pass: drawn there again, full-frame with no depth, it covered every surface under a showcase camera whose far plane let it through, andOverlayTestspins it; the fog's air backdrop is gated the same way, since drawn there again it took every pixel as open to the far plane and a captioned low mist became one sheet below the horizon, found 2026-10-22 by bisecting the Atmosphere example to the commit that moved.aSkyBackdropNeverCoversTheSceneUnderAnOverlay drawCaptioninto the overlay,OverlayTests; any new full-frame no-depth draw in.fogNeverCoversTheSceneUnderAnOverlay encodetakes the same!passOverlaygate) (PipelineKey, an effect pipeline at the view's sample count with the pass's depth and stencil declared), so a blend mode composites against the picture as a canvas run's does against the clear (a transparent layer composited after would have multiplied against nothing); its depth is its own, cleared, and it carries the clip stencil when the frame clips. Clipping is per surface: the block starts unclipped and a clip inside it clips the overlay alone (.effectInPass ClipFrame.overlay). Over an accumulation surface the pass draws over a copy of the pile, live and headless, so the overlay never joins it. The scans that read the batch list as scene content skip flagged runs where it matters (the hidden layer's near-field extent, the instanced mover upload); a 3D shape in the overlay sorts among the block and sits over the scene, and a frame with no overlay returns its input before touching the GPU, so every other frame is byte-identical (the snapshot suite). InsidemakeBatch { }and inside a layer block the body draws as the surrounding content, noted once.drawCaptiondraws in the overlay wherever one can be opened (Drawer: not in a layer, not in a batch recording) and in place otherwise, so a caption stays sharp over a lens, a streak, or a bloom and never joins a pile..canDrawOverlay OverlayTests(6): sharp under the lens where the same bar in the frame blurs away, over everything whatever the call order, a multiply reading the finished frame, never joining a pile, a clip per surface, and the vector order.Docs/; Guide Ch 35 § The frame through the camera's lens: depthOfField().Drawing/ Effects .md#withoverlay Lens flare (
lensFlare(_:)/lensFlare(/amount: lens: ) noLensFlare(),Lens+LensInterface+LensFlarein3D/LensFlare.swift;Renderer/+ShaderFlare .metal applyLensFlareinMetalRenderer+Flare). The camera's own contribution: light that reflects off two of the lens's interfaces instead of passing through them and reaches the sensor in the wrong place. Every ghost is followed ray by ray, written from the published real-time ray-traced flare method, with the published matrix (first-order) formulation beside it for what first order is good for, and the thin-film anti-reflective coating reflectance, the exact single-layer form (every round trip in the film summed per polarization, one closed fraction on the CPU and in.swift ollin_flare_coated;aCoatedSurfaceReflectsWhatAThinFilmDoesholds both directions through three glasses, three wavelengths and 0 to 60 degrees within 2%, where the earlier two-beam form read twice the reflectance head on; it reaches 1 at the critical angle by itself, so no blend toward bare glass) (all credited inATTRIBUTION.md). ALensis a stack ofLensInterface(radius / thickness / index after / clear-opening height / iris flag / optional coating wavelength / optionalabbeNumber), the same table a lens patent prints. Bundled:Lens.doubleGauss(1950s 100mm f/2 six-element, 11 interfaces → 20 ghosts in a run of sizes, the chain a flare is known for; its last thickness is the paraxial back focus the table works out to, and one radius the patent's scan garbles was settled by the focal length landing on the patent's normalized 100),Lens.heliar(1950s ~100mm, 9 interfaces → 13 ghosts, most of them wide, faint and cut by the barrel: a veil more than a chain), andLens.standard, what a barelensFlare()uses: the double Gauss multicoated at f/5.6 (any lens wide open is haze and a single coating is one color; f/5.6 since 2026-10-22, the look the old f/8 drew while the iris was set from the entrance pupil's radius).stopped(to:)closes the iris to the f-number read at the entrance pupil: the iris radius is f/2N timesLensOptics, the height at which a ray parallel to the axis entering at height 1 crosses the iris (0.69 on the double Gauss, 0.80 on the Heliar), so the double Gauss wide open reads the f/2 its patent prints;.irisScale multicoated(hands the wavelengths out by a golden-ratio walk, never a front-to-back sweep (a ghost is a pair of surfaces and the brightest pairs are neighbors, so a sweep gave the double Gauss five blues). The matrices are checked against real rays, and they were wrong for a month without that.from: to: ) everyGhostAgreesWithRealRaysfollows a near-axis ray through the real spheres (Lens.trace, exact vector optics) and demands the matrices' sensor point, iris point and both incidence angles to 1e-5, for every ghost of both lenses. As shipped on 08-20 the chain passed through the inner reflecting surface before reflecting off it and mixed two conventions on the backward leg (the inverse of a forward refraction is real-slope; the travel and the reflection were slope-along-travel), so every ghost was misplaced and missized by factors of 2.6 to 7.5 and nearly all landed on the light's side of center; the incidence angle also had the lean's sign wrong (a ray aimed at the center of curvature must meet the surface head on: slope plus lean). The only check then was the straight-through path (directPupilScale ≈ 0,directScale ≈ focalLength), which has no reflection in it. One convention throughout: heights real, slopes measured along the way the ray travels; a surface met from behind is the same sphere with its radius negated and its media swapped, as a refractor and as a mirror; the inner surface is never crossed. Both reflections stay on one side of the iris. The tracer (SwiftLens.trace, mirrored inollin_flare_trace): surfaces met in the path's strict order, never by nearest, with a negative ray parameter allowed so a sphere carries past its own rim (those rays are never drawn, they feed the interpolation); the root taken is the pole, by the sign ofradius · direction; a flat glass surface refracts (the Heliar has one; only the iris is a bare plane, and it records where the ray crossed);.z relativeHeightis the largestr / clear heightover every glass surface; each reflection's coating is evaluated at that ray's true angle; and what crosses a surface is what does not reflect there, which is what lets the mesh have holes: a ray's light falls to nothing as it nears the angle it could no longer leave the glass at, so the neighbors of a lost ray are already dark. On the GPU a ghost is one instance of a shared grid (flareGridSides16/32/64, picked so a cell spans ~16 canvas pixels, where a 300-pixel barrel arc strays a tenth of a pixel from its chord), traced in the vertex stage, three rays a vertex: itself and its two inward neighbors a full cell away, so the light a cell is given is the light it carried in (squeeze= the area ratio; measuring over half a cell while drawing whole ones lit stray triangles).squeezehas a floor from the source's own picture on the sensor plus a pixel (soft.z, what keeps a caustic finite) and a cap at a twelfth of first order's ratio (a fold finer than the grid would come out as beads). A lost neighbor is asked for on the other side, and a ray with none carries nothing; a lost vertex is put where a surviving neighbor landed so its cells close up. The grid always covers the whole front opening (pupil · (): trimming it to first order's preimage of the iris is wrong for a strongly bent ghost, whose real rays enter nowhere near there. The fragment clips softly at the barrel (1.12 + barrel softness) relativeHeightthrough 1, as soft as the source is wide) and at the iris (the blade walk +ollin_flare_overlap), keeps its earlydiscards (removing them, since the pass adds, measured 10 to 25% slower), and adds into a half-size, 4x multisampled, memoryless canvas resolved totracedLight(PipelineKey= the caustics splat's additive depthless shape +.flareGhostTrace isFlareTrace): half size because a ghost's edge is never sharper than its source is small, multisampled because a fold caustic is a mesh silhouette no soft-edge test reaches (at one sample, 2-pixel stairs). The composite addsghostLight+tracedLight+ the full-size star. The followed ghosts read the visibility strip in the vertex stage, per light (left out at first, a hidden lamp still flared; the occluder probe caught it). Color: three channels in one pass at the printed index for most ghosts; seven wavelengths, one pass each, only when the colors part by more than 1.5 canvas pixels and the ghost reachesflareColoredFrom(0.02), since wide faint veils part by the most pixels and would otherwise take seven passes each for nothing (that, a 96-grid and five rays a vertex were 2.6M rays a frame, +18 ms). BudgetflareMaxTracedDraws144; over it the faintest give up their colors. Ringing inside a crisp edge is straight-edge Fresnel diffraction read off the iris's edge distance, scaled per ghost byLensGhost.ringScale= sqrt(2|m| / (lambda B)) from the iris-to-sensor matrix, per channel, and worked out only while the source's blur is under one ring. What first order still draws: a ghost whose source is wider than the opening it came through is a picture of the source, its bends smeared away, and the backward per-pixel map has that smear in closed form (ollin_flare_ghosts: per-channel maps, the coating from a per-lens tableLens.coatingTableread at the middle of the stretch of the opening that really passes, never the rim, the source's disc through a cubic overlap ramp that caps at the ratio of the areas,meetingfor two openings both smaller than the source).followedcross-fades the two per ghost overmax(0.3…0.6, so nothing changes hands in one step;sP/ pupil, sI/ inner) MetalRenderer(internal, test-only) turns following off. Level, anchored and the lens's own: set once under standard conditions (iris open, 0.15 rad, a 0.02 rad source) as the lower of two ceilings, no ghost above.flareFollowsRays lensFlareGain0.1 and all together adding no more thanlensFlareVeil0.025 to a normal frame on average (both lenses are bound by the second). Closing the iris brightens every ghost by the entrance pupil's area ratio, held exposure (LensOptics.stopGain, capped at 64x; ruled 2026-10-22 over the September per-ghost rule, under which a ghost the front glass bounds did not brighten): the iris takes light from the scene and the held exposure gives it back, so an iris-bound ghost keeps its light in a smaller shape and a barrel-bound one comes out brighter at its own size. It dims the star's arms by the square as it lengthens them. A directional source's projected depth is held at 1; a point source's visibility depth is pulled 2% toward the eye; visibility is its own 4x1 pass, a 17-tap ring oversourceSize. Composites after motion blur, before the frame filters, on all three chains. Not a defect: the Heliar's (6,8) ghost is a hexagon with curved-in sides and sharp cusps (it passes the iris first and is bent hard after: pincushion distortion of the iris's image), and a near-focus ghost can fold into a small comet. Both were chased as artifacts. Isolate a suspect by drawing one ghost at a time before theorizing. The star (LensFlare.star/starSize/wear,3D/): the far-field (Fraunhofer) diffraction of the iris, its own power spectrum, so the arm count is the blade count for an even iris and twice it for an odd one, a round iris throws only a halo, and stopping down grows it. CPU bake (vDSP FFT over an anti-aliased 512² aperture, 48 wavelengths at scaleApertureStar .swift 550/lambdawith the analytic CIE fit, ~100 ms release), cached by blade count and dust in twentieths,rgba16Float. Load-bearing: the aperture edge is anti-aliased (a hard step lays false arms down the diagonals); scaled so its mean is 1 with a 4000 ceiling; a smoothstep window over the outer 18%; drawn extentstarSize * openIris/held at 8x.iris wearis the wear on the opening (uneven and bowed blades split and fray the arms; specks and scratches become needles), seeded from the blade count;wear: 0is the clean polygon the arm-count tests measure. An edge normal lies along x first for the ghosts, the star and the defocus filter alike. Three extras from outside the spherical glass, all0by default:streak(+streakLength/streakAngle/streakTint) is what cylindrical glass does to a light (the front group of an anamorphic lens, or the fine grooves of a streak filter made to imitate it): a cylinder bends light one way only, so it fans a light across itself into one line through the source, as thin as the source is wide (max(), with a faint skirt and asourceSize · 1.2, 1.3 px) (1 - t²)^1.5taper; it is closed form in the full-size composite. (An early draft of the docs claimed an anamorphic lens does not throw this line, on the strength of one write-up; it does, from its own cylindrical elements, and the claim was checked and taken out before it shipped.)dirtis the scattering term of the published dirty-lens image formation model: grime on the front element is too near to focus, so each speck is the defocus kernel, the iris's own shape and size (it takesapertureBladesand shrinks with the f-number), lit by the flare's sources with a forward-peaked falloff1 /and by the visibility strip; up to( 1 + ( d / flareDirtReach)²)^1.5 flareDirtSpecks160 instanced quads from one fixed seed (so dirt stays put), added onto the half-size first-order canvas throughPipelineKey..flareDirt halo(+haloSize) is a look and not optics, and the docs say so: corona diffraction from fine particles was worked through as its basis and set aside, since it puts a central glow ~57x brighter than its ring; the ring is nine wavelengths with the analytic CIE fit, each at its own radius, spread a third of what diffraction would give (three channels gave three hard bands).Lens(.anamorphic( squeeze: ) Lens.squeeze, 1 on an ordinary lens) is opt-in because it changes the look a good deal: what forms behind the cylindrical front group is stretched sideways with the picture (the light reaches the lens atframe.x / squeeze, the ghosts' and the star's x is stretched back by it; for the followed ghosts it is carried in the aspect handed to the tracer, for the first-order oneshalo.w), and the dirt is left alone: the tall oval an anamorphic lens is known for belongs to blur far from it. For a point a distance z in front of an afocal cylindrical pair the displayed blur is (z + L + D) / (s z + L + D/s) as wide as tall (s the squeeze, L the pair's spacing, D the way on to the pupil), which is 1/s far off, matching real bokeh, and about 1 at z = 0, on the glass. The specks were drawn tall at first on the assumption that front dirt is bokeh; @eaviles asked whether that was right, and the derivation says it was not. The source stays round on the frame, so it is an ellipse1 / squeezewide on the sensor, and every soft edge is worked out against that: a bladed iris's distance is measured on the frame (each blade's distance scaled bybladeStretchbefore the largest is taken, or a crease runs down every corner's bisector), a round edge narrows the source along its normal (ollin_flare_narrowed, the support function under a crisp edge fading to the outline for a picture of the source), and the area cap carries thesqueezeon both sides (ollin_flare_overlapand the CPU's shares, which must agree). Left as a disc on the sensor, a ghost's sides are twice as soft as its top and a near-focus ghost is a 2:1 picture of a round lamp (probe: across-over-up 0.89 of the plain lens's, 0.53 without). The halo stretches with the ghosts (the whole flare does, per the 2015 course inATTRIBUTION.md); the streak does not. Same glass, same ghosts:optics()does not change. Three rules of the iris distance, all lenses: past a corner it is the distance to the vertex (the top two blade distances and one root; largest-of-planes miters the corner outward, a spoke from every corner of a wide soft rim, and draws a round source through a small opening as a polygon); red and blue take green's distance carried by one dot product only within green'sslack(the same blade still first and the second still inside), and ask again past it (a near-focus ghost parts its colors by more than its width, and the unguarded shortcut creased it); and the followed ghosts'lightandvalidarecentroid_perspective, since the pass is multisampled and a plain varying is read at the pixel's center even when only a corner sample of a sliver is covered, which extrapolated to negative light: single black pixels in a veil (probe: no pixel darker with the flare on; 20 were). All of it measured free, old shader against new in one saturated process (7.46 ms both, a 6x blade walk read 25.4).wearwasdustfor a few hours on the day it was added, and was renamed before release so it would not sit besidedirt. All three measured free (5.55 ms against 5.55). Probes: the streak is one line and nothing a row above it, the halo peaks at its radius with a dark inside, the dirt goes out with a hidden lamp; each seen to fail with its behavior broken. Cost at 1080² on the M2, one source, debug host: +1.2 ms for a stopped-down chain to +4 to +5.5 ms for a lens whose ghosts each fill the frame; the first-order loop is free once every ghost is followed. Measure only with the GPU saturated (frames back to back, wall clock over 120, variants by shader reload in one process, a variant with the triangles thrown off screen to split rays from fill): the drained-GPU read hid a 20 ms regression and read a cubic as slower than twoacos. Example3D/; snapshotEffects/ LensFlare lens-flare; Guide figuresGhostChain+StarPoints(both probes);LensFlareTests(23 pure: an anamorphic lens asked for and clamped, the extras off by default and clamped, real-ray agreement for every ghost, the departure from first order toward the rim and ghosts on both sides of center, the barrel stopping a ray halfway up the opening, the focal-plane check on both lenses, the iris rule, coating minimum, TIR continuity, cemented junctions, stopping down, multicoating and its neighbors, the matrices, the dispersion curve, the channels parting, the coating table) +ApertureStarTests(7) +LensFlareRenderProbes(12, the anamorphic one reading the ghosts' spread across against up, and the rest in linear light at a fraction of the usual level: adds light, fades rather than ends under an occluder, a wider source softens the ghosts' edges (read only over flat scene, since a ghost crossing the lit bulb steps by its whole level at the bulb's edge), stopping down gathers the light and adds none, following the rays stops a ghost at the barrel (48% of first order's pixels, 73% with the clip taken out, so the line is 60%), the star lands on the source, the blades reshape it, off is byte-identical; the fade, the star pair, the source, the iris and the barrel probes all sabotage-verified red).Docs/.3D/ LensFlare .md Temporal upscaling (
temporalUpscaling(/_ quality: ) noTemporalUpscaling(;) MetalRenderer+Upscaling+.swift ollin_fx_velocity_fillinRenderer/). The live window renders the whole frame at a reduced size and the platform temporal scaler (MetalFX) reconstructs the full canvas from the jittered history: the tier maps to a render fraction (ShaderCombine .metal .performancehalf per axis /.defaulttwo-thirds /.detailthree-quarters, clamped to the device range), per-pixel cost falls by the square, edges stay temporally anti-aliased. Per-frame state like TAA; same envelope (main canvas + active 3D camera, 2D no-op with a note, targets/accumulation keep MSAA) plus asupportsDevicegate (Apple silicon; elsewhere note + full res). Load-bearing: every geometry-side pass sizes to the render size (the logical canvas never changes and the encode sets no explicit viewport, so shrinking the attachments is the whole change; off, the sizes are equal and the frame is byte-identical by construction); the scaler replacesapplyTemporalAA(it is the jittered accumulation — feeding it the averaged output would integrate twice) and dropstaaHistorywhile it runs; its motion texture is the unscaled velocity fill (raw previous − current pixels y-down, both VPs unjittered — the buffer's designed contract atmotionVectorScale1; the raw-not-scaled passthrough is test-pinned; the far plane takes the sky's turn under an environment and zero over a plain clear color, like the blur's fill, pinned against a surface at the same pixel under one turn and against a camera that only travels), its jitter offsets are the content's own pixel shifts from the shared Halton table extended 16 → 32 (cyclingmin(32, ceil(8·s²))phases; TAA's first-8 cycle and the export's ≤16 prefix are untouched, prefix test-pinned); motion blur under it runs at output size reading the render-res depth/mover by UV with the mover values rescaled by amoverScalewhose (1,1) default multiplies exactly; a same-frame repeat returns the slot's output without re-encoding (the scaler's internal history must advance once per frame, thetaaHistoryrule); creation failure flips the support flag (note once, never retry per frame). Headless/export never upscale (a live frame grab carries the upscaled picture the window shows):headlessTemporalAAActiveroutes an upscaling sketch to the full-res deterministic TAA supersample, pinned byte-identical to asking fortemporalAntialiasing((the export is the full-quality equivalent of the live preview; the GPU benchmark also stays full-res). Live verification is measurement (the artificial-life honesty rule): converged static-scene frame diffs 0.08-0.11/255 mean (inside the TAA-on band, and stiller than un-upscaled because the scaler absorbs the RT-reflection sparkle), FPS A/B 29 → 60 (vsync-capped) at) .performanceon the M2 probe scene; record in ARCHITECTURE.md. Example3D/(tier + toggle parameters);Effects/ Upscaling UpscalingTests(9, fill + gate sabotages verified red; no pixel snapshot — the scaler is a stateful platform object). Mechanism:ARCHITECTURE.md§ Temporal upscaling.Docs/.3D/ 3D .md#temporal-upscaling Frames between the drawn ones (
frameInterpolation(/) noFrameInterpolation(;) MetalRenderer+Interpolation, sharing.swift encodeFXVelocityFillwith the upscaler). The live window runsdraw()on every other refresh, and the platform frame interpolator (MetalFX, macOS 26+) builds the frame between the two drawn either side of it from color, depth, and the same motion field the upscaler reads, so a scene that holds 30 drawn frames moves at the display's 60. Per-frame state like TAA. Load-bearing: the drawn frame is held back one refresh and the made one goes to the drawable first (the made frame belongs between the two, so showing the drawn one first would run time backwards), which is where the one-refresh input latency comes from; the runner askshasHeldFrameat the top of a refresh and then runs no sketch code at all (the clock is untouched, so the next step spans both refreshes and the motion keeps its real-time speed); the two drawn frames are kept in a ping-pong pair (writing the newer one must not touch the older one the interpolator is reading, and the newer one is still needed a refresh later);isDepthReversedis false (Ollin's depth runs 0 near, 1 far, and the platform default is the other way); the jitter offset is 0 because the color handed over is always a resolved frame (TAA's resolve or the upscaler's output) already on the reference grid;hostAllowsInterpolationcarries what the renderer cannot see (a take playing or recording, a stillnoLoop()sketch, a wall of displays), a reload callsdropHeldFrame(), and a sketch that stops the loop inside the draw that just ran has its held frame presented straight away (it would otherwise never be asked for another refresh, leaving a guessed picture as the final still); the depth resolve must be allocated for it (it was gated on TAA / blur / upscaler / flare, so the first live run made nothing at all until interpolation joined that condition — caught by the live-loop probe, not by the seam test). The interpolator repeats the drawn frame rather than smearing when it cannot follow the motion, including the first frame of a run, which is why starting up shows no artifact. Needs a camera with a field of view (verticalFieldOfView: perspective, or derived from a pinhole calibration; orthographic returns nil and the frame is drawn normally with a note). A frame grab never interpolates, and an export writes only the frames the sketch drew unless it is asked for slow motion out of made frames (--made-frames, its own bullet below), which drives the same interpolator through its own export slot;frameInterpolation(itself still leaves an export untouched, test-pinned byte-identical to not asking. The motion field is) slot.motion, never what the fill returns (that is the mover pass, whose unwritten pixels carry the sentinel -16384): binding the return value warped every frame that declared awithMotionmover, which nobody saw on screen at 60 fps and the export measurement found at once. Example3D/(toggle + speed parameters);Effects/ FrameInterpolation FrameInterpolationTests(7: the made mark lands halfway (history sabotage verified red), the warm-up repeat, the projection-to-fov mapping, the gate, the held-frame alternation, the live loop over an off-screenMTKViewwith an off counterfactual, the export contract; no pixel snapshot — the interpolator is a stateful platform object). Mechanism:ARCHITECTURE.md§ Frames between the drawn ones.Docs/.3D/ 3D .md#frame-interpolation Line drawing (
Sources/;Ollin/ 3D/ LineDrawing .swift Sketchover.lineDrawing( of: creaseAngle: spacing: ) [Mesh]or one, plusMeshfor placement). A scene written down as 2D paths with what the surfaces hide taken out, which is what puts a 3D scene on a pen plotter: the paths are ordinary canvas line work, so SVG, PDF, G-code and DXF carry them where a lit mesh reaches none of those. Three passes of CPU work: weld (positions merged on a grain of 1e-6 of the scene's own span, since a hard-edged mesh holds a copy of each corner per face and without it every edge reads as a boundary), classify (an edge is kept when it has one face, when its two faces turn opposite ways on screen, or when their normals differ by more than.transformed( by: ) creaseAngle), and walk (each kept edge sampled everyspacingcanvas points against the faces that could cover it, found through a grid of the canvas, with each change of visibility pinned by eight halvings, then the stretches chained end to end taking the straightest continuation at a junction). Load-bearing: the facing test is the screen turn of a projected face, not a normal against a view vector, so it needs no winding convention and catches a silhouette on any tessellation; the depth compare interpolates one over the depth under perspective and the depth itself under an orthographic camera, and needs a bias of a thousandth (an edge lies on its own faces); faces with no area are dropped or a lat-long sphere's poles scribble, since the direction of a degenerate cross product is arithmetic noise (the first render showed it as a black blot at the pole); a stretch shorter than a canvas point is dropped, which is the width of that bias where a hidden edge runs into the silhouette it ends on; geometry behind the camera is cut at the near plane, not at the eye, since a point at the eye projects nowhere; and the chaining takes the straightest neighbor at a junction, without which a cube's outline breaks into five paths instead of closing.hiddencarries the covered stretches for the draughtsman's dashed line. Ten tests inLineDrawingTests: a cube shows nine edges and hides the three at the far corner (by their middles, since the two corners on the diagonal land on one place); it comes back as few paths with the outline closed; a wall takes out the middle of what stands behind it and leaves the ends; a ball is its silhouette alone at the radius the camera says, once round; no crease angle is the whole tessellation; a plane is its border; nothing behind the camera is drawn and something half behind it is cut at it; the hidden set meets the far corner and is a third of what is seen; an empty scene draws nothing. The occlusion test and the silhouette classification were both verified red by sabotage. Snapshotline-drawing;Examples/;Export/ LineDrawing Docs/; Guide Ch 46 § A 3D scene on the plotter:3D/ LineDrawing .md lineDrawing(of:)+ the SceneAsLines figure.Sample models.
OllinSampleModels(a product of its own, never part ofOllin, theOllinSamplePhotosshape: an app that skips the import ships none of it), one model so far,SampleModel.duck, a rubber duck (Alexandr, CC BY 4.0, 1,592 triangles) as one.glbwith its single 1K base-color texture packed inside and the whole file a quarter of a megabyte (everyFileStaysUnderAMegabytepins it under one); the file marks its material unlit through a glTF extension the reader does not honor, so it draws lit like any mesh, and the shading baked into its texture is soft enough that the two read as one,load()ing through the library's ownBundle.moduleinto aMeshthat carries itsMeshMaterialand a texture (everyModelBringsItsOwnMaterialAndTexture), withurlfor a loader that takes a path (loadScene) and acredit(artist / source page / license / license URL;credit.lineis the one-line form). A model arrives as saved, in its author's units, sonormalized(scale:)is the fit (everyModelNormalizesToItsScale). A model is added by packing its download withScripts/pack-glb.py(a loose.gltfwith its.binand textures folded into one.glb, every texture held to 1024 on its long side and re-encoded, JPEG where it has no alpha; a packed file renders within JPEG requantization of the loose one, no pixel off by more than 30 levels on the three-texture model it was checked with), then astatic letwith its credit, a line inall, and its entry inTHIRD-PARTY-NOTICESand.md ATTRIBUTION.md. Wired like every satellite: theSatelliteenums in both manifests (so every host and the examples link it),.spi.yml,API/. TheOllinSampleModels .txt 3D/example cycles it under the space bar with the two files saved beside it (a textured cube, a crystal with no material); Guide Ch 28 § A mesh from a file names it as the file there is to load first.Geometry/ LoadedMesh OllinSampleModelsTests(6).Docs/.3D/ SampleModels .md Scene import (
Sources/+ theOllin/ 3D/ Scene .swift GLTFDocumentsplit inMeshLoaderGLTF)..swift loadScene/Scene(contentsOf:)is the structure-preserving complement toloadMesh: a glTF/GLB file's default scene as a tree ofSceneNodevalues (name, authored local transform kept verbatim as a matrix — never decomposed, so nothing is lost to a TRS round-trip; an optionalMeshin node-local space, that node's primitives merged by theloadMeshrules) plus the authored cameras (core glTF) and punctual lights (KHR_lights_punctual) resolved through their nodes' world transforms into ordinaryCamera3D/Lightvalues the sketch applies itself (camera(,scene .camera ?? …) light(_:)each); the USD family (.usdz/.usdc/.usda/.usd,SceneLoaderUSD) is read natively end to end — one.swift USDStageparse serves structure, meshes, cameras, materials, lights, animation, and skinning; Model I/O is out of the USD path entirely. Load-bearing: the node tree keeps authored child order and every node carries per-prim identity (sourceIndex, assigned depth-first in authored order — what every track binds by, so a name duplicated across branches animates exactly the prim that authored the samples); meshes rebuild from the authored data — indexed on the authored points normally, expanded per face corner when normals orprimvars:stare faceVarying/per-face (the deforming form must stay indexed, so there such a set drops;primvars:normalswins overnormals,primvars:st:indicesdereferences and a blocked (None) indices attr reads as unauthored, fan triangulation in authored winding,leftHandedreverses, a bad-index face skips whole); materials read the boundUsdPreviewSurfacespec-correctly —inputs:diffuseColorre-encodes linear→sRGB (the glTF-factor treatment; the fixture scripts author linear literals computed from the designed display colors, so the committed assets kept their look and no snapshot re-recorded) and a connectedUsdUVTextureresolves its image through the usdz package entries or the layer's folder (USDAssetStore),primvars:the fallback; cameras resolve from the prims' authored attributes (fov = 2·atan(verticalAperture / 2·focalLength), ortho height = verticalAperture/10, near/far fromdisplayColor clippingRange) through the sharedresolveCamera(tail;projection: near: far: world: sceneCenter: ) visibility = "invisible"hides its subtree and aguide/proxypurpose skips render (nodes stay in the tree; meshes and lights skip — the lights go through the same walk, so a hidden light stays dark);upAxis/metersPerUnitare deliberately not applied (a scene arrives as-authored, theloadMeshcontract; probed: the platform importer ignored both too); Material/Shader/NodeGraph/Skeleton/SkelAnimation/BlendShape/GeomSubset prims never become nodes (each is consumed by its own pass); a subdivision-surface mesh draws its control cage (mesh.subdivided(_:)is the user's refinement path); the raw tree's format-dependent shapes (.tokenvs.string, tuple arrays) normalize at this consumer tier through the sharedusd*accessors onUSDValue— new USD consumers use those, never re-switch.Mesh.loadUSDis the merged form over the same walk with node transforms baked into the vertices (the platform merge read local vertex data, so a multi-part file's parts piled at the origin — a real fixed defect); first authored material wins, UVs all-or-nothing; STL/PLY/ABC keeploadViaModelIO. USD lights (SceneLoaderUSDLights: the walk attaches specs that move with their nodes for the UsdLux prims — SphereLight→point, +.swift shaping:cone:angle→spot (half-angle° ×2 →coneAngle, softness →penumbra), DistantLight→directional, RectLight/DiskLight/CylinderLight→rect/disk/tube area lights (extents scale with the prim's transform; cylinder length runs local x) — all emitting local -z, worlds from the internal xformOp evaluator,inputs:prefix with bare pre-21.02 fallbacks, the same per-kind brightest=1 normalization over intensity×2^exposure and linear→sRGB colors as glTF; the usdz leg pinned by a test-built 64-byte-aligned stored zip both readers accept). USD transform animation (SceneLoaderUSDAnimation: the same raw-tree read bakes each animated prim's op stack — composed local matrix at the union of its authored sample times via.swift localXform(at:)/USDAttribute, decomposed to TRS keys with hemisphere-continuous quats — into ONE unnamed.sampled( at: ) SceneAnimationfor the layer's whole timeline (scene), so pivot pairs / single-axis / matrix ops all play; timebase =.animations .first timeCodesPerSecond??framesPerSecond?? 24 offset bystartTimeCode; interpolation is a runtime stage setting never authored in-file — linear default, quats slerp, non-lerpable holds — so baked tracks are LINEAR; the bake returns path-keyed entries the scene walk maps ontosourceIndex, and each animated prim's decomposed rest pose installs as its node'strsbase; crate leg pinned against /usr/bin/usdcat (a reference crate writer, tool-gated) baking byte-identical tracks from both containers). USD skinning (SceneLoaderUSDSkinning: UsdSkel skeletons/skins/blend shapes resolved from the same raw-tree read into the shipped deforming tier — attach-only now, the walk already built every mesh. Load-bearing: each Skeleton prim synthesizes joint nodes — a container named after the prim at its evaluator world transform, one node per joint nested by the joint paths, TRS base = local rest (derived from the world-space binds when.swift restTransformsis unauthored), appended after the tree nodes with joint identities numbered past every prim index, so SkelAnimation joint tracks, blend-shape weights tracks, and xform tracks all bind by the one identity scheme;inverseBind = inv(makesbindTransform)·geomBindTransform worlds[joint]·inverseBind·pexactly the UsdSkel equation through the shipped pose path;elementSizeN / constant-interpolation rigid bindings / theskel:jointsremap all resolve (past 4 influences the heaviest win); morphs apply before the skin (probe-pinned by the rigid-binding test)); any otherloadMeshformat degrades honestly to a single-node scene with no cameras or lights.drawScene(_:)is a save/multiply/drawMesh/recurse/restore walk overmodelMatrix, so every mesh rule (materials, shadows, reflections, export/batch gating) applies with zero new rules — byte-identical to the equivalent manual transform-stack calls, pinned bySceneLoaderTests. Per-material submeshes: a multi-material mesh (glTF distinct-material primitives; USDmaterialBindGeomSubsets — first subset claims a contested face, unclaimed faces keep the mesh's own binding) carries internalSceneMeshPartindex slices on its node over the one merged vertex order, so morphs/skins pose once anddrawSceneemits one ordinarydrawMeshper part off the posed arrays (CoW struct copies, nothing duplicated); the publicmeshstays whole with the first material (standalone draws unchanged), a single-material node carries no parts (the untouched byte-identical path), andpartsVertexCountguards a swapped mesh back to the whole-mesh draw (the skin-alignment treatment) — parts-vs-manual byte-equality + swapped-mesh render probes inSceneLoaderTests. Load-bearing:Mesh.loadGLTF's own merge loop is untouched (it bakes world transforms as it appends and smooths missing normals after baking, so rebuilding it over per-node local meshes would not be byte-identical — the two share only theGLTFDocumentreaders, andMeshLoaderTestspinloadMeshunchanged); light intensities normalize per kind to brightest = 1 (glTF's lux/candela mean nothing without distance falloff, which Ollin's punctual lights don't model), colors re-encode linear→sRGB; the camera'stargetis the scene-bounds center projected onto the view axis (orbit-friendly), orthoheight= 2·ymag; cameras/lights move with their nodes: the loaders attach internal node-local specs (SceneLightSpec/SceneCameraSpec, emitting down local -z, intensities normalized at load) andscene.cameras/scene.lightsare computed properties re-resolving through the tree's current transforms on every read, so a moved carrier node — by hand or by an applied animation — carries its camera/light, while assigning either array (tweaking one element in place counts) freezes it to the hand-set world-space values (fixedCameras/fixedLights);node(_:)returns a copy, the subscript writes back in place (scene["part"]?spins about the node's own pivot);.rotate( dt, axis: .unitY) Scenetakes the bare public name, so the hosts spellsome SwiftUI.Scene(theImage/Environmentprecedent); the bundled demo assets are generated byScripts//make-sample-scene .swift make-animated-scene/.swift make-skinned-scene/.swift make-usd-scene/.swift make-usd-animated-scene/.swift make-usd-skinned-scene(the textured-cube precedent — no third-party license). Scene animation —.swift scene.animations(SceneAnimation,3D/) +SceneAnimation .swift apply(_:at:)plays the file's node-TRS keyframe tracks on the sketch clock: absolute posing (same time → same pose, so per-frame application converges; loop by wrappingtimeoverduration, one-shots hold their last key per the spec's clamp), samplers per spec (STEP / LINEAR with shortest-arc slerp for rotations / CUBICSPLINE Hermite with segment-duration-scaled tangents and normalized quats; rotation outputs may be normalized ints, decoded by the spec equations). Load-bearing: an animated node's base is its authoredtrsfrom the file's own fields — never decomposed from the matrix (a matrix-authored node hastrs == niland no track touches it, per spec) plussourceIndex(the file node index tracks target); thepositionsetter syncstrs.tso a hand-set position survives a rotation-only track (a handrotateon an animated node is overwritten by the nextapply— standard animation semantics); tracks sort by node index (the determinism rule). Skins & morph targets (3D/+ theSceneSkinning .swift localMeshDatamerge) — the deforming tier, posed bydrawScenewith no new user API: deform data is stored on theSceneNode, not the publicMesh(skinIndex/vertexJoints/vertexWeights/morphTargetsinternal;weightspublic — the hand-drivable blend-shape surface the weights animation channel also writes; node weights override the mesh's authored defaults, the spec's precedence). Load-bearing: joint matrices are scene-root world × inverse bind (onenodeWorldTransforms(pre-walk, only when the scene has skins — a skinless walk is structurally unchanged, byte-identity still pinned) and a skinned mesh's own node chain is ignored (the spec's rule): the posed mesh draws under the) drawScenecall's model matrix, pinned by render probe; morphs apply before skinning; a misaligned skin falls back to the undeformed draw with a one-time note, never a mis-draw; skin attributes merge all-or-nothing across primitives (the UV rule) and morph data drops whole on a target-count mismatch; the weights channel stores k scalars per keyframe (CUBICSPLINE groups all in-tangents, then all values, then all out-tangents per key —WeightsSamplerpins the layout);readVec3reads sparse and zero-filled no-buffer-view accessors (the morph-exporter staple); vertex weights renormalize over the influences actually used, a zero-weight vertex keeps bind pose. The per-node warning surface is public:wearsSeveralMaterials+placementIsExact(a shear that TRS can't reproduce;drawScenestill draws the verbatim matrix), the reads theSceneExplorerexample leans on — a read-only lens on a scene file (orbit or the file's camera, stage parameters, per-light toggles, a part stepper that highlights or isolates one part inside a capsule-edge bounds cage, the warnings said on the part that carries them; it never edits the file,ollin new --from-sceneis how a scene becomes source; one non-obvious rule it states in a comment: the light rig is frame state, not stack state, so anoLights()insidewithStateunlights the whole frame). Examples3D/+Geometry/ LoadedScene AnimatedScene+SkinnedScene(each bundles a glTF and a USD stage; F swaps) +SceneExplorer(all honor env overrideOLLIN_SCENE; the animated ones declareloopDuration, wraps verified byte-identical — the USD ones pinned by Metal-gated render probes); snapshotsloaded-scene+animated-scene+skinned-scene+usd-scene+usd-animated-scene+usd-skinned-scene;SceneLoaderTests+SceneAnimationTests+SceneSkinningTests+USDAnimationTests+USDSkinningTests(usdcat crate cross-check + a platform bind-matrix oracle). Mechanism:ARCHITECTURE.md§ Scene import.Docs/3D/Scenes.md.USD parser core (OllinUSD) (
Sources/— internal, no public API; the substrate of the complete USD-native arc). Ollin's own clean-room reader opens all three containers —Ollin/ 3D/ USD/ .usdatext (recursive descent, a deliberate superset of the grammar),.usdccrate 0.8-0.10 (bootstrap + TOC sections + ValueReps, LZ4 via Apple Compression + the delta/varint integer coding),.usdzpackage (own central-directory zip; default layer = first usd-extension entry;USDStage.openkeeps the archive + layer name so the scene loader can resolve package assets) — content-sniffed, never by extension, yielding one raw tree (USDStage/USDPrim/USDAttribute/USDValue) in authored order (crate: path-traversal order overridden byprimChildren/properties); this tree is the only source the whole USDloadScene/loadMeshpath reads (the scene-import bullet). Envelope: flattened single layers + self-contained packages, variants at defaults, no composition — out-of-envelope constructs (variantSets, references/payloads, splines, relocates) skip string-aware as.unsupported, never a throw. The xformOp evaluator (USDXform.swift, the raw tree's first consumer tier):USDPrim+.localXform( ) USDStage.visitPrimscompose authored ops perxformOpOrder— listed ops outermost-first (= left-to-right column-vector composition), row-vectormatrix4d(its four rows load directly as simd columns), degrees, a three-axis rotate's value always (x,y,z) angles with the name picking application order,!invert!+!resetXformStack!honored, dangling ops skipped — cross-checked against Model I/O's own composition of the example camera (USDXformTests). Load-bearing: the raw tree keeps the file's shape — tuple arrays flat with an arity, float arrays stayFloat(bit-exact cross-checks), and untyped metadata differs by format (text.stringArrayvs crate.tokenArray— consumers normalize, the raw tier doesn't) — with one deliberate exception: quats arrive real-first (w, i, j, k) from both containers (crate stores the raw struct imaginary-first, the one shape where the containers genuinely diverged, so the crate reader reorders scalar + array quats at decode); the crate traps (AssetPath's token-vs-string index asymmetry, Vec2h's raw-half inlining, the 64-bit integer coder's wider vint widths, TimeSamples' double indirection, payload-0 = empty array, sub-16-element "compressed" arrays stored raw) are honored in code and documented — don't re-derive them. Verification is all local: Model I/O exports.usdaand.usdc(crate 0.8) from one asset — export both under one file stem (the root prim is named after the file) — the two independent parser paths must agree and match the Model I/O read-back; for a file Model I/O didn't author,MDLMesh.vertexCountis the expanded per-face-corner count (== ourfaceVertexIndicescount), never the authored points count. System vectors: the CoreUSDEdit shaderball (crate 0.9; its authored child order — the one Model I/O alphabetizes — is pinned at both the parser and the loaded-Scenelevel), the PencilKit pen usdz set (0.8). Reparse pinned byte-deterministic.USDParserTests; format-study credit inATTRIBUTION.md. Mechanism + format facts:ARCHITECTURE.md§ The USD parser core.Camera control & cinematic moves. Two opt-in halves over the shipped
Camera3D, both driving theCamera3D.orbitingpose (object-on-a-turntable, not scene-flythrough) and set as the frame's camera — a sketch that calls neither keeps its own.cameraControl()hands the camera to the viewer (drag orbit, scroll dolly, right-/shift-/option-drag pan; exponential damping toward an input-driven goal + a capped momentum flick; the canonical orbit-control model,deltaTime-corrected, studied not ported).cameraMove(_:)plays a curatedCameraMove—.turntable/.sway/.pushIn/.pullOut/.tilt/.orbitAndRise/.reveal/.handheld(cyclic ones phase-driven, finite ones eased from the base at the move's clock each frame, handheld a private Perlin field). A move's clock reads the frame being posed (pose, then advance, the ordertimekeeps: a move's first frame is its start and export frame N shows it at N/fps at any rate; advancing first put every exported frame a step ahead,CameraClockTestsat 30 and 60 fps). Both take their framing arguments as the rig's home (CameraRig.frame, aCameraFraming): the first call opens on it, and a changed argument moves it, so a@Paramin the framing tunes the window the way an export frames it (a move's base glides to each changed part only, so a move that departed from a hand-framed angle keeps it; the controller glides only while it still rests at home, until the viewer orbits, pans, dollies, or snaps away; the lens under every driver; an exponential approach at 8/s, since a dragged parameter changes the framing every frame and an eased glide restarted every frame never moves, landing exactly within 1e-9), and a constant changes nothing, byte for byte (aConstantFramingMovesNothing). They compose over the current pose (CameraRig.lastModere-syncs the controller's goal after a move, and a move resumed after the hands re-bases from them even when it is the same move), so "frame by hand, then drift" is one call after another, and the rig clamps elevation off the poles. All three calls take afrom: Camera3Dform seeding the opening shot from any authored camera (a loaded scene'sscene.camera— the "open on the authored framing, then hand the viewer the camera" one-liner):Camera3D.orbitPosedecomposes eye/target into the orbit pose, an orthographic camera opens the rig flat (frame(, frame height mapped to the equivalent fov at the target distance so the projection toggle holds scale),orthographic: ) near/fardefault to the camera's own, and roll is dropped (the rig is y-up by design). The sharedTimeline<Value:sequencer (Tweenable> Sources/— timed keyframes + per-segment easing +Ollin/ Math/ Timeline .swift loops,FrameAdvancinglike@Eased,TweenableoverDouble/Vector2/Vector3) is the substrate, available to sketches (the future@Paramkeyframe client too). The rig (Sources/+Ollin/ 3D/ CameraRig .swift CameraMove.swift) is a plainletadvanced explicitly, notFrameAdvancing(the Mirror-collection cache only sees pre-first-frame stored properties); its platform-neutral input surface —scrollDeltaY(double-buffered inadvance()so a wheel event between frames is never lost),modifiers(mapped behind the AppKit seam likeKeyCode),rightMouseIsPressed, themouseScrolled()hook — is plumbed once throughOllinMTKViewso it reaches standalone + gallery + OllinLive.cameraShowcase(_:)is the fused default the ~42 auto-orbit3D/*examples adopt: it plays aCameraMovethe viewer can interrupt and, afteridleReturn(10s) of no input, eases back overreturnDuration(4s, Hermite, shortest-arc azimuth) to the home framing (the last call's framing, not wherever the viewer left it), then resumes — a 3-phasedriving/manual/returningstate machine, byte-identical to a plain move when uninteracted (so headless/export/snapshot paths are unaffected and corecameraMove/cameraare untouched)..autoOrbit(period:)is its curated default move;activeCameraexposes the resolvedCamera3D(e.g. placing geometry at the cameraeye, asDepthCompositingdoes). Scene inspection views —cameraView(_:)/resetCamera()snap the rig to canonical angles (CameraView:.resetrestores the home framing; the six axis views swing only the orbit angle, keeping target + radius;.isometricis true isometric,.cornerthe deprecated alias), gliding by default (animated: falsecuts) and handing the pose back to the active driver viaCameraRig.driveron completion, so motion resumes with no jump; byte-identical when no snap is active (camera-movenot re-recorded); surfaced by the host Camera menu (OllinCameraCommands, ⌘0–⌘7 in all three hosts) →OllinActiveSketch→SketchRunner(applied next frame); a 2D / hand-set-.requestCameraView camera()sketch ignores it. Live-only scene chrome:cameraAxis()shows the interactive orientation widget (AxisWidget, a SwiftUI sibling — click an axis to snap, plus reset / isometric / an Ortho⇄Perspective toggle) andgroundGrid()a faint reference floor at y=0 (a.gridPipelineKeypass, depth-tested-but-not-writing, outside the deferred render graph) — host chrome like the FPS overlay, never exported, 2D no-op, toggleable from the Camera menu. The Ortho⇄Perspective override is session-scoped:SketchRunnerclearsollinonce per launch (the axis/grid toggles re-sync from the sketch's own flags on reload, but the projection override had no such reset) — persisted, a stale orthographic toggle in a host's private defaults domain read as broken rendering a session later: parallel view rays flatten the environment backdrop to a single average color and reroute every reflection, and nothing on screen names the menu that did it (the gallery is where it bit — the same examples looked correct standalone because each bundleless host has its own defaults domain). Load-bearing grid invariant: the infinite-grid LOD divides the once-computed base world-uv derivative by each decade scale — never.hud .orthographic dfdx()of a pre-scaled uv (the derivative spike at a LOD boundary shatters the lines into a crawling dotted band, a real fixed bug); major lines are distinguished by width in the one line color, not a brighter color or a separate per-class fade (the old form read as stacked planes at staggered depths — don't reintroduce it). Examples3D/SceneViews,3D/CameraControl+3D/CameraMoves(the lower-level demos); snapshotcamera-move(a deterministic.turntable— the input-driven paths are covered by theCameraRigTests/TimelineTestsCPU units, since a snapshot can't drive synthetic events). Full mechanism:ARCHITECTURE.md§ Camera rig.Docs/3D/Camera.md,Docs/(theHelpers/ Animation .md Timelinesection). The rig moves once a frame however often the frame asks for its camera (Sketch.takesRigStep,CameraRig): two asks, on the canvas and inside a layer, ran the motion at twice its speed and took a scroll twice..steppedFrame A camera for a layer (
Drawer.camera(_:)insidewithTarget;layerCameras,layerCameraScopes,withPassCamera(, andfor: ) shadowFitCamerainCore/Drawer.swift; the layer passes ofencodeEffectTargetsinMetalRenderer+Effects). A camera set inside a layer's block is that layer's: its pass draws through it, and the canvas and every other layer keep theirs, so one frame shows one 3D world from several places. A layer that sets none is drawn through the canvas's. Inside the block.swift activeCamera,project(_:),cameraRay(through:), andlineDrawing(of:)answer for the layer at the layer's own size. Load-bearing: the renderer runs every layer pass insidewithPassCamera, so the view and projection, the lighting's eye, a light readrelativeTo(.camera), the fog's framing, a marched field's ray, a mesh field's cull, and the depth the layer hands on all answer for the layer; a frame whose canvas set no camera borrows the first layer's once the drawing is done (firstLayerCamera), for the passes that belong to the frame and not to a surface; a layer through another camera never takes the canvas's light grid. A layer's solids receive the frame's shadows:encodeEffectTargetstakes the frame'sShadowMapsand hands every layer pass (plain, feedback, accumulator, a field's seeds) the map array, the cube array, and the structure the frame's one shadow pass rendered, all of them in world space, and the casters are packed from the camera the maps were fitted around (shadowFitCamera, whichwithPassCamerasets while a layer's own camera is in force), never from the pass's own: a directional, spot, or panel map is a box placed by the frame camera's target and distance, and read by another camera's it is taken for a box somewhere else, so the shadow lands on another part of the floor. The eye and the fog stay the layer's. A lamp readrelativeTo(.camera)is another lamp in a view through another camera and no map was rendered from where that one hangs, so there it keeps its slot (a slot is a layer of the map array) at strength 0: it lights and casts nothing. The structure reaches a layer only in a frame where a caster traces (ShadowMaps.accelis nil otherwise), so a layer draws through the traced build of the lit fragments only then, and through the shadows-only build at that (tracesShadowsOnly), never the one that reflects. Every solid of the frame casts, whichever surface it was drawn on, as it did before. A marched field's cast reaches a layer's solids the way it reaches the canvas's: through the map under a directional or spot caster, and by the receiver's own march under a point or traced one, at full resolution (the reduced-resolution pre-pass is the canvas's alone), which is the march an export's canvas makes. What stays the canvas's: a directional or spot map covers what the frame's camera frames, so a layer aimed well away from it is lit where the map does not reach (the fitted-frustum envelope every 2D caster has); the contact shadows, the traced and deferred reflections, the caustics, temporal anti-aliasing, depth of field, motion blur, and the flare are passes over the canvas's view. Measured (M2, a 480² layer beside a 1280×720 canvas, nine solids, the difference of two differences): +0.36 ms under a sun, +0.23 ms under a lamp's cube, about +1.5 ms under a traced lamp.LayerCameraTests(40: each view against a twin drawn alone through its camera; for the shadows, a layer at the frame camera's distance within 3 levels of its twin, a layer through the canvas's camera, a layer aimed elsewhere finding the shadow where it falls, a lamp's cube and the traced lamp from any view, and a lamp that follows the camera; eleven planted defects, each red).Docs/3D/3D.md§ A camera for a layer; Guide Ch 49 § A second view of the piece: a window for a layer;Examples/.Installation/ SecondView RGBD recordings + live USB (Record3D) (
OllinRecord3Dsatellite).Record3DRecordingopens a Record3D.r3dclip andRecord3DDevicereads a tethered phone's live USB RGBD stream — both unproject color + depth with true intrinsics into aPointCloud(over the coreRGBDFrame/CameraIntrinsics; a cloud measures itself viacentroid—nilwhen empty — andspreadRadius, the RMS distance about it, the two numbers a framing camera eases toward). All Apple-native decode (a minimal ZIP reader + LZFSE + JPEG) and a clean-roomUSBMux(usbmuxd) client to TCP 1337; the formats read clean-room (Record3D's library is LGPL — read its public structure, never translate; credit as a product reference, vendor nothing). USB only, not WiFi. Gotchas:Kis column-major at capture resolution → scale to the depth grid; the depth grid isn't in the metadata (derive from the LZFSE float count + capture aspect); usbmuxd'sPortNumberis network byte order; the trailing live-stream slot is a JSON misc blob, not confidence; unprojection lands in ARKit camera space (y-negate + z-negate).RGBDFramegaineddepth(/atNormalizedX: y: ) unproject((hole-robust median, y-flip). Recorded poses:normalized: ) Record3DRecording/.poses pose(at:)(which throwsframeOutOfRangeoutside the recording exactly asframe(at:)does, and isnilonly for a frame with no recorded pose, the Optional and the throw meaning two different things) — per-frame camera-to-world from the metadataposesarray ([qx,, quaternion order pinned by the identity's 1 in slot 3), the sweep-fusion path for a saved clip; a clip captured without world tracking (TrueDepth) stores every pose as the identity — real motion can't be recovered after the fact, so probeqy, qz, qw, tx, ty, tz] posesfor variation before fusing (single frames reconstruct fine).Docs/3D/Record3D.md,Docs/3D/RGBD.md; examples3D/Record3DCloud(file playback, live USB when a phone streams),DepthLiftedPose.iPhone capture app (Ollin Capture +
OllinPhone). Ollin's own iOS app (Apps/OllinPhoneApp, xcodegen + Xcode) streams on-device ARKit perception over USB: a 3D body skeleton (each joint a position and an orientation quaternion with a camera-observed flag — ARKit's rig fills unseen joints in, and those report untracked — plus the anchor's world transform standing the skeleton in the same ARKit world the depth sweep and room mesh use, and the person's estimated scale viaautomaticSkeletonScaleEstimationEnabled; bodies bundle per frame like faces, so an empty set clears a person who left), a face (deforming mesh with its topology and per-vertex texture coordinates + 52 expression blendshapes + the two eye poses and the look-at point the eyes converge on, up to 3 faces), world-facing rear-LiDAR depth (aPointCloud+ the 6DoF camera pose, via the coreRGBDFrame), person segmentation (a matte + cutout, via the core-liftedSegmentationImages— fed by the rear camera in Segment mode, ARKit's on-device segmentation, or by the front camera in Selfie mode, the app's one non-ARKit sensor: anAVCaptureSession+ Vision pass whose capture connection rotates buffers upright (so the wire's turn count is always 0) and mirrors them like the front-camera preview — the matte is computed from the delivered buffer, so matte/color alignment is by construction, and both modes use the same.segmentationwire kind so the Mac side needed nothing new), the hands in view (up to 4 at once, each a 21-joint skeleton found on-device by Vision over the ARKit frames in Hands mode — every joint an upright 2D image point, plus on a LiDAR phone a metric 3D position in ARKit world space, lifted through the scene-depth map and the camera pose), the text it can read (each line aPhoneTextin Text mode — the string, the reader's confidence, and four upright corner points, lifted to world space the same way), the pictures and objects it knows (a reference picture or a scanned.arobject, found in the room as a named 6DoF placement with its real size, in Markers mode), a map of where the picture draws the eye (a coarse attention heat map plus the regions it peaks in, in Attention mode), how the picture is moving (a dense motion field between consecutive frames, in Flow mode), the reconstructed room mesh with the flat planes in it, the room's light, and CoreMotion device motion. The Mac clientPhoneDevice(@MainActor, self-retrying) exposeslatestBody/latestBodies/latestFaces/latestHands/latestHand/latestTexts/latestText/latestMarkers/latestMarker/marker(named:)/latestSaliency/latestSaliencyHeatMap/latestSaliencyFrame/latestFlow/latestFlowFrame/latestMotion/latestFrame/latestSegmentationMatte/latestSegmentationCutout/sceneMesh/planes/latestLight;PhoneBody/PhoneFace/PhoneHand/PhoneMotionmirror the Vision accessor shape;PhoneBodyaddsworldPosition(_:)/worldCenter/orientation(_:)/modelTransform(_:)/worldTransform(/ofJoint: ) scaleFactor/isJointTracked(_:)and a public init so a pose stages with no phone (the tests and the staged-figure verification do). Transport: the sharedOllinUSBMuxtunnel + thePhoneWirecodec (pure Foundation/simd, compiled verbatim into both ends;streamPort1338). World-pose fusion — the coreWorldCloudaccumulator places each depth frame by its pose into one fixed world cloud (sweep the phone, fuse the room); see the Fusing a sweep bullet for it and for the drift correction that keeps a long one registered. Room mesh — ARKit scene reconstruction streamed per anchor block (.sceneMesh, one block per message, keyed by a stableUUID, with aremovedretirement notice);PhoneSceneMeshkeeps the newest of each in arrival order (apply/remove/reset) and buildsmesh(whole room, world space),mesh(of:)(filtered by label, unreached vertices dropped), andmesh(colored:)(unwelded, a color per triangle);PhoneSurfaceis the per-triangle label (wall/floor/ceiling/table/seat/window/door/unclassified, raw values contiguous from 0). Load-bearing: the phone reads a block's geometry inside the ARKit callback (the Metal buffers are the session's, and nothing promises they outlive the call) and throttles the send instead (a FIFO queue, ~15 blocks/s, so a block that stops changing still gets its turn); a geometry source is read three floats at a time honoring its ownstride(aSIMD3<Float>is 16 bytes over a 12-byte entry and would run past the end);phoneSceneChunkplaces positions with w=1 and normals with w=0, and refuses a whole block whose index runs past its vertices;sceneMeshVersionis the rebuild gate (a room is hundreds of thousands of triangles, sodraw()must not rebuild per frame); removal rebuilds the id→slot map, since every later block shifts down; and each block carries a per-runscannumber, becausesessionmoves the world origin, so the Mac must drop the old room rather than mix two coordinate spaces (leaving Room mode and returning is a new run). Flat planes — ARKit plane anchors stream beside the mesh from the same session (.run( …, .resetTracking) .plane, one anchor per message, sameid/scan/removedshape, its own FIFO ~20/s), so surface and planes share one world origin;PhonePlanecarries the label (the samePhoneSurface),PhonePlaneAlignment(horizontal/vertical), world-spacecenter/normal/width/height, the convexboundary, plusarea/mesh/outline/bounds;PhonePlanesis the id-keyed set (apply/remove/reset) withflat/upright/planes(of:)/largest/largest(of:)/floor/foundSurfaces/bounds/mesh(colored:). Load-bearing: plane detection needs no LiDAR, so the Room session starts either way and addssceneReconstructiononly when supported (the mode is useful on a non-Pro phone);phonePlanereverses an outline whose winding disagrees with the anchor's up axis (a fan built the wrong way faces backwards and the fill vanishes;anOutlineWoundTheWrongWayIsTurnedRoundpins it, verified red by sabotage) and synthesizes a rectangle fromplaneExtentwhen no outline arrives (turned byrotationOnYAxis), so every reader downstream has exactly one shape to handle;largestmeasures the outline's area (a fan of cross products), neverwidth × height, or a long thin shelf outranks a floor;floorfalls back to the lowest horizontal plane, because a label arrives late. Room light —frame.lightEstimatein every mode via the sharedLightSampler(aLightReportingprotocol on all six ARKit streamers, throttled to 5/s), so a mode switch never interrupts it;PhoneLightscales lumens tointensity(1000 lm = 1), turnskelvinintocolor(Color(kelvin:)) andambient(that color scaled by intensity, clamped at 1.5 forambientLight(_:)), and exposesdirection/keyIntensity/sphericalHarmonics/keyonly in Face mode (ARDirectionalLightEstimateis face-tracking-only, 27 coefficients as rawData).PhonePlaneandPhoneLightboth take a public init so a room and a reading can be staged with no phone (the Guide figure and the tests do). The eyes and the gaze —PhoneFaceaddseyePosition(_:)/eyeOrientation(_:)/gazeDirection(_:)(face-local, perPhoneEye), their world twinsworldEyePosition(/_: ) worldGazeDirection(,_: ) lookAtPoint/worldLookAtPoint(the convergence point),headTransform(the head pose composed fortransform(_:), so the face-local mesh stands with the eyes inside it), andmeshUVs;mesh()carries the texture coordinates only when they align with the vertices (a misaligned set is dropped, never shifted onto the wrong vertices), and a public init stages a face with no phone (the Guide figure and the tests do). Load-bearing: the eye poses andlookAtPointare sent over the wire face-local (the SDK's own convention — relative to the anchor's origin), stood in world through the head pose; the gaze axis is the eye's +z (out of the face; a device-unverified parameter — if a live run reads backward, flip it ingazeDirection, one place). Hands —PhoneHandcarrieschirality(from the camera's view) /confidence/ per-jointhas(_:)/confidence(of:), the 2D overlay (point(_:in:)/points(in:)/bones(in:), upright normalized on the wire whichever way the phone is held), the 3D side (position(_:)/bones()/cloud()/center/hasWorldPositions), the gesture staplepinchDistance(thumb tip to index tip, meters,nilunless both lifted), and the staticskeleton(20 bones) /tips/fingerChains; a public init stages a hand with no phone (the staged-render verification and the tests do). Load-bearing: the pose model runs behind a drop-if-busy gate on its own queue (a slow pass skips frames, never backs up the camera) and everything the lift needs is copied inside the ARKit callback (the room-mesh lesson); the model is handed the device-hold orientation and its points come back upright, which is what the wire carries, and the 3D lift maps each point back onto the camera-native depth grid throughPhoneWire— pure shared arithmetic, pinned by a Mac test (.bufferPoint( fromUpright: quarterTurnsCW: ) mapsUprightPointsOntoTheBuffer) — then takes a median depth from a small window (a fingertip's own pixel is often a hole at the silhouette edge), unprojects through the depth-grid intrinsics, and applies the camera pose; a joint over a depth hole keeps its 2D point withhasWorldPositionoff, soposition(_:)is honest about what lifted; the empty set clears hands that left (the faces precedent);PhoneHandJointraw values stay contiguous 0…20 (the wire carries a joint as one byte; pinned like the blendshapes); without LiDAR the mode still runs and hands stay 2D. Text —PhoneTextcarriestext/confidence, the 2D overlay (corners(in:)/bounds(in:), upright normalized on the wire), and the world side (worldCorners/worldCenter/worldWidth/worldHeight/hasWorldPlacement, plusworldTransform— an orthonormalized frame fortransform(_:): origin at the quad's center, x along the reading direction, y up the line, z out of the surface,nilon a degenerate quad); a public init stages a line with no phone (the Guide figure and the tests do). Load-bearing:TextStreamermirrors the hand streamer exactly (its own queue behind the drop-if-busy gate, everything the lift needs copied inside the ARKit callback, the device-hold orientation handed toVNRecognizeTextRequest, corners lifted through the shared depth arithmetic — now extracted to the app'sDepthLift.swift, which both streamers use, with the median window clamping its pixel first so an edge corner can't build an inverted range); a line lifts all four corners or none (three corners are not a quad; the all-or-nothing normals precedent); it reads at the.accuraterecognition level (.fastmisses room-scale text; a few finished readings a second, absorbed by the gate);latestTextranks byimageArea(the shoelace area of the normalized quad — recognizer confidences cluster near 1, so area picks the sign you mean); the empty set clears lines that left (the faces precedent); the placement test is sabotage-verified (a flipped normal turns it red); the worldTransform z axis faces out of the surface toward the reader (a device-unverified parameter — if a live run reads backward, flip the cross inworldTransform, one place). Markers — the pictures and objects the phone knows (.marker, bundled per frame in Markers mode): each aPhoneMarkercarryingname/kind/isTracked/position/size/corners/facing/across/upandplacement, an orthonormal frame with its origin at the middle of the thing, x across the width, y up the height, z out of the face, ready fortransform(_:);PhoneDeviceaddslatestMarkers/latestMarker(the biggest one being followed)/marker(named:), and a public init stages a find with no phone (the Guide figure and the tests do). The library is the app's own Documents folder (UIFileSharingEnabled+LSSupportsOpeningDocumentsInPlace, so Finder and Files reach it), read at mode start and on a Read the folder again button. Load-bearing: a picture's printed width is carried in its file name (poster@30cm.png/card-50mm.jpg/plate 12in.heic/tile_0.4m.png; cm/mm/in/m), since no image file carries one, and the parser lives in the sharedPhoneWire(markerWidth(/fromName: ) markerName(/fromFileName: ) markerStem) so a Mac test pins arithmetic the phone runs — the unit must end the name (diagram,platinumstate nothing), only a known reference extension is stripped (teapot.arobjectkeeps its name;tile_0.4mkeeps its decimal point), and a size outside 1 cm…5 m is refused rather than trusted (a wrong width puts the print at the wrong distance rather than losing it); ARKit folds its own scale estimate into the anchor, soPhoneMarkernormalizes the basis and reports that scale throughwidth/heightinstead (a scaled frame would scale everything drawn through it,anEstimatedScaleBecomesSizeNotAScaledFrame); a picture anchor lies in its own x-z plane with +y out of the printed face, so the placement turns a quarter (x = anchor x, y = −anchor z, z = anchor y) — a device-unverified convention, and if a live run draws into the wall, that quarter turn is the one place to flip (sabotage-verified red); an object anchor is not trackable (found once, holds its place, reportedtracked), so an object marks a place and a picture marks a moving thing; each reference isvalidated as it loads, so a picture with too little detail is named on the app's screen rather than looked for in vain; sending is paced (every frame while anything is followed, 5/s while nothing is), so an idle library does not stream at camera rate; andapplyModestops every session from one list, so a tenth mode cannot forget one. The wand — the phone held as a pointer (.wand, one reading per camera frame in Wand mode, plain world tracking so it needs no LiDAR and no depth):PhoneWandcarriesposition/pointing/up/across/placement(orthonormal, x across the screen, y up it, z out of it toward the holder, sopointingis its -z, matching how a camera looks in Ollin's own 3D) plusray(the coreRay3),point(at:),isTracked,isPressed,pressCount, andtouch, withPhoneDeviceand a public init so a wand stages with no phone (the tests and the Guide figure do). Load-bearing: ARKit fixes the camera basis to the landscape sensor whatever the hold, so the frame turns by the hold's own quarter-turn count, and that arithmetic lives in the shared.latestWand PhoneWire(a Mac test pins what the phone runs) — the raw pose and the turn are both sent over the wire so the fix is a Mac rebuild rather than a phone one, and a wrong count tips the drawing without moving the aim (device-unverified; that one function is the place to flip it, sabotage-verified red); the press is carried twice,.wandFrame( fromCamera: quarterTurnsCW: ) pressedfor the state a drag reads and a risingpressCountso a tap that landed and left between twodraw()calls is still seen (the poll->=-never-==rule in another dress); the thumb is-1…1across and up behind a flag, so nothing touching survives the trip as nothing rather than as the middle of the pad, and it reads as a rate (a few centimeters of pad, a whole room); the basis is normalized defensively and a collapsed pose falls back to the world axes rather than handing a sketch a direction full of NaN; the button keeps working whileisTrackedis off, since tracking comes and goes as the room is recognized; and the phone-side pad is oneDragGesture(, so the landing, the slide, and the release are one gesture. Attention — where the picture draws the eye (minimumDistance: 0) .saliency, one reading per analyzed frame in Attention mode):PhoneSaliencycarries the coarse heat map (salience(at:in:)/salienceNormalized(— the query turns the top-down heat rows over for the lower-left convention and clamps at the edges, sabotage-verified red) andat: ) regions(PhoneSalientRegion:bounds(in:)/center(in:)/confidence/hasWorldPlacement/worldCenter), withstrongestRegionby confidence;PhoneDeviceaddslatestSaliency/latestSaliencyHeatMap(a tintable white-alpha glow via the sharedSegmentationImages, cached by sequence) /latestSaliencyFrame(the color frame stood upright lazily); public inits stage a reading with no phone (the Guide figure and the tests do). Load-bearing:SaliencyStreamermirrors the text streamer (its own queue behind the drop-if-busy gate, the device-hold orientation handed to the request, so the heat map and boxes come back upright and are sent over the wire that way; the color stays camera-native with the turn count beside it); only each region's center is lifted (a box's corners land on the background); a heat plane whose stated dims outrun its bytes is refused at init, so a query can never index past it; every reading carries a heat map, so there is no empty-clear and the last reading holds between passes. Device-unverified parameter: whether the model's heat plane arrives upright under every hold (if a live run reads turned, the streamer's orientation hand-off is the one place to fix). What the phone hears — the built-in sound classifier over the phone's own microphone (SoundStreamer, SoundAnalysis, the same 1.5 s window the Mac's classifier settled on by measurement), streamed as the.soundkind (=14): the whole judgment every window (every label with its confidence, strongest first, a two-byte count since the vocabulary is three hundred-odd, the window's start and length on the phone's audio clock counted from when listening began), never the audio. Load-bearing: the wire runs one way, so the threshold and the crossing live on the Mac:PhoneSounds(device.sounds, a@MainActorclass over its own lock, fed straight from the read thread) keeps the level (confidence(of:)/topClassification/classifications) and the trigger (drainingevents()+timeSinceHearing() with the Mac classifier's own crossing-from-below rule (a held set of what is above, so a continuing sound fires once), over the same_: ) SoundClassification/SoundEventvalues, which moved fromOllinAudiointo the core (Core/, the satellites-cannot-depend-on-each-other rule) so a sketch written against either pair of ears reads the other unchanged; an event'sSoundClassification .swift timeis the end of the window it crossed in, and between readings the Mac carries the phone's clock forward with its own so a fade ontimeSinceHearingruns smoothly rather than stepping once a window;isListeningis read off the readings (one within 3 s), since nothing on the wire says the switch went off;hear(is public so the ears stage with no phone (the tests and the Guide figure do). Hearing is a switch, not a mode (the app's_: at: duration: ) Hearchip, remembered in its defaults): it needs no camera, so it runs beside every mode, survives a mode switch, and asks its own microphone permission (NSMicrophoneUsageDescription); an audio-session interruption pauses it and the end of one restarts it. Device-unverified: the microphone's format on the A17 and the classifier's pace there. How the picture is moving — optical flow between consecutive rear-camera frames, measured on the phone (FlowStreamer, Vision'sVNGenerateOpticalFlowRequestat medium accuracy over the ARKit frames, in Flow mode; plain world tracking, so no LiDAR) and streamed as the.flowkind (=15): a dense map of(dx, dy)float pairs at a bounded size (the frame scaled to 256 on its long side before the pass, the field averaged 2×2 to ≤128 across, ~100 KB a reading), the interval between the two frames measured, the model's confidence, and the color JPEG, all camera-native with the device-hold turn count beside them.PhoneFlow(device.latestFlow) reads the way the Mac tracker's field reads —vector(at:in:)/samples(in:every:)/averageFlow(in:)/flowNormalized(at:)/averageFlowNormalized/size/confidence— over the sameMotionFieldvalue (field), which moved fromOllinVisioninto the core (Core/, closure-backed:MotionField .swift init(, the Vision tracker wrapping its observation in the closure so a camera-resolution map is still never converted up front), so a helper written against either takes both;width: height: confidence: flowNormalized: ) intervalis the one read the Mac's tracker cannot give (its analysis gap breathes with load), so a vector over it is a speed;latestFlowFrameis the frame stood upright lazily; a public init stages a reading with no phone (the Guide figure and the tests do). Load-bearing: the Mac stands the map upright by turning the grid and every vector in it by the same quarter turns (PhoneFlowPlane: one clockwise turn sends the top row to the right column and a rightward vector downward; pinned against the shared.upright rotatedCGImageso the map and the color frame agree cell for pixel), a query reads bilinearly between the four nearest cells (the map is coarse and a particle crossing a cell edge must not snap) and clamps at the edges, and a map whose stated size outruns its vectors is refused at init and at decode; Vision's raw vectors under this request are the motion of the picture itself (forward), the opposite sign from the newer API the Mac's tracker negates — pinned byvisionsFlowRequestReportsTheMotionOfThePictureover confetti at the streamer's.mediumaccuracy, so the phone puts the map on the wire unsigned andwireFieldin the streamer is the one place to flip if a device ever reads backward; the streamer scales each frame into one of two owned BGRA buffers it alternates (ARKit's capture buffer is never held past the pass that read it, and the previous frame the next pass measures against is the streamer's own copy), behind the drop-if-busy gate every Vision streamer runs, andstop()forgets the previous frame so a mode coming back does not read the gap as one huge motion. Device-unverified: the classical flow's pace on the A17 at 256 across, and whether the hold's turn count stands the field up under every orientation (the raw map and the turn are both sent over the wire, so a fix is a Mac rebuild). Body / Face / World / Segment / Selfie / Room / Hands / Text / Markers / Wand / Attention / Flow / Touch are behind a phone-side toggle (mutually exclusive; motion always streams; light streams in every ARKit mode — Selfie and Touch run no ARKit session and send none; thirteen modes outgrew the segmented control, so the app draws five rows of chips, a short row padded so every chip keeps its width, with Hear and Air beside them as switches rather than modes since neither needs a camera). The screen as a control surface — Touch mode (.touch, kind 16) runs no sensor at all: the glass is the sensor, so no camera session starts and the phone stays cool through a set.TouchStreamerassigns each finger a rising number that is never reused and sends the whole live set every time it changes (PhoneTouchSample: the clock plus aPhoneTouchPointeach — id, -1…1 position,hasForce/force,radiusas a fraction of the screen's width,age);PhoneTouches(thePhoneSoundsshape:@MainActor,nonisolatedlock, publicfeel(_:at:)so a figure or a test stages it with no phone) gives the level (down,isTouching,touch(id:)) beside the trigger (drainingtaps(), non-drainingtapCount,timeSinceTap), overPhoneTouch/PhoneTapwithpoint(in:)onto a canvas rectangle. Load-bearing: a number the Mac has not seen is the landing, which is the whole tap derivation and is why a drag fires once rather than per frame (aNumberNotSeenBeforeIsALanding, verified red by sabotage); the reader feeds every message intoPhoneTouchesoff the main actor whiledraw()sees only the latest, so a finger that lands and leaves between two frames is gone fromdownand still intaps(); an empty list is a real reading (the last release), so the decoder must accept count 0 or the Mac holds a finger that left, and the reader callsreleaseAll()on a dropped connection for the same reason (the phone sends only on a change, so a cable pulled mid-press is a note that never ends);hasForceis carried besideforcebecause a screen that cannot weigh a press reportsmaximumPossibleForce == 0(most iPhones since 3D Touch), so a sketch readsnilrather than0; the pad is a plainUIViewwithisMultipleTouchEnabled(SwiftUI's own gestures follow one finger), all four phases funnel into one report of the whole live set, and a mode switch away sends one empty reading. The air around it —.air(kind 17),CMAltimeterrelative-altitude updates behind the app's own Air switch (a switch, not a mode: no camera, and the altimeter asks its own Motion & Fitness permission, so a sheet never opens mid-performance;NSMotionUsageDescriptionwidened to say so).PhoneAircarriespressure(kPa,hectopascalsfor a weather report) andaltitude, relative by design — meters above wherever the phone started, good to about a tenth of a meter, negative going down, which makes lifting the phone a continuous control that costs no camera; CoreMotion's own units are the wire's, so there is no conversion to get wrong in two places. The wire's second direction — the first traffic from Mac to phone.PhoneDevice.use(_:)names aPhoneCaptureMode(the mode list moved into the shared wire file, so it travels both ways) andlook(for:)hands over[PhoneReference](a picture's own bytes plus the printed width no image file carries, or an.arobject), so the.swiftsketch carries the whole piece and a phone that has never seen it learns what to look for the moment it connects. Three decisions, made once: the framing is the same 12 bytes both ways (one version byte for the whole wire); the tag space is its own, numbered from 1 beside the sensor kinds, because a frame's direction is decided by which end reads it and never by its bytes; and the magic differs (PhoneWire), the one place the framings part, which is what makes a sensor frame written down the cable fail at its header instead of decoding as whatever request shares its number (.requestMagic aSensorFrameIsNotARequest, sabotage-verified). Declarations, not commands: the device keeps the mode and the library and says both again on every connect, so plugging in (or launching the app) late is the same as doing it first; a tap on the phone still wins, and the sketch readslatestState(kind 18,PhoneStateSampleintoPhoneState: mode,isSupported,referenceCount,referencesAreDeclared,status,notes, sent on change) to learn where it landed — the only place a picture ARKit judges too plain to find is ever heard about, which is why the answer exists at all. The library protocol isPhoneLibraryInbox, in the file both ends share so a Mac test pins what the phone runs: alibrary(count:)opens a declaration and throws away a half-staged one, eachreferenceappends, the set commits on the frame that completes it, count 0 commits an empty library at once ("look for nothing"), a stray reference is dropped, and a half-received library never commits, so a cable pulled mid-declaration leaves the phone looking for what it was looking for before; no generation number, because TCP orders the stream. The reading end's framing arithmetic isPhoneWire, in the same shared file for the same reason: it holds a partial frame for the next read, skips one that is framed right but will not decode, and returns nil (drop the connection) only when the bytes are not this framing at all. Requests are drained by the read thread between reads (.takeRequests( from: ) sendPending), so the socket is touched by exactly one thread and the second direction adds no lifetime hazard of its own;SO_SNDTIMEOmatches the read timeout so a phone that stops reading cannot park that thread inside a write. A declared library replaces the app's own folder (whose screen says so, and whose re-read button hides) until the sketch disconnects, when the folder takes over again. A picture is fitted on the Mac: pastPhoneReference(1024 px, ARKit wants detail rather than size) it is redrawn and encoded JPEG at 0.9 then 0.6, and within that and one frame it travels byte for byte so a hand-made PNG arrives exact; at most.maxPictureEdge PhoneWire(32) travel. Gotchas: the segmentation upright-rotation must be an accelerated.maxReferences CGContextdraw, not a byte loop (debug-build frame rate); the 52 blendshapes are sent over the wire positionally soPhoneBlendShaperaw values must stay contiguous 0…51;strongestBlendShapessettles a tie by that listed order, never by the dictionary's own, which differs from process to process (PhoneFaceTests);.tiedBlendShapesComeInTheirListedOrder PhoneWire.versionstays 1 pre-1.0 (both ends rebuild together).Docs/3D/Phone.md; examples3D/PhoneBodyPose/PhoneBodyFigure(a solid mannequin posed by the joint orientations, standing where the person stands) /PhoneCostume(ribbon trails + rotation-twisted plumage worn by the live skeleton; header credits its Super You inspiration) /PhoneFace/PhoneGaze(eyeballs at the streamed eye poses, beams converging on the look-at bead) /PhoneDepthCloud/PhoneWorldScan/PhoneSegmentation/PhoneRoomMesh/PhoneRoomPlanes/PhoneHands(the hands as solid little skeletons in the room, a pinch closing into a bead, a 2D overlay without LiDAR) /PhoneWorldText(each readable line as wire-frame stroke type on a framed panel, standing where it hangs; a 2D overlay without LiDAR) /PhoneMarkers(a city of columns rising off every print the phone recognizes, framed by the print's own edge; a scanned object as the box its scan measured) /PhonePointer(the beam out of the back of the phone landing on a ball, a press picking it up, the thumb pushing it out along the beam, letting go dropping it) /PhoneAttention(the heat map as a warm glow over the live frame, confidence-weighted frames on the regions, an eased bead trailing where the attention has been) /PhoneSounds(every sound that starts ringing out in its own hashed place, the strongest label named, six familiar levels as bars with the threshold a@Param) /PhoneFlow(the field as streaks colored by speed over the live frame, and dust that it carries) /PhoneTouches(every finger as a disc sized by its width, a ring where each landed, the lift down the right edge);PhoneSceneMeshTests(19),PhonePlanesTests(24),PhoneBodyTests(6),PhoneFaceTests(7),PhoneHandTests(8),PhoneTextTests(8),PhoneSaliencyTests(7),PhoneMarkerTests(10),PhoneWandTests(12),PhoneSoundsTests(14: the wire round trips including a 320-label vocabulary and a truncated reading, and the invariants over staged readings),PhoneFlowTests(15: the wire round trips and a truncated map, the three quarter turns against the shared image rotation, the reads over staged maps, and Vision's own sign under the phone's request),PhoneTouchTests(17: both wire round trips including an empty set and two truncations, the landing rule and the drag that does not re-tap, the tap that outlives the frame it fell in, the cable pulled mid-press, the draining split, the canvas mapping, and both kinds' raw values),PhoneRequestTests(36: the request round trips, both crossed-frame tests, the header refusals, the whole inbox rule, the stream reassembled at seven chunk sizes, the mode list, the state round trips, and the Mac-side reference building including the fit; four sabotages red) +MotionFieldTests(4, the core value on its own); Guide Ch 40 figuresRoomAsSurface+RoomAsPlanes, and Guide Ch 39 figuresHandsAsSkeletons+GazeAsBeams+WordsInPlace+AttentionAsHeat+FlowAsField+PrintAsStage+WandAsPointer+HeardAsMarks+GlassAsPad+DownTheCable(one declaration as a sequence, its byte counts read from the shipped encoder).waitingMessageon a device nobody started (or that was stopped) says to callstart(), onPhoneDeviceandRecord3DDevice; a stopped reader keeps no sentence, and a connection attempt still in flight at the stop writes none.A recording of the phone's stream (
OllinPhone:PhoneRecordingFormat, shared verbatim with the app;.swift PhoneRecording,.swift PhoneRecordingVideo,.swift PhoneCamera.swift; the app'sRecorder.swift). The capture app's Record button writes the stream to a folder in its Documents with no cable (<Mode> <date>:.ollinrecording stream.bin, the wire's own framed messages each stamped with a time;camera.mov, HEVC with the microphone's sound;recording.json), andPhoneDevice(plays it back through the path the cable uses (playing: PhoneRecording) PhoneStreamReaderis the one intake for both sources)..ingest latestCamerais aPhoneCamera(pose, lens, picture, all upright for the hold), anddrawPhonePicture(with_: ) camera(_:)puts a sketch in the room the phone saw. Load-bearing: (1) a frame goes to both files or to neither. Camera recordkis written only after the video took picturek, the writer numbers it, and the reader throwsframesDisagree(when the counts or the times (4 ms) part. (2) The writer is one serial queue for both files and the sound, and a live writer drops a whole frame at the call once 3 pictures wait, since a waiting picture holds one of the camera's own buffers. A live writer opens its video off the first picture offered and keeps none until the video is open (frame: ) VideoGate): the recording's first frame is the first one offered after that, and the pictures of the opening are before the recording, never drops. Opened inside the first frame's own write, the video stood in front of every frame behind it and all but the three allowed to wait were dropped (measured on the M2: the opening takes 106 ms in a cold process and frames 4 and 5 of 180 were lost; a phone lost its first tenth to half second).startSessionis called on the first kept frame, at its time, and sound from before it is left out. (3) The format file imports nothing of Ollin's and compiles into both ends, so the Mac's tests write with the phone's writer. (4) A record's time is the newest camera frame's at hand-over, and a frame's records are everything before the next camera record, by position, never by comparing times. (5) The recording follows the sketch's clock throughFrameAdvancing, so the device has to be held by the sketch. Its place is worked out from an anchor, never added up, and a frame is read with a quarter-frame margin, so a sketch at the recording's rate, half of it, or twice it never sits on a boundary, the loop point included. (6) A seek backward or a loop resets the device and feeds from record 0, opening the last record of a kind whose newest value replaces the one before and every record of a kind that adds up (room blocks, planes, sounds, touches). (7) A depth frame is stored without its JPEG and takes the video's frame as the sensor delivered it for color; a large record is LZFSE, both lengths bounded before anything is set aside. Its depths are packed (PhoneDepthPacking, record flag bit 1, format 2): each a 16-bit count of millimeters, written as its wrapped difference from the median of the left sample, the one above, and the plane through those and the one between, folded so a small difference of either sign is a small number, low bytes then high bytes, then LZFSE. Back within 0.5 mm and a float's own last digit up to 65.535 m, clamped past it, no reading as zero; the rest of the frame bit for bit; every map stands alone. The frame inside the packed body carries a grid of no size, since the wire refuses a grid its samples do not fill, and the size sits with the planes. Measured: a LiDAR-shaped map with 0.5 to 8 mm of noise at a meter weighs 22 to 43 KB against 162 KB as floats, where float16 loses up to a millimeter and weighs more, half and quarter millimeter steps cost 5 and 10 KB, and LZMA gains under a tenth; the phone's own figure is not yet measured. A format 1 recording reads as before, and a record longer than a wire frame can be is never written (one written ends the recording there for every reader). (8) Standing a frame upright is three turns that must agree:PhoneWire,.uprightLens wandFrame, and aVTPixelRotationSessionon the picture. (9) The camera record (wire kind 19) also crosses the cable in every ARKit mode; its picture crosses beside it under The camera's picture on the cable. (10) A dropped frame is named: the description'sdroppedlist holds each one's capture time from the first frame, its reason (writerBehind,videoNotReady,timeNotLater,videoFailed), and how long after its capture it reached the writer, the first 2,000 of them;PhoneRecordingand.droppedFrames droppedFrameCountread it. The delay is what tells frames held up before the writer (a busy main thread) from a writer that fell behind on frames delivered on time. (11) What stood before the first frame is written with it: the newest light and state and the newest of each surface and block handed over before the first frame are kept by key and written after the first camera record at its time; a retired surface is forgotten; anything else from before the first frame (a depth map) belongs to pictures the recording does not hold. The app hands the newest light over at Record, since a reading goes out only five times a second, and forgets it on a mode change. (12) A recording with no frame leaves no folder:finish()removes it and throwsnoFrames, or the video's own failure when it never opened;removeEmptyRecordings(sweeps what a stopped app left, at launch, and touches no folder that holds a video. (13) On the phone, every ARKit streamer reportsin: ) session(through its_: didFailWithError: ) LightSampler; the mode's status line carries the sentence to the screen and the cable; a recording says "no picture from the camera yet" after 1 s and ends after 5. Its sound is under A recording's own sound, and a real thing hiding a drawn one under Drawing on a real surface. Not done: the cause of Room mode's bursts of dropped frames is not found: a World and a Room load on the writer's queue lose no frame on the M2, so the next phone recording's named frames are what say. The phone's half builds for a generic device and has not yet run on one. Proof:PhoneRecordingTests(a synthetic room written by the shared writer; a pin within a pixel on every frame at four holds and three crops; crossed files caught; two runs pixel-identical; ten plants) andPhoneRecordingWriterTests(a live writer with a planted 0.35 s opening loses no frame and its frames are contiguous; a frame behind forty blocks is named and is in the recording or the list, never both; no folder after no frame or a video that would not open; the light and the surfaces on frame 0 through a device; a packed depth map within the bound with its specials, under a third of the float form, and no trap on broken bytes; none of it reads a clock); example3D/;Phone/ PhoneRecordingPins Docs/3D/Phone.md§ A recording; Guide Ch 40 § A film that knows where the camera stood: a recording and § Looking through the phone's camera: camera(_:), with theRecordingAsPathandPinsHoldfigures.A recording's own sound (
OllinPhone:PhoneRecordingSound; the core seam's.swift ExportAudioSource). A recording made with the microphone is heard with the sketch and carried into an export, with nothing to switch on:.hasSoundToExport recording.volume,isMuted,hasSound. Load-bearing: (1) The decoded track starts on the first frame. The video file places its sound with an edit list (a phone's microphone starts a fraction of a second after its camera), andAVAssetReaderTrackOutputhonors it: measured through the shared writer, a click is decoded on its own sample whether the sound began 0.258 s late, on the first frame, or before it, the gap as silence and the encoder's priming gone. Each buffer is placed by its own time, never appended, so a hole is silence and not a shift. (2) Decoded once, at the rate it will be played at (the output's own for a window, the file's for an export), by the system's converter, so playing is a copy: one channel, 16-bit, capped at an hour and bounded before memory is set aside. At a rate that is not the track's the converter hands its output over nine samples early at 48 kHz (0.19 ms), measured and left. (3) A block is placed by the time it will be heard, never by a count of the frames asked for. Fed at 44.1 kHz under a 48 kHz output, the engine's own converter asked for 471 frames every cycle, and a counted place was 57 ms off in 45 s; fed at the hardware's rate the device's clock ran 3.9 parts in a million against host time (0.2 ms a minute). So the source node runs at the hardware's rate, andPhoneSoundRendererworks a block's place out from itsmHostTime, the output'spresentationLatency, and one frame of time for the picture to reach the screen. (4) The offset between host time and the recording's place is the smallest reading of a run (PhoneSoundClock). The device hears the clock a little after the runner read it, by an amount that varies, so each frame's reading is the true one plus that. A reading more than 5 ms from the one held starts over (a held clock, a capped step, the transport). (5) Carry on, start, jump, or stretch (PhoneSoundVoice, no clock and no device inside it). Within 2 ms the read is a copy of the track. Past that it runs a thousandth fast or slow (1.7 cents) through a 32-tap Kaiser-windowed sinc at 128 phases, until the error crosses, and locks onto the next whole sample; measured, a tone read that way is at least 91 dB clean to 18 kHz at 48 kHz, where a cubic through four samples is 21 dB at 12 kHz. Past 40 ms it jumps: ITU-R BT.1359 puts the first notice of sound ahead of its picture at 45 ms, and a stretch from there would leave it off for most of a minute. A move by hand (seek, a clock that ran backward) jumps however small, through a serial. (6) Every start, hold, and jump is a 10 ms fade, the two halves of a jump adding to one, so a steady level holds straight through (a 100 Hz tone cut at full level leaves 48 dB less outside itself with 10 ms, 36 with 5). One thing fades out at a time. (7) A loop's seam and a recording's end are split on their exact sample inside a block, and a place within a millionth of a sample of the end is the end: sample counts summed as seconds land a hair short of it, which made a run of one sample and a second jump at every seam before it was caught. (8) Held when the sketch is held, with no word from the runner: with no frame for three frame steps (never under 0.1 s) the audio thread fades out on its own, and carries on from the recording's place when frames come back.pause()andstop()say so at once. The audio thread only tries its lock, so it never waits on the sketch; its closure is built outside any actor, and everything it touches is made before the first sample. (9) Under an export nothing plays. The place is written down against the export's clock (PhoneSoundMap: steady play is one entry however long; a move, a pause, a level, or a switch ofloopswrites one; a clock that ran backward forgets what was written ahead of it), and the same voice makes the sound from it exactly: a jump past one sample, never a stretch. A pause is written on the frame it was called on, so nothing is heard twice when play carries on; a seek lands on the next frame, with the picture. (10)PhoneDeviceanswersExportAudioSource, since the sketch holds the device and a framework object is never looked into.hasSoundToExportis what keeps a device on the cable, and a recording made without the microphone, from declaring a silent track; an instrument always has. The device answersTransportMutabletoo, so frames the transport replays pass unheard. (11) The output is opened on the first frame with something to hear, so a recording muted from the start never takes it; the track decodes off the main thread; a change of output lets the engine go and the next frame opens one for what is there.recording.lastErrorspeaks for the picture and for the sound, each cleared when its own thing works. Not done: no bundled recording has sound; a sketch cannot read the sound (no tap); how the sound sits against the picture on a real display is by ear. Proof:PhoneSoundPlayerTests(10, no file and no device: a copy sample for sample, a seam on its sample at a whole and a half-sample length, a level that holds through a jump, 300 parts in a million for a minute with no jump and under 3 ms off, a stretched tone 75 dB clean, the hold when frames stop and the place on their return, a move by hand against a drift, the offset, the map),PhoneRecordingSoundTests(8, a recording with clicks written by the phone's own writer: decoded on the sample; in an exported sound file on the sample, again a lap later, after a seek, and silent through a pause; within a millisecond in an exported video; the level and the mute; no track from a silent recording; a missing track said in a sentence; no output opened when muted), nineteen planted defects each red on its own test, andtheOutputFollowsTheRecordingunderOLLIN_SOUND_LIVE: the Mac's real output at 80 dB down, read back from the audio thread (on the M2: open 0.18 s in, within 0.81 ms of its place over two laps, two jumps for two seams, silent on a pause and when the frames stop).Docs/3D/Phone.md§ Its sound; Guide Ch 40 § What the microphone heard: a recording's sound.The camera's picture on the cable, and the phone as a viewfinder (
OllinPhone:PhoneCameraFeed; the shared.swift PhonePictureCompressor, which holds the compressor both directions use,.swift PhoneCameraGate,PhoneCameraSequence,PhoneCameraSender, andPhonePictureColors; the hold inPhoneStreamReader; the app'sCameraVideoStreamer). In every mode that runs an ARKit session.swift deviceis the camera's own picture off the cable, HEVC at the size the sensor delivers, and.latestCamera? .picture device.use(.room)besidedevice.show(self)makes the phone the viewfinder of a sketch running on the Mac. Load-bearing: (1) the connection is the asking. The phone compresses only while a client is onPhoneWire(1340), and the Mac dials only while a drawn frame read.cameraPort picture(released after two seconds, the feed's thread ending ten seconds later), so a sketch that reads only the pose costs the phone no video. (2) A picture and its camera record are one message (wire kind 20), and while the picture arriveslatestCamerais the newest decoded picture's own record, never the newest sensed: the pose a sketch draws through is the pose of the picture it draws on. (3) A frame is skipped before it is compressed, never after.PhoneCameraGatelets a frame in only with a client there and fewer than two pictures not yet taken by the connection (contentProcessedis "taken"). A picture is numbered when it is let in, so one lost afterwards (too big for a frame of the wire) leaves a gap,PhoneCameraSequencerefuses everything built on it, and the gate forces the next to a keyframe. (4) The color tags travel beside the picture, as H.273 code points read off each buffer. A format rebuilt from HEVC parameter sets carries the range and neither primaries nor matrix, and a decoder left to guess takes anything past standard definition for BT.709: a camera's BT.601 frame came back 40 levels off in its strong colors (measured 2026-11-26), 2 with the tags. (5) What was read from a frame waits for that frame's picture.PhoneStreamReaderholds a body, a face, the hands, the text, the markers, the wand, a depth frame, a matte, the attention map, and the motion field until the picture clock passes their capture time, so they sit on the picture as they do out of a recording. The planes, the room mesh, the light, the motion, the touches, the sounds, the air, and the state go straight through. Nothing is held once no picture has decoded for a quarter second, at most 240 wait, and the two threads that take messages in share one.arrive intakelock. (6) Each read thread owns its decoder, so a thread started after a stop never meets the one on its way out; the turn upright runs on the decoder's thread into a pooled buffer; the texture is wrapped on read, once a frame. (7)showkeeps the mode: it asks for Sketch mode only when the sketch asked for none. Whether the screen is the sketch's is the phone's to say (PhoneStateSample, written after the notes so a recording's older state still reads;.showsSketch PhoneState): always in Sketch mode, and in any other mode while a picture client is connected and the person has not put the picture away. The Mac sends frames only while it holds. (8) One compressor serves both directions (.isShowingSketch PhonePictureCompressor) and one picture codec the wire (appendPicture/readPicture), and the phone's whole sending path (PhoneCameraSender) is in the shared file, so the Mac's tests run it. Not done: the delay of either crossing is unmeasured (phone day P2), the cable's picture is not handed to a vision tracker's tap, and the viewfinder has no Record. Proof:PhoneCameraVideoTests(6, device phase, insidePhoneMediaTests: camera-shaped frames through the phone's sender, a socket pair in uneven chunks, the Mac's feed, each picture upright within 2.5 levels of its frame holding the record it was sent with; a lost picture caught and the keyframe recovering; a stalled cable skipping whole frames; the device handing a sketch one frame's picture and pose) +PhoneCameraLinkTests(15: the gate, the count, the hold, the wire cut at every length,showand the screen flag); seventeen plants red; the app built for a generic device and has not yet run on one. Example3D/;Phone/ PhoneViewfinder Docs/3D/Phone.md§ The camera's picture on the cable and § The phone as a viewfinder; Guide Ch 40 § The camera's picture off the cable: a livePhoneDeviceand § A viewfinder: the camera's picture under the sketch, with theViewfinderLoopfigure.Drawing on a real surface (core:
Plane3inMath/Plane3.swift;Sketch,.withPlane( _: ) unproject(_:onto:),painted(with:from:),occluding,drawImage(;_: topLeft: topRight: bottomRight: bottomLeft: ) Drawer.drawFlatMeshandensureFlatMeshBatch;ollin_mesh_picture_vertex/_fragmentandollin_mesh_occluder_fragmentinRenderer/;Shader3D .metal PipelineKey/.meshPicture .meshOccluder.OllinPhone:PhonePlane.plane,withPlane(,_: PhonePlane) painted(,with: PhoneCamera) PhoneCamera/.pictureCamera ray(/through: covering: ) canvasPoint(). A wall a camera's picture shows becomes something a sketch works on: drawn on in meters, pinned to, lifted off in pieces that keep the picture's pixels, and able to hide a drawn thing. Load-bearing: (1) The paint is read per pixel. A painted vertex carries, in itsof: covering: ) colorslot, its place in the picture times its distance from the painting camera, and that distance ((u·w, v·w, ·, w), worked out in doubles from the rest position); the three run straight across a triangle and the fragment takes their ratio, so two wall-sized triangles at a slant are exact. Dividing per vertex is the defect a plant proves red. The fill rides in thetangentslot's four half floats, since the color's slot is taken. (2) A mesh takes its pixels where it stands when the block opens (PicturePaint, the model matrix at.restModel painted's entry): a transform before the block places, a transform inside it moves, a stretch included. One block around a whole placed scene reads every placement as a move, which is the mistake the first test made. (3) The fragment takes the place in the picture and its screen derivatives before any discard and samples withgradient2d, throughimageSamplerand a premultiplied pipeline, the image path's own reading, so painted-in-place is the picture again. (4) Outside the picture, or behind the painting camera, nothing is drawn, depth included. (5) Both looks stand outside the lit scene.GeometryBatch/.picture meshOccludermark the run,meshOutsideLighting(the grid, a painted run, an occluding run) is what the secondary passes test where they tested the grid alone: the shadow casters, the traced scene, the reflection and caustics buffers, the scatter mask, the hidden layer. A painted vertex has no surface color for a traced hit to read, and casting from the shadow map but not the traced scene would make the look depend on the GPU. (6) Consecutive painted meshes with one picture share a run (currentBatchPicture), so a wall of lifted tiles is one draw;ensureSolidMeshBatchchecks the two flags so a lit mesh never joins it. (7) The occluder is the picture mesh's vertex stage with the color write mask empty (isDepthOnly); its fragment returns clear throughollin_blend_ready. Routing it to the lit pipeline looks the same, because its vertices carry a clear color, so the plant that proves the mask pairs it with an opaque fragment. (8) An image on four points weights each corner by how the diagonals' crossing divides its own diagonal and rides the picture run; a crossing outside either diagonal notes once and draws nothing. (9)cameraRay(through:)returns aRay3and reads a real lens backward, the fit of the picture into the canvas included. (10)Plane3(through:)takes the direction of least scatter from the closed-form eigenvalues of the 3 by 3 scatter matrix; "along a line" is a middle eigenvalue under a millionth of the largest, since the closed form's own rounding leaves a few parts in a billion. Measured: painted in place, flat faces come out on the picture's own values (0 pixels); a curved rim, where a triangle is seen edge-on and shaded half a pixel past its edge, moved 6 pixels of a ball by up to 2 levels; on a recording's video, 1 to 3 pixels of 307,200 by one level at the picture's own size, and 357 to 491 of 420,000 by one level where the canvas enlarges the picture by a quarter (the rasterizer snaps a triangle's corners to 1/256 of a pixel). A moved piece matches the pixels it left within 2 levels, which is the present pass's dither at two positions. Not done: a lifted piece that floats shows again, flat, in the picture behind it (a block joined to the wall by its sides covers its own place); 2D calls do not followwithPlane(a layer laid on four points is the route); nothing finds a surface from depth, so a World-mode recording, which carries no planes, has none; an occluder hides only as much as the mesh it is given; a vector export draws none of it, a spatial export writes a painted mesh plain and leaves an occluder out. Proof:SurfaceDrawingTests+Plane3Tests(18 tests),PhoneSurfaceTestson the synthetic room's tiled wall (four clicked corners within a pixel of their marks on every frame at three holds and crops; a mark on a lifted tile found within a pixel of where the lifted face puts it; a ball behind the wall hidden with the frame equal to the plain picture), 19 plants red; a mark on a wall has to be flat (a ball sunk into it shows a half-ball whose visible middle is off its center by pixels from the side), and two saturated marks a hue step apart bleed into each other through the video codec. Examples3D/andPhone/ PhoneWallTiles 3D/, each with the bundledPhone/ PhonePoster Wall.ollinrecording(written byPhoneSurfaceTestsunder.writesTheWallRecording OLLIN_WRITE_WALL_RECORDING);Docs/3D/Surfaces.md,Docs/3D/Phone.md§ Drawing on what the phone saw; Guide Ch 40 § A wall as a canvas in meters: withPlane(_:), § The picture as paint: painted(with:), § A real wall that hides a drawn thing: occluding, § A click that stays on the wall: pinned points, and § A flat drawing on a wall: an image on four points, with a figure each.A surface from depth (core:
DepthSurfaceandRGBDFramein.surface( atColumn: row: pose: tolerance: minConfidence: ) 3D/, the package entryDepthSurface .swift DepthSurface.grownover raw arrays;OllinPhone:PhoneDeviceand.surface( under: covering: tolerance: ) surface(,at: tolerance: ) PhonePlanes/.nearest( along: ) nearest(to:),PhonePlane/.intersection( with: ) distance(to:)). A wall, a floor, or a box's face fitted from one depth frame, so a World-mode recording, which carries no surface, can be drawn on, and a click chooses the surface in any recording. Load-bearing: (1) The fit is a region grown from a seed: a first plane from the 9 by 9 samples around the seed (every candidate passes through the seed and two samples of a fixed ring, in a fixed order, the most samples within half the tolerance wins, and at least two fifths of the window has to agree), then every 4-neighbor within the tolerance joins, and the plane is fitted again from running sums each time the patch is half as big again. No random choice anywhere, so one map gives one surface. (2) Two fifths of the seed's window has to agree, never fewer. A plane seen edge-on holds every sample along one line of the map whatever its depth, since their lines of sight all lie in it, and a line is nine samples of the eighty-one: with the bar at nine, random depths gave a "surface". A guard on how squarely a surface faces the camera was tried beside the bar and removed, since it refused a table top seen from a low angle and the bar already keeps the edge-on plane out. (3) The tolerance is meters up to two meters and widens in proportion past that. (4) The surface comes back facing the camera, with the room's up read off it onceposeplaces it, its origin the middle of the box around its outline, its outline the convex hull of the patch's rim counter-clockwise from the front. (5)surface(under:)asks the found surfaces along the line of sight first and fits only where none is met;surface(at:)takes a found surface within 5 cm, else fits where the depth measured at the point agrees with the point (5 cm or 3%) and the fitted plane passes through it, so a point behind a wall or behind a solid gives none. The depth frame's own camera is used, in the sensor's frame, so the hold needs no handling. (6) A fitted surface is one frame's reading and is kept by the sketch; refitted every frame it trembles. A point of the room in a@Paramis how a choice survives into an export (PhoneWallTileschosen;PhonePoster's four corners, the first choosing the surface). Proof:PhoneDepthSurfaceTests(the synthetic room's depth ray-cast from its own numbers with 3 mm of noise at a meter; the wall within a centimeter and a degree on four frames, the floor, a solid's face that stops at its edges, an edge that gives one surface or none, the same map twice, eleven things that are not a surface, a World recording through the device in two holds, a Room recording's found surfaces by ray and by point); both examples pixel-identical on the bundled recording and seen working on a World recording written bywritesAWorldRecording(OLLIN_WRITE_WORLD_RECORDING);Docs/3D/RGBD.md§ A flat surface from depth,Docs/3D/Surfaces.md§ The surface under a click; Guide Ch 40 § A wall the phone did not report: a surface from depth. Not seen on a phone's own depth.Faces in a picture (
OllinPhone:PhoneExpressions(.swift PhoneExpression,PhoneExpressionEvent,PhoneExpressions,device.expressions);PhoneFace/.surface( at: ) worldSurface(at:)/textureCoordinate(/along: ) occluder()/expression(_:);Sketch.withFace(_:);PhoneCamera,.isMirrored PhoneRecording,.isMirrored PhoneCaptureMode. Core:.isMirrored Sketch, the own-coordinate arm of.painted( with: _: ) Drawer.drawFlatMesh). A face the phone tracks is somewhere to draw: paint that follows the skin, the head as what hides, a spot of skin a thing rides, and expressions as events, the same from a recording and from the cable. Load-bearing: (1) Paint by a mesh's own coordinates is the picture path with the coordinate as the place: the vertex'scolorslot carries(u, v, ·, 1)where projective paint carries the place times its distance, so one fragment and one batch kind serve both (PicturePaintsays which), clear texels are discarded before depth, and a mesh with no coordinates is skipped with a note. On a flat sheet it is.toPicture == nil drawImage(pixel for pixel, and over the same mesh drawn in_: topLeft: ...) occluding { }it passes everywhere (one vertex function, one depth,lessEqual). (2) Draw the occluder first when the paint has clear parts, or paint on the far side of a turned head shows through the near side's clear texels. (3)occluder()is the face's mesh plus an egg sized from the mesh's own bounds (half-width as the unit: 0.98 of it to each side, 1.25 behind, 0.6 ahead of a middle 0.3 behind the mesh's back, 0.4 above the mesh's top), kept inside a head of those proportions so it errs toward hiding too little. The proportions are from head measurements and the synthetic head, and its fit on a real face is on the live-check backlog. (4) An expression is judged at intake, per reading, per face (PhoneStreamReader, so the cable and a recording share it), with two levels (.ingest begins,ends), faces followed by nearest head within 0.3 m, a lost face carried as it was, and a departed one dropped. A recording feeds only the newest face of each step, so a blink shorter than a step taken by a slow sketch can be missed, and a seek backward resets the judging with the rest of the device.timeSince(_:)counts on the readings' capture clock, never the wall clock, so it repeats under an export. (5) A Face recording is a mirror and stays one (ruled by research, 2026-11-30): ARKit delivers the front camera's picture, the camera's place, and every anchor mirrored together, so they agree and nothing is flipped on either end.isMirroredfollows the mode (face,selfie), is written torecording.jsonfor a person reading it, and is answered from the mode for a recording made before it was written. The public pages name left and right only as the stream's own labels: which real sideeyeBlinkLeftis has not been checked on a phone. Tests:PhoneExpressionsTests(9, staged),PhoneFaceTests(the skin and the occluder against the synthetic head's formula),PhoneFaceRecordingTestsinPhoneMediaTests(paint within a pixel of the formula and of the picture's own marks across a head turn, the head hiding what goes behind it, the occluder inside the pictured head's outline, each expression once per lap and again on the next, the cable's bytes reading what the recording's player reads). The synthetic head isSyntheticHeadinTests/;OllinPhoneTests/ PhoneFaceSupport .swift OLLIN_WRITE_FACE_RECORDINGwrites the example's bundled recording. Example3D/;Phone/ PhoneFacePaint Docs/,3D/ Phone .md#drawing-on-a-face-in-its-picture Docs/; Guide Ch 40 § More to draw on: a face.3D/ Surfaces .md#paint-by-a-meshs-own-coordinates The phone's own sensors (
OllinPhone:Sensors/the readers;PhoneSensorHub;.swift PhoneOwnSensors(.swift PhoneSensorDriver,PhonePictureConverter);PhoneDevice;.readsOwnSensors OllinRuntime/;PhoneProject .swift Examples/). The third place one sketch reads3D/ Phone/ PhoneViewfinder PhoneDevicefrom: in a sketch built for a phone,PhoneDevice()is that phone's own sensors, read in the app's own process with no capture app and no cable. On a Mac it is the cable as before, andreadsOwnSensorssays which. None of it has run on a phone. It is proven on the Mac (PhoneOwnSensorsTests, 13, each shown red on a planted defect: the same frames handed to a device that plays a recording, one fed as the cable feeds it, and one fed as the readers feed it read the same camera, surfaces, and light, and a sketch draws the same pixels from the phone's path as from a recording), by builds for iOS, and in the simulator, where a real ARKit session refused the mode and its reason reached the sketch aswaitingMessage. Load-bearing: (1) the readers are one copy. The files ofSources/compile into the library and, by path, into the capture app (OllinPhone/ Sensors/ Apps/), so they import Apple's frameworks and never Ollin, and each is guardedOllinPhoneApp/ project .yml os(; anything that names a library type (iOS) && !targetEnvironment( macCatalyst) PhoneSensorHub) lives outside that folder. The capture app keeps its own mode switch, on purpose: about a hundred lines in two copies, because nothing here can run that app and every later recording comes from it. (2) The camera's record is built in one place (PhoneCameraSampleover an.init( _: index: quarterTurnsCW: ) ARFrame,Sensors/), for the cable, a recording, and the phone, so the three cannot read a lens differently. (3) Readings and frames are handed over on the main thread, straight into the reader'sCameraRecord .swift ingest, so adraw()sees one frame's picture, camera, and readings together. The picture is the camera's own buffer, stood upright and made BGRA when a sketch reads it, once a frame: one rotation-session pass turns a two-plane camera frame and converts it (within 6 levels of its colors), and for a BGRA frame it is byte for byte the recording's own turn. (4) A mode is a session of its own.use(_:)on the phone forgets what the last mode read (every reader starts with.resetTracking, so the room has a new origin), no camera starts before a mode is asked for (the phone's motion alone runs), and asking for the running mode does nothing. For the same reason a reinstall on each save starts the room over; the checkpoint carries the clock and the parameters, never the tracking. (5) Live means reporting.isLiveandisRunningare true while anything arrived in the last second, motion included, so a mode the hardware cannot run is learned fromlatestStateand.isSupported waitingMessage, and a failed session fromlastError, cleared by the next frame. (6)show(_:)is inert there (the sketch is on that screen: no sender, nothing dialed,isShowingtrue untilstop()), which is what lets the viewfinder'suse(.room)besideshow(self)run unchanged. (7) Left out: Touch and Sketch modes and the wand's pad, which are the capture app's own screen, and the sound classifier and the barometer, which each ask a permission of their own. (8) The appollin phonewrites is namedOllinPhone, like the library, twice over. As a module the build fails (Multiple commands produce OllinPhone), so the app's code compiles into.swiftmodule OllinTetheredSketch; as a scheme the build ended well having built the library and no app, so the project carries a scheme of that same name and the tether and the build test ask for it. (9) A recording beside the sketch is bundled as a folder (type: folder, in the tether's spec and the generator'sios-appspec); listed like a folder of pictures its three files land flat in the app and the recording is not found. The generator no longer refuses the phone library for a phone app. Tests:PhoneOwnSensorsTests(insidePhoneMediaTests),PhoneProjectTests,PhoneProjectBuildTests,IOSAppProjectTests.Docs/3D/Phone.md§ The sketch on the phone itself;Docs/§ In the simulator; Guide Ch 40 § No Mac in the room: the sketch on the phone.Tools/ OnThePhone .md A place on a mesh (
Sources/:Ollin/ 3D/ MeshSurfacePoints .swift Mesh.surface(at:),Mesh,.textureCoordinate( along: ) Ray3.hit(_: Mesh)). A texture coordinate as the address of a spot on a surface that bends: from a coordinate to aPlane3standing on the surface, and from a ray to the coordinate it first meets. Load-bearing: the plane's facing is the mesh's own normals blended across the triangle (the flat facing without them), never the unwrap's handedness, so a mirrored unwrap still faces out; itsupis the direction the point moves as the coordinate goes up the image. Both read every triangle (a few thousand is the size they suit) and work in the mesh's own space. A ray meets either face of a triangle, nearest first, and only in front of its origin. Tests:MeshSurfacePointsTests(6, no GPU).Docs/.3D/ 3D .md#a-place-on-a-mesh Fusing a sweep, and keeping it registered (
Sources/+Ollin/ 3D/ WorldCloud .swift 3D/, core, source-agnostic).CloudRegistration .swift WorldCloudis a voxel accumulator:add(places a camera-space cloud by its pose and keeps one point per cube, so re-seeing a wall refreshes it in place and the cloud is bounded by surface area rather than frame count;_: transformedBy: ) PointCloudand.transformed( by: ) Vector3are the placement primitives..transformed( by: ) add(_:correcting:)/align(_:from:)line the frame up against what is already fused before merging, which is what stops a long sweep smearing (a tracker's per-frame error never cancels, so it grows into tens of centimeters); the fix is kept incorrectionand returned asCloudAlignment(pose, correction, overlap, error, passes, applied). Frame-to-model point-to-plane ICP, implemented from Low, UNC TR04-004 (2004). Load-bearing: the recovered angles must rebuild a true rotation matrix, never the linearized one the system was built from (it is not a rotation, so feeding it back swells the scan a little every round) and onlysolverAnswersWithATrueRotationcatches this, because at a well-tracked frame's angles the two matrices agree; the 6x6 normal equations are solved through their eigenvectors with a pseudo-inverse threshold, so a direction the geometry does not pin down is answered with zero instead of a huge number (one blank wall corrects across itself and never slides along itself);correctionis the next frame's starting guess, which is what leaves only the newest error to find and lets one ring of cubes be enough; correspondence is approximate by design, the cube holding the point answers in one hash lookup (the grid keeps one point per cube) and the wider ring is paid only by misses; normals are fitted per voxel on demand and cached, widening to two rings when the neighborhood is thin (a feed sparser than the grid gets none at one ring, found by test); overlap counts points that found a surface, not points that got a normal (conflating them makes the guard refuse good frames); the step's turn is read from sine and cosine, never the trace alone (the trace is flat near zero, so a convergence test on it can never pass in single precision); a fit with too little overlap or one asking for a jump is refused and the cloud goes in at the fix earlier frames established, never at the raw reported pose. Measured at about 5 ms per round in the debug build against a 46k-point model at 1200 samples, roughly half what merging the frame costs. The pseudo-inverse cutoff is a conditioning threshold, not a numerical one (unmeasured = 1e-3of the largest eigenvalue): set near the floating-point floor the solve answers a direction the geometry does not pin down at all, and a camera facing one flat wall slides along it a few cm a frame while overlap and leftover error both stay perfect (measured: 0.416 m of slide over 20 frames became 0.011 m when the cutoff moved from 1e-8 to 1e-3).CloudAlignmentreports the smallest of the six eigenvalues over the largest (Gelfand et al., 3DIM 2003) and.stability Settingsrefuses on it (default 0, so the live path is unchanged; the loop matcher raises it)..minStability Docs/3D/Phone.md(World fusion, Keeping a long sweep registered); examples3D/(no hardware, side by side, C cycles the right half) andDepth/ ClosedLoopScan 3D/(C cycles it);Phone/ PhoneWorldScan WorldCloudTests(8) +CloudRegistrationTests(15), all GPU-free.Closing a loop: recognizing a place already scanned (
Sources/+Ollin/ 3D/ ScanGraph .swift 3D/PoseGraph.swift, core).ScanGraphwraps aWorldCloud, corrects every frame the same way, and keeps a keyframe everykeyframeDistance/keyframeTurn(pose, reported pose, a cloud thinned tokeyframeDetail, and thereachof what it saw). A new keyframe near an old one (searchRadius,maxViewAngle, at leastseparationkeyframes back) is fitted against a patch built from that old one plus itsneighborhood; an accepted match becomes a robust edge in a pose graph, which is straightened, and the fused cloud is rebuilt from the keyframes' new poses.add(_:correcting:)returns anUpdate(alignment, keyframe,Loop);Loopcarries keyframe/recognized/overlap/error/moved. The solve is least-squares Gauss-Newton with Levenberg damping on the SE(3) manifold, written from Grisetti et al., A Tutorial on Graph-Based SLAM (2010), with the box-plus retraction and numerically-differentiated Jacobians from Blanco-Claraco (2010/2021); the sparse normal equations are never assembled and are solved by diagonally-preconditioned conjugate gradients. Load-bearing: one pose is held (Grisetti's gauge fix; without it the recovery tests fail, verified red by sabotage, while a "the held pose never moved" test cannot fail because two mechanisms enforce it); the retraction is a body-frame turn plus a world-frame move, and the numeric derivative must go through that same retraction; the matching fit runs twice, wide then narrow (a single narrow pass mis-converges on an error bigger than its reach and reports a confident wrong answer: at 0.5 scale drift a one-pass match made the scan worse, 0.40 → 0.45, where the two-pass one gives 0.37 → 0.08); the matcher setsminStabilitybecause a match against one flat wall records drift as though measured (aMatchTheGeometryCannotPinDownIsRefused, verified red by sabotage);rebuild()must resetworld.correctionto the last keyframe's straightened pose or the live feed keeps adding frames where the map used to be; every odometry edge weighs the same (weighting each by its own fit's stability was built and measured on two scenes, helped one and hurt the other, and was dropped);turnScaledefaults to the scan's own medianreach(fixed too small in a big room, the scan comes out square but turned). Envelope: drift past roughlymatchingis refused rather than guessed. Measured on a staged 1.15-lap sweep with the per-frame fit off: worst keyframe error 0.223 m → 0.048 m. What it buys is a scan that agrees with itself, which is not the same as a scan in the right place: one closure pulls the two ends of a walk together and shares the difference along the chain, so it earns most of it at the point of return, and in a small room where nearly every frame sees something already fused the per-frame fit has taken most of the drift out before the walk gets back (the Guide figure's staged room is one such: the closed half draws each wall once and holds a quarter fewer points, while its poses score no better against the truth)..range * reach Docs/3D/Phone.md(Recognizing a place already scanned); examples3D/(no hardware, side by side, true walls overlaid) andDepth/ ClosedLoopScan 3D/(C cycles reported / lined up / closing);Phone/ PhoneWorldScan PoseGraphTests(9) +ScanGraphTests(14), GPU-free; Guide Ch 38.Accessibility: color vision and motion (
Sources/+Ollin/ Color/ ColorVision .swift Core/+ theAccessibility .swift .colorVisionFiltercase). The author-facing half of the accessibility tier (the viewer-facing half is the bullet below):ColorVision(akind+ aseverity, theSimstruct-plus-Kindshape;.normal/.protanopia/.deuteranopia/.tritanopia+ theprotanomaly(_:)family;Kind: ParamOption) drivesColor.simulated(_:)/Palette/.simulated( _: ) Ramp.simulated(_:)andFilterfor a whole frame, plus the palette judgment.colorVision( _: ) confusions(under:)/confusions()/isColorblindSafe()and the publishedPalette(Okabe-Ito)..colorblindSafe Sketchreads the system setting through the AppKit/UIKit seam. Load-bearing: at severity 1 the model is a projection along the missing cone's axis onto the dichromat's surface, built at load from published measurements rather than stored numbers: Brettel, Viénot and Mollon 1997's two half-planes for every kind (the gray axis with 475 nm and 575 nm for protan and deutan, with 485 nm and 660 nm for tritan; a separator through the gray axis and the missing cone's axis picks the half, and no projection crosses it), over Smith-Pokorny 1975 cones and the Vos-corrected sRGB primaries, with the display's white as the neutral axis (every gray comes back exactly). The derived matrices match the reference implementation's printed ones to its own rounding (2.5e-5; it rounded its anchors and its primaries). Viénot 1999's single plane was built and measured, and refused at his ruling: it is exactly.prefersReducedMotion r = gin linear RGB, so every blue reads lavender (0.03 to 0.06 OKLab from Brettel's), though it stays inside the display by design. A severity below 1 is the straight line in linear light from the color to its projection: Machado, Oliveira and Fernandes's anomalous table (shipped until 2026-10-09) was measured against a projection end and removed, since its path carries pure blue 0.17 (protan) and 0.20 (deutan) OKLab away from where severity 1 puts it. A result outside the display range is clamped channel by channel (the GPU fragment clamps only the low end, since a layer may carry light brighter than white for the tone map), and that is measured, not inherited: in the viewer's own two cone responses (white = 1) the clamp moves what a protanope sees by 0.011 on average (max 0.035), the nearest in-range point on their surface by 0.066 (max 0.20), and a pull toward the gray of equal luminance by 0.26 (max 0.78, green and yellow near-white, blue navy; built, ruled, and retracted the same session), because the clamp's error runs along the confusion line. So idempotence is exact for every color whose simulation stays in range (202 to 245 of the 343-color cube per kind) and bounded for the rest (a second pass moves what the viewer sees by at most 0.044). It belongs in linear light (pinned against display-value application bytheModelIsAppliedInLinearLightNotToDisplayValues); the filter needs no encode/decode; its rows are the positive half (0 to 2), the negative half (3 to 5), and the separator (6).ColorVision.matrixis gone (two transforms per kind);applied(is the raw model. The judgment is the whole OKLab distance, lightness included, and that is the load-bearing fact for the docs: red against green keeps only 23% of its gap across the hue plane under protanopia and 7.6% under deuteranopia (78% under tritanopia), though the whole distance keeps 90% under protanopia because one is far darker, so two colors that differ only in hue merge, and a lightness difference saves them (measured twin pair: 0.281 → 0.013 matched for lightness, 0.601 stepped apart). The 0.06 default tolerance is measured, not guessed (toLinear: _: _: ) colorblindSafe's worst pair 0.078 under deuteranopia, a familiar six-color chart set 0.013 under protanopia, both pinned).prefersReducedMotionapplies nothing by itself (only a sketch knows which movement carries the piece) and reads false headless, so an export is machine-independent. ExampleColor/ColorVision(a photograph seen four ways over the two palettes: a picture is checked by filtering a layer, a palette color by color, and underpreviewevery column is drawn in its true colors so the one filter over the finished canvas is the only thing simulating, which is what the mode claims); snapshotcolor-vision(both paths in one frame, so a drift between theColorcall and the filter shows);ColorVisionTests(11) +ColorblindPaletteTests(5) +ColorVisionRenderProbes(5, Metal-gated: the filter pinned against theColorcall for every kind at two severities over three patches that leave the range and use both halves of every kind's surface, and a brighter-than-white patch read in linear light); the web page'sSimulatedprobe inWebEffectsTests.Docs/; Guide Ch 2 § Will everybody see it? + the ColorVision figure, Ch 3 § When somebody would rather it stopped: reduced motion. The projection's own invariants (idempotent, the kept cones unchanged, the worked values, the seam between the halves, the monotone dial) are under Physical invariants. Ahead in ROADMAP: complex-script text.Helpers/ Accessibility .md Linear frames for compositing (
Sources/,Ollin/ Export/ EXRExport .swift Sources/).Ollin/ Renderer/ LinearFrameCapture .swift --export-exr <path>writes one frame as an OpenEXR file, and--export-sequence <dir> --exrwrites a numbered folder of them off the same fixed-timestep drive;OllinAppand.exportEXR( _: to: frame: fps: quality: ) exportSequence(are the calls. The file is the frame before the present pass: linear light, Rec. 709 primaries, half components free to run above 1, premultiplied by coverage in..., writesEXR: ) A, plusZ(32-bit float, distance from the eye in the sketch's own units) whenever the frame drew through a 3D camera. Load-bearing: the writer is hand-written, not ImageIO, for two reasons measured here, namely thatCGImageDestinationpasses components through a profile conversion (8.0 came back as 8.0001, with ~1e-4 leaking into channels that held nothing) and that aCGImagehas nowhere to put a fifth channel; the format written is the one every reader opens, single-part scanline,NO_COMPRESSION, one block per row, channels in the alphabetical order the format requires (A,B,G,R,Z) with the offset table backfilled after the rows. The capture is opt-in (MetalRenderer, read in.capturesLinearFrame renderedFrameandaccumulatedFrame), so every other export is byte-identical; it blitspresented(the texture the present pass is about to read) and the resolved scene depth inside the frame's own command buffer, and the depth resolve is forced on for such a frame. Depth is inverted on the CPU over the camera's near/far with the same curveollin_fx_depth_normalizewalks (near*far /, orthographic linear), in Double: single precision made a far plane of 1000 read 1000.244, since the subtraction cancels. A supersampled export reduces depth to canvas size by the nearest sample under each pixel (the front surface, the multisample resolve's own rule). A flat frame writes no( far - d*( far-near)) Z(its depth buffer holds a sort key, not a distance);--made-framesis refused with--exr(a made frame is built after the present); the recipe is stored in the standardcommentsattribute; a cleared pixel reads exactly the camera's far distance; no normal or per-object-matte pass exists, the renderer keeping no geometry buffer to write one from.EXRExportTests(10 tests, with a parser of the test's own: the header and channel list, the system's OpenEXR reader opening the file, the recipe in the comments, linear light against the PNG's encoded byte, a 2x-white overlap the PNG cannot separate, coverage premultiplied on a see-through canvas, noZon a flat frame,Zas distance with the far plane in the corners, a supersampled export still canvas-sized, and a two-frame sequence). Verified against the referenceexrheader/oiiotool.Examples/;Export/ LinearFrame Docs/§ Linear frames: EXR; Guide Ch 45 § The frame before the tone map: OpenEXR.Output/ Export .md Describable output (
Sources/+ the accessibility overrides onOllin/ Core/ SketchDescription .swift OllinMTKViewinCore/). The viewer-facing half: a sketch says what it shows, so a generative piece is not opaque to a screen reader.SketchView .swift describe(_:)is the whole piece in a sentence,describe(_:as:in:)one named part with an optional canvasRectangle,noDescription()clears both; they fill the publicSketch(.accessibleDescription SketchDescription= summary +DescribedElements carryingname/text/region,spoken= "name: text",lines= the summary then the parts). Author-provided only — nothing is derived from the drawn shapes (a list of what was drawn is not a description of what it means; the vector recorder is the seam if that ever changes, noted in DESIGN-NOTES). Load-bearing: parts are keyed by name in first-named slot order and a removed part keeps its slot, so a part that comes and goes returns to its place rather than the end of the list — the reading order must never move under somebody walking it by hand (the defect that only showed when the example was rendered: a sun below the horizon on frame 0 put "the sun" last all day);==compares what reads (summary + present elements), never the slots; the AX surface is pull-based off the sketch (isAccessibilityElement/accessibilityRole/accessibilityLabel/accessibilityChildrenoverrides), role.imagewith no parts and.groupwith them, the child elements kept and updated in place (a screen reader follows an element by identity, so rebuilding them each query drops its place), and.layoutChangedposts only when the set of parts changes (SketchDescription, names + whether there is a summary), never on a reword — else a per-frame description interrupts sixty times a second; a region maps canvas→view through.shape viewRect(scale + the y-flip, AppKit counting up from the bottom), no region = the whole canvas; a sketch that says nothing changes nothing (the view keeps its default AX, and the SVG is byte-identical —role/aria-labelledby/<title>/<desc>are emitted only for a non-empty description). Travels with the work: SVG<title>+<desc>(the standard place, first children, XML-escaped) and the PDF document title; PNG/GIF/video carry nothing (no standard slot — stated, not faked), andVectorRecordingcarries the description so SVG and PDF cannot drift.OllinMTKViewandmakeOllinMTKVieware internal (were file-private) so the tests drive a real view — the wiring is the feature. ExampleBasic/Describing(a day over a bay, words written from the same numbers as the picture, the sun dropped from the description when it sets); no pixel snapshot (the output is words);DescriptionTests(18, five sabotages verified red).Docs/; Guide Ch 45 § Saying what it shows: describable output + the SayingWhatItShows figure.Helpers/ Accessibility .md Math & motion.
map/dist/lerp, the bare shaping scalarsclamp/fract/step/smoothstep(spelled + argument-ordered to match the shader library so the vocabulary carries into per-pixel code;Easing.smoothstepis the same curve as anEasing, renamed fromsmoothStep), their siblingswrap(_:_:_:)(floor-based circular clamp — continuous through negatives,wrap(a, 0, .tau)for angles), the genericclampover anyComparable(+clamp(_:to:)range form, soIntindices clamp uncast),unipolar/bipolar(the −1…1 ↔ 0…1 pair;unipolar(is justsignedNoise( x)) noise(x)), the sequence buildersfractions(/_: inclusive: ) angles((endpoint-exclusive by default so a ring never doubles its seam;_: from: turns: ) inclusive:for fence posts),polar(_:_:around:)(thecenter + Vector2(pair as one call; examplescos, sin) * r Motion/Petals(all three) +Motion/Spokes(fractions+polar)), the numerical slopesderivative(andat: step: function: ) gradient(overat: step: field: ) Vector2andVector3(Math/: central differences divided by the run the coordinates actually hold, the stepDerivatives .swift cbrt(ε)·max(|x|, 1)when nil or not positive; sin, exp, a cubic at 1000 and hand-worked partials to 1e-8, a quadratic exact at a given step, a forward-difference plant red;Docs/§ Slopes, Guide Appendix B § A number field's slope: the gradient with the Slope figure),Helpers/ Math .md spherical((its 3D twin, angles first: azimuth about +y from +z, elevation above the xz plane, the same convention as_: _: _: around: ) Camera3D.orbiting, whose eye it reproduces) withVector3.azimuth/.elevationreading the angles back (a 500-sample round trip pinned), the angle unitsDouble.degrees(_:)/.turns(_:)/.focalLength((a lens's vertical angle on the 36×24 mm frame lenses are named for,_: sensorHeight: ) 2·atan(h/2f);fieldOfView:) (call-site sugar into the radian API), the loop-phase helpers.focalLength( 35) loopProgress(/over: phase: ) pingPong((0…1 sawtooth / out-and-back fold of the sketch clock;over: phase: ) phaseis a fraction-of-loop head start), the timersevery(_:phase:)/after(_:)/everyFrames(_:)(true on the one frame that crosses a beat, so a periodic event needs no counter;phaseshifts a beat the same fraction it shifts a lap. Load-bearing: the previous frame's clock reading is held exactly (Sketch.previousTime, set inadvance) rather than worked out astime - deltaTime— those differ by a rounding error, and a crossing a frame lands on exactly then falls inside two windows and counts twice (3 of 6 frame rates read 6 beats where 5 were due). Frame 1 has no frame before it, so it borrowstime - deltaTimethere, which is what makes the start of the clock a beat atphase: 0and not one under a phase. A beat is a change of period index (!=, not>), so a clock sent backwards — a replay starting over — beats in the period it lands in, and a stopped clock does not beat. OneBoolsays "now" once: a frame spanning two crossings reports one.everyFramescounts the first frame as the first beat (1, n+1, 2n+1).sway(is the value-source sibling (over: in: shape: phase: ) Math/Sway.swift): low end to high end and back once a lap, over fiveSwayShapes (.sinedefault /.triangle/.saw/.square/.wander). Load-bearing: every shape closes its lap exactly, which is what lets a swaying sketch keep aloopDuration—.wandergets there by touring a closed circle through the field (noise(loop:)), nevernoise(time). The four worked-out shapes start at the low end and.wanderstarts where its field does;.triangle/.sawarepingPong/loopProgressmapped, which is the second construction their test asserts against.SwayTests(13 tests; the lap-closure one must sample off-boundary — Perlin is exactly zero at every whole number, so checking only at lap 0/1/2 passes a wander that does not loop, which a sabotage proved); exampleMotion/Sway.wave(is the raw-sine sibling (_: amplitude: around: phase: ) center + sin(, rate in rad/s so a hand-written wave carries over verbatim; closes a loop only whentime * rate + phase) * amplitude loopDuration * ratelands on whole turns —swayis the loop-exact one). The convenience tier is pinned byConvenienceHelperTests(22 tests; the sugar forms are checked by byte-identical A/B renders against the blocks they replace, sabotage-verified red).TimerTests(15 tests, the deciding one built from a second construction: a beat is exactly the frameloopProgresswraps on); exampleMotion/Beats), a resolution-relativescale, seedablerandom/noise(randomGaussian/randomVector/ring/randomChoiceuniform+weighted /shuffled/curlNoise(in the plane and in space:curlNoise(x, y, z)is the curl of a potential made of three offset copies of the field; both forms read the field's closed-form gradient,PerlinNoise, so a curl is three lattice walks rather than the six or eighteen a difference stencil costs, and the gradient is of the calibrated.valueAndGradient 0...1field exactly, zero where it clips; unnormalized on purpose, since a normalized curl is no longer divergence-free, take.normalizedfor a direction;CurlNoiseTestspins both forms against differences taken through the public field and the zero divergence, away from the clip; the shader library'sfloat3 curlNoise(mirrors it over the 3D value noise by differences,float3) ComputeTests) /.shaderCurl3DIsDivergenceFree signedNoise, a masterseed();Sketch.randomnessexposes theSplitMix64itself as a settable property, which is what puts the standard library's randomness (randomElement(,using: ) shuffled(using:),Int) and Ollin's own.random( in: using: ) using: Rgenerators (WaveFunctionCollapse,.solve LSystem.expanded,ShapeGrammar.run,WangTiles.fill) on the sketch's seed rather than on the system's dice, the one silent way a seeded sketch stops reproducing. It forwards to the samerngrandom()draws from, so it is one stream, not a second;&randomnessneeds the setter, so a direct assignment cannot also keeprecordedRandomSeedhonest (the setter runs on every use), which is whyrandomSeed(_:)stays the way to seed and the doc says so.RandomTests(4 new tests); gotcha: zero-widthrandom(a, a)consumes no roll, so parameter-scaled jitter rollsrandom(),-1, 1) * amount NoiseFields(Math/: the three seeded fields, Perlin, simplex and Worley, as one publicNoiseFields .swift Sendablevalue carrying every noise method the sketch has, so the sketch's ownnoise/fbm/curlNoise/simplexNoise/worley/ the loop and tiling forms are one-line forwarders ontoSketch.noiseFields, the typed core under the bare calls;noiseSeedreseeds the stored value,carryRuncopies it,noiseField()closes over it for aFormula. Load-bearing: it is a value, so a copy taken before a reseed keeps reading the old field, which is the property that letsDispatchQueueor a task group read it off the main actor with no lock and no isolation hop, the reason it exists: the.concurrentPerform Rendering/LineSprayexample'sDriftbends 38k lines a frame across every core through it.NoiseFieldsTestspins the copy against the sketch's own readings for every field, the value semantics across a reseed, and an off-main-thread read landing the same numbers), noise with nothing cut off (noise(and…, clamped: false) signedNoise(, plain and looping, on…, clamped: false) NoiseFieldsand the sketch: the field with its contrast and no clamp, read throughPerlinNoise. Load-bearing: it is.unclampedSignedValue noisebit for bit wherevernoiseis strictly inside its range (the unsigned form is the same(signed + 1) / 2), so the two can be mixed; it runs to about -0.5 and 1.5 (signed, -2 and 2), which the page says with the one-line squeeze back into0...1;noiseitself did not move; a line's field never leaves its range, so the 1D form isnoise(x)and exists for symmetry. The overloads take a requiredclamped:label and no default, sonoise(x, y)resolves as it always did.UnclampedNoiseTests: 800,000 reads of a 2D field with none on an end and no disagreement, the same for 3D, signed, and the four looping forms, 4 reads in 100 cut by the clamp it leaves out; four plants red. FigureGuide/), looping noise (Figures/ 05-Noise/ NoiseUnclamped .swift noise/signedNoiseloop:+radius:overloads — one lap tours a closed circle through the field and closes exactly,loopisfract-wrapped; the 2-coordinate form uses a 4D lattice, canonical 32-gradientgrad4, its own contrast gaingain4calibrated to the 3D feel; the 3-coordinate form (noise(, with_: _: _: loop: radius: ) signedNoise/fbm/signedFbm/ridgedFbm/turbulencebeside it, onNoiseFieldsand the sketch) uses a 5D lattice: 32 corners hashed one axis at a time (corners sharing their low coordinates share the lookups) and blended one axis at a time, the 80 gradients with one zero component and four signed (the zero axis by(h * 5) >> 8, 51 or 52 table values each), andgain5= 1.8 calibrated on 400,000 samples to the 3D field's spread (sd 0.520 against 0.522, 6.4% clipped against 6.0%), so moving a sketch fromnoise(x, y, z)to its looping form keeps its contrast (LoopingNoise3DTests: every form closes, the lattice equals a corner-by-corner sum to 1e-12, zero at lattice points, the spread pinned; red under a hashing and a gain plant); circle centered at (0.5, 0.5) off the integer lattice on purpose),fbm/signedFbm(1D/2D/3D + 2D-loop forms, octaves/gain/lacunarity, normalized sooctaves: 1==noise, name matches the shader lib), tiling noise (tilingNoise/signedTilingNoise/tilingFbm/signedTilingFbm: bothuandvare mapped onto closed circles, so the field meets itself at every edge and a picture repeats with no seam.detailis deliberately a frequency, not the circle radius (tilePointdivides by.tau), sofbm(u * 8, v * 8)becomestilingFbm(and keeps its grain; au, v, detail: 8) radius-shaped parameter made stone read as sandpaper. Load-bearing fortriplanarTextured, which repeats its picture across the whole surface: a non-tiling map draws a straight line at every wrap, loudest in a normal map, where the two sides light differently and the line reads as a crease. That was a real defect in the Ch 28 Bench figure, isolated by counterfactual to the normal map alone (25.6/255 step, falling to 3.0 with the map off)), the noise-variant family (Math/+ additions inNoiseVariants .swift Noise.swift; every name mirrored in the shader lib's noise module, all reseeded by the onenoiseSeed):simplexNoise/signedSimplexNoise(1D/2D/3D, Gustavson's structure over the shared seeded permutation, contrast gains 81.3/87.7 calibrated to the Perlin field's ~2%-clip feel),worley((seeded SplitMix-hashed cells;x, y[, z], feature: .nearest/ .second/ .border, jitter: ) .borderis zero on cell walls),ridgedFbm(Musgrave's crease fold with octave-weight feedback, reparameterized onto fbm's gain/lacunarity) /turbulence/warpedFbm(iq's two-level self-displacement;warp: 0==fbmexactly), each with the 2Dloop:form, deterministic + pinned byNoiseVariantTests,Generatorlegs on the Layered effects bullet,Docs/, examplesGenerators/ Noise .md Randomness/(simplex, its signed reading, worley and turbulence on one set of coordinates) +NoiseKinds Patterns/RidgeLines+Shaders/DomainWarp+Effects/Cellular, snapshotsridge-lines+noise-toolkit;Double.tau; easing (theEasingcurve catalog +@Eased, the derive helpersreversed()(1 - f(1 - t); a built-in lands on its family partner by identity, since every catalog ease-out is exactly the reflected ease-in, pinned over all 32) andmirrored()(the curve on the first half, its reverse on the second; the catalog ease-in-out for the eight families built that way, a curve of its own for back and elastic, whose in-outs carry their own constants, and an out-in the catalog lacks for an ease-out); a derived curve's identity is the operation over its origin, so two derivations of one closure curve compare equal and stay off the menu like the closure itself;EasingDerivedTests; exampleMotion/; Guide Ch 3 figureDerivedCurves DerivedCurves, plus theTimeline<Value:keyframe sequencer — worked exampleTweenable> Motion/Timeline), input smoothing (OneEuroFilter+@Smoothed), and the damped spring (Math/:DampedSpring .swift DampedSpring<Value:+Smoothable> @Sprung, the thirdFrameAdvancingsibling — each step evaluates the exact closed-form damped-oscillator solution across the under/critical/over-damped branches, so any dt is stable and steps compose exactly (frame-rate-independent, pinned byDampedSpringTests); perceptualduration/bounceparameters (bounce 0 = critical, clamped (−1, 1]), velocity carries across retargets,kick(_:)throws; exampleMotion/Springs), all frame-rate-independent and auto-advanced per frame.Docs/,Helpers/ Math .md Docs/,Generators/ Random .md Docs/,Generators/ Noise .md Docs/.Helpers/ Animation .md Complex(Math/Complex.swift, promoted from the limit-set generators' internal scalar, which now reads it):real/imaginary, the polarinit(,magnitude: argument: ) .i/.unit(_:),magnitude/magnitudeSquared/argument/conjugate/reciprocal/rotated(by:)/squareRoot(), theVector2bridge both ways (coordinates copied, the y flip left to the framing),Numeric+SignedNumeric+ both literals +Codable+ adescriptionthat reads as written, andComplex.exp/.log/.pow(aDouble, aComplex, and an exactIntpower by squaring)/.sqrt/.sin/.cos/.tan/.sinh/.cosh/.tanhas static members on the principal branch. Two type-checker facts are load-bearing and were both measured: the transcendentals must never be free-function overloads (a freepow(/_: Complex, _: Double) sin(_: Complex)joins the candidates for everypow(2, x)/sin(x)in the program, and with a literal-taking type in play a plain easing curve took 3 s to type-check andEasing.swiftstopped compiling outright; as members they never enter that search, and the spelling matches the Swift numerics package, whose elementary-functions protocol is NOT in the standard library, so there is nothing to conform to), and the mixedComplex/Doubleoperators are@_disfavoredOverload(without the marklengthsover doubles is ambiguous, since.reduce( 0, +) 0can be the type's literal and+ (Complex, Double)fits, and three framework files stopped compiling; disfavored, they measured as cheap as no overloads at all).ComplexTestspins both with a literal-heavyDoubleexpression that has to compile.ComplexTests(11 tests); the GPU twin is the shader library'scomplexmodule (under User-supplied shaders); examplesShaders/(the ratio shader with the circles of Apollonius and the circles through both points worked out on the CPU and drawn over it, landing on the rulings),ComplexPlane Shaders/(the imaginary part ofImaginaryLog clogof that ratio through a cosine palette that never completes a cycle, so the branch cut between the points is a soft seam;turnscloses it at a whole number), andShaders/Meromorphic(a ratio of two cubics built withcmulfrom six roots moved asComplexvalues, the palette's frequency a parameter), snapshotcomplex-plane,Docs/, Guide Ch 23 § Multiplying turns: the complex plane.Helpers/ Complex .md Canvas, capture & tooling.
canvasSize(theCanvasSizeenum, 1080² default) previewed perwindowMode(.auto/.fixed/.resizable);PaperSize(Core/: the ISO A series and the US three in millimeters,PaperSize .swift .landscape/.portrait,init?(named:), andcanvasSize(dpi:)landing on the sameCanvasSizepage presets, test-pinned);FrameRate(Core/: every publicFrameRate .swift fps:takes one, a literal stands in (fps: 60), the broadcast rates are exact fractions (.ntsc= 30000/1001,.ntscFilm,.ntscDouble, beside.film/.pal),--fpstakes a name, a number, or a fraction, and the two video writers place frame k at k·tick/timescalethroughmediaClock, which keeps a whole-number rate's 1000× clock byte-identical; internals stayDoublethroughframesPerSecondat the boundary, andSketch.frameRate, the measured live rate, stays aDouble); a maintainedExamples/set incl. aRecreations/section; headless capture (OllinApp.image(of:),--export) + deterministic frame-sequence export (--export-sequence+--skipwarmup; a warmup frame renders whenever the frame holds a persistent picture (noClear, orDrawer.usesFeedback: a feedback, an accumulator or line spray, a sim field, SSR history), inrenderFramesand the spatial-video loop alike, or the first written frame starts from an empty layer while the sketch's own state is--skipseconds on; a picture that is its clock alone skips the render;PersistentLayerExportTests); every export holds a sketch that stopped its loop, as the window does (Sketch=.exportHoldsFrame !isLooping && takePlayer == nil, read after a draw:renderImagecaptures the frame the loop stopped on and runs its settle passes there,renderFramesbreaks and writes the last readback for every frame left (rendered once if the hold came in a warmup frame that never rendered), the vector and spatial recorders take a fresh recorder each frame and keep the last, the spatial video writes the held pair, and the web recording ends, so a still's page is one frame and holds still; a replayed take still draws every frame, since it was written only on frames a window drew;--benchuntouched; ruled by @eaviles 2026-10-02, and it moved one media still,Shapes/Watercolor's grain, while its export fell from half an hour to one draw;NoLoopExportTests);--at Snames a still's moment in seconds (stillFlags: the frame is S × fps rounded,nanreads as 0, and it wins over--framewhen both are given; the sheets, the separations, and the spatial file read the same reader), so--at 2is--frame 120at 60 fps pixel for pixel (StillRateTests); every one-frame flag reads--fpsbeside--frame(--export,--export-exr,--export-plates, the vector family, through onestillFlagsreader), so a still lands on the sequence's moment at any rate, where until 2026-09-22 only the sequence and grid paths read it and--frame 30 --fps 10was drawn at half a second (StillRateTests); every headless drive drains its own autorelease pool once per drawn frame (renderImageper settle pass,renderFramesper frame, the stereo, vector and web drives, a contact-sheet tile, a figure render, a replay scrub): a device buffer arrives autoreleased and a synchronous drive never returns to a run loop, so a warmup frame and a written one alike used to be held until the process exited (issue #23 — 3,600 frames at 1080² reached a 15 GB physical footprint on an 8 GB machine and spent the run swapping. A/B on one M2 over 300 frames of a sketch that re-feeds aLineSprayevery frame: without the pool, one 4560K readback region per drawn frame (5 at frame 0, 235 by frame 226) and 106 MB climbing to 1.3 GB; with it, one region throughout and a flat 108-127 MB). Acontinuecannot leave a closure, so the warmup pathsreturnout of the pool instead;HeadlessDrainTests(5) counts the witnesses each drive leaves standing in the frame's pool, all five verified red by sabotage. export supersampling (--render-scale N/OllinApp, 1…4 — the frame is drawn N times across the canvas and box-averaged back to canvas size in linear light, ahead of the tone map, so the one 8-bit quantization point stays in the present pass; the viewport stays in canvas units, so it is a sampling rate and the sketch draws in the same canvas either way..exportRenderScale --settle N/OllinAppdraws each written frame N times with the clock held (.exportSettle advancewith the sametime,deltaTime0,frameCountcounting on, which is what keeps the renderer's repeat-encode guard from skipping the persistent layers) and writes the last, in both headless drivers (renderImagesettles only the captured frame,renderFramesevery written one, warmup once); the recipe recordssettle; refused beside--replay,--record-take, and--made-frames. The split is load-bearing: geometry and the screen-space pre-passes run at N×, everything that treats the frame as a picture (motion blur, flare,postProcessfilters, the tone map) runs at canvas size, or a pixel-radius filter would silently shrink to half its asked-for width at 2×; what it sharpens is the tessellated fill, outline text, and fine detail, never the analytic SDF shapes or the fringe strokes, which carry their own coverage; arenderTargetlayer keeps its recorded size and a piling canvas (noClear) renders at 1, both said out loud rather than silently; an over-large ask clamps to the ceiling with a printed line.RenderScaleTests(4, both the convergence-toward-4× probe and the blur-keeps-its-width counterfactual verified red by sabotage);Docs/); video & GIF export (Output/ Export .md OllinApp/.exportVideo exportGIF,--export-video/--export-gif— AVAssetWriter h264/hevc/prores +GIFWriterover one fixed-timestep drive; codec /--bitrate/--qualitycontrol, the last gated#if arch(arm64)); a GIF is written as it is drawn (GIFWriter,Sources/, public:Ollin/ Export/ GIFWriter .swift init(/path: width: height: palette: loops: ) append(_:delay:)/finish();exportGIF(palette:),--gif-palette shared|per-frameon--export-gifand--export-loop): each frame is drawn into the writer's own sRGB context at the writer's size (which is how--gif-widthscales, so the export has no scaler of its own), keyed, diffed against the frame before, quantized and LZW-coded into the open file the moment it arrives, so the buffers are sized once and no frame outlives the call that took it (GIFMemoryTests:heldBytespinned equal after 1 and 200 frames at 480², and every frame handed over is built on memory whose release callback the test counts, so the run never falls behind by even one). That second test used to be read off the process footprint, and it cannot be: the suite shares its process with every other suite in its shard, so the number is the sum of what all of them do in the same seconds. It went 144 MB past an 87 MB bound on a writer holding nothing (CI, 0.9.0), and it would equally have passed while leaking had a neighbor freed as much in the same window. Both halves are verified red by sabotage (a retained frame, a buffer that grows per frame).VideoExportTestsreads the whole export the same way, off memory the test owns: the headless drives take their frame memory fromOllinAppwhen a test installs one (.frameMemory ExportFrameMemory, package,Sources/: the readback buffer wraps that memory without a copy, page-aligned as Metal asks, and the frame image is built over a copy of its own, each handed back through a release callback; a normal run installs nothing and the image copy path is the same one either way), so the invariant is that no piece outlives its frame by more than the beat Metal takes to let a readback go (measured in hand-outs, two per frame: a beat's lag is two, a held frame the whole run; a byte bound of one readback plus one image read that beat as a hold on the runner, 2026-09-22) and every piece comes home, over a 120-frame GIF and a 60-frame video at 480², with a 200 MB hog allocating and touching its pages beside the export in the same process to show the number is not the process's; the count of pieces handed out is checked too, so a drive that stopped asking the ledger could not pass by never being counted; verified red by a planted retained readback. The table:Ollin/ Export/ FrameMemory .swift .shared(default) is a median cut over 6-bit bins of the first frame, written as the global table sized to its colors (a 60-color frame gets 64 entries and 6-bit codes, which is where the system writer's smaller files came from; the transparent index is the last entry). A box whose bins sit within 3 levels RMS of its mean is not split and entries within 6 levels of each other are merged after the cut (a median split parts a dominant bin from its dithered neighbors first, and the present pass dithers, so without the merge a flat sky flips between two entries a level apart: the garden figure's first frame went 9157 to 4952 B). Colors that arrive later join the table in place: a frame has left its table when its mapped pixels' squared error spread over the whole frame exceeds max(8, 2× the training RMS) (a fade-in) OR at least 8 moved pixels average over max(12, 3× training) (a pale tree of 18 pixels a frame growing over dark soil, which is almost no energy over the frame; the strip a moving shape uncovers reads 10-15 over its pixels against a training of 6.5 and stays under both bars); then the frame's colors farther than 8 levels from every entry are written into the global table's free entries on disk (seek, never touching an entry a written frame points at), a table with no room left is grown to the next size that holds them by one streamed copy of the file so far behind a wider head (a written frame keeps its narrower codes and its own transparent index, both valid under the wider table;moreNewColorsThanFitGrowTheTable), and only past 255 colors in all does the frame, and every frame after it, carry a local table..perFramechooses per frame. Diffing: unchanged source pixels take the transparent index under disposal 1 and the frame is cropped to the changed box, a no-change frame is one transparent pixel keeping its delay; a picture whose first frame carries alpha with a clear pixel is written whole with disposal 2 every frame (a pixel can clear again), the cut at half coverage with the color un-premultiplied, decided once from the first frame.loopscounts plays as ImageIO reports them (0 forever, 1 no loop block, n stored as n-1). The LZW coder (codes from the table's width plus one to 12 bits, a clear when the dictionary fills, an 8192-slot open-addressing dictionary) is byte-identical to ImageIO's on the same index image (the system's own decoded first frame re-coded lands on its byte count). Measured against the system writer on the same frames: 12% smaller on a drawn-like piece (5500 against 6226 B), within 5% on a full-gamut plane where every pixel is its own color (the first frame's tiling, at a lower error, 2.56 against 2.63 levels), every sub-frame on the same rectangle within a few bytes, every frame decoding within 1.25× the system's error; on the Guide's garden (83 frames at 420², a cream tree and lichen arriving over dark soil) 63.7 against 67.0 KB with no local table and no pixel past 32 levels from the system's file. The crops run a pixel wider than the system's, which diffs after quantizing where this diffs the source.GIFWriterTests(15) +GIFMemoryTests(2) + the export peak test;Docs/§ Animated GIF; Guide Ch 45 § Motion: video and GIF); perfect-loop export (Output/ Export .md --export-loop+ the declaredSketch.loopDuration— renders exactly one period as a seamless GIF or video by extension; the GIF lap is computed against the centisecond-quantized rateexportGIFwill actually play, or the frame count drifts off one period; exampleMotion/PerfectLoop, seam-verified byte-identical one period apart); vector SVG export (--export-svg— a CPU-only serializer, curved SDF shapes traced via marching squares, a cell whose two crossings disagree in normal bent through the corner where their tangent lines meet, so a sharp corner is not chamfered by the cell's diagonal,SDFOutlineTests; the opt-in--hatch/Hatchingfill-to-line-work transform for pen plotters, every fill on one shared lattice of half-steps so neighbors line up, or withcentersLinesthe nearest whole count of lines across each shape's own extent, half a step in at each side, counted rather than stepped so rounding never drops the last line,SVGExportTests); the vector record holds what the canvas shows (Drawerand its.svgRecord( _: fill: stroke: as: ) VectorKind,SVGCommand,Export/; the statements and their plants are under Export invariants): a path with an open contour is written as its fill over the closed contours alone and then its stroke, and a clip takes its region from closed contours, an empty region dropping its content for every writer (VectorField .swift withoutEmptyClips: readers disagree about a clip path with nothing in it); abackgroundwipes the recorder (SVGRecorder.wipekeeps the clips still open and reaches the canvas's recorder from inside an overlay block), and inside a layer's block it wipes that layer's record alone; a layer's drawing is held aside (Drawer.vectorLayers) and adrawImageof the layer records a placeholder (SVGCommand.layer) thatresolvedLayersfills in once the frame's draw has ended, so it holds what the frame drew into the layer before the call or after it, placed, cut to the rectangle it was drawn into, over the layer's own ground, and as a group (groupPush: an isolated<g>with its opacity and blend, a transparency layer in the PDF) when it is see-through or blended; a filter's or a combine's result resolves to the layer it was made from and says so once, a feedback layer to this frame's drawing, and a generated pattern, a simulation field, an accumulator, and a carrier are skipped as images are; every built-in shape's record says what it is (as: .regionor.mark): underhollowit is written as the band (the outline stroked at the band's width with round joins throughShape.stroked, a circle's the ring between two circles), inside a combine block it is a leaf of the block's field, and its outline takes a round join and one width (the canvas's band is round at its outer corners whateverstrokeJoinsays, and a profile leaves it alone); a merged field is traced (recordVectorField): a block's shapes arrive as outlines (SDF.Node.outline), the field is the node programSDF.flattenwrites for the shader, run on the CPU op for op with a leaf's distance read from its outline, andSDFOutlinewalks it by halving blocks of cells while the outline can still be inside, in cells 1.5 canvas points across whatever the transform's scale; a shape farther from a point than the field's joints reach is read as its distance to its box (.trace( lo: hi: cell: steepness: ) VectorField.far; a field with a morph reads every leaf exactly), and a cell the field crosses flat is not searched for a corner, which took sixty unioned circles from 105 s to 4.7 s in a debug build with the same outline (2026-12-02); a blend mode ridesSVGStyle.blend(mix-blend-mode,plus-lighterfor.add; a PDF has multiply, screen, lighten, and darken), and a mode a format lacks is written plain and named (droppedBlends: a comment in the SVG, a line on stdout for the PDF); the SVG's root carries the canvas's miter limit and the PDF sets it (vectorMiterLimit, 8), numbers keep six significant digits, a stepped ramp's color is written at both ends of its band, a polygon is hatched by the nonzero rule its fill uses, and a line of no length is dropped before it is recorded; a paper canvas (CanvasSize.isPage: the presets are.pageat one pixel per point, so.a4is not.size(595, 842)) writes its SVG size in points and a pixel canvas in pixels; vector PDF export (--export-pdf/OllinApp.pdf/exportPDF— replays the same recorded commands (OllinApp, the shared front half) through a Core Graphics PDF context, so the SVG and PDF of a frame can't drift; hatching and.recordVectorFrame --frameapply, both vector flags may be passed in one invocation; 1 canvas px = 1 PDF pt, so the paperCanvasSizepresets (.usLetter/.usLegal/.a3/.a4/.a5, points-sized, portrait like the sheet) export true-to-size pages, and.dpi(300)scales the pixel grid for print-res raster while the.pagecase carries the point size so the PDF page stays the physical sheet;PDFExportTestspins structure + rasterized-pixel probes); print-separation export (--export-separations/OllinApp— one grayscale master per declared.exportSeparations printInksink + a registration-marked overprint preview; the machinery and invariants live in the Geometry & color bullet); reproducibility metadata — every PNG / SVG / PDF / video export embeds a one-line JSON recipe (ExportMetadata: the recorded seed(s),@Paramvalues, working-dir git hash +-dirty, frame/fps) — PNGDescriptiontext chunk, SVG comment, PDF Subject, video description item; GIF has no slot; the video writer defersstartWritingto the first rendered frame so the recipe can carry the seedsetup()applies (writer metadata is immutable once writing starts); seeds are recorded at init fromvariationand re-recorded byrandomSeed/noiseSeed(Sketch/.recordedRandomSeed recordedNoiseSeed;ExportMetadataTests); the recipe names both commits ("git"the sketch package's,"ollin"the framework's, each-dirtywhen its tree is, each absent where its repository cannot be read): the framework's is read in the directory this source was compiled from (#filePath), the checkout a path dependency points at or the package checkout SwiftPM made, since a sketch that depends on the framework by path changes its frame with no change of its own."ollin"is the commit the binary was built from, which is not always where the checkout stands (Export/): a host left open across a pull, an example's product from last week, a runner kept to compare against used to name the later commit with nothing to say so. No clock names the right one (a commit is usually made after the build it describes, and a pulled one can be older than a build it was never part of), so the reader goes by what the build system goes by, which sources were written after the binary was linked (the date on the image the framework is linked into,FrameworkCommit .swift #dsohandle), and by where the checkout's own log places it at that moment. None newer: the checkout's commit, as before. Some newer: the log's commit when everything that differs between it and the files was written since; a build committed afterwards names that commit (the files' dates walk back to the last commit the binary saw); a build with changes no commit holds says-dirtyunder the commit the checkout stood at."ollinCheckout"rides beside it only when it is another answer.-dirtyand "newer" are read over what reaches a binary (Sources/,External/,Package.swift), so an edited page marks nothing.FrameworkCommitTests(12, each on a scratch repository whose commits, file dates, and log carry chosen times: moved on, committed afterwards, pulled, moved back, two commits on one file, a file removed, no log); what stays inexact is inDESIGN-NOTES.md§ New output surfaces; parameter values on the command line (--param name=value, repeatable,Core/) — the way back in the recipe opens, on every export path and on the windowed one. The text is read against the parameter's current stored kind (number / bool / menu choice / color / vector / rect / insets / range / text / swatch strip), a menu choice matched loosely against the control's own labels (ParamOverride .swift easeOut=ease-out= "Ease Out", which is what lets one rule serve bothParamOptionandParamChoiceswithout the erased type), a swatch list spread evenly unless a stop names its place (#000@0), and aRampkeeps the space it mixes in (only the colors move). Applied before the canvas is sized (Sketch, which every headless drive,.canvasSizeForRun( ) OllinApp.run, andSketchRunner.initread), beforesetup(), and again after it, before the first frame throughAnyParam.restore, so acanvasSizethat reads a parameter takes the run's size (a sketch rendering once per aspect sized itself from an environment variable until 2026-09-23) and whatsetup()builds from a parameter reads the run's value (an extension registered behind a switch never saw the flag until 2026-09-22), it clamps like the row, wins over a value the sketch's ownsetup()set, and reaches the recipe (captured once the sketch has run). The seam isSketch.runSetup(), which every headless drive calls instead ofsetup(); the windowed path applies it once at launch (SketchRunner, after a restored checkpoint) so a reload keeps what the inspector has since turned. Nothing is skipped in silence: an unknown name or an unreadable value stops the run and lists what the sketch has. The sweep's parameter flag moved to.applyLaunchParams --sweep-param(--paramsets a value on every tile alike, so naming one parameter both ways stops the run rather than flattening the sheet).ParamOverrideTests(17; the after-setup()order, the before-setup()pass on the drive and on the window path, and the drive seam);Docs/, Guide Ch 45 § Passing the parameters back in.Output/ Export .md#setting-a-parameter-for-the-run --capture-source(Export/) turns thatCaptureSource .swift -dirtydead end into something checkoutable — the working tree is written into the repo as a commit on no branch, every written path is renamed after it (out.png→out-93ae989.png, a sequence directory too), and the recipe gains acapturefield. Load-bearing: nothing the user owns moves — the tree is staged into a throwawayGIT_INDEX_FILE(a copy of the live index, so the stat cache holds and only changed files are re-read; rebuilding fromread-tree HEADre-hashes everything), so index / worktree /HEAD/ branches are byte-identical after (theCaptureLeavesTheRepositoryAlone, verified red by dropping the temp index);git add --allis what pulls in untracked files while honoring.gitignore(git stash createcannot, which is why it isn't used); the commit is anchored atrefs/orollin/ captures/ <tree sha> git gccollects it (verified red by dropping theupdate-ref), and keying the ref on the tree is also the dedupe — the same source re-exports to the same capture id; identity is forced viaGIT_AUTHOR_*env so it never needs a configured user and never signs a person's name; resolved once per process at flag-parse time (before the export branches read their paths), so a 600-frame sequence hashes the tree once; clean tree → the id isHEADand no commit is written.CaptureSourceTests(14, pure git + Foundation, no GPU);Docs/; Guide Ch 45 § The recipe in the file. The whole export/bench flag surface lives inOutput/ Export .md#captures-that-know-their-source OllinApp(.handleCommandLine( _: makeSketch: ) Sketch.main()routes through it, andOllinLiveruns it on a loose watched sketch file —swift run OllinLive Sketch— compiling the file only when a flag matches, so any Guide-style sketch exports without needing a target); the.swift --export-gif … extend(...)SketchExtensionseam (setup / beforeDraw / afterDraw / afterFrame / frameRendered, opt-inwantsRenderedFrame/wantsRenderedTexture;afterFramefires on the headless drives too, once per rendered frame (a settle draw included, a warmup frame only when it renders) with the export clock's rate and step and the frame's own unsmoothed times, the renderer timing its headless encode, GPU run and wait throughcommitHeadlessand the drive handing them over throughOllinApp, since.reportHeadlessFrame FrameInfo.profilewas unreachable from an export until 2026-09-22 (HeadlessFrameReportTests); the pixel hooks read the on-screen frame, never a second render: the runner asks every extension once before the frame is drawn and hands the renderer aFrameGrabRequest, the renderer tone-maps the finished picture once more into a canvas-sized display texture inside the frame's own command buffer (a larger picture minified through a mip chain, the same size byte-identical to the headless render), blits it to a shared buffer when an image is wanted, and delivers from the completed handler on the main run loop in every common mode (a main-queue block cannot run while another spins the loop, a run-loop block can), in frame order; textures and buffers come from a pool a delivery returns to, so nothing is written while a consumer reads it; a frame being handed out is drawn no smaller than the canvas, an accumulating pile keeps its size and is brought to the canvas size on the way out, and the ground grid leaves the window while a hook is armed; a frame nobody asks for pays nothing. Measured: the lit scene explorer records at its unarmed rate (45.7 against 46 fps at 1080²), where the re-render took it to 19;FrameGrabTestspins the pass count, the byte-identity, the size floor, the minification, the pile, the order, and the grid gate, the floor and the gate verified red by sabotage); live reload (swift run OllinLive, the typed@Paraminspector controls (aPaletteis a strip of blocks and aRampa band with a draggable handle per stop, both one.swatchescontrol kind persisted as.colors(; the band is sampled from the value so it is the blend the sketch draws; a stop stops at its neighbors;stops: space: ) Easingsits on theParamChoicesmenu tier because a built-in curve carries its name as its identity; a number box's text belongs to the typist until Return, Tab, or a click away commits it, clamped (ParamNumberEditinLive/: nothing the row clamps or snaps is written back while typing, which is what turned a first "2" over 10...375 into "10.00" and "300" over 50...500 into 500; a partial previews on the canvas only inside the range, and in a min/max pair only while it keeps the order, an end committed past the other pushing it along; Escape puts back the value from before the first key); a box reads the value's own digits with the trailing zeros taken off, no grouping mark, six significant figures for a value from outside (ParamNumberField .swift ParamNumberText), and a commit never re-reads that text; every drag (slider, scrub, pad, two-thumb track) lands on the power of ten under one point of travel (.display ParamNumberText, an end kept exact), so what it leaves, and what Save writes, has the digits a person would type;.dragged ParamNumberBoxTeststypes through the field editor into a real box, red on the old binding with 11 issues) (+ show-rules:$parameterset in.show( when: $other) { ... } setup()hides a row while its source keeps it inert, polled on the rows' 100ms sync cadence; a fully hidden group drops its card; hiding is display-only, so the value still persists/restores and OSC/MIDI keep driving it;AnyParam.isShown/ParamHandle.isShown, the section split testable viaParametersListView; folded groups:.visibleSections group:takes aParamGroup(ExpressibleByStringLiteral, so the plain spelling holds) andgroup:renders that section as a disclosure card that starts closed — one folded member folds the whole group, the default (unnamed) group never folds, folding is display-only like hiding, and the open/closed state is remembered per sketch (.folded( "…") ParamFoldMemory, keyed on the name each host's monitor card shows, passed asParametersListView(; an untouched group writes no key, so it keeps its declared start); gates:sketchName: ) ParamTests+OllinLive --paramtest), the sharedFrameStats); the sketch dylib compiles optimized (-O) in every host (SketchLoader,.Optimization .speedby default;--no-optimizeon OllinLive / OllinLiveCoding / OllinRun compiles it plain, for debugging: asserts fire, a crash names every frame), becauseswiftcdefaults to-Ononeand a CPU-heavy sketch ran several times slower under the live window than in release (issue #17; measured under a release host on 50k points moved by six octaves of noise a frame: 35 ms optimized against 80 ms plain with the framework's noise, 52 ms against 1,170 ms with noise written in the sketch);OllinLive --selftestpins that both compiles render the same pixels; and as one whole-module job (-wmo): the driver otherwise runs one frontend per source (the sketch and the factory shim), each loading the framework's module, which was most of a small sketch's compile — measured on the loader's own line, a 20-line sketch went from 1.00 s to 0.57 s plain and 0.95 s to 0.61 s optimized, a 470-line one from 0.96 to 0.74 and 1.48 to 1.09 (SketchCompileArgumentsTestspins the flag); the live-coding performance host (swift run OllinLiveCoding— evaluate-on-command over the same engine; see the Live coding block under § Live reload below,Docs/); the examples gallery (Tools/ LiveCoding .md swift run OllinExamples;Scripts/is the release-by-default wrapper,OllinExamples --debugopts out — the sketches run on the host's build configuration, and under a debug host a heavy example'ssetup()+ first frame stall the whole app on the main thread (worst of a 40-example sweep: ~2.6s debug vs ~0.2s release; a few asset-decoding examples keep ~1–1.6s either way; the sketch dylib compiles optimized here too since issue #17, which does nothing for that stall (framework code) and costs a first-visit compile about half a second on a 479-line example, paid back within the first second of any example that does its own CPU work per frame)) — a two-sidebar host on the OllinLive window recipe (fixedHStack+.contentSize+ unified gradient toolbar + title-bar accessory toggles, the chrome shared via the coreWindowChrome.swift): left, the example list as one navigator-idiom outline (ExampleCatalog.treeflattened over the persisted disclosure set; folder rows carry a per-category SF Symbol fromcategoryIcons— unknown categories fall back tofolder— plus a trailing count; bottom filter bar, ⌘F focuses it, Esc clears, Return runs the first match) — every row is selectable, folders included, so ↑/↓ sweep the whole tree, ←/→ close/open a folder and step out/in, ↩ toggles a folder or relaunches the running example (the fold arrows and ↩ are handled throughonKeyPress, neveronMoveCommand— the focused list's table view consumes arrow keys before any move command fires, soonMoveCommandleft/right is dead here;.ignoredlets ↑/↓ through to the list); the stage followsrunning, not the row selection (parking on a folder never blanks the canvas), the running example marked in accent purple with level bars while the selection capsule stays the system accent; the canvas takes keyboard focus only on click (SketchView(, a glass "click the sketch to use the keyboard" hint floated only for sketches whose source reads keys,keyboardFocus: .onClick) Example); the stage is a fixed square and the loaded sketch aspect-fits into it (letterboxed on black, never scaled up — SwiftUI doesn't clip an oversized frame, so a non-square canvas used to paint over both sidebars and swallow their clicks, each click taking the keyboard with it); a fresh instance is covered by a "Starting…" card until its first frame renders (its.usesKeyboard setup()runs on the main thread inside the first canvas draw, so a heavy one used to leave the stage black for seconds with no word; a per-instanceFirstFrameSignalextension clears the cover, so a stale frame from the outgoing sketch can't drop it early); the list holds keyboard focus explicitly (a@FocusStatere-planted whenever a fresh example lands on the stage, on a folder row's button toggle, and on the filter's Return — an example switch tears the outgoing canvas down, and a canvas that held the keys can only clear the first responder, so arrow keys used to die after one switch); right, the hidable inspector (⌘/, the sharedMonitorCardView+@Paramparameters — so the gallery omitsOllinHUDCommands/the detached panel). Two leak invariants are load-bearing (both broke for real): the compile cache holds dylib paths, never liveSketchinstances — a switch instantiates fresh viaSketchLoaderand the release of the outgoing instance is what stops its audio/capture/players — and the gallery's mutable state lives in the.instantiate @ObservableGalleryModelclass, never spread view-struct@State, because escaping closures stored in lazily cachedListrows capture whole view values and a view value carrying the stage inline pins outgoing sketches (sound bleeding between examples, resources piling toward a crash; found by--cycletest, traced withleaks --trace). Gated by the windowed harnessswift run OllinExamples --cycletest [n](spread over the catalog, or--cycle-filter a,b+--cycle-holdfor pinning one down), which walks the real selection path and fails if any outgoing instance stays alive;--self-shot <png>writes a window self-capture (cacheDisplay, so no screen-recording TCC; the Metal canvas comes out blank by design).Examples/3Dis grouped into topic subfolders (Camera/Depth/Effects/Environments/Geometry/Lighting/Materials/Phone/Raymarching), targets renamed to match (Example-3D-<Group>-<Name>); render-correctness snapshot tests (Tests/OllinTests— re-record all viaOLLIN_RECORD_SNAPSHOTS=1, or scoped: set the variable to a case-name substring (or several, comma-separated) and only matching snapshots record while the rest still compare, so one new reference no longer rewrites the other 241;0/empty means compare, the variable's value decides, never its mere presence; recording writes the source tree while comparison reads the built bundle, so the nextswift testis what verifies a fresh recording; a failing case writes actual + reference + an 8× diff into$TMPDIR/); CI. The AVFoundation link lives in the core for offline export only.ollin-snapshot-failures/ Docs/,Output/ Export .md Docs/Core/Canvas.md,Docs/. EveryHelpers/ Parameters .md OllinApp.export…call throwsExportError(kindunsupported/unrendered/unwritable, thepath, the writtenframereached, the sentence) and never stops the process: the video, GIF, and spatial-video writers remove a clip stopped partway and reset the soundtrack state, zero frames isunsupported,exportHEICandexportWidgetthrow too (the widget run on a run that drew no picture), the calls that hand back a picture throw it too (image(of:), the fourcontactSheet(of:)forms,plates(of:),separations(of:), each non-Optional, thepathempty; one throwingheadlessRenderer(carries the renderer's own message, where it used to answerfor: path: ) niland print;ExportErrorTeststhrough the package.aRendererThatWillNotStartStopsEveryHeadlessCallTheSameWay OllinApp), and.plantedRendererRefusal handleCommandLineis the one place a failure becomes a printed sentence and exit status 1.OllinApp(package) makes the encoder refuse a named frame for a test (.plantedVideoRefusal ExportErrorTests). A frame the GPU throws away never reaches a file:commitHeadlessreturns whether the buffer ran and leaves the sentence onlastHeadlessFailure(a headless failure is never printed as the only sign; the live path'sGPUFailures.checkstill notes its own),renderedFramedraws a frame again up toheadlessRedraws(2) times whencanRedraw(nonoClearpile, no persistent layer, no compute dispatch, no subframe moment, any of which the discarded buffer may have half-written), forgetting the TAA, traced-reflection, caustics, and path-trace histories and the same-frame stamp first so the redraw neither blends with nor serves the discarded encode; otherwise it countsunrecoveredFailures, which only grows, and every export drive throws.unrenderedwith the GPU's reason at the next frame it writes (throwIfFailed(, so a warmup or settle draw that failed stops it too).since: ) OllinApp(package) drops named headless commits unrun for a test;.plantedDiscards ExportErrorTestspins the redraw byte for byte and both throws, each red under its plant.copyFrame()puts the next frame the window shows on the clipboard as a PNG through the frame-grab hook (a one-shotFrameCopierextension armed per call, so the grab's own rules hold: canvas size, no second render, no host chrome); a still sketch draws one frame for it throughredraw(), and with no window nothing is armed (SketchConvenienceTests, read off a named pasteboard, never the person's). The window survives a GPU hang (MetalRenderer,.replaceSpentQueue GPUFailures): a frame the system blames for a hang (its code 3) or refuses for prior errors (4) marks the queue spent from the completed handler, the next live frame takes a new queue from the same device (textures and pipelines are not bound to a queue, so nothing is rebuilt), drops the layer readbacks the refused frames owed, and hands the runner a sentence the stats card shows (.queueIsSpent FrameStats); a victim of another process's reset (5) replaces nothing, and the headless path keeps its own answer (draw again or throw). Measured: a process that hung on a point-light figure went on rendering hundreds of figures on fresh queues, while the window on the spent queue showed its last frame for good..gpuNotice GPUHangRecoveryTestsrecovers from a planted hang on the live path (plantedLiveHang); its real-hang case runs only underOLLIN_REAL_HANG=1on a quiet machine, since a reset makes every other process drawing a victim. A failed frame names its pass (GPUFailures,.passReport MetalRenderer): a command buffer made with.makeCommandBuffer( reportingPasses: ) errorOptions =hands back each pass's outcome with its error, and the failure's sentence ends with the pass that failed, by its label and its place in the frame (.encoderExecutionStatus "canvas (), or with the passes that were running when the system names none (it hedges the same way, since a fault in one process reaches passes in others). A drive that waits for its frame always asks; the live window asks once a frame of its own has failed (headless)" ( 3 of 4) GPUFailures), so a healthy window's frames keep no record and name no pass. A pass is named where it is made (.hasFailed countedEncoder's caller, andnamedComputeEncoder/namedBlitEncoder/namedStructureEncodertaking#function), and only on a reporting command buffer, since the label is read only out of a failure.GPUPassReportTests(9: the sentences are built from records made in the test, so nothing has to fail on the GPU). The frame loop holds for sleep (OllinMTKView): the will-sleep notice pauses the view and the wake releases only a hold of the loop's own, so no frame is committed as the GPU powers down (.holdForSleep ScreenWakeTests). Every headless drive enters and leaves throughOllinApp.DriveMode(the three drive flags as one value, entered with the drive's own mode and restored to what it found; nothing else writes them), so a sketch that renders a second sketch from its ownsetup()keeps its export mode. What each satellite does with the mode is still read at 37 sites in 26 files, counted 2026-11-28.Physical invariants (
Tests/,OllinTests/ LightingInvariantTests .swift FrameInvariantTests,.swift ColorScienceInvariantTests,.swift Tests/; the 2026-10-06 triage of the physically based tiers, 36 tests with the color-vision review's three, 19 more from the 2026-10-09 survey of the photoreal tier, and three from the 2026-10-16 review of the lit surface's energy split). Each pins a statement that holds whatever the implementation and reads it off a render, an image, or rendered samples against a twin or an analytic value, never against the code's own arithmetic, so a plausible-looking defect (the class a snapshot cannot see) turns one red: a lossless surface returns the furnace's constant field (a white diffuse sphere, a clear coat, sheen, a thin film over a perfect mirror at four thicknesses, a clear glass ball, each bounded both sides, and the diffuse disc flat out to its rim), the environment is linear in its intensity, a shadow never adds light (the map and the traced point caster), black walls bounce nothing and bounce never outshines the pool it came from, a caustic never takes light, a lens gives back what its shadow took less what its glass reflects (0.78 to 0.92 of it, under a sun, a lamp, and a lamp with a reach), and dispersion keeps its total, fog follows Beer-Lambert and stays between the surface and its own color, a beam never darkens, a tone curve is monotone, bounded, neutral, and the one its name promises, the dither is unbiased, the jittered average conserves the frame's light within 1% (one unjittered frame misses half a percent of a highlight it samples at pixel centers alone), a streak never outshines its source, keeps the mover's light within 1% at shutters 0.5 and 1, and stays within 2% of the box's value of the subframe export region by region, a proof never widens the gamut and keeps a gray neutral, a dichromat's simulation is a projection (simulating twice is simulating once wherever the result stays in range, the two cones the viewer has respond to a color and its simulation alike, each kind's halves meet on their separator and nothing crosses it, the transforms match the published worked values) and a partial severity never overshoots its end, a plucked string and a struck body only ever lose energy, a driven body stays bounded at any drive, a mirrored place swaps the ears, and placing never amplifies. The survey's: a white dielectric returns the field from every side (a plate head on, at 60 degrees, and at grazing, through both ambient pipelines, and in the trace, whose surface function is the lamps' own), an anti-reflection coating never brightens its glass and dips to the quarter-wave value at its design thickness, a disk light falls off as its closed-form form factor, a spot's shadow meets its caster's base, the bounce on a ceiling the lamp never reaches matches a 64-deep path trace of the room (the light room's bounce against the dark room's within 6% of the trace's own ratio, each inside the grid's 0.85 to 1.3 envelope, for the standard and the physically based finish), a rough copper floor throws copper onto the ceiling by what the trace throws and a fifth of what a matte copper would, the traced furnace holds with the environment importance-sampled, an environment's sun reaches the scene, the frame is linear in its light under aerial perspective (a lamp's, and a sky's when its intensity doubles), a clearer sky casts harder light (the procedural sky's own sun against the model, facing-to-away and sun-to-shadow), the far air is the sky's horizon, a floor gathers the whole sky, an emitter lights its neighbors under global illumination as the trace does, a lamp bounces nothing from past its reach, a panel's shadow is the light-weighted share it blocks, a shadow ignores where the camera aims, a lamp lights nothing past its reach in the window and the trace, an index-matched pane changes nothing in the trace (and a block does not at roughness 0.08), still 2D passes through the live resolve (read off the live loop: one renderer, one drawable, 64 refreshes), a sprayed dot keeps its light at any count and focus and wherever it falls on a pixel, a flat aperture blurs to the thin lens's circle, and a lens coating reflects what the exact single-layer film does. Load-bearing: every invariant that holds (35 of the first 36, and every statement the survey enforces, under ten plants of their own) was verified red under a planted defect of its own (a shader or source edit, restored after; a plant that misses the path a probe runs reads green, which is how two bounce plants had to move from the environment ambient to the lit path, and the spatializer's centered pan sits at 0.6 of the dry stream per ear, so a placed stream must be doubled beforeOllinAudioTests/ SoundInvariantTests .swift placingNeverAmplifiesreads; deleting the probe field's recursion read green at albedo 0.5, where an open room's higher bounces fit inside the bound, so that plant drops the hit's albedo), and a pin records its gap by construction; a probe that reads a path trace or the probe field gates onSnapshotas well as.hasRaytracing hasMetal, since a runner without ray tracing has neither; a furnace probe reads the disc against the backdrop so the auto-exposure cancels; a statement about an 8-bit read is judged by row or by block, since the present dithers one level into every pixel and at a mid gray one level moves a pixel's squared transmittance by 0.02; and a probe that measures light brighter than white tone-maps with Reinhard and unrolls it on readback (renderUnrolled), since a clipped read had shown a caustic's excess as 1.08 where the whole of it is 1.5. Measured gaps stand aswithKnownIssuepins, failing the day it closes (Swift Testing fails a test whose known issue stops occurring, so a fix must take the pin off; the caustic's, a deposit of 1.5 times its shadow, the motion blur's, a gain of 5% of a 24 px mover's light at the default shutter and 25% at a full one, and the color-vision table's, not a projection (a blue moved 0.064 on a second pass) with a tritan dial that overshot its end, came off that way): the generic CMYK profile does not round-trip (4 to 11 levels on a second proof, yellow the worst). That gap is the system profile's own, since the proof is the system's transform. The survey's pins (2026-10-09, each filed under Photorealistic 3D inDESIGN-NOTES.md, measured, never predicted; the probe field's two, emission and the light room, came off 2026-10-12, the sky's two, its sun with no beam and the aerial veil no light scaled, on 2026-10-14, and the environment's diffuse weight, a panel's unweighted shadow, and the tracer brightening a ball behind a pane of index 1 on 2026-10-16, two more joining them that day, and the sprayed dot in focus on 2026-10-17): the trace running hot in a lit room (its continuation reads the room blurred to the footprint while the environment's own draw reads it sharp, so a lamp's blurred skirt is counted beside its sharp core: a matte ball 0.475 where the window reads 0.384 and a continuation-only trace 0.372), light behind a solid counted twice in the trace (a block of index 1 brightens the ball behind it 8% at roughness 0.5), the live resolve softening still 2D (a hairline reads 85, 219, and 111), and the flare's two-beam coating (0.0086 against the exact 0.0043 head on into 1.67 glass). Survey B (2026-10-11, the sound, the color science, and the solvers): 35 more acrossSoundInvariantTests(16),ColorScienceInvariantTests(3),FrameInvariantTests(6), andTests/(10, new), each read off rendered samples, a file, or a body's own motion. What holds, each red under a plant of its own (twelve plants: the string's tuning allpass dropped, a shape's mode ratios scaled, the delay's neutral mix off by a percent, the strike's push ten times taller, the reed's closing pressure doubled, the driven loops' period stretched by 0.4%, the gamut's cusp chroma scaled by 0.97, the HDR metadata insertion mode dropped, gravity scaled in both bridges, the 2D body damping raised, the restitution scaled in both bridges and on the 3D ground): a plucked string sounds its note within a cent from MIDI 33 to 93 and a bowed or blown one within five cents from 45 to 93 at pressure 0.8, a struck disc rings at a circular membrane's Bessel ratios within 1%, every struck preset is a sum of tones with nothing on the renderer's ceiling and the bell's foreign lines over 50 dB under its prime, a softer strike is darker and never louder and as loud at 48 kHz as at 44.1, an instrument inside a struct in an array, a dictionary, or an object of the sketch's own reaches the export and is advanced, a note asked for on frame 0 or frame 10 starts on that frame's first sample, a hearing range changed at frame 30 is heard from that frame with the earlier note untouched, an unplaced sound plays at the never-placed level in both ears and pans again when placed again, every tube speaks from pressure 0.3 at every pitch, the delay, the room, the equalizer, and the convolution at their neutral settings pass the sound to the byte, the gamut map keeps hue within a ten thousandth of a turn and lands inside the gamut within 0.006 chroma of the true boundary, a free body falls half g t squared within 1% in both worlds, a body in either world coasts at zero drag, drag is one reading in both worlds and at every frame rate (a particle at 0.01 keeps the same share at 30, 60, and 120 Hz and a rigid body the same share as the particle), a hinged bar returns to the pivot's height within 5% for ten seconds in both worlds (the 2D one within 0.1% at one piece a frame, the 3D one at sixteen) and a Verlet bob on a rod does at sixty-four, a ball at restitution 1 returns to its drop within 5% in both worlds and one at 0 does not bounce off a default floor, a body that named a bounce keeps it when the world's changes and one that named none follows, a world's drag reaches its bodies when changed and never a kinematic one, a settled box rises when gravity is turned upward in both worlds, a spin reads back as set at a 1/60 and a 1/30 step, and the HDR export declares its mastering display (a 1000 cd/m² peak on P3 primaries) and its content light level (MaxCLL 1000, MaxFALL 400) in the track, with the PQ codes of a gray within 0.004 of the standard's; and since 2026-10-17 a black pixel separates to black alone, an absolute proof of white shows the stock and the simulated paper is its profile's media white, the dither is unbiased at every alpha and a see-through file keeps its levels, an eight-bit file of a wide frame is dithered, the wide PNG keeps sixteen bits and the HEIC ten, and the gain map rebuilds a highlight's edge within 5%. The survey's pins (each filed under Sound, synthesis, and spatial audio inOllinPhysicsTests/ PhysicsInvariantTests .swift DESIGN-NOTES.md; the eight physics pins came off on 2026-10-14, the seven color-file and print pins on 2026-10-17): the clarinet and reedy tubes at MIDI 93 sound a weak fundamental under their twelfth (the sound's other eight came off on 2026-10-16).Drawing invariants (
Tests/, the 2026-10-25 survey of the 2D drawing paths and the recorded page, with the disk's and the stroke's statements rewritten on 2026-11-12 when both were fixed and the outline's on 2026-11-30: 50 tests, most run over several sizes, angles, or positions, each a statement that holds whatever the implementation, read off a render against an analytic value or a twin render). The statements, by path. The analytic disk: a disk's ink is its area within 3% from 0.2 to 3 px at each of a hundred places on the pixel grid (read in linear light before the present pass, since a handful of pixels at one 8-bit level each would be most of the reading), the hundred agree within 2%, a dot under a pixel moves with its center (the ink's center within 0.08 px of the dot's), it keeps its ink under a scale, a turn, an uneven stretch, and a canvas zoomed out eight times, and stays a pixel wide under the stretch; an ellipse lays its area at any turn, down to one thinner than a pixel; a disk far larger than the canvas ends where the circle does (within 0.02 px down every column); a particle drawn as a mark, as a quad and as a point, and one drawn as light lay their area; and a disk in a layer two and four times coarser than the canvas lays its area on the layer's texels. The region fills: two half-rectangles are one rectangle to the byte and a grid of tiles at a fractional pitch is one solid away from the seams' ends, and two colors meeting at a fractional edge show no paper between them. The stroke band: an outline's ink is its length times its width from 0.3 to 4 px, a thin outline is as dark on the diagonals as on the axes (its darkest pixel there at least 0.9 of the axes', where a band a pixel wide covers 0.914 of a pixel it crosses on the diagonal), a box's outline turned off the axes is its length times its width from 0.5 to 3 px, a small stroked circle lays the area of its ring within 3% from 0.5 to 4 px across at 0.3 to 2 px of width at each of a hundred places on the pixel grid and the hundred agree within 3%, a shape draws the same whatever else is in its run (within one 8-bit level between two builds of the shape fragment), a long stretch of one kind of shape is cut into a run of its own that asks for what it holds while shapes that alternate stay one run, an outline 0.3 px wide moves with its edge (the ink's center within a tenth of a pixel of it at eleven places across a pixel), a small ellipse's outline holds across the grid (its ink varying under 35% at 2 by 1 px, 10% at 4 by 2, and 4% at 8 by 4, where it varied 91% and 36%), a hollow band is as wide as declared (plus the half-pixel halo each of its edges gets from the fill ramp) and centered on the outline, and a stroke sits where its alignment says (the band's centroid offset by exactly half the weight, an inside stroke never past the edge, an outside one never within it). The fringe strokes: a stroke reads as wide as its weight within 2% at 0, 30, 45, and 90 degrees from 1 to 17.3 px at eight positions across a pixel, a hairline from 0.3 to 0.7 px lays the ink of its width within 5% the same way, a stroke in a layer two and four times coarser than the canvas is as wide as its weight on the layer's texels (the layer drawn back with each texel kept whole), a hatch of 1 px lines reads one tone at 45, 30, and 10 degrees and across the patch, dark on light and light on dark, within 0.4% of full light (the statement that settled the edge), the ribbon's rim hides nothing drawn later behind the stroke under a 3D scene's depth, a turn too tight for the rim keeps one coat, a pixel a translucent stroke covers whole reads as the fill's interior at the same alpha (the perceptual remap touches partial coverage only), a translucent zigzag of a dozen corners at every turn from 30 to 120 degrees under every join is one coat with no hairline inside it, and a cap adds exactly its area (nothing, the weight squared, a disk of the weight). The triangle fills:OllinTests/ DrawingInvariantTests .swift drawRect, the same corners as a polygon, and as a shape differ nowhere but on the edge itself, a holed shape's ink is its outer area less its hole under both winding rules, a polygon's ink is its shoelace area (a convex one through the fan, a concave one through the triangulator), and a concave outline handed todrawPolygonfills the region it encloses and draws whatdrawShapedraws to the pixel, a star drawn in one stroke filled whole. The media: a dry medium is nowhere darker than the plain stroke at full density and lays no more ink in all at a lower one, wet paint is nowhere darker than the plain stroke and oil lays no more in all, a wet wash never lightens its ground, and a wash's darkening is monotone in its water. A retained batch replayed under a translation, a rotation, and a scale draws what the same calls draw (the analytic shapes and the triangles to the byte; a stroke's baked fringe within a mean of 0.02), and a replayed stroke is its weight times the replay's scale. A drawing exported as SVG and read back draws the same pixels within the mean tolerance, and where the two differ by more than 32 levels the pixel is on the edge of a filled shape and nowhere else (0.9% of the frame: a built-in shape's fill and the same outline filled as a polygon anti-alias their edge differently by design, the disk by its perceptual share and a region with its halo outside, where a polygon is multisampled); its outlines alone, a built-in circle's and ellipse's against the same outline read back as a stroked curve, differ nowhere by 32 levels. Atlas text carries the ink of its outline within 3%, a picture drawn at its size on whole pixels is its bytes, and a blend mode is its arithmetic in linear light (add, multiply, screen, lightest, darkest). The page: one scene per door, each at the tolerance its door documents (the primitives, the vertices, the points the page expands, pictures and atlas text, the effects, the fields, the media, a moved control), in one table through the shared browser gate. What held was verified red under a planted defect of its own (twenty-three plants: a centered fill ramp, the band's ink scaled by a tenth, a hollow band at three quarters, a halved alignment bias, a disk's area scaled, a constant disk footprint, the perceptual remap over the whole alpha, a fattened glyph, a squashed replay, a dry ink over one, a wet drag the wrong way, a wash that lightens, a wash that turns back, a multiply with the wrong factor, the fringe's outer edge a half pixel out, the inner crossings refused, a half-length square cap, the fan's vertices scaled, every shape non-zero, the replay's transform dropped, a stretched picture, a circle written a fifth too large, a page a third too bright; and on 2026-11-12, against the rewritten disk and stroke statements, twenty-eight more, twenty-seven red each on its own statement: the disk as a ramp again, its area scale dropped, one floor for both axes, no floor, the two-unit quad, a quad reaching half as far past the edge, the straight-edge form alone, the exact forms alone, a corner read that takes every corner as inside the circle, the walk without its arcs, the rectangle form for every pixel, a small dot's tent at full ink (the disk's and the particle's each), the tent switched off at a pixel with no fade, a particle on the straight edge alone, a particle's square and its quad cut short, and the light particle's ramp; the stroke's far edge ignored, the old ramp along the normal, the column's share in place of the pixel's, the rim not discarded, no rim, a hairline at full coverage, the fringe a canvas pixel in a coarse layer, the crossing tested against the rim, and a ribbon's coverage as a plain ramp. The twenty-eighth, the rim left unclamped along a tight turn's crossing, stays green: what it changes is a sliver under a pixel that no probe here resolves, and the clamp is kept as right by construction; and on 2026-11-30, against the outline's statements, the runs, and the curve's cut, twenty-one more, each red on its own statement: the old two-ramp band, every edge read as a diagonal, no pixel's footprint under a pixel wide, a hairline band at full coverage, a ring with no inner disc, a thin ring at its footprint's full ink, the band at every size with no ring, an ellipse's edge stepped by the distance's screen derivative, the disks' own build drawing a disk 3% larger, a region's outline left out of a build that has one, a run's needs replaced rather than gathered, the outline's bit never set, the head of a cut run handed the stretch's set, a curve cut by its length alone, the degree's constant halved, the length's floor dropped, a smooth run's bend ignored, the drawer's tolerance left unscaled by the transform, a circle cut by its length alone, every polygon taken as convex, and the once-round count dropped. A band's far edge ignored stays green: a band is never under a pixel wide on screen, so a pixel square to it meets one edge at a time, and on a diagonal the plant moves a pixel by under 5% and the ink by 0.6%); the scratch probe that diagnosed the disk showed a 0.3 px disk at every phase once its footprint was held constant, which is the plant that found the cause. What fell is pinned with its measurement and the date (every one awithKnownIssuescoped by a plainifto the cases that fall), and the ranked list of the causes with their fixes is under Rendering and color frontier inDESIGN-NOTES.md. The first two on that list, the analytic disk below a pixel and the fringe stroke under the multisample mask, came off it on 2026-11-12 (their mechanism and what was measured are inARCHITECTURE.md§ The 2D drawing paths). The next two, the stroke band's thin end with its footprint and the curve cut by chord length, came off it on 2026-11-30 (ARCHITECTURE.md, An outline's band and How finely a curve is cut; the round trip's far pixels had been read as the curve's facets alone, and measured by element they were mostly the outlines' edges, 226 and 444 pixels on a stroked ellipse and circle against none now, with the fills' rims left as the design they are). What stays pinned: the overlap of two fills' halos where a seam meets the outer edge (one pixel per seam end, up to 67 levels), and the wash's dry end (the gouache picks the ground up and the glaze does not, so the first quarter of water darkens by 0.5% before the glaze thins). The pixel readers are two, and which one a path promises is part of the invariant: the strokes, the disk, and atlas text remap their coverage to perceptual alpha, so for black over white the display byte's shortfall from white is the geometric coverage; the region fills, hollow bands, and the triangle path composite in linear light with no remap, so their coverage is the shortfall in linear light. A white ground is a clean 255 under the dither (measured), so a paper baseline subtracts to nothing.Effect invariants (
Tests/, the 2026-11-09 survey of the effect chain and the layers, its blend statements rewritten with the fix of 2026-11-10, its size statements with the fix of 2026-11-15, its map and tone statements with the change of the same day, its filter arithmetic with the fixes of 2026-11-26, its layer statements with the fixes of 2026-11-27, and its loop, spectrum, and field statements with the fixes of 2026-11-28, when the readings it had left unmeasured were measured: 103 tests, each a statement that holds whatever the implementation, read in linear light before the present pass, half-float components premultiplied by coverage over a cleared canvas so a layer's own alpha is the frame's, against an analytic value or a twin render). The statements that hold, by family. A layer: a drawing made in a canvas-sized layer and drawn back is the drawing made on the canvas, to the number, over nothing, over a ground, and through a second layer; an empty area of a layer leaves the ground under every blend mode; an opaque layer over an opaque ground under a mode is the mode's arithmetic; a see-through ink under a mode is the mode's arithmetic weighted by the ink's coverage, on nine drawing paths (an analytic shape, a triangle fill, a fringe stroke, a field, a picture, a shader paint on each of the three 2D paths, and a solid), withOllinTests/ EffectInvariantTests .swift .lightestreading the ink over black and.darkestover white, and the canvas left opaque; an ink of no alpha changes nothing under any mode over a ground holding light past white and below black; a surface's alpha is its coverage under every mode (two half-clear marks leave 1 over a ground, 0.75 over nothing under a mode that lightens, and 0 under one that darkens); over nothing a mode that lightens leaves the shape as.normaldraws it and a mode that darkens leaves the ground under the layer untouched; a wash multiplied over a layer tints its picture at every coverage and leaves the bare layer bare; a shape's edge under a mode, anti-aliased or blurred, lies between the ground and the shape and opens no hole; lights added in a layer cover as their marks cover, and the layer added back is the lights added on the canvas; a see-throughbackgroundis the same color drawn; the page blends as the Mac does (0.017 levels mean on a sheet of every mode);compose { }is the same calls written by hand, to the number, and under a transform it draws where the drawing would; a layer starts each frame clear, kept handle or not; a layer opened first shows a layer made after it;backgroundin a layer's block clears that layer, earlier blocks included, and nothing of a second layer drawn inside it; several results made off one layer each match the frame that makes that result alone. A filter: at the setting that asks for none of its effect it returns its input, light past white and see-through pixels included (41 filters to the number,invertat 0,levelsat 0, 1, 1 with its light past white, alumaKeyband that keeps everything,lightLeakat an intensity of 0, and one mirrored tile among them; 16 tone filters within one half-float step, since they take the color out from under its alpha and put it back); a Gaussian or box blur keeps the layer's summed coverage within 0.3%; a Gaussian'sradiusis its standard deviation in pixels and a box of radius r is 2r + 1 wide, on a plain render and on a supersampled one brought back down; a one-color half-clear shape keeps its straight color at every coverage through twelve blurs and warps and the oil paint (premultiplied through the chain, no fringe); a glow never darkens a channel, and a threshold no pixel reaches leaves the frame; an exposure up then down and a channel swap done twice are the picture;mirrorkeeps one half and reflects it, andtile(count: 2)is four half-sizedrawImagecopies, to the number; a warp about the center keeps a centered disc round on a 2:1 layer. One filter's arithmetic (2026-11-26): an ordered dither keeps a flat field's mean at 2, 4, and 8 levels and every pixel sits on a level;contourleaves a flat field flat, white included, and draws a line where a ramp crosses a level; grid lines cover1 - (1 - weight)²of the layer at weights of 0, 0.02, 0.1, 0.3, and 1 (within 0.002, a weight of 0 drawing nothing) and leave the ground between two lines alone; a mirrored tiling starts with the plain tiling's first cell and the cell beside it is its reflection; a kaleidoscope shows the wedge from the middle toward the right edge (a mark in it shows eight times under four segments and at its own place, a mark across the middle shows nowhere); a motion blur on a 2:1 layer is one length across, down, and at 45 degrees, 24 px for a quarter of a 96-pixel height, a one-pixel line under a 64-pixel smear is one streak even within a tenth that holds the line's light, andFilteris one long row of taps at thirteen lengths (the two rows span the length, no tap over a texel from the next up to 4,096, 64 taps a row at most, infinity and not-a-number held to nothing); the four ink filters over a clear background write ink alone, no color past its coverage and none of the clear color's white at a soft edge; the six basic patterns hold a half-clear white as a layer holds it; a glitched bar writes no color past its coverage;.motionBlurTaps grainholds over 800 values at a seed of 0 and of 200,000, and the next seed is another pattern;vibranceat -0.25 to -1 keeps red the largest channel and stops at its gray;coloramaover a ramp of written grays is the wheel in order at the ramp's own brightness (one turn, two turns, and shifted a quarter, within 0.02), black still black, a color keeping its value; film grain keeps a flat mid-gray's mean as displayed (0.4999) while its light rises 1.3% at 0.05 and 21.4% at 0.2. A layer's scale: on a layer kept at 0.25, 0.5, 1, and 2 a Gaussian of 4 spreads by a sigma of 4 canvas pixels, an outline of 6 grows a disc by 6, a mosaic of 8 has cells of 8, and a shadow offset by 40 lands 40 away; twenty-three sized filters and three combines are their twin at half size and at twice (the same texels in a full-size layer that many times as large, with the sizes multiplied by hand: the mean difference is 0.00000 at half and under 0.0002 at twice, where sizes read in texels sit 0.004 to 0.16 away), eight filters that also hold a length of their own sit within half of that distance,shockandvhsare read against the full-size picture, and five patterns likewise; a measured field reads canvas pixels and holds its reach in them; eight filters that reach one pixel change a smooth picture by the same amount on a layer at twice the size (edges 0.03886 against 0.03894;relightis among them and held before the change too), and the median takes a two-pixel speck out at either. Tones as written: twenty-six readings of a flat written gray throughthreshold,invert,posterize,solarize,levels,lumaKey, and the contrast ofcolorGradecome back as the written gray due, within 0.002 (a cut at 0.5 betweenColor(white: 0.49)andColor(white: 0.51), the negative of 0.25 as 0.75, three posterize levels with 0.5 in the middle, a contrast of 2 taking 0.4 to 0.3); a ramp of 96 written grays underthresholdis black up to its value and white from it, at 0.25, 0.5, and 0.75; three colors of one luminance fall on the side of a cut their gray falls on;levelsat a gamma of 1.001 is within 0.01 of the picture where it holds 3.0, and under a white point of 0.5 the flat that holds (3.0, 1.6, 0.4) comes back (3.0, 1.6, 1.0) with no texel brighter than the brighter of white and what it held. A layer read as numbers: a displacement map ofColor(white: 0.5), of 127 or 128 in 255, and of a mid-gray mark on a clear layer moves nothing, to the number; a full push along an axis moves a texel by the amount and none across (read off a base whose red and green are its own column and row), a weaker push by its share less the still step, a weak push in the direction its two channels name, and a soft-edged mark on a clear layer by its own alpha at every pixel (within 0.1 px, no two neighbors more than 1.5 px apart, a pixel the map never reached exactly still); a mask ofColor(white: 0.5)keeps half, of 0.25 a quarter, of mid-gray at half alpha a quarter, and a blurred white mark its own alpha; a streak field ofColor(white: 0.25)at one turn smears a dot straight down and of 0.5 straight across, and an eighth of a turn above and below zero smears it along the falling and the rising diagonal; a flat layer's normal map is the color written as (0.5, 0.5, 1) and moves nothing as a displacement map or a streak field. A combine: seventeen neutral settings return the base to the number; a mask by black, by nothing, or by no alpha keeps nothing;mixand a wipe are the base at 0 and the other layer at 1, andmixis the straight line between. What persists: a feedback loop drawing last frame back whole holds a picture for a hundred frames to the number; in single precision it fades as its gain to the frame count and a running mean settles on its value; an accumulator's picture is the mean of its passes, andreset()starts it over wherever indraw()it is called; a layer that draws a feedback layer's image shows this frame's; a combine with a layer nothing drew into is the combine over an empty layer. The frequency domain and the measured field: a picture to its spectrum and back is the picture, bare and through a mask that keeps everything, and the lowest frequency alone is the picture's mean; a measured field is within 0.4 px of the true distance to a disc's edge with a unit direction that lands on the edge; a checkerboard is its cells; the reaction's resting mix and a still fluid's dye stay put. Thirty-one held statements were each seen red under a planted defect (twenty-five plants in four rounds: seventeen in the shaders at once, each turning its own test red and no other statement's; the image fragment scaled, which reddens the twin, the held feedback frame, and the running mean; a dimmed mask; then on the Swift side screen's two blend factors, the accumulate kernel, areset()that keeps the sum,composeignoring its blend, a filter result reused for a second filter of the same layer, and the Gaussian's sigma). A twenty-sixth plant found nothing and says why: the headless render makes its filter textures fresh, so no test throughOllinApp.imagecan see a pooling fault of the live path. The blend statements of 2026-11-10 were each seen red the same way (four rounds in the shaders, three on the Swift side): the weighting skipped for multiply and screen (eight straight-alpha paths, the picture path untouched), the minimum's color not laid over white (straight and premultiplied apart), each of the two colors a fragment covering nothing hands over, a stroke fragment returning its color bare (its path alone, andBlendReadyFragmentTests), each mode's alpha factors put back (each reddening its own mode's rows), the clear color unweighted, and on the page its own weighting helper and its layer clear, each alone. The map and tone statements of 2026-11-15 were each seen red the same way (twenty-three plants in six shader rounds: every reader put back on the stored value, eleven at once, each reddening its own rows; then the map's alpha weight dropped, the still zone taken per channel, the mask's alpha weight dropped, the soft ramp left undecoded, the exact returns ofinvertandlumaKeyremoved, the clip put back inlevels, and the curve written the plain way, which is one float short at 1 and turnedmask by whitered by a half-float step; then the still zone removed, which a map at 127 or 128 sees; then the angle held to black and white, which lays a field below zero flat; then the cap onlevelsremoved, which returns 15.2 for 3.0, and held flat at white, which cuts 3.0 to 1). The arithmetic statements of 2026-11-26 were each seen red the same way (twenty-six plants: eighteen in the shaders at once, each old line put back and each reddening its own rows and no other statement's, among them the four ink filters and the six patterns one by one; then the grid's thin-line share and the kaleidoscope's fold; then on the Swift side grain's seed added to the position again, the motion blur's step taken without the layer's shape, and its sixteen taps; then three wrong coloramas in turn, the old hue turn, the hue read on stored light, and the wheel with no brightness). The survey's list is closed (2026-11-28): no statement is pinned as a known issue. The last three causes are fixed and their statements held: a loop holds its light (a feedback layer and a kept canvas keep single precision by default, and the half-float loss is itself a held statement,aLoopInHalfFloatLosesLight, since the reference states it), a masked spectrum returns its picture from a default layer, and a field's direction ends at its reach. What the survey had read and not measured is measured, each reading a test: droste on a tall layer, a wave's row against its column, a push on a wide layer, a radial blur's streak and its taps, the three zero cases, the bare angle, a kaleidoscope's middle, liquid metal's aspect, a moved picture at either precision, a field's own textures at the precision asked, a fluid's small addition, a field read as numbers, a field handed another sim, a cold magnet across an odd seam and one that does not wrap, a seeded start at any seed, and two neighboring large seeds; with the layer statements beside them inLayerBookkeepingTests(a result kept past its frame, a snapshot of a layer left alone, the slit scan's map, an environment fed a layer left alone, a frame count that starts over) andLayerWindowTests(a window on a frame that leaves its layer alone). Each was seen red under a planted defect (twenty-nine plants in five rounds: twelve in the shaders at once, ten of them reddening their own tests and no other statement's, and two that found nothing and say why, brushwork's guard, since this GPU answers 1 for 0 to the 0 and the guard is for a GPU or a page that does not, and the angle's answer at zero under the kaleidoscope, whose middle pixel never lands exactly on the center; the Ising wrap gate alone; fourteen on the Swift side at once, reddening eighteen tests, each its own; the field readback put back to one kind of sim; and the self-warp's textures put back to half float, run alone under Metal's validation, which refuses the copy by name, a single-precision source into a half-float destination). One reading trap: a mask drawn withdrawRectspills its edge ramp into the neighboring texels, so a one-texel mask is a polygon.Text invariants (
Tests/, the 2026-12-02 survey of text: 38 tests, each a statement that holds whatever the implementation, read against Core Text's own layout of the same string, a glyph's outline as the font gives it, the built-in BDF parsed a second time, or the ink of a rendered frame). Held: a line is as wide as Core Text sets it at that size in a static face, kerning and all; a kerned pair sits where the font puts it; the four vertical anchors and the three horizontal ones are the font's own metrics; lines stand ascent plus descent plus leading apart; a line breaks only between characters and never beside a no-break space or a word joiner; wrapping loses nothing but spaces and no line of more than one piece passes its box; a stop that hangs is all that passes the edge, by no more than its advance; columns fill from the side they are asked to and Latin letters stack; justified lines reach both edges and a paragraph's last keeps its width; the shapes of a word enclose the ink the word lays (1%); every glyph of the bitmap font moves the pen by its file's advance and lights its file's bits. Pinned, each with its measurement and date, taken out when its fix lands: a box under the default alignment (text one ascent above it); text scaled by the transform (the outline cut at 0.3 units whatever the scale), a small round letter's ink, and solid type's volume (one cause); Windows line ends in a string and in the three font files; a tab (27.4 em); the system face laid out at one point (7 to 21% wide) and an emoji's size at display sizes; a word's weight in the two text modes (the atlas 42% heavier at 16 points) and atlas text turned 45 degrees; stroked text by route; a wrapped line of a right-to-left paragraph and the side its stop hangs; a one-word justified line; a long dash and an ellipsis in a column set in the default face; text along a closed path; an emoji underOllinTests/ TextInvariantTests .swift tintandnoFill(), and two pictures in one piece; the bitmap font's.bottomand.middle,textDescent(), andtextBounds, its capital's height, its see-through seams, its stamped route and its doubled squares, a row past 32 pixels; the stroke font's top; a mosaic glyph past its cell and a ramp remembered across fonts. Planted (2026-12-02), each red, the sources restored after: the wrap's limit times 1.2, the justified extent times 0.9, hanging off in a box, a break one unit late, the bottom anchor at 0.9 of the block, the line step times 1.1, the BDF advance plus one. The ranked causes are inDESIGN-NOTES.md§ Rendering and color frontier; the readers' reports, the probe logs, and the pictures of each pinned failure are kept on the desk, outside the repository.Export invariants (
Tests/, 39 tests, and the four file statements at the end ofOllinTests/ ExportInvariantTests .swift Tests/; the 2026-12-02 survey of the exports, each written file read back by a reader that does not share its writer: the system's own SVG and PDF renderers, ImageIO, AVFoundation, the system's color conversion, and a G-code interpreter, a stitch decoder, and an STL reader written in the suite from the formats' rules). Held: the ink of a holed shape, a clipped disc, a stroke under an uneven scale, and a corner mark is the same on the canvas, in the SVG, and in the PDF (3%), the y axis flipped once; both files parse for an empty frame and for 2,000 shapes; both files put geometry where the canvas did under a scale of 0.0123, and a stroke drawn in a unit square keeps its width; an open curve is not filled, hides nothing under the default fill, and a shape with a closed outline and an open one fills the closed one alone; a hollow circle's band is its length times its width in both files (2%), and a hollow rect, star, heart, ellipse, and triangle have their two rims where the canvas has them (the ink of a 4-point outline on both, 2%); a built-in shape's outline has the canvas's corners (a box, a star, a triangle) and a 20-degree corner reaches as far (2 pixels); a blend mode is named in the SVG (read as text: the system's SVG renderer draws every shape plain) and the PDF's overlap is the canvas's for multiply, screen, lightest, and darkest (6 levels, on full and empty channels), with the mode a format lacks named; a layer is in the files where the canvas shows it (drawn back whole, placed and cut by its own edge, over a ground of its own, drawn back before it is drawn into, wiped in a later block, drawn into another layer), and so is what a clip of open outlines and aOllinAudioTests/ SoundInvariantTests .swift backgroundinside a clip or an overlay leave (2%, and the same places); a see-through layer is one picture (its overlap no darker than one shape alone); a filtered layer is its own drawing in the files; a merged field is the same region (a smooth union, an intersection, a mirrored block, a field built by hand, a unit field under a scale, a stroked union, a bridge between two discs that do not touch, stepped, ribbed, and beveled joints, a sculpt block; 5%, the canvas laying a filled region's soft edge outside it); an A4 sketch is 210 mm wide in both files and a page at 300 dpi keeps its sheet; a stepped ramp is hard on both sides of its edge; a line of no length is in no file; a hatched pentagram's middle is hatched; the pen-down length an interpreter adds up is the length drawn (1%), inside the sheet, no cut in the air, no number a controller would misread; a circle drawn at its size strays under 0.02 mm; a sphere, a torus, and a box are closed in their STL (every edge shared by two triangles going opposite ways, normals with the winding, the volume enclosed); a halftone at 15, 45, and 75 degrees keeps its tone (0.01); process plates on a standard canvas are the system's own separation (2 levels); the spot separation lays a see-through pixel in light; white is bare on every plate and an ink's own color is on its plate alone; a 24-pixel mark keeps its color in a GIF, a late color shows under a per-frame table, and an exported GIF holds the time asked; every video frame is stamped n ticks of its rate (30, 60, NTSC, 12.5) and shows its own picture; a video of an even canvas, and a ProRes one of any, is the canvas's size; a flat color is itself in a PNG and a GIF and the PNG names its color space; a sequence is numbered from its start; a linear value survives the EXR, read by ImageIO; a note in a video is heard on its frame (2 ms) and the sound runs the picture's length. Pinned, each with its measurement and date: a dash one pixel long on the canvas (a butt end's half pixel); a DXF's order; the G-code header's travel, a scaled circle's 48 sides, a profiled stroke, a clear stroke, a stroke on its clip's edge; every embroidered path's first stitch; an open mesh flipped by its place and a small coordinate written 0; a halftone's nine tones on the axes; process plates on a wide canvas and a see-through pixel on the process path; a small mark and a late color in a GIF and the writer's delays; an odd canvas in H.264 and HEVC; a note in slow motion, a skip off the frame grid, and the instruments a live recording finds. Planted (2026-12-02), each red, the sources restored after: the closing cut of a closed path dropped, the halftone threshold times 0.9, a frame's time one tick late, a sequence numbered one on, the fill rule left out of the SVG, the STL's triangle count less one, an ellipse cut into 12 sides, a GIF delay one hundredth long, the soundtrack pumped two frames ahead. One plant found nothing at first, and the test was the fault: a hole wound against its outline is a hole under either fill rule, so the probe's hole is wound with it. Planted again when the vector record was made to hold what the canvas shows (2026-12-02), 21 defects, each red: an open contour filled, a line of no length recorded, the files' miter limit at 4, a built-in outline mitered,hollowunread, three decimals, a stepped ramp blended, a polygon hatched even-odd, no blend in the record or in the PDF, a layer's drawing left on the canvas, abackgroundthat wipes nothing (on the canvas, and in a layer), a combine block's shapes written solid, an open outline closed by a clip, a see-through layer ungrouped, a paper canvas in pixels, a placed layer uncut, a layer resolved before the frame ended, the far bound at zero, and a trace that prunes too eagerly. Two plants were masked by a neighbor in the same batch and were run again alone, and one statement was sharpened for it: a see-through layer reads neither white nor black. Measured once and not a test (2026-12-02): the system's web engine, drawing the written SVGs, gives every blend mode's overlap the canvas's color (plus-lighteramong them), a see-through layer one gray, and an A4 page 210 by 297 mm. A measurement the statements carry: the canvas lays a filled region's soft edge outside the region, so a 10-point hollow band reads 4,036 dark pixels for a geometry of 3,770, and the files are compared with the geometry. The ranked causes are inDESIGN-NOTES.md§ New output surfaces.Transparent output (
Sources/present fragments,Ollin/ Renderer/ ShaderEffects .metal MetalRenderer,.displayImage( transparent: ) VideoCodec). A canvas whose background alpha is under 1 (.hevcWithAlpha background(.clear);Drawer) leaves the file see-through:.hasTransparentBackground --exportwrites a PNG with alpha,--export-sequencea folder of them,--export-gifa hard one-index cut, and--export-videoan alpha channel through the two codecs that carry one,proRes4444andhevcWithAlpha(VideoCodec); any other codec composites over black, as the window does, and the export says so on its first frame. Load-bearing: the canvas composites premultiplied in linear light over its clear color (the normal blend's.carriesAlpha one /alpha factors), so the resolved texture already holds coverage; the present pass takes aoneMinusSourceAlpha keepsAlphauniform (encodePresent(, aalpha: ) PresentAlpha, set by the headless render, the accumulate path, the made-frame path, and the frame grab, never by the window's drawable, which stays opaque and byte-identical) and, with it set, divides the coverage out before the tone map (a half-covered white maps as white at half, not gray at full). A pixel holding more light than coverage has its coverage raised to hold the light, on the exposed light and before the curve (ollin_present_map: marks added over a clear canvas sum their light and cover by the over rule, so ten whites at a tenth are 1.0 of light at 0.65;acomes back as the larger of the coverage and the brightest channel's light, up to 1, and the color as the light over it). So the frame laid over black is the opaque present's picture wherever the light fills the pixel, under every tone map, and along a soft edge too under.clamp; raised after the curve the excess is hidden (under.reinhardthe white pile stores 204 at alpha 166 and shows 168 over black where the window shows 188), and not raised at all the pile stores white at alpha 166 and shows 211 where the window shows 255. A pixel whose color is within its coverage is untouched (an ordinary edge stores the same alpha whatever its color,anOrdinaryEdgeKeepsItsCoverage), and the EXR, which never goes through the present, keeps light and coverage apart. The raise is for any light past its coverage, not only added piles: the soft edge of a color brighter than white, or of an ordinary color under an exposure above 1, stores more alpha than it covers; over black it is the window's picture along the edge, and over another backdrop it shows less of the backdrop than the window drawing over that backdrop, never more (at a half-covered pixel over mid gray, 11 levels short for a color three times white and 42 for an ordinary color at an exposure of 2; without the raise the same pixel is short in the shape's own brightest channel instead, over black included).TransparentOutputTests(four tone maps),.addedLightOverBlackIsTheWindowsPicture aBrightEdgeOverBlackIsTheWindowsPicture(both cases, the shortfall bounded at 48). An export stores straight (.straight: the encoded color as drawn beside its coverage, the form a PNG holds, the dither on that stored color, so 64 grays at alpha 0.1 are 64 values in the file where premultiplied bytes held 26, and a flat field at alpha 0.2 averages to its fraction where the dither, scaled by the alpha, could not straddle a code); a frame grab stores premultiplied (.premultiplied, the form a texture shared live through Syphon or an LED map is read in: the coverage quantized first,enc(straight) * ain the encoded domain, the convention a reader of an 8-bit image with alpha divides back out, premultiplying in linear light having read a half-covered mid gray ~40% too light, and the dither on that stored value under the alpha's ceiling so white under coverage stays exact and no channel passes the alpha); the float readback premultiplies its linear components in either mode; the read-backCGImageis taggedfirst(straight) orpremultipliedFirst/premultipliedLastonly for such a frame, so an opaque frame keepsnoneSkipFirstand its bytes; the video and recorder fills clear the pooled pixel buffer before drawing a frame that carries alpha (a pooled buffer still holds its last frame) and mark itkCVImageBufferAlphaChannelMode_PremultipliedAlpha; anextendedclip has no alpha channel, sohevcWithAlphathere falls back tohevc. A frame filter runs on the premultiplied frame ahead of the present, so a blur spreads coverage with color.TransparentOutputTests(12 tests: the tag and the corner/center bytes, an opaque canvas unchanged, half cover stored as drawn, the tone map on the straight color, a translucent ground, the PNG and the GIF read back, a blurred frame keeping its coverage, ProRes 4444 and HEVC-with-alpha clips read back throughAVAssetReader, h264 over black, the flag spelling);FrameInvariantTests/.aSeeThroughFrameKeepsItsLevels theDitherIsUnbiasedAtEveryAlpha(the file) andFrameGrabTests(the grab), each red under its plant..aGrabOfASeeThroughCanvasIsPremultipliedAndUnbiased Examples/;Export/ Cutout Docs/§ Transparent output; Guide Ch 45 § Leaving the background behind: transparent video.Output/ Export .md Path-traced export.
--path-traced [N](+--pt-depth, default 8) switches the still/sequence/video exports to an offline path tracer over the same scene the raster window tunes live — physically soft area shadows, color bleed, mirror-in-mirror reflections, real solid/thin glass with tinted transparent shadows, emissive meshes sampled as lights, base-color textures read at hits, and a thin-lens depth of field (Camera3D.aperture/focusDistance, read by the traced camera only; the focus is measured from the eye and the opening sits at the eye, the ray re-aimed at the focus point and walked back out to the near plane,lens.wnaming an orthographic camera whose opening sits at each ray's own foot in the eye's plane; measured from the near point with the opening there, the focus landed a near plane too far and the blur rans / (s - near)wide, andtheTracedLensFocusesAtTheDistanceFromTheEyepins the bar at the focus sharper than one a near plane beyond it). Programmatic switchOllinApp(.pathTracedExport PathTracing); the bare flag's sample count follows--render-quality(64/256/4096; the detail tier is a final still, not a general default, and a sequence multiplies it by the frame count); needs an RT GPU, else a one-line note + the raster render; contact sheets, vector exports, and--benchstay raster by design. Load-bearing: the trace runs in its own completed command buffers before the frame's other encoding (chunked adaptively toward ~1s of GPU work per buffer — watchdog + progress; the still export prints a rewriting sample line, the sequence drivers keep their per-frame line) — only then may the frame's shadow pass re-fill the shared accel/offsets rings the trace used; the scene handoff generalizes the caustic-geo pattern (buildShadowAccel(breaks coalesced runs on any batch-finish change and uploads onepathTraceMats: ) OllinMaterialper geometry); matcap batches are excluded from the traced scene and keep rastering (the unlit emissive-look finish — an area light's glowing prop must not swallow the light's own next-event rays); the traced layer composites once, at the first solid mesh batch (premultiplied over, so silhouette edges blend and draw order against 2D holds) with the fragment writing the primary pinhole depth, so wireframe/grid/matcap and the untraced 3D kinds (points, strands, raymarched fields, and any copy batch the traced scene turned away) still raster and occlude correctly. Integrator conventions are raster parity: punctual lights keep the un-normalized legacy Lambert for standard/toon/gooch and the full microfacet terms for the physically-based finish; area lights are physical withcoloras radiance (a tube radiates by its silhouette ribbon, length × diameter, never its full skin — the full-skin form overshoots by ~π); the environment samples the same equirect at the same normalization × intensity as the skybox/IBL; no environment → the flat ambient is the miss field, which makes an ambient-only scene an exact furnace (PathTraceTestspins the mean within 3/255). A light that declines to throw casts nothing here either. The tracer keeps no caster list and needs nocastShadows(), so without the flag it throws from every light in the frame while the raster throws from none, and a preset's fill (which setscastsShadow: falseexactly to open the shadow side) would grow a shadow in the export alone. The flag is stored inOllinLight(0 = throws, so a default light packs byte-identically and the raster reads nothing new), and the tracer skips that light's visibility ray; the raster's own resolution is untouched (CPU-side.shaping .w shadowCasters, four slots, gated bycastShadows()). So in the raster the flag is a cost dial too, and in the export it decides the picture alone.PathTraceTestspins it: the shadowed floor patch comes back to the lit floor's brightness within 6/255, having sat 139 levels below it. Variance controls, each from the published technique: environment importance tables (512×256 latitude-weighted luminance CDFs + solid-angle pdf grid, cached per equirect texture; the environment strategy reads the same filtered picture the continuation reads, at the level the cone reaches along the drawn direction), the power heuristic through one shared lobe-pdf function on both sides (bias otherwise), filtered importance sampling on lobe-side environment reads (mip from the sampled pdf's solid angle — mirrors stay sharp) widened by the ray cone (below), path-space regularization (the light list's evaluation at a vertex past the first scatter floors roughness at 0.25 and reprices its compensation and body there — the single-pixel-glitter fix, since a listed light has no pdf division and no partner; the environment and mesh-light strategies keep the sharp lobe, since each is paired with the continuation through the power heuristic and the pair is one estimate only while both price one lobe: a floored lobe on one side lit a ball behind a pane of nothing 12% brighter; the continuation stays exact so mirror chains stay sharp), a crossing is no scatter, through a thin pane or into and out of a solid (it carries the vertex's pdf, its pairing, and the leg's length on, since that vertex's shadow rays already passed it on the straight line: a reset there credited the light behind a pane in full beside the share its strategies had counted, 8% at roughness 0.5, and behind a block of index 1 the same 8%; past a solid the pickup is weighed against the table at the direction the ray leaves with, so a lamp the table draws reliably is the straight pass's and the room the bent path's, and the straight pass is never the whole estimate, since a polished ball behind the block read 0.42 of itself that way at 256 samples, a near-mirror lobe being light only its own continuation samples well,anIndexMatchedBlockChangesNothingInTheTrace; the regularization and the bounce bound count scatters, not crossings, and a shadow ray through a pane takes1 - Fat the index the continuation crosses with), and Russian roulette from depth 3. An opt-in grain filter over the finished render (PathTracing.denoise,--denoise; off by default on @eaviles's call, so the plain flag always writes the estimate the tracer arrived at, even though the measurement below says leaving it on would cost no accuracy): the trace also fills two guide layers at the first hit (base color after maps + the running sum of each sample's luma²; shading normal + primary distance), written only whilept.meshLights.wis up, else a 1×1 stand-in is bound to texture slots 5/6 and nothing is written or allocated. A four-kernel chain (ollin_pt_denoise_prepare→_atrous×5 over a ping-pong pair →_finish) filters the demodulated radiance (light ÷ first-hit albedo, re-modulated at the end, so a texture edge or a painted pattern is never blurred, only the light on it), edge-stopping on normal agreement (power 128), relative distance (0.02 × the center's own distance, opened by the tap spacing), and luminance divided by the measured variance (the unbiased sample variance of the mean,/(N-1), 3×3-blurred before use since a pixel's own estimate of its spread is itself noisy; it is stored in the alpha channel and is filtered with squared weights)._finishwrites back intoaccumin accum's own units (radiance × coverage), so the composite fragment is untouched. The load-bearing measurement is that it never trades the picture for smoothness — against an 8192-spp truth render of the example scene, the filtered frame is closer at every count tried: 17.60 → 9.13 RMSE at 64 spp (the accuracy of ~240 samples) and 5.48 → 3.89 at 2048 (the accuracy of ~4070, i.e. ~5 min of M2 tracing saved), so what it removes at the deep end is residual grain, not detail. On a sequence it also cuts flicker rather than adding it (consecutive frames of the moving example at 48 spp: 2.85 → 1.21 RMSE, max jump 249 → 156). Cost does not show against run-to-run noise at 1080² (four compute passes). Settings were swept, not copied: wider luminance blending (σl 8/12/16) buys ~1.5% RMSE and costs ~30% of the kept high-frequency detail, so the published σl = 4 over 5 passes stands. Two envelope facts: a true sparkle (rough metal catching a small bright source) reads softer, since glitter and grain are the same signal to a variance-driven filter; and one sample has no spread to measure, so the pass never runs atsamplesPerPixel == 1. A bound on what one bounce may add to a sample (--pt-clamp X,PathTracing; 0, the default, is none): every contribution the kernel adds goes through.maxBounceLight ollin_pt_add, and the bound applies to light that has scattered at least twice on its way to the eye, which is the production definition of indirect light: the environment or an emitter met atdepth > 1(two or more bounces out) and a light strategy run at a bounce vertex (depth > 0); it holds the contribution toXin its brightest channel, scaled whole so its color holds, and sums the luma it took off into the statistics layer'sw(allocated full size when bounded, as under the stop). What one scattering shows (a lamp in a mirror, the environment in a bead, the lamps a surface faces) is direct and never bounded, so a lit plane with nothing to bounce light between is byte-identical under any bound (theBoundLeavesTheFirstHitAlone). The off-by-one is load-bearing: bounding everything past the first hit instead took half the light out of a scene of two thousand polished beads mirroring a lit studio (energy 0.35 to 0.52 of the reference at bounds of 2 to 8) for under a decibel, since those beads are their one-bounce reflections. It is a bias and says so:boundedLightSharereads the accumulation and the statistics back once per frame, before the denoiser rewrites the accumulation, and the report'slightDropped(the dropped luma over kept plus dropped) reaches the recipe as"clamp"and"clampDropped"(to a hundredth of a percent) and the sequence export's closing line. The point is the grain a per-pixel statistic cannot read: a lamp caught through a polished surface every few hundred samples, which no count smooths and which keeps every pixel of a polished scene open under the stop; bounded, the fireflies on the floor beside a near-mirror ball (its pixels far above the floor's own level) fall by more than half at the same count while the floor's ordinary sampling noise stays (the lamp's area, sampled), its mean holds within a percent, and it settles at a lower mean count under a threshold (aBoundOnABounceCutsTheFirefliesAndSaysWhatItTook, the firefly probe at 160²: 48 samples, bound 2, 40 pixels more than 24 levels over the floor's median against none, the whole spread 4.1% to 2.4%, the mean 162.2 to 161.6 of 255, the bound taking 0.3% of the frame's light, the stop's mean 45 to 42 of 128 at 0.04). The limit is applied per contribution (the shape of Cycles' indirect clamp), not to the sample's total, so a path that legitimately carries several bounces of ordinary light is untouched. Measured on the scene that asked for it (two thousand polished beads mirroring a lit studio, 128 samples at 1080² against 1024): a bound of 4 took 7.5% of the frame's light (9.3% at 2, 5.5% at 8) for a tenth of a decibel, and the stop's mean stayed at 86 of 128 with or without it; that scene's grain is one-bounce light (the studio's lamps through each bead's glossy lobe), which the bound leaves alone by design, and the recipe's share is what says a render is the wrong case. The probe's floor, speckled by a mesh light caught through a near-mirror ball two bounces out, is the case it is for; a.glowingsurface is credited whole wherever a path lands (no light strategy), so a small hot glowing mesh speckles everything that sees it after one bounce and is not a case for the bound either (the first probe used one, and the test read nothing until the lamp became a mesh light). Adaptive sampling (--pt-noise X,PathTracing;.noiseThreshold --pt-min N,minSamplesPerPixel): a per-pixel stop once the pixel has settled, so the count becomes the most a pixel traces. The statistic is the standard error of the brightness the viewer sees (the trace adds each sample's squared luma, the backdrop luma behind a primary miss, and one to a per-pixelstatslayer; behind a miss the brightness is the environment along the ray when it draws as the skybox, else the clear color's luma, so a silhouette over a bright sky counts and the same edge over black does not), divided by the square root of the mean below 1 and by the mean above it (Dammertz and colleagues' measure with Cycles' two refinements;ATTRIBUTION.mdhas the lineage), against the threshold: 0.01 is about one 8-bit level of standard error at any brightness. The rounds fall at fixed sample indices whatever the GPU's timing (the minimum, then everyPathTracing= 8; the automatic minimum is the square root of the cap rounded up to a multiple of 8 and never under 8), a check between rounds (.checkStep ollin_pt_converge) closes the settled pixels and a dilation (ollin_pt_dilate, 3×3) keeps an open pixel's eight neighbors open and writes the open pixels into a compacted list (each SIMD group reserves one range with a single atomic add and fills it in lane order; the list's order is whatever the adds made it, which cannot move a pixel's bytes since its sums depend on its own samples alone); from the first check on, a dispatch runs over that list, one thread per open pixel, never over the grid (pt.open.x), because a settled pixel in a grid dispatch keeps its SIMD lane busy for as long as any pixel in its group still traces: measured on the example scene at 512 and a 0.02 threshold, the grid dispatch dropped 40% of the samples and saved 5% of the time. Nothing open ends the frame. The kernel adds every sample onto the running sums in sample order from the texture's value, never a chunk total added at the end, so the frame is the same bytes however the host cuts a round into dispatches by GPU time (theTracedFrameIsTheSameBytesUnderAnyCutforces cuts of 1, 5 and 7 throughOllinApp, for a fixed count and under the stop); before this the fixed path's last bits followed the clock too. The composite divides each pixel by its own count (the.pathTraceChunkSize statslayer's z,PathTracedLayer; a fixed count keeps the one reciprocal and its bytes), the denoiser is untouched (its statistics are per hit)..counts MetalRenderer(reset at the top of every pass, so an untraced frame reads nil) carries the settings, the resolved minimum and the mean count reached; the still, sequence and EXR recipes write it as.lastPathTraceReport "pathTraced":(each only when it applies, the mean to a tenth, the dropped share to a hundredth of a percent), the video recipe the settings alone (one recipe per file, written before its second frame), and{"samples", "depth", "denoised", "noise", "minSamples", "meanSamples", "clamp", "clampDropped"} renderFramesprints the run's mean once at the end. The progress line adds the share of pixels settled. Measured (adaptiveSamplingSpendsTheCountWhereTheGrainIs, the grain probe's room at 160², cap 256, against 2048): 0.005 reached a mean of 140 for the full count's error (0.77 against 0.75; a fixed 140 errs 1.01), 0.01 a mean of 77 (0.90), 0.02 a mean of 38 (1.31; a fixed 38 errs 1.87); the minimum barely moves it (8/16/32 at 0.01: 73/77/84 for 0.906/0.902/0.897). On the example scene at 1080² against 2048 (release, M2): fixed 512 104 s 29.65 dB; 0.02 mean 306, 105 s, 29.60; 0.04 mean 217, 88 s, 29.20 (fixed 224: 45 s, 26.69; fixed 432 at the same 86 s: 28.94); 0.08 mean 143, 64 s, 27.95 (fixed 144: 29 s, 25.47; fixed 312 at 62 s: 27.75). The stop saves samples first and time second: the pixels that settle are the cheap ones (margins, matte floor) and the open ones (glass, the mirror floor, the blur) cost two to three times the average per sample, so 58% fewer samples bought 15% less time; at equal time it is a quarter of a decibel ahead, at equal samples two and a half. The compacted dispatch measured within the run-to-run spread of the grid dispatch on that scene (0.02: 105 against 96 s, 0.08: 64 against 66) and is kept for the frame that is mostly settled, where a grid dispatch runs a SIMD group for every block that holds one open pixel. The envelope is the rare bright path a pixel has not seen when checked, which no per-pixel statistic can count: two thousand polished beads on black are grain from edge to edge at 128 and at 512 samples (a fixed 128 sits 21 dB from a 1024 reference; each bead mirrors a studio with hot lamps, so every pixel catches a firefly every few hundred samples and its spread never comes under a usable figure), so only the margins settle (mean 87 of 128 at every threshold up to 0.04, 38% of pixels at 512 and 0.06) and the time does not move; a bound on what one sample may carry is the lever there, filed with the other open end inDESIGN-NOTES.md. Reuse across a sequence (--pt-reuse [N],PathTracing; 0, the default, is none; bare = 8): after the trace and before the filter,.reusedFrames ollin_pt_reusefollows every pixel back to where it was in the previous frame and carries that frame's sums in (encodePathTraceReuse,MetalRenderer+PathTrace). The motion is the raster's own:.swift encodeMoverVelocityruns for the frame's declared movers (withMotion, instanced copies included; previous minus current, pixels, y-down, the MetalFX contract) and wins where it wrote, and every other covered pixel reprojects its surface point throughdrawer's view-projection, which also gives the depth it expects there (a mover's previous depth is not known, so its own stands in); a backdrop pixel holds still. Under a lens a pixel follows the movers inside its circle of confusion: the reuse uniforms carry the aperture, the focus distance, and the pixel's footprint and angle, each pixel's circle is.previousCamera3D R |s − d| / (d s θ)pixels (orthographic:R |s − d| / sover the pixel width), and a pixel blurred past three quarters of a pixel takes the mean of the mover words a 5×5 sampling of that circle finds (a sharp pixel reads its own word), because a blurred mover's light spreads far past the pinhole footprint the velocity pass wrote its motion at, and followed at zero motion a defocused bead sweeping the frame left a trail of its blurred light a frame long (the peer's scene: subject 20.29 → 21.04 dB, carried 221.7 → 239.9 of 256). Each frame of a run traces its own stretch of every pixel's random stream (pt.open.z, the frame's index in the run timescarriedCap, carried inPathTraceHistory): the stream is a pure function of pixel and sample index, so without the offset every frame of a still scene retraced the same paths and the history averaged identical samples (the first probe settled to 2.38 levels of error where a fixed 64 read 1.43; with the offset 1.19, under a fixed 64 as a running mean should be); outside reuse the offset is 0 and the stream is what it always was. A pixel is classed by its own samples, not by its center ray: a center hit gives the surface point, a center miss with hits (a silhouette pixel) takes its samples' mean hit distance along the center ray, and only a pixel with no hit is the backdrop; classing silhouette pixels as misses let them hold still under a pan and carry their edge light along as the edge passed, a stripe a frame (the pan probe read 3.36 against 2.89 alone; 1.76 after). The history is read through the four texels around the spot, each admitted only if it held the same surface. Coverage is part of the signal: a texel joins unless its share of hits disagrees with the pixel's by more than 0.6 (a surface that arrived or left), an empty pixel admits only texels under 0.15 coverage (a quarter-covered texel is a silhouette that moved past, and carrying it into the empty pixel behind drew the pan probe's stripe again), and a silhouette pixel keeps the empty texels in its footprint so the bilinear mix gives it its partial coverage; turning away every texel whose hit state differed selected for luck (in a sparsely covered blurred field most texels have no hit by chance at a few dozen samples, the survivors were the bright ones, and the peer's field read 5% bright, more the more it carried, while every sharp bead fattened; the rule took the subject from 21.04 to 21.95 dB). Where both the pixel and the texel hit, the view depth (the pixel's surface point from.frameIndex ollin_pt_pixel_point, measured along the view axis from the eye, so perspective and orthographic read alike) within 2% of the expected plus twice the largest change to a covered neighbor, the facing within 0.16 between unit normals (about nine degrees) plus four times the largest change to a neighbor, both opened by the local change since a bilinear read spans a texel. Light follows the facing, not the material point, so the interpolated history must face the pixel's way: a reflection does not move with its surface (a ball turning in place carries its surface points around while its image of the room, and its shading, stay put), and the spread test cannot tell the wrong light fetched there from a rare path the frame has not caught, so after the per-texel tests the history interpolated at the spot is compared with the pixel's own mean facing within 0.03 (about two degrees) plus three times each side's sampling error (ollin_pt_facing_error: the normal sum ofhitsunit normals shortens by half the squared spread, so the spread is the root of twice the shortfall and the mean's error that over the root of the count; a small curved bead or a pixel whose lens samples land on several surfaces reads a wide one) plus a quarter of the squared local change (the interpolation's own slack), or the whole history is dropped. A tolerance without the sampling term failed at random on the peer's bead scene under its lens (a mixture pixel's mean normal is noise) and the frames flickered more with the history than without. The per-texel facing test stays loose (0.16 + 4× the local change): it only asks whether a texel is the same surface at all. The neighbors' depth change is measured on the same per-pixel surface depth as the pixel's own (a center hit, else the mean hit distance), so under a lens the change is the smooth one of the blur and not a jump between beads. Trust by spread is the load-bearing rule and it is two-sample: the carried mean may sit three standard errors from the frame's own, the two spreads combined (sqrt(, each from its own Σluma² in the guide layer), and is clamped per channel to that distance beyond it; the one-sample form (the frame's spread alone) darkens a firefly history, since a frame that caught no rare path reads a tiny spread and pulls the brighter truth down to it. The carried spread follows its mean (Σluma² scaled by the luma ratio squared). The cap isvarC/ n + varH/ nH) carriedCap(frames × count): past it the history scales so the whole holds the cap, a running mean from then on. The result is written over the frame's own sums and the per-pixel count intostats.z, so the composite divides per pixel (thecountslayer is bound under reuse as under the stop), and out as the next history (PathTraceHistory: accum, both guides, a meta layer of count and view depth; one per renderer, dropped on a size or drawer mismatch, the mode off, or a frame that was not traced, so a run never reads a history that is not its own). The guide layers are filled under reuse (the spread and the facing live there) whether or not the filter runs; the filter, when asked, runs on the carried sums and so fades as the history deepens. The first frame of a run tracesreusedFrames × samplesPerPixel(no history at this size for this drawer), so a sequence starts settled and a still rendered alone reproduces a sequence frame's settledness rather than its bytes; the recipe writes"reuse"and"carriedSamples"(the mean ofstats.z, read back once per frame) and the sequence drivers print the run's mean. Determinism: every step is a pure function of what the earlier frames left, so a sequence is the same bytes twice (TracedReuseTests), and the mode off is byte-identical to the frames rendered alone. Measured on the 160² probes against converged renders (TracedReuseTests): a still scene at 16 × 4 carried reads 1.19 levels where a fixed 64 reads 1.43 and 16 alone 2.95; a panning camera 1.76 against 2.89 alone; a bright box sliding over a dark floor leaves the uncovered strip within the noise of the reference (no ghost) while the far floor settles; a polished ball spinning in place comes out at 4.49 against 4.66 alone while the floor beside it settles; the first frame equals a fixed render of the carried count to the rounding of a division. Measured on the scene that asked for it (two thousand polished beads sweeping under a still camera with a lens, 1080², depth 4, twelve frames at 60 fps of its lap, against a 1024-sample render of the last frame): 32 samples a frame with 8 carried (241 of 256 held) took 57 s for the twelve frames where 128 alone took 136 s; the subject read 21.95 dB (32 alone 20.31, 128 alone 24.05; denoised 22.57 against 25.73), the whole frame 23.66 (22.14, 25.59), and consecutive frames sat 20.62 dB apart (32 alone 18.68, 128 alone 19.90; denoised 21.49 against 21.12), so the sequence is steadier than the baseline at 42% of its time and each frame's fidelity lies between 32 and 128. Two limits, measured and left in: the bilinear history read at a sub-pixel offset every frame a surface moves spreads a pixel-wide lamp speck into its neighbors, and in eight bits that reads bright, since the speck was clipped at white and its spill is not (the mid-tones read +4.5 levels against the reference where 128 alone read −1.4, the bright class −11 against −7.6: light moved from specks to their surroundings; energy holds in linear light); and a blurred field whose movers inside one circle of confusion move at different rates (the back hemisphere of the sweep) is followed by their mean and smears along the sweep. Two guards were measured and refused: dropping the history where the movers in a circle disagree by over a pixel (it refused most of the back field, carried 241 → 146, and the frame fell back to its 32-sample error and flicker), and taking the nearest texel where the four texels disagree beyond their errors (the pan probe's error rose from 1.76 to 2.29 from the positional jitter). The edge-aware or Catmull-Rom read and the differential motion are filed inDESIGN-NOTES.md. What it cannot follow is written inDESIGN-NOTES.md: a reflection on a moving polished surface (the virtual-position vector), and a stop that reads the carried spread. A pixel's worth of a curved surface (the ray cone). A cone (signed width and spread,coneWidth/coneSpread, plus the lens opening's anglelensSpreadfrom the focus plane) travels with each path: it starts at the pixel's width and angle (pt.cone.xy), a thin lens opens the width to the whole opening and turns the spread inward by it (so|width|past the focus is the circle of confusion), the width grows by spread × distance at each hit, and a reflection adds twice the triangle's mean edge curvature times the footprint (ollin_pt_curvature: Reed's per-edge formula from the vertex normals, averaged, world-space for a copy through the query's transforms, the sign flipped on a back face; the footprint foreshortened by|Ng·d|held at 0.1). At each opaque scatter the sampled lobe's footprint (one over its pdf, as a disc's full angle) folds into the spread in quadrature (ollin_pt_widen), so it reaches the next curved surface; a glass reflection takes the curvature term, a crossing keeps the cone. The lobe-side miss reads the environment atollin_pt_env_lod: the cone's solid angle (spread ⊕ lens, as a cone's, saturating at the sphere) over the mean texel, never coarser than the level whose cell is a sixteenth of the turn (22.5°, level 6 of a 1024-wide chain; at the chain's top the read averages the room before the lobe's Fresnel and cosine weigh it, and the bead field read 9% bright between its beads there against 2% at this cell, for 2% more spread), from the tracer's own latitude-weighted copy of the equirect (ollin_pt_env_mip, one dispatch per level averaging the four source texels by the sine of their own latitude, cached beside the tables inptEnvTableCache, bound at texture 9): the plain box chain weighs the poles like the equator and read 2 to 3% dark at levels 4 to 6 and 9 to 12% at 7 to 9 on the bundled interior. The table's draw reads the tracer's filtered copy at the level the continuation would read along that direction (the lobe's pdf at the drawn direction folded into the cone as the hit folds its own,.filtered lodE), so the two strategies estimate one integrand and their weights sum to one over it (theTraceAgreesWithTheWindowOnABallInALitRoom): the draw read sharp beside a blurred miss counted a lamp's blurred skirt at nearly full weight beside its sharp core (a matte ball in the bundled interior traced 0.475 where the window read 0.384 and a continuation-only sharp trace 0.372, a metal one at roughness 0.5 0.434 against 0.379; the two the other way round, the draw blurred beside a sharp miss, read 25% under), and a draw read blurred while the pair priced two lobes (the floored one on the draw's side, before the regularization moved to the light list) is what lost 13% of the bead scene's light in the footprint session, not the blurred read. A draw whose lobe is sharp at its direction reads finer than the table's cell, where the sharper read's spike is the lobe's own weight to take; one whose lobe is wide reads coarser. The backdrop keeps the original texture at the table's level. The light list is shaded through a lobe widened by the footprint's normal spread (hDirect: σ = curvature × footprint / √12, α² += 2σ², the raster's specular anti-aliasing; its energy compensation re-priced at the widened roughness, or a defocused bead's highlight at roughness 0.5 lost its multiple scattering, 4% of the frame), and only the light list: widening the whole lobe (the continuation, the table pairing) turned the beads satin and read 14% bright at the center (rejected), and the light list has no sampling pair, so its widening costs the pairing nothing. Measured on the bead scene (2048 polished beads, lighting-only interior, thin lens, 1080², against a sharp 1024): per-sample variance over the subject 22.3 → 6.4 (−71%; the jitter and the lens frozen left 7.9, so two thirds was the footprint; at a fixed hit the lobe's draw left 3.4 and the table's 4.5; the point light's spike through the near-delta lobe was the 6.7 common to every strategy probe), 128 against the reference 18.0 → 19.3 dB, 128 against its own 1024 23.7 dB where the sharp pair sat 18.0, and every region within about 2% of the reference (the whole subject +0.6%, the bead interiors −1.0%, the rim −1.6%, the defocused field between beads +0.7%; the unfiltered 128 itself sits +0.8% and +1.4% by the same measure). A flat mirror reads as before (aFlatMirrorReadsTheEnvironmentAsBefore, its reference recorded under the kernel without the cone); the bead field converges (aPolishedBeadFieldConvergesAtItsFootprint: 32 against 512 samples, RMS 10.2 over the beads' pixels, 19.7 before, bound 14). The surface maps keep their footprint of pixel width plus spread × distance (no curvature), so textured snapshots are untouched. Every integrator probe inPathTraceTests, and thepath-traced-3dsnapshot, namesdenoise: falseexplicitly (redundant against today's default, and kept so that flipping the default can never quietly re-aim them) (they measure the sampling, not the filter); the filter has its own five probes (moves-a-thin-render-toward-the-truth, still-helps-a-nearly-converged-one + strength-follows-the-measurement, keeps-a-hard-texture-edge, the filtered furnace, determinism). Deterministic by construction: sampling is a pure function of (pixel, sample index, bounce) and accumulation order is fixed, so the same command renders the same bytes (pinned). Glass (transmission > 0, physically-based): a stochastic weight-free mix by the transmission fraction routes that share of paths to a microfacet dielectric — VNDF micro-normal, exact dielectric Fresnel, TIR reflects, a thin pane (thickness 0) passes straight through with no bend, a solid bends by Snell and pays Beer-LambertattenuationColor^(per interior segment (tint applied on the crossing in only, never the exit) — with estimator weight the outgoing Smith G1 alone (the VNDF pdf cancels the rest), so a polished clear sphere is a furnace-exact lossless dielectric (pinned within 4/255). A glass vertex runs no next-event pass and marksd/ attenuationDistance) prevNEE = false; the next miss or emissive hit then takes full weight — the MIS bookkeeping rule; breaking it under- or double-weights everything seen through glass. Transparent shadows: NEE visibility runs a closest-hit walk that passes through transmissive geometry (albedo × transmission per thin sheet / solid entry + Beer inside, a straight line — the bent, focused kind stays the livecaustics()feature's), gated by a scene-level any-transmission flag so glass-free frames keep the cheap any-hit ray. Textures & surface maps: the accel run also breaks on map identity across all five slots (gate-aware: a texture only counts while its finish gate —normalScale/mrGate/occlusionStrength/emissive.w— is up); a per-geometry bindless five-slot resource-ID table (OllinPTTexEntry: base, normal, metallic-roughness, occlusion, emissive;useResourcesresidency; the white stand-in in an unbound slot is the base slot's multiply identity, and the gated slots are never read unbound) is sampled at the hit's interpolated uv at the ray-cone mip (pixel footprint at the eye + spread × path distance, over the triangle's own texel density; per-map resolution folded in per slot). The maps compose exactly as the raster surface-mapped fragment: the normal map bends through the interpolated vertex-tangent frame (bitangent = sign · cross(N, T), bend on the raw frame, flip to the viewed side after) whileOllinPTHit.Ngkeeps the geometric normal for the ray machinery (epsilon offsets, the below-horizon break — the raster's detail-vs-position split; unmapped scenes are untouched since Ng == N there); the metallic-roughness channels multiply the finish-table factors (which carry the drawing-state × mesh-material product — the vertex w slots carry only the drawing state, so a gated hit must read the table); the occlusion ramp dims the environment share only — the env NEE term at the vertex and, via a carriedaoPrev, the paired lobe-side miss pickup, both halves scaling together so the MIS pairing stays consistent; direct lights, emissive hits, and surface-to-surface bounce light stay undimmed (the trace occludes those with real geometry); the emissive map multiplies the factor at hits and at mesh-light NEE sample points, while selection, pdf, and the reverse MIS weight all stay factor-based (map texels never exceed 1, so the factor pdf's support covers the glow). Triplanar base color + normal map project at hits through the raster's ownollin_triplanar_surface(level-0 reads, matching the raster's mipless textures). Emissive-mesh sampling: a CPU power CDF over the glowing geometries' triangles (luminance × area, two-sided); because selection is power-proportional and the point uniform, the area pdf at any sampled point is luminance / total power — no per-triangle lookup — which is what makes the reverse power-heuristic weight at a BSDF-found emissive hit computable from the hit alone (full weight at depth 0). Envelope: height (parallax), the detail pair, and decals stay raster-side (a traced hit reads the flat surface at its plain uv), layered lobes trace as their metallic-roughness base, thin-pane pass-through ignores frosting (roughness shapes its reflection only), and the shadow walk's tint skips the per-interface Fresnel. A finish's look is drawn where the camera sees the surface (ruled 2026-11-11: as the window shows it). The lit fragment paints a highlight, cel bands, a warm-cool ramp, a rainbow sheen, flakes, a glow through the body, a rim, and a grating's rainbow by formulas of its own, and the kernel draws the same formulas (ollin_pt_direct's look branches andollin_pt_look_layers, KEPT IN STEP BY HAND withmeshLitColor's tail) at every look vertex: one the path reaches before it has scattered off a matte lobe (seen; a pane or a solid crossed, a glass reflection, and a sampled specular lobe keep it; a cosine lobe ends it). Past a matte scatter a surface is its plain body, so a stylized surface lights its neighbors exactly as a matte one of its color does, to the byte (aStylizedSurfaceLightsItsNeighborsAsAMatteOneDoes), which is what stands in for a furnace: a rim and a sheen's floor add light of their own in the fragment, and here they add it to the picture alone.ollin_pt_has_lookis the gate, so a finish with none (the default material, a physically based one with no grating and no layer) runs the plain sum term for term. The light terms take the traced visibility in place of a shadow map; the glow through a body takesollin_pt_through, a walk that starts under the surface, passes the body's own far side, and hands on to the ordinary shadow walk (a shadow ray from the lit side is stopped by the body itself in every frame, which put the glow out). A warm-cool surface the camera sees ends its path (the ramp stands in for the ambient and the bounce as well as the diffuse). Under a panel the cel band and the highlight are the fragment's own whole-panel integrals (the two area-light tables, bound at textures 10 and 11,ltcEnabledraised by the pass): the exact diffuse integral banded, and the fitted integral of the highlight's lobe times the strength, each times the share of the panel one ray per sample sees. A band cut from one sample's share was grain at the panel's horizon, a sampled microfacet lobe of the same width read 3 levels bright from its long skirt, and the exponent's own distribution read up to 6 dark; the tables are parity by construction and carry no grain. The highlight answers the light list alone (no room, no environment), the grating the punctual lights alone, and the tracer still reads nosoftnesswrap. Measured (a sphere alone, one light, 256 px, 64 samples, 8-bit levels from its window twin, a pixel and by 8-pixel region): every look under a directional light within 0.30 and 0.14; under a panel 1.85 (the sampled matte body's grain, the plain matte control included) and 0.23; flakes finer than a pixel 7.66 and 2.06 for glitter and 1.31 and 0.46 for sequins, since the window draws one flake a pixel and the trace averages them; the hologram is read with no flat ambient, which a metal's traced body reflects and its raster body does not.TracedLookTests(10: the table of 30 rows, each look against its plain body, the neighbors statement on 8 finishes, a look in a mirror, through glass, a shadowed highlight, a shadowed panel, the glow stopped by another body, the furnace for the looks that answer to a light, determinism; 17 plants red on their own statements). Still traced as their base: clearcoat, the fabric sheen, anisotropy, and scattering under the surface. A time budget a frame (--pt-seconds S,PathTracing; 0, the default, is none): the sample loop stops at the sample where the wall clock runs out (.secondsPerFrame DispatchTime, measured from the first dispatch; the setup, the reuse, the filter, and the readbacks are outside it), sizing each dispatch to the time left from the wall seconds the last one took per sample (to the nearest sample; under half a sample's worth ends the frame), so a frame lands within about a sample of its budget rather than a dispatch (a dispatch is sized toward a second of GPU work). The frame the clock leaves is a fixed render of the count it reached, byte for byte: the kernel adds samples in order onto the running sums and reads nothing of the frame's total (pt.counts.xis the loop's bound alone), the composite divides a fixed render by the count reached (invSamples:), and under the stop the checks fall at the same indices either way, so a budgeted adaptive frame equals the stop at the reached count as the cap with the same1 / reached minSamplesand the same mean;TracedBudgetTestspins both against renders of the recorded count, plus the floor and the terms.--pt-min Nis the floor the clock may not cut under (PathTracing: the named minimum, else one sample, clamped to the count; the dispatch stops at the floor so the clock is asked exactly there; the per-pixel stop's.timeFloor firstCheckis untouched). Under reuse the first frame of a run gets the history's worth of time (timeBudget(:tracingTheHistory: ) reusedFrames × seconds, since it traces that worth of samples), and a budgeted reusing sequence is not the same bytes twice (each frame's count follows the clock and a frame is a function of the frames before it), which the Docs say beside the recipe. The bare flag's cap under a budget is the detail tier's 4096 whatever--render-quality, since the clock decides and a final still's count is the ceiling a fast scene converges to first; a named count stays the cap. The report carriesreachedSamplesPerPixelandsecondsTraced; the recipe writes"seconds"and"reachedSamples"(a video's recipe drops the count, one frame's figure, as it dropsmeanSamples); the sequence and video drivers end with the counts reached (least, most, mean) and the mean seconds a frame against the budget; the progress line under a budget reads samples and seconds rather than a share of a count. Measured on the example scene (1080², M2, release build, launch to file): a fixed 128 took 29.5 s;--pt-seconds 10traced 50 samples in 9.9 s (10.7 s in all) and--path-traced 50rendered the same bytes; the same budget at--pt-depth 2reached 93; with--pt-noise 0.04the same 50 and nothing settled, since the first check under the bare cap of 4096 is 64 (--pt-minbrings it forward, and the Docs say so); three frames at--pt-seconds 5 --pt-reuse 4traced 101, 25, 25 samples in 20, 5, 5 s.PathTraceTests(furnace ×3 incl. glass, parity, texture parity, transparent + tinted shadow, the emissive floor pinned to the analytic small-emitter irradiance ±18% with a low-spp noise bound, determinism ×3, off-is-off, snapshotpath-traced-3d; the maps probes: normal-map halves apart + raster parity, mr map byte-equal to its factors, occlusion black/white furnace exact, emissive map head-on to the analytic byte and through the light sampler to the scaled floor irradiance, triplanar trace-vs-raster parity — the flat-face probes stage onMesh.plane, sinceMesh.boxcarries no uvs and a uv-less mesh silently degrades every uv-gated map); example3D/;Effects/ PathTraced Docs/.Output/ PathTraced .md Slow motion in an export (
SlowMotioninSources/;Ollin/ Export/ SlowMotion .swift --slow-motion N [--made-frames], theslowMotion:argument onexportSequence/exportVideo/exportGIF, and--export-loopthrough the last two). The file keeps its own--fpswhile the run is covered byfactortimes as many frames, so the motion takes that much longer to watch;--secondsstill counts the sketch's own time and--framesstill counts what the file holds. Two forms. Drawn (the default) steps the clockfactortimes finer and draws every written frame: exact, any sketch, any factor above 1, and it costs the factor's worth of render time. Made (--made-frames) draws what it would have drawn anyway and fills each gap with the platform interpolator, so it needs a 3D scene under a perspective camera and does half speed only (one frame per gap, and MTLFX offers no phase to ask for). Motion measured in seconds slows under either form; motion measured in frames (a fixed step perdraw(), nodeltaTime) slows only under the made one, since a finer clock just hands it more frames. Load-bearing: the clock rate and the file rate are separate inrenderFrames(SlowMotion), and the recipe's.clockRate( playingAt: ) fpsis the clock, so a still re-renders from it unchanged;"madeFrames":is written only when the file really holds them; the refusal is asked after the firsttrue performDraw()(the camera cannot be known before) and exits before any file is written; a made frame is built after its render from the picture and depth that render kept (keepForMadeFrame/exportMadeFrame), which is why the export forces the depth resolve;newestmoves only when a gap is consumed, so a warmup frame's keep is harmless. The measurement found a shipped bug in the live path (recorded under Frames between the drawn ones): the velocity fill returns the mover pass, not the field, and binding it as motion warped every frame that declared a mover. Measured 2026-08-29 against the same moments drawn for real: a made frame lands ~6x closer than either neighbor (mean 0.13 of 255 against 0.67…0.97), and costs about 11 ms against 20 ms for a drawn frame at 1080 square, so half speed took 1.9 s where drawing every frame took 2.4 s (3.3 s against 5.1 s at--render-scale 3). Limits: the first gap of a clip repeats its neighbor (one pair is not enough history, and six warm-up encodes buy exactly what three do); a flat overlay has no depth, so a caption over a moving scene can smear (the platform'suiTextureslot is unused);--replayis refused (a take carries one input frame per drawn frame); spatial video does not take it.SlowMotionTests(15: the finer clock against the still path, the made form's own drawn frames byte-exact, the closer-than-either-neighbor probe sabotage-verified red, the head-of-clip repeat, the flat-sketch refusal). No pixel snapshot (the interpolator is a stateful platform object).Docs/; Guide Ch 45 § Slower than it happened: slow motion.Output/ Export .md#slow-motion Motion blur from subframes (
--subframes N [--shutter F],OllinApp/.exportSubframes exportShutter;SubframeShutter+ the drives inSources/, the moment loop inOllin/ Export/ Subframes .swift renderFrames,foldSubframeinMetalRenderer+Effects). The accumulation buffer: each written frame drawn at N moments across a shutter centered on the frame's instant (moment i at the middle of its share of the opening, as the canvas blur's streak centers) and averaged in linear light; any sketch, 2D and shaders included, at N times the render cost; applies to.swift --export,--export-exr,--export-sequence,--export-video,--export-gif,--export-loop,--export-grid,--export-sweep, and combines with drawn slow motion (the shutter is then a share of the finer frame). Load-bearing: the fold sits inrenderedFrameafter the overlay, before the linear capture and the present (a single-precision running mean ping-ponged throughollin_fx_weighted_sumat 1/N; a moment before the last commits without presenting, so the one 8-bit quantization point stays put; an EXR gets the mean with the last moment's depth); every moment is a draw (ruled 2026-10-08):timesteps through the opening,deltaTimeis the time since the previous draw (adeltaTimesim stays exact),frameCountcounts each draw as under--settleand drawn slow motion, so frame-counted motion runs N times as fast; a moment before time 0 is drawn at 0 (the first frame is half blurred); the shutter isexportShutter, else the sketch's lastmotionBlur(, else 0.5, read before each frame; the canvasshutter: ) motionBlur()stands down while a moment is drawn (motionBlurActive); a picture the GPU carries between draws (noClear, a feedback layer, anAccumulator/LineSpray, a simulation field, SSR history) is refused by name before anything is written (ruled 2026-10-08), as are--settle,--made-frames, and a take; a held (noLoop) frame renders once as it is; the recipe writes"subframes"and"shutter".SubframeExportTests(9: the analytic streak column by column and its light within 0.2%, a flat shape's light, a still picture byte-identical, the clock of every moment, time 0, the sketch's shutter, the stand-down, the refusal, the recipe; five plants each red).Docs/; Guide Ch 45 § Slower than it happened: slow motion.Output/ Export .md#motion-blur-from-subframes Live recording (performance capture) (
Sources/+Ollin/ Export/ SessionRecorder .swift Core/). Records a live run in real time — frames as rendered, the sketch's sound as played — into one movie:CaptureAudioSource .swift startRecording(/to: audio: ) stopRecording(/completion: ) saveFrame((a still,to: completion: ) ~/Pictures/Ollin/, PNG/JPEG/HEIC/TIFF by extension, no extension a PNG, any other refused) /isRecordingsugar over the publicSessionRecorderextension (audio:.sketchdefault /.microphone/.sketchAndMicrophone/.none;codec:reusesVideoCodec, h264 default; default file~/, a phone's to Photos, see Capture on the phone); hosts wire ⌘⇧R (OllinLiveCoding stage chip + saved toast; OllinLive menu) and OllinLive takesMovies/ Ollin/ <Sketch> <stamp> .mov --record(film from the first frame). Video uses the CGImage frame-grab hook (wantsRenderedFrame, armed only while recording; the frame is the one the window shows, read off the on-screen render, so a take costs one tone-map pass and a copy per frame and never a second render) into AVAssetWriter's real-time mode with host-clock PTS (a slow frame lasts longer; a frame the encoder can't take is dropped, never awaited, and counted). Audio: the coreCaptureAudioSourceseam (Mirror-discovered off the sketch's stored properties likeExportAudioSource; Synth/AudioPlayer/Tone conform — a node allows one tap per bus, so capture sharesinstallAnalyzerTap's fan-out viaCaptureTapRelay, never a second tap) feeds per-sourceAudioCaptureSinklanes mixed on the writer queue every 100 ms, 150 ms behind the clock, with the offlinetanhknee. Load-bearing: a lane places buffers by host-time stamp with a running counter — the counter wins under 50 ms jitter, the stamp wins past it — so a device gap becomes silence, never a slide (the A/V drift killer on long takes); the audio track is declared whenever mode ≠.none, so a late-entering instrument lands mid-file in sync; a recording survives a live-reload swap (reload(to:)carriessketchto the new instance, whose.sessionRecorder setuphook rescans its instruments; hosts must address the current sketch viaSketchSession—.currentSketch core.sketchdeliberately stays the first mount, and a recorder wired to a stale instance films nothing); the movie is opened on its first frame, at that frame's size (RecordingTakeis nil until then; the sound lanes wait in the take), since a writer sized from the declared.writer canvasSizetook a.resizablecanvas's first frame for a size change and ended every such take with nothing in it; a later size change finishes the file cleanly (a movie's frames are all one size); the main thread never waits on the encoder (found 2026-12-04 in the iOS simulator): the movie is built and opened on the writer's queue (RecorderWriter), since the first encoder a process builds took 198.7 ms there (1.0 ms for a second take in the same launch) and, built on the main thread, stopped the window and left a hole right after the take's first frame; a frame waits on that queue only while the frames there fit in.begin RecorderWriter(128 MB: ten at a phone's full screen, never fewer than the renderer's 3 in flight;.waitingBudget theFramesThatMayWaitAreWhatTheBudgetHolds,aWriterBehindCostsFramesNotMemory), since each holds a copy of the whole picture (12.6 MB at a phone's full screen) and frames used to be admitted on the encoder's readiness alone, which says nothing of what already waits; three were measured too few (the queue's work on a frame ran 27 to 87 ms at the 90th percentile in the simulator and up to 135 ms, and three turned away 7 and 38 frames of two takes); a frame the queue finds the encoder not ready for is counted too (one simulator take wrote 46 of 180 frames, counted 29 drops, and lost 105 without a word), so every frame handed over is in the file or in the dropped count (lastTakeFrames);RecorderWriterbuilds one in the background once a process, when a recorder is attached or the phone's control appears; a movie that cannot be opened ends the take at once, with the reason; a take is its own.readyEncoder( ) RecordingTake(writer, destination, start, dropped count), and the recorder'sPhase(idle/recording/finishing/failed) moves only for the take still current:stop()returns before the file is closed, a take started inside that window used to have its writer cleared and its destination reported by the old file's completion, and could then never be stopped (SessionRecorderTakesTests);lastErrorsays why a take or a still did not go as asked (a file not finished, a take stopped before its first frame, Photos refused, the room's sound missing, a take or a still that could not begin), cleared when one goes well;stop(completion:)always answers, at once withnilwhen nothing records (it used to drop the closure), else with aSessionRecorder(.Destination .photos/.file(path)) once kept; quit, Control-C, and SIGTERM finalize viastopAndWait()(an unfinished writer is an unplayable file; the recorder installs its own DispatchSource signal handlers once, kept for the process's life);.extendedrefuses (HDR stays offline),.widetags P3; aVideoPlayersoundtrack doesn't reach a take yet (its tap carries track time, not host time); headless (isRenderingHeadless) refuses with a pointer at--export-video. Verified live: a 20 s take at a solid 60 fps with sound in every 5 s window across a mid-take hot reload, finalized by SIGTERM.AudioCaptureSinkTests(6, the timeline placement) +SessionRecorderWriterTests(a real writer, no audio hardware — CI-safe on purpose) +RecorderWriterTimingTests(the writer held to what it was handed: every frame at its stamp to the microsecond, a gap left empty, a click heard at its sample, none dropped) +SessionRecorderTakesTests(the take sized by its frames, the answered stop, a writer held still costing frames and never memory, a movie that cannot open ending the take) +CaptureKeepingTests(the still's formats and names); exampleExport/Record.Docs/; Guide Ch 47 § Keeping the take.Output/ Recording .md Per-frame profiler (
Sources/+Ollin/ Core/ FrameProfile .swift Renderer/). The "why is my sketch slow" tier over the shippedFrameCapture .swift FrameStats/extension-seam machinery: a publicFrameProfileis a property ofFrameInfoandFrameStats, carrying the four-way time split (cpuDrawMS/cpuEncodeMS/gpuMS/waitMS), the submitted work (drawCalls/passes/computeDispatches/batches), and the geometry each path drew (triangle / fringe / SDF instance / field quad / image / glyph / mesh / point splat / particle / clip). Load-bearing: the counts are taken in the encode loop beside eachdrawPrimitives, never derived fromdrawer.batches, so a batch the renderer skipped (an image whose texture failed to build) is not counted, andFrameProfileTestspins that difference; every render encoder in the renderer goes through the onecountedEncoder(choke point (a_: _: caller: ) #function-defaulted label, so a new shadow / probe / filter pass counts itself and can name itself), which is why the pass number stays honest as passes are added; the wait is timed apart from the encode (the frame-time readout's own lesson: timing across the triple-buffer semaphore measures vsync and says nothing), sowaitMSis reported as headroom rather than folded into CPU cost; GPU time comes from the command buffer's owngpuStartTime/gpuEndTimein the completed handler, which runs off the main actor, so it passes through anOSAllocatedUnfairLockand reads the timestamps into a local before the lock's closure (MTLCommandBufferis notSendable) and lands one or two frames late, hidden by the smoothingSketchViewapplies to all three measured times; headlessrenderedFrameresets the counts too, so an export and a test read the same profile. UI: a cost tier on the sharedMonitorCardView(so all three hosts and the detached panel get it at once) in the Photos-info-window idiom the card already follows — cells carry facts, the bars carry time, and no number appears twice: one cell grid holds FPS · Canvas, one cell per drawing path in use (SDF / tri / point / particle counts), then the Draws / Passes / Batches counts (per-path breakdown in their tooltips), filling hairline-separated rows four at a time with the last row taking the remainder (eight cells run 4+4); a path's cell stays once it has appeared, so a particle count dipping to zero for a frame doesn't reshuffle the grid, and the set clears when the frame counter restarts on a reload; under the grid, the two bars on one scale (the frame period), deliberately not stacked (the CPU builds frame N while the GPU draws N-1, so the two overlap rather than add) are the only place milliseconds appear (a grid CPU cell would repeat the bar's number, so there is none). GPU frame capture:Sketchand.captureGPUFrame( to: ) View ▸ Capture GPU Frame(⌘⇧G, a one-shotOllinHUDthe runner takes and clears) wrap the frame that asked (the request is taken between.captureFrameKey performDrawandrender) in anMTLCaptureManager.gpuTraceDocument, and print the frame's pass list beside the path; Metal refuses to capture unless the process was launched withMTL_CAPTURE_ENABLED=1, so the refusal prints the exact line to run rather than failing silently.FrameProfileTests(8, incl. the one-time first-frame setup passes, which are real and stay counted); no pixel snapshot (the output is numbers).Docs/; Guide Ch 19 § Which half is slow: the cost row.Tools/ Profiling .md Dragging a shape into place (
Sources/+Ollin/ Live/ SourcePick .swift OllinRuntime/+SourceEdit .swift OllinRuntime/). In both live hosts, Command-drag moves, resizes, or turns the shape under the pointer by rewriting the numbers that placed, sized, or aimed it, in the sketch's own source, andShapeDrag .swift ⌘]/⌘[put it in front of or behind its neighbor by moving its line; under OllinLive the edit goes to the file and the watcher reloads it like any other save, and on the OllinLiveCoding stage it goes to the editor buffer, which the host then evaluates, so nothing is held in the window that the text does not say. Three parts: aSourceSite(#fileID/#line/#columndefault arguments on ~74Sketchshape methods, plus aSourceMovenaming which arguments carry the position (.scalarsfor bare numbers,.pointsforVector2ones), the size (.uniformfor sizes that scale together,.axesfor a width and a height), the anchor the position numbers stand at (.center/.corner/.apex), and any angle arguments); the drawer's per-frame pick list (recordSourcePickfromappendSDFanddrawLine, cleared inbeginFrame) read back bySketch; and the rewriter (.sourcePick( at: ) SourceEdit.moving/.resizing/.turning/.planningMove). All of it ispackage, so it is host machinery rather than sketch API. Load-bearing:#columnis the call's(and columns are UTF-8 bytes (measured, not assumed), so the whole scan works onArray(source.utf8)and an accented comment ahead of the call cannot shift the edit by a byte; the site is matched by file name, never path (a live compile builds from a copy under the same name, the rule diagnostics already carry); every edit replaces the text of a number already there and edits apply back to front, so spacing, comments, and line breaks survive (a call spread over lines is one call); a whole number stays whole (a drag under half a point writes nothing, which is what keeps hand-placed shapes on the grid) and a fraction keeps the author's digits;clearSite()on return is not optional (an unmarked draw, e.g. text,drawShape, the plural helpers, would inherit the previous line and pick as the wrong one); the drag is converted through the inverse CTM's linear part, so a shape underscale(2)writes half the drag; regions are shape-aware (ellipse / box / apex-up wedge / capsule, a line's grab radius at least 5 points) and the topmost is the last drawn (sabotage-verified); the outline and its handles are a SwiftUI sibling of the canvas, never ink, so they cannot reach an export; a modifier released during a drag keeps the controller armed for that drag alone, and it stands down when the drag ends (modifierHeld, read indragEnded), where it used to stay armed and the editor over the stage went on ignoring clicks until the next modifier event (--dragtest); a refusal names what stands where the number would be (width / 2,cx) instead of failing silently, and a computed argument leaves every number alone. A resize changes the size numbers only and holds the position numbers still, so a shape grows from wherever its call says it stands, which is what theanchoris for: a corner-placed rectangle offers three handles because the fourth sits on its own anchor and can scale nothing, and a corner on the anchor's row or column moves one side only (the right edge is where a width is dragged). The factor is a ratio, not a distance (a corner's offset from the anchor, projected along itself for a uniform size), so it reads the same at anyscale, and it is floored at 0.05 so a corner pulled through the middle leaves something to grab again; a corner radius and a count (sides:,points:) are not sizes and stay as written. A turn swings a shape's points about the centroid of those points (computed from the file's own numbers, never the pick region, so a multi-target call likedrawArrowstill turns about its centerline) or moves its angle arguments (an arc'sstart:/stop:), and a shape with one point and no angle offers no knob at all, because its direction lives in arotatethis does not touch; an angle is written to at least three decimals (a whole radian is most of a quarter turn) and a turn never writes-0(the sine of a half turn is not quite nothing). Handles are canvas-space: corners on the outline, the turn knob 26 points clear above the top edge, grabbed within 11; hovering a handle keeps the shape it belongs to (a handle stands outside its shape, so a fresh pick there finds nothing and would clear the very outline that put it on screen). A coordinate that is a bare name adjusts a parameter instead (SourceEditreports names rather than refusing, so a mixed call writes its number and adjusts its parameter): the host matches a.planningMove Param<Double>of that name whose value equals the coordinate the frame drew with (SourcePick.placedAt, single-point shapes only, which is what keeps a local variable shadowing a parameter's name from moving the wrong thing), writes it through the control the inspector row uses (so it clamps to the row's range), and records it as tuned, so nothing recompiles and the value survives the next reload. Tracking is off unless the modifier is held: cost with it off is one branch per draw call, measured at +3.96 ms per 100k circles in a debug build (57.47 against 53.51, an A/B against the same tree without the arguments), which is the argument passing itself, not the branch. Reordering by key (OllinRuntime/,SourceReorder .swift SourceEditover.reordering( _: line: column: by: ) SourceReorderStep.forward/.backward/.toFront/.toBack): with a shape outlined,⌘]/⌘[move its line past the neighboring draw call's in its own block, Shift all the way, taken inOllinMTKViewbefore any menu and only while a host is installed and answers.performKeyEquivalent reorderHovered. The ink travels: the block is read as items (a draw call spanning its lines, an ink verb with its kind, blank, comment, or an opaque nested{…}/other statement); the ink kinds the neighbor changed (fill/noFillone kind,stroke/noStrokeone,strokeWeight,strokeCap,strokeJoin,strokeAlign,hollow/solid,blendMode) are restated for the shape where it lands (from the ink in force at it, or the drawer's own start for fill/stroke/strokeWeight:fill(.white),stroke(.black),strokeWeight(1)), put back after it only where a later shape uses them before they are set again, and an ink line left with nothing to color is removed (its kind re-set before any shape), plus a post-pass that drops an ink line saying what is already in force within the stretch the move touched (a reverse move then leaves the file byte-identical, pinned); a shape undernoStroke()carries no stroke details; a comment directly above the shape moves with it. Refusals name the line:.blockedBy(for anything between that is not ink (astatement: ) translate, alet, a nested block; a move to the front stops there after ≥1 step and reportsstoppedBy),.inkUnknown(for a kind nobody can read off the block,statement: ) .notAlone(line:)for a call sharing its line,.alreadyAtTheEdgeat either end. One controller, two hosts:ShapeDragControllerlives inOllinRuntimeover aShapeDragHostthat names its source, reads it, writes it, and records a parameter (LiveSessionreads and writes the file;PerformanceSessionthe buffer). On the stage,writeSourceisreplaceBuffer(an ordinary edit, so it marks the document and one ⌘Z takes it back) followed byevaluate()(the clock carries), andreadSourcerefuses by sentence whenever the buffer is not the text the stage was built from (sourceOnStage, set on each successful evaluation): typed since ⌘↩ asks for an evaluation, and mid-compile asks to wait, because a site names a line of the evaluated text and a drag during a compile would add to numbers the stage has not shown yet. The modifier reaches the canvas through a local.flagsChangedmonitor inOllinMTKView(installed beside the pressure monitor, key window only, theflagsChangedoverride standing in only where no monitor is up), since on the stage the editor holds the keys and the override never fires; a modified press is taken before the canvas claims first responder, so a drag never takes the keys from the editor; the editor stops taking hits while the dragisArmed, which is what lets the pointer through the text to the stage; and the overlay sits above the code, measured against the letterboxed frame (onGeometryChange) and the stage's own canvas (stageCanvas, updated per evaluation, so a sketch that changes its canvas keeps the outline true). Gates:SourceReorderTests(18, pure),SourceEditTests(38, pure text, inOllinRuntimeTests; the negative-zero rule verified red by sabotage),SourcePickTests(16), andswift run OllinLive --dragtest, which compiles a sketch, picks its circle, writes the file, recompiles, finds the shape where the drag left it, resizes it by a corner, swings a line about its middle, drives the move, the corner, and the parameter-name drag throughShapeDragControlleragainst a stub host, and brings a covered circle forward by the key, recompiles, and finds it on top at the overlap (the one proof text cannot make), then sends it back to the file as written, andswift run OllinLiveCoding --dragtest, the buffer half: the drag writes the buffer and evaluates it while the file on disk stays as written, the shape is found where the drag left it, a drag mid-compile and a drag over typed-and-unevaluated code are each refused by their sentence and leave the buffer alone, a parameter's name sets the parameter with no evaluation, and the bracket key reorders through the buffer and back. ExampleLive/DragToEdit; no pixel snapshot (the output is a file).Docs/(§ On the performance stage),Tools/ DragToEdit .md Docs/; Guide Ch 1 § Moving something by hand, Ch 47 § Moving a shape on stage: the Command-drag.Tools/ LiveCoding .md The performance host on a controller (
Sources/+OllinLiveCoding/ PerformanceControls .swift ControlsCardView+.swift ControlTest.swift). OllinLiveCoding's own actions (evaluate, evaluate fresh, hide the code, the code's backdrop and size, record) answer to MIDI and OSC beside the sketch-level@Parambindings, as a host preference, never the sketch's. Load-bearing: the host polls both satellites' inboxes (MIDIInput/.messages( ) OSCReceiver) on a 60 Hz main-thread timer, so no host action ever runs on a Core MIDI or Network callback thread; OSC has a fixed namespace (.messages( ) /ollin/evaluate,/,ollin/ evaluate/ fresh /ollin/code/hidden,/,ollin/ code/ backdrop /ollin/code/size,/ollin/record) live whenever the port (ollin, 0 = off) is set, while MIDI is learned per action (.livecoding .oscPort learn(_:): the next note, controller, or OSC message binds; a note is refused for a fader's action; one control serves one action, so a control learned twice moves; the map persists as JSON underollin); a note fires once per press on its channel, a controller button fires on the rise through 64 (its release ignored), a fader maps 0…127 onto the backdrop's 0…1 or the size's 9…32; over OSC a bare message turns a toggle over, a value sets it, and a button's.livecoding .controls 0release is ignored. The view settings are written to the same defaults the@AppStorageviews read, which is what moves the menu's picker with a fader.OllinInspectorwent public for the card. Gate:.Palette OllinLiveCoding --controltest(learning, MIDI matching, the fixed addresses, persistence, a UDP loopback, and a virtual-source MIDI loopback that is passed over where Core MIDI is absent).Docs/§ The host on a controller; Guide Ch 47 § The host on a controller: OSC and learned MIDI.Tools/ LiveCoding .md Code completion at the caret (
Sources/+OllinRuntime/ CodeCompleter .swift Sources/+COllinSourceKit Sources/). The performance host completes names from the Swift toolchain's own completion service, reached at runtime:OllinLiveCoding/ CodeCompletion .swift CodeCompleterfinds the two frameworks beside.load( ) swiftc, opens the out-of-process one first (a crash there comes back as a refused request, never as the stage going down) and the in-process one as the fallback, and binds each entry point by name over Ollin's own C header (COllinSourceKit: the handles, the one struct that crosses by value, a typedef per call; the toolchain ships no header, and nothing is linked, so a toolchain without the service loses completion and nothing else). A completion is a session at one point in the text:open(at the start of the word (or right after a member dot) checks the buffer once and answers the first list,_: source: arguments: filter: limit: ) update(filters the same session with more of the word typed (about a millisecond),_: filter: limit: ) close(_:)ends it; the rows keep the service's own order (an exact and a short match first, the buffer's own class before a global), matched by prefix, never fuzzily (a fuzzy match on a word with no real match dredges the longest system constants up from the bottom of the namespace; an empty list is the honest answer on a stage), underscored names hidden,not_recommendedrows dropped. The arguments come fromSketchLoader: the compile's own module search paths plus what the service does not infer (.completionArguments( sourceFile: ) -sdk,-parse-as-library, and a module name that is never the file's own, since a module calledSketchshadows the class every sketch extends). Load-bearing: offsets cross as UTF-8 bytes while the editor counts UTF-16 (CompletionText/.utf8Offset utf16Offset); the word start is scanned back over identifier characters and a run that starts with a digit is a number, not a word; a dot triggers a member list after a name or a bracket, never after a digit or another dot (0.5,..<); the service's<#T##display##type#>placeholders are reduced to the editor form<#display#>(the compiler recognizes it and names its line when one is left behind; Tab finds the next, wrapping); every request runs on the controller's own serial queue, never the main thread and never the cooperative pool, tagged with a generation so an answer for a caret that has moved on is dropped; the first request costs seconds while the service reads the framework's modules, so the host warms it up at launch, off the main thread. In the host the list is a subview of the editor's own container, never a window, so it goes into fullscreen with the editor and hides with the code; Escape opens it and closes it (and so never leaves fullscreen), Up and Down move, Return and Tab take the row, Tab walks the placeholders when no list is open, and the text view's own predictive completion is off. View ▸ Complete as You Type is the preference; Sketch ▸ Complete Name (⌥Esc) opens it regardless. Gates:CodeCompletionTests(10, pure text: word starts, member dots, placeholders, offsets, kinds, the arguments) and the completion phase ofOllinLiveCoding --selftest(drawCioffers the positionaldrawCircleasdrawCircle(beside its labeled overload, narrowing keeps<#x: Double#>, <#y: Double#>, <#radius: Double#>) drawCircles,Color.filtered byreoffersredtypedColor).Docs/§ Completing a name; Guide Ch 47 § Finishing a name as you type: completion.Tools/ LiveCoding .md Two-speed evaluation (
SketchSession, on in OllinLiveCoding,.landsPlainBuildFirst --single-buildturns it off; OllinLive stays single-build). An evaluation under a loader that optimizes starts both compiles at once, plain and optimized, from one source snapshot: the plain build lands first with the clock as asked and is the one landing the host hears about (onSuccessonce;reloadCountandlastBuildSecondsrecord it), then the optimized build swaps in silently through the same landing path with the clock always carried and the tuned parameters re-applied as at any swap; the phase is.optimizingbetween the two (SketchSession.Phase, one value for the whole lifecycle:.idle,.compiling,.optimizing,.failed;isOptimizingandisSettledread it, andisSettledis the one meaning of "settled" every host and gate waits on, so a pick is never made against a plain build about to be replaced), which both hosts' chips show as a muted "Optimizing…" throughSketchSession, the one mapping onto.status InspectorStatus(compiling, then the failures by how much of the sketch each stops:.errorfor the Swift compile,.setupFailed,.shaderError; then.optimizing,.plainBuild,.watching); an optimized build that fails behind a landed plain one leavesoptimizedBuildFailureas the sentence why and the chip at "Plain build" until the next evaluation, where it used to read as settled with only a printed line to say otherwise. Load-bearing: one task owns both builds, so a newer evaluation's cancel refuses both of the older one's and an older optimized build can never land over newer code (pinned by starting the newer evaluation from inside the older one's landing hook); a plain build that fails fails the evaluation at once and the optimized result of the same text is refused, never reported twice; an optimized build that fails on its own leaves the plain build on stage and prints; with no runner yet (the first mount) the second build replacessketch, which is what lets the headless gates see both. The second swap does to the run whatever the first did (the samekeepRun, since it is the same code): an evaluation that carries the run carries it across both, and one that starts it over runssetup()andreloaded()twice a fraction of a second apart, which is the flag's remaining reason. What it buys is the optimizer's share of the compile, measured on the M2 with-wmo(medians of three, evaluation to swap): 20 lines 0.63 s plain / 0.68 s optimized against 0.60 s for the single build; 150 lines 0.68 / 0.84 against 0.76; 470 lines 0.78 / 1.16 against 1.09; the two compiles together cost each about 0.07 s. The pixel pin compares decoded pixels, never PNG bytes: the export recipe carries the@Paramvalues and the gate's sketch reads its build level into one on purpose, so the files differ while the pictures (with the sketch's own sine and cosine arithmetic) are identical, and the optimizer does not fuse multiply-adds (probed, 0 of 100,000 differing). Gates:OllinLiveCoding --selftest(both landings timed against the single build, the pixel pin, the single-build control) and--sessiontest(every carry under two-speed, supersede against both builds, the clean failure).Docs/; Guide Ch 47 § Performing the code itself: live coding.Tools/ LiveCoding .md#the-evaluate-loop A reload refused after a framework rebuild (
SketchLoader,.LoadError .frameworkRebuilt( module: at: ) SketchLoader/.launchedAt processLaunch/frameworkModules(/inTrace: under: ) rebuiltModule(in_: since: ) Sources/). A live host loads a sketch dylib compiled against the module files beside its own binary, so a build that rewrote them while a window ran made the next save compile against a framework the host is not: it loaded and crashed (two windows went that way, a release build having added a stored field toOllinRuntime/ SketchLoader .swift Shape). Every compile writes its loaded-module trace (-emit-loaded-module-trace-pathinto the work dir) and the loader keeps the framework modules it names, the paths under the discovered-Idirectories, both sides resolved through their links (the compiler names.build/; a host run asout/ Products/ Debug/ ... .build/debug/...finds its directories through the link, and an unresolved prefix match found nothing and never refused, which the host gate caught and the unit tests could not). The reference is the process's own start (sysctlKERN_PROC_PID__p_starttime), never a baseline captured at first use, so the gallery's first selection minutes after launch is held to the same moment; a module written after it refuses with one sentence, The framework was rebuilt since this window opened (Ollin at 2:02:07 PM), so the edit was not loaded; relaunch to run it., through the session's ordinary failure path, so the sketch on stage keeps playing. Checked before each compile against the last trace's modules (a refusal without compiling against files a build may still be writing) and after it against its own; only the modules a compile read count, so a rebuilt test target or an unrelated host never refuses, and the SDK's modules are never read. The module files are never touched to test it: a build product with a new timestamp sends the next build back through everything above it, so the gates setlaunchedAt =instead. Pins:.distantPast FrameworkRebuiltTests(4: the trace filter, through a link too; a module written after launch refuses and names itself in both build layouts; older modules and missing files load; the launch is the process's), OllinLiveCoding--sessiontest(on a running stage: refused with the sentence, the sketch on stage the same instance and six frames drawn through the refusal, the same text loading under a loader launched after the build), OllinLive--selftest(the load refused, then the same file loaded). Every host goes throughSketchLoader: OllinLive, OllinLiveCoding, OllinRun, the gallery, the generator preview, the figures.Evaluating what changed (
Sources/+OllinRuntime/ SourceRegions .swift Sketchin.carryRun( from: ) Sources/+Ollin/ Core/ RunCarry .swift SketchRunner+.reload( to: keepClock: keepRun: ) PerformanceSession). The performance host reads each evaluation against the text the stage was built from, and when the edit moved nothing but method bodies the run underneath carries on instead of starting over:.evaluate setup()does not run again, the canvas keeps what is piled on it, and the drawing state, the random streams and the@Savedproperties come across, so a long exposure keeps its ink and a piece mid-set does not go back to its first frame. What per-block evaluation can honestly mean in a compiled language: the whole buffer still compiles and the whole instance is still replaced (the code is in a new dylib, so no method can be swapped on a live object); what is per-block is the decision and the editor's pulse, which lights the declaration the caret stood in. Load-bearing: the carry iscarryRun(from:), and it adopts the runningDrawerwhole rather than copying fields out of it (a drawer holds no reference back to its sketch, so the accumulated canvas, the style, the fonts, the images and the retained batches all come across, including anything added later) beside the generators,view2D,isLooping, the@Savedset matched by name (each property its own success), and the two thingssetup()registered rather than computed: the extensions the sketch installed for itself and the automation it wrote (adopted without doubling what the runner re-attaches, and the fresh instance seeds the pointer in the same branch that firesreloaded(), or a cursor-following sketch reads (0, 0) until the mouse next moves); the decision is the host's, never the session's, because only the host has both texts.SourceRegionsis a bracket-counting line scan, not a parser (comments and bare attribute or modifier lines join the declaration under them; braces inside strings, raw literals and comments are skipped), comparing header-for-header with whitespace collapsed and comments dropped, so a reworded note or a rewrapped signature is the same declaration. It refuses to carry the run whenever a declaration changed, whensetup()or anything reachable from it by a fixed-point name walk changed, and whensetup()names a stored property that is not@Saved(theCracksshape: state built insetup()would come back nil and the sketch would draw nothing or crash, so a restart is the safe answer and the failure mode of being wrong the other way is one unnecessary restart). A carried swap firesreloaded()from the no-setup branch of the draw loop, and hands the pause back to anoLoop()sketch throughpauseHoldover(the flag the camera snap already used, renamed for the second caller: it is the same "un-paused for one piece of work" idea). Both swaps of a two-speed evaluation carry it, or the silent second one would restart the piece a fraction of a second later.--single-buildis unchanged. Gates:SourceRegionsTests(17, text alone),OllinLiveCoding --selftest(the block under the caret at five positions, the three edit kinds, and the runner A/B where a carried swap shows six accumulated bars and a restart shows one; verified red by sabotage),--sessiontest(supersede with a runner attached, against both a carrying and a restarting evaluation, and the two-speed carry; verified red by sabotage).Docs/; Guide Ch 47 § Performing the code itself: live coding.Tools/ LiveCoding .md#what-the-edit-changed Parameters written back into the sketch (
Sources/+OllinRuntime/ ParamWrite .swift ParamSaveActionon the sharedParametersListView+LiveSession/.saveParams PerformanceSession). The other half of the shape drag: the values you turned in the inspector go into the.saveParamsIntoBuffer @Paramlines that declared them, so a good set outlives the run instead of being typed back by hand. The destination is the source and never a preset file, and the method isSourceEdit's byte scanner pointed at a property's default rather than a call's arguments. Load-bearing: only the parameters the host recorded as turned are written (SketchSession), each carrying what it holds right now, so a parameter turned by hand and then moved by a fader saves where the fader left it; the written names are dropped from the tuned store (.tunedParams forgetTunedParams) the moment they stand in the text, or the stale tuned value keeps winning and the next hand edit of that default reads as ignored; declarations are found by walking forward from each@Paramattribute (past its own parentheses and any modifiers tovar <name>) rather than back from avar, because forward is where a string or a comment can be skipped safely, and two parameters of one name in a file are refused as ambiguous rather than guessed; the hunt for the=stops at the end of the line, so a declaration carrying no default cannot reach forward and take the next statement's value. Two rules keep the written file compiling: aDoubledefault written whole is aDoubleonly by the range beside it, so a fractional value keeps its point (86.0, never86), and aClosedRangewrites both ends with a point (40...50reads asInt); a whole value under a whole default stays whole, so a round number reads as its author wrote it; and a call around one literal keeps its wrapper (Opacity(0.5)becomesOpacity(0.75),Tempo(120)becomesTempo(96), the form a type of your own takes, for the number / bool / text payloads), since the bare literal put over the whole call compiles only for a type that takes a literal. What it refuses it names in one sentence under the button: a default that is worked out (side / 3,houseRadius, and arithmetic over numbers alone,600.0 / 2, which is a sum the author meant), a parameter declared in another file, a choice with no name in code (a closure-builtEasingcarries a serial), a call around more than one value (Tempo(, which used to be written as the bare120, beatsPerBar: 3) 120and silently drop the bar). A color writes to four decimals, finer than one 8-bit channel step; an option keeps the spelling it was written with (.dotsorStyle.dots). In OllinLive the button writes the file and the watcher reloads it like any other save; in OllinLiveCoding it writes the editor buffer throughEditorController(undo, caret, and scroll kept, the document marked dirty), because there the buffer is the truth and ⌘S is the only thing that touches the disk..replaceBuffer ParamWriteTests(34, pure text; the fraction rule and the string skip each verified red by sabotage) andswift run OllinLive --savetest, which compiles a sketch, turns nine kinds of parameter, writes them, recompiles, and reads them back off a fresh sketch with nothing restored into it; no pixel snapshot (the output is a file).Docs/§ Saving what you turned; Guide Ch 1 § Saving the values you tuned.Helpers/ Parameters .md Putting a parameter back (
Param.declaredValue/Param.reset()/AnyParam.reset()in the core,Sketchwith the package.resetParameters( named: ) parametersResethook,SketchSession+ the observable.resetParams( _: ) tunedNames,ParamResetActionon the sharedParametersListView,RemoteReseton the remote wire). A tuned parameter goes back to the value its@Paramline declares without quitting the host. The declared value is kept beside the current one, taken once from the clampedwrappedValueat init, and a reset jumps to it the wayrestore(_:)does (a smoothed parameter never glides back). The sketch does the resetting and tells the host which names went back (resetParameters(firesnamed: ) parametersReset), one route for the Mac inspector, the remote surface, and a sketch's own call, so the session's tuned store follows every one of them: the names leaveparamValues(andtunedNames, kept observable where the values are not, so the marks move), the row stops reading as tuned, the save button skips it, and the next reload takes the file's value. Nothing else moves: no reload, nosetup(), the same sketch instance, so the clock, the seed, and an accumulating canvas carry on, a value onlysetup()read keeps whatsetup()built from it, and an automation track wins its parameter again on the next frame. Inspector: a 5-pt accent dot after the name on tuned rows only (a click resets that row), Reset in every row's context menu (the keyframe diamond keeps its own menu, since the nearer one wins under the pointer), Reset on a group header once one of its rows is turned, and Reset all beside the save button (every parameter, tuned or moved by a wire); the action reaches the twelve row kinds through a private environment value, so no row kind threads it. The detached panel and the gallery, which keep no tuned record, show no marks and offer no reset. The remote page's Reset all sends{"kind":("reset"} namesfor a few), queued and applied at the frame boundary like a set. Command-Z and Shift-Command-Z stop at the canvas (OllinMTKView): a host with nothing to undo left the pair unclaimed and AppKit handed it to the first responder, so a sketch's.isUndoKey keyPressed()read a plainz(the material explorer advanced its preset under an undo the inspector never offered); other Command combinations still reach the sketch.ParamTests(+2),ParamResetTests,UndoKeyTests,RemoteWireTests(+1), and two--sessiontestphases (tune, reset, the name gone, the run unmoved, a reload after a reset taking the edited file's value, reset all; and under a runner, a reset under a track with the frame and the clock held and the track winning back).Docs/§ Putting a parameter back; Guide Ch 1 § Saving the values you tuned.Helpers/ Parameters .md The generated API reference (
.spi.yml+Sources/+Ollin/ Ollin .docc/ Ollin .md Scripts/api-docs.sh). Every public symbol of the 22 library modules as a DocC page, written from the source itself and hosted by the Swift Package Index for the modules.spi.ymlnames. The writtenDocs/pages stay the curated reference and this is the completeness net under them. Load-bearing: the catalog is the core's landing page and curates all 470 of its top-level names into 18 groups, because uncurated DocC sorts 4,618 declarations by kind and the page reads as a wall; no DocC plugin is a dependency (the index injects its own, and a plugin dependency is resolved by everybody who depends on Ollin), so the script drivesswift package dump-symbol-graphplusdocc convertdirectly, and it is that one dump rather thanswift build --target X -Xswiftc -emit-symbol-graph, since a warm build recompiles nothing and emits no graph at all. The dump builds in a folder of its own (--scratch-path, about 3 GB): it compiles the whole package under other flags, so in the main build folder it recompiled everything on every run and the next ordinary build there recompiled everything back (207 s of every preflight, found 2026-11-10), and the graphs are read from where the command says it wrote them..build/ symbolgraph .spi.ymlhas a 1,500 byte ceiling (SPIManifest's ownmaxByteSize), so it carries the target list and nothing else. The script fails on a warning, and on a library product missing from.spi.yml(which is how the two stay in step, and it caughtOllinSamplePhotosthe first time it ran), which is what makes it the only gate here that reads a doc comment: it found 40 on its first run, every one invisible to every other gate (a link at a symbol that had gone, and parameters still documented under the names the naming sweep dropped,intensityforamount,rotationforangle,strengthforamount). CoreGraphics is re-exported, so the standard math functions appear in the generated surface and the landing page says why. InScripts/on a framework change, about a minute and a half warm; no pixel snapshot (the output is pages).preflight .sh Names in the prose are real (
Scripts/+check-names .sh Scripts/, on everycheck-names-allow .txt preflightrun; ~2 s). The gate for the defect the 2026-09-12 review found by hand: a rename sweeps the code and leaves the prose behind, and nothing else reads an inline backtick (the snippets never used the name, the links still resolve, a grep still hits the prose itself). It reads every code span inDocs/,Guide/, the root README and this file, with fenced blocks set aside, against an oracle of every identifier in every tracked code file, every tracked path and its components, and the public surface underAPI/; a page's own fenced Swift widens the oracle by the names it defines, a fenced shell or text block by every word. Six checks: (1) every identifier in a span exists somewhere in the oracle (arguments inside parentheses, quoted strings, hex colors, andMy…/Your…placeholders are the reader's; a trailing-underscore or glob prefix matches by prefix); (2) a call written with labels (.bloom() matches a public overload by name and by label in order, with omissions allowed and a variadic taking a run,threshold: amount: radius: ) Type.namelooked up on the type when Ollin declares it and left alone when the platform does (String(describing:)), and the contributor files also allowed an internal declaration fromSources/; (3) a flag such as--export-exris spelled by a host, a script, or a workflow (the extensionless wrappers included); (4) a repository path exists, aGroup/Namenames an example at either level of the two-level catalog, and a.md#anchorlands on a heading or an explicit<a id>, for backticked spans and for the bareDocs//Guide/pointers in this file,CLAUDE.md,DESIGN-NOTES.md,ROADMAP.md,ARCHITECTURE.md,AGENTS.mdand the Guide's PLAN and AUTHORING pages, none of whichcheck-linksreads; (5) Appendix D's Contents line lists its sections in order; (6) every bullet here that names aDocs/page is findable in Appendix D by a stemmed word of its name (a bullet with noDocs/page is internal and only noted). What it cannot see: a stale name whose spelling survives as an unrelated identifier (physarum(agents:) after the facade becamemakePhysarum, while physarum lives on as a variable) and a call written without labels, which is why prose about a call writes the selector with its labels. The allowlist holds foreign names only, one per line under its class (p5, Processing, openFrameworks and OPENRNDR outside the comparison tables of Appendices C and E, whose foreign first column is skipped by construction; Apple types the code never spells as an identifier; tools and shells; techniques cited by another library's spelling; notation): a name that used to be Ollin's is never allowed, the prose is fixed. First run found 70-odd stale names (intensity/strengthwhere the label isamount, theminimum…/maximum…family after the min/max rule, themake…facades, addStaticColliders foraddStaticBodies, aframeRenderedhook written without itsimage:label, a mesh loader written without itswithExtension:label) and 31 hand-written anchors in this file that resolve only through the<a id>tags the Docs pages carry. Sabotage-verified red on a stale selector, a misspelled identifier, a dead anchor, and a dead flag planted in one page, all four reported by line. No tests of its own beyond that;--listprints every note.The surface holds its names (
Scripts/+check-api-names .sh Scripts/, on everycheck-api-names-allow .txt preflightrun; under a second). The naming pass's settled rules as a lint over the listings underAPI/: limits aremin…/max…;intensityonly where the type or name says light; a resource-making method ismake…and a value-type dot static stays bare; a scalarBoolproperty reads as a third-person assertion or asis…/has…/wants…;advance(by:)againststep(_:); a loader spellswithExtension:and itsin:bundle takes no default; a publicseed:isInt(a Filter/Generator/Sim shader seed staysDouble, a generator's state wordUInt64); a highlight exponent ends in Sharpness (specularSharpness); Sketch hooks are past tense, its geometry calls carrydraw, its stack ispushState/popState;knobnever appears; the value vocabulary isnumber/int/text/bool; a destination is aStringpath (a URL overload beside the String form passes);start()reportsisRunning,connect()isConnectedand is undone bydisconnect(); a Boolean label is a participle or an assertion, never a bare order (inverted:, notinvert:);update…is not a house verb (a per-frame advance isadvance(by:)/advance(to:), a discrete run isstep…); a no-argument listing of what the system has isavailable…(). Load-bearing: it reads the listings, never the tree, so it sees exactly whatapi-surfacerecorded; an allow entry that matches nothing fails, so the list cannot outlive its exceptions; a name that is Ollin's own drift is renamed (pre-1.0, no shim, named in the changelog), never listed. Its first run found 53 (ten.sh --record minimum…/maximum…names, twenty-fourUInt64seeds, seven bare-adjective Booleans, five URL-only writers, anextension:label, twointensityeffect amounts, a timeline step with a labeled count, two ping-pongadvance()s, a SyphonisActive/stop()), all renamed the same day. The read-for-meaning pass the lint cannot do runs beside it (2026-09-16, the whole surface read against its own doc comments): it found twelve GPU sims spelledupdate…whose every doc comment began "Step … one frame", aset(_:)on four smoothed values whose act is jumping (assignment already sets, and glides), aring(that returns a random point and collides in spelling with theinnerRadius: outerRadius: ) SDF.ringthat is one, anindex:for a refractive index beside theior:every other surface spells, five bare-order Boolean labels, astrengthfading an effect, two Core MIDI listings and a screen-capture one that ask the system on every call, and oneEasinglabel spelled two ways. Those three classes became rules here, so they cannot come back. The second such pass read the satellites (2026-09-19, module by module rather than whole-surface, since the first had read the core): twenty-nine names moved, and the classes it found are ones a lint over a listing cannot see at all, because each needs the implementation read beside the name. A magnitude named for the wrong axis: a hearing range over what is a distance, a bare scatter besidepositionJitterandpitchSpread, a wavetable's length over one cycle's samples, nowhearingDistance,timingJitterandsamplesPerCycle. A word the same module already spends on something else (labelsfor scored results where a vocabulary islabelstwo types away,notefor a roundedPitchwhereNoteis a type,spinfor an angle where the framework'sspinis a rate). A name that asserts more than the value holds: an isConnected reporting that points are playing, a standard lookup answering for uncatalogued values too, an isValid checking a filter rather than a topic, a confidence over a softmax share that sums to one across a set, nowisPlaying,known(for:),isValidFilter(_:)andshare(of:). A unit that lives only in a doc comment: a sampling interval taken as milliseconds in anInt, nowsampleEvery(. And a loose match under the exact-match label, which the lint cannot judge because both spellings are legal: a Bluetooth device and a window were both found by substring under a_ seconds: Double) named:-shaped label, and both now takematching:. Its other half settled how a failure is reported (the rule is inCLAUDE.md), which no listing shows either, since a signature cannot say what a body does with its failure; the violations it fixed and the ones it left are named in the changelog and under Developer experience inDESIGN-NOTES.md. No pixel snapshot (the output is text).API/README.md.The surface reads as a version (
Scripts/api-diff.sh+Scripts/api-diff.py, on everypreflightrun with a framework orAPI/change; pure text, under a second). The listings underAPI/at two points (the last tag against the tree by default;--from/--toany two refs) read as what changed, what it costs, and whether the shim rule holds. Load-bearing: a line is keyed by its container's kind and name, never its head line, so a type that gains a conformance does not move every member under it; a removal is paired with an addition in the same container before either is reported alone, surest first (the same name with other labels or types is changed, the same types under another name renamed, the leftovers paired on the name alone, one inside the other or mostly alike, and said to be likely on their line, since pairing whole lines matched any two short declarations on their keyword); a removed type folds its members into itself and a removed type whose members reappear under another name is a renamed type; a member whose text, with the type's name read asSelf, sits under a protocol the type now conforms to is moved, not removed, the protocol the type gained preferred when several supply it (the 0.8.0Vectorprotocol: 24 lines a plain diff calls removed); a member a standard-library protocol still supplies is moved too, found in theSTANDARDtable inapi-diff.py(whatSequence, theCollectionfamily,Equatable,Hashable,Comparable,Identifiable,CustomStringConvertibleand the string literals give a conforming type), read whenever the type conforms at the end (a type that was a collection all along and drops its ownisEmptybreaks no call site either) and never while it still declares that name and labels (that is a change, and the pairing reports it);Self,Element,Indexand the literal types are read off the type's own listing at the end, and a placeholder it does not settle matches nothing, so a gap in the reading reports a removal and never a move; the table leaves out every member whose meaning a type may own (contains(_:), sinceContour's is a hit test and the library's a membership test, plusmin()/max()/sorted()/reversed()andrandomElement()/shuffled(), which draw from the system generator where a seeded sketch draws from its own);--selftestcompiles one call per table line against a type that declares only its protocol's requirements, each binding its resultinoutto the claimed type, which admits no conversion (a plainlet x: T? =passed a plantedremoveLast(by optional promotion); a type head that only gains is extended, an addition, and one that drops a conformance or changes its generic clause is a change. The bump follows the from-version's major: at zero any public change is a minor and a release with no public change a patch; from 1.0 a removal of any kind is a major, an addition or a deprecation a minor. The shim rule reads as: a line present at the start, gone at the end, and not deprecated at the start is a violation; a line deprecated at the start and gone at the end finished its grace cycle, allowed by the rule and still a major. Before 1.0 the violations are a count in the summary and the run exits clean; from 1.0 on, or under) -> Element? --strict, they fail (--warnforces the count). A second rule reads the tree in either era: every@available(in a module lives in*, deprecated Sources/and carries<Module>/ Deprecations .swift renamed:ormessage:, so the shims are audited in one place and every one offers the fix-it (the one shim that existed,CameraView.corner, moved there).--changelogprints the entry's skeleton in the changelog's own "oldisnew" form (an Added bullet per new type and per container with new members, a Changed bullet per rename, signature change, move and removal, a Deprecated bullet per shim with its replacement), for a person to group and explain; the facade's own members print bare, everything else qualified by its type. Measured: 0.7.0 against 0.8.0 reads 23 renamed, 35 changed, 24 moved, 3 extended and 60 removals with no twin, and every rename in that release's Changed section lands on one skeleton line; a listing line deleted by hand goes red under--strictnaming the selector and is counted under--warn; aBaggainingCollectionand droppingcount/first/isEmptyread asBag.countisBag.endIndex, a major and three shim violations before the table, and reads as three moves, a minor, and a holding rule with it; five planted table lines go red, each named; no release pair from 0.1.0 to 0.10.0 reads differently, except that the rename count stopped counting a type that only gained conformances (0.9.0 to 0.10.0 said six renames, all six such types).--selftestruns fixtures for every class first on each preflight, so a change to the reader cannot pass on a wrong reading. No pixel snapshot (the output is text).API/README.md.Every public name has a page (
Scripts/+check-api-pages .sh Scripts/, on everycheck-api-pages-allow .txt preflightrun; a couple of seconds). The reverse ofcheck-names.sh: that one reads a backtick in the prose back to the tree, this one reads every declaration underAPI/forward to the reference, and asks whether any page names it. Nothing did that before, and nothing could, because every other gate starts from the pages:check-linkswalks the navigation,check-snippetscompiles the fences,guide-coveragecounts the matrix rows,api-docsbuilds the generated reference from the doc comments. A public name no page mentions was invisible to all five, which is howMesh.klein,Material,.rimSharpness Installation,.Projection MPEZoneandController.dpadshipped with nothing written about them anywhere. What counts as named: a type by its name in some page's code, where the code is the page's code spans, its fenced blocks, its headings, and a one-word bold run (- **roughness** runs from 0 to 1, which is how a page of settings names its fields); a member by.nameorname(anywhere in the reference, or by its bare name on a page that also spells its owner or one of that owner's ancestors. Three rules keep it from lying in either direction: a member ofSketchis looked up bare wherever it appears, since the facade is called with no receiver andkeyIsPressedlives on the Input page, which has no reason to spellSketch; a nested type counts when the reference names something under it, since a page writeschannel: .magnitudeand never spellsFourierChannel; and a type with no page swallows its members, so the gap is the page, reported once, not one line for each of forty-five members. Exempt by construction, each class named for the allow list: a member a declared conformance requires, Ollin's own public protocols included, read from the listing (Vectoris documented once and every conformer'scomponent(_:)is that same name); an operator, a subscript, andcallAsFunction, which have no identifier to write; a conformance typealias;wrappedValue/projectedValueon a property wrapper andbuildBlockand the rest on a result builder; an@objc overrideof a platform method; a deprecated shim; and an initializer of a type the reference hands over another way (amakeSwarm(count:), aLight.spot(…), a documented property that already holds one). Everything else deliberately bare is listed with its reason inScripts/, by dotted path, by glob, or by the source file that declares it, which is the honest form for a whole tier that is public because another module compiles against it: the phone, room, remote, laser and lighting wire protocols, the host types the inspector and the timeline are built from, and a catalog the reference names as a set (the 78 risograph inks, ARKit's 52 blend shapes, Vision's joints). An entry that matches nothing fails, so the list cannot outlive what it excuses; a name missing because the reference is a page short is never listed, the page is written. First run: 1,198 gaps. 542 were the wire and host tiers and the catalogs, allowed in 27 lines; the other 656 were written into 89 pages, among themcheck-api-pages-allow .txt Mesh's whole generator list,Material's rim and gooch and subsurface colors,StrokeFont's metrics,FrameProfile's ten counters,ScanGraph.Settings' ten,Installation's projection and schedule,Take.Event's nine cases,SwarmChemistry, every satellite's error type at the call that throws it, and a stale.Recipe minimumSize:label onRectangleDetectorthat no gate had caught. What it cannot see: whether the mention teaches anything (a name inside one fence is named, and the Guide's coverage matrix is where teaching is tracked), and two owners' members that share a spelling. Sabotage: a public func and a public type added to a listing with nothing written about them both go red, named by file and line. No pixel snapshot (the output is text).API/README.md.The changelog stays short enough to read (
Scripts/, on everycheck-changelog .sh preflightrun; milliseconds, with a--selftest). An entry, in every section of the file, is a bold title ending in a period and at most 60 words (link targets not counted): what changed, the call to type, what to do about a change, and a link to theDocs/page; an opening paragraph is 80 words at most; a bold line by itself groups a long list by area. Load-bearing: the measurements and a defect's cause stay on the reference page and in this file, never in the entry, because the release page is the same text (Scripts/); every section is read, the first release included (0.7.0 to 0.17.0 were rewritten in this form on 2026-11-19 and 0.1.0 to 0.6.0 on 2026-11-25, each with its release page, and a link in a published section must exist in the tree at that release's tag as well as today's, whichrelease-notes .py release-notes.pychecks before a page is regenerated); and a second thing to say is a second entry, never a longer one. The form was cut to two sentences once (2026-09-12) and had drifted back to a median of 91 words with one of 401 by 0.18.0, which is why it is a gate.The stranger's build (
Scripts/, at a release, by hand; a cold run is a clone plus a debug build, about two minutes on the M2). Every other gate reads this repository, so nothing exercised the one route somebody else takes: a line in a manifest, a tag fetched from GitHub, a framework that has to build from that checkout alone and draw. The script generates what the generator writes for a stranger (release-smoke .sh ollin new --remote, amac-sketchpinned.upToNextMinor), points SwiftPM at a cache of its own so the fetch is a real clone rather than whatever the machine already holds, builds it, and renders one frame headless. Five tests, each printed as it passes: the tag exists on origin, because that is where SwiftPM looks; the manifest pins the published framework in the form the README tells a consumer to use; the resolve answers from that repository at a version on the pinned minor (a newer patch is the pin working); the build compiles with the dependency fetched rather than pathed; and the frame is the canvas the sketch declares with ink on it. The ink test is the one that would rot into a check of whether a file exists, since a framework that renders nothing still writes a file, so the frame is read back through ImageIO and a pixel counts as ink when it differs from the corner by more than two levels;--selftestruns that reader against a blank fixture and an inked one and refuses the run if the blank one passes. What it catches that a green tree cannot: a resource left out of a target, a product that is not public, a tag never pushed, a manifest naming a version nobody published, a dependency reachable only from this machine. When it runs: the tag has to be on the remote, so before a release it is a rehearsal against the tag already out there and the proof for a release comes right after its tag is pushed.--template/--withwiden what the project pulls in,--warm-cachemakes a re-run quick, and the honest run is the cold one. Green on 0.8.0 (twice, the same 3,936 inked pixels); red on an unpublished tag and on a blank frame. No pixel snapshot (the output is a report). Contributing.The suite runs in an order that keeps it honest (
Scripts/test.sh+Scripts/+shard-tests .sh Tests/README.md). One rule decides the order: a suite that measures the outside world against a clock, or that holds a device or a name only one process can have, runs on a quiet machine; everything else runs together. Four lists are its cases (sensitivethe wall-clock and device suites,loopbackthe ones talking to a real system service,crowdedthe ones that cannot share the machine with the drawing shards,runnerwhat CI cannot do at all), and the desk'sshardrun now uses the same quiet phase the runner's recipe does (four phases: the device suites, then the loopback and crowded ones, thenOllinTestsacross four processes, then every other target). On the runner the recipe is spread over machines (.github/, since 2026-11-13): one job compiles and saves the build to the cache, four machines restore that exact build and each run a share (workflows/ build .yml Scripts/,test .sh ci 1/ 3 2/3,3/3are nine shards ofOllinTestsdealt byOLLIN_SHARD_PART,ci restis every other target), and the examples compile beside them, so a push is answered in about 28 minutes where it took 76 to 93. Three rules hold it up: every machine makes the same deal from the bundle's listing alone and is held to the count of its own shards; the required checkBuild (macOS)is a one-line job that passes only when the compile and every share passed, so the ruleset never learns the matrix; and five macOS jobs is the account's limit, which the examples and the four shares fill, so a fifth share waits in the queue instead of helping. Load-bearing:.serializedorders one suite's tests and says nothing about a sibling, so two suites sharing a machine-global name still collide; Core MIDI is that case (the endpoints are global and an input connects to every source), and both loopback suites are therefore nested under one serialized parent (CoreMIDILoopback), the trait being recursive. A phase only helps a suite competing with other targets: one that fails while running alone has a defect, and the four measured non-load failures (a suite starving inside its own target, a parked cooperative pool, a deadline read before its probe, a main-actor hop from a nonisolated suite) are written down beside the rule rather than re-derived.Tests/README.mdis where a new test's placement is decided;Scripts/test.shnames the lists and points there. The handoffs run under Thread Sanitizer (Scripts/, a milestone checktest .sh tsan preflightruns, never a per-commit gate, by cost): every target whose tests run without the GPU (the wires, the phone's codecs and readers, the audio engine, the mutation harness, the two feeds), built with.sh --milestone --sanitize=threadinto.build/tsanso no object is shared with the plain build; the reports go to files (log_path) and print after the run, and any report fails it whatever the tests said, since the sanitizer sets its exit status only when its runtime finalizes. The drawing suites stay out (a render's threads are Metal's, uninstrumented; a snapshot compares pixels; a drawing suite is main-actor bound, so the slowdown lands on the one thread it waits on). One class of report is excused inScripts/, an ordering that runs through a system framework the sanitizer cannot see into (Core MIDI moves the receive block to its thread over a lock-free queue in its C++ runtime, so the initializer's stores report against the callback's reads), by the narrowest frame (tsan-suppressions .txt MIDIInput.init) so a real race on the same object still reports; a race in Ollin's own handoff is fixed in the source, never listed. The child an exit test spawns does not come up under the sanitizer, so the harness's dying-case self-test refuses itself there (underThreadSanitizer, read off the loaded images). Measured 2026-09-23 on the 8 GB M2: the cold instrumented build 3m51s at a 1.7 GB peak, the run 9m28s for 1,310 tests over 17 bundles (four minutes of it the listing, each bundle loaded twice under the sanitizer), free memory never under 2.4 GB, 5.7 GB of disk. A planted race (the serial port's descriptor store read byisOpenwithout its lock) reported at both lines; the committed tree reports nothing. No pixel snapshot (the output is the run).What the tests reach (
Scripts/+test .sh coverage Scripts/;host-gates .sh Tests/README.md§ Coverage, and the hosts' own gates). A reading tool, never a gate and never a percentage target: the shard run's four phases and every host gate under an instrumented build, one report by file in.build/coverage/(report.txt,summary.json,merged.profdataforllvm-cov show). Load-bearing: it builds in place (a second whole build under its own scratch path is 13 GB), so the next plain build recompiles everything, about four minutes; every process writes its own profile (%p-%m) and they merge once at the end, becauseswift test --enable-code-coveragesets its own path and clears it at the start of every invocation, so the phases run plain--skip-buildover the instrumented products; a failing test still counts what it ran. The report reads every test bundle and every host executable and leaves outTests/,External/,Examples/, and.build. What a read cannot see: a path the desk's device never takes (the raster point-light shadow runs only without ray tracing, which the CI runner has and the desk does not). The hosts test themselves through flags of their binaries that noswift testreaches (OllinLive's five, OllinLiveCoding's four, OllinRun's, the generator's--stagetest, the gallery's--cycletest);host-gates.shruns the eleven in about 71 s and the gallery's cycle with--all(about two minutes more), on everypreflightthat touches a host orOllinRuntime, with--allon a gallery change and at a milestone. First read, 2026-10-10: 83.2% of 186,385 lines (78.6% before the host gates counted), the coreOllinmodule 86.7%; what stays unreached is mostly SwiftUI views, device and network backends, and the command fronts the scripts drive.Bytes off a wire never trap (
Tests/, theOllinMutation/ Mutation .swift OllinMutationtarget, Foundation only, a regular target underTests/like the browser gate;Tests/, one suite per wire, 35 tests, GPU-free, about 17 s in the quick pass; the section inOllinMutationTests/ Tests/README.md). A seeded mutation harness over every decoder that reads a network or a cable: OSC packets and bundles, TUIO, the OSCQuery message and request routes, MQTT and its remaining-length field, Link datagrams and the engine that acts on them, the phone wire both ways and the picture framing, the room's frames, the HTTP head and the WebSocket frames of the remote surface, MIDI bytes and words and the timecode walk, Art-Net and sACN and the receiver, the Record3D stream and codec, the usbmux reply, Firmata, the serial line assembler, the Bluetooth formats. The one invariant: every case returns a value, returnsnil, or throws; a trap is the failure. The case list per seed is fixed (MutationRun.run): the seed itself (a seed that does not decode is reported inseedsRefused, since it tests nothing), the empty input, every truncation (a spread of 288 past 512 bytes), the field sweep (every value inMutatorat widths 1, 2, 4 and 8 in both byte orders at every offset in the first 128 bytes and the last 32, which is where the length fields live and what found four of the seven), then.extremes( width: ) countrandom mutations of one to three stacked edits (truncate, flip a bit or a byte, splice, insert, delete, an extreme field, swap, repeat a run, and.decimal, a number as text such as1e300ornanwritten over a run of digits, the edit for a protocol that carries numbers as words, which found the MQTT one). A trap ends the process, so the log is the proof:MutationLogwrites the case about to run (name, seed, case number, the bytes in hex) withpwriteandftruncatebefore every call and removes the file when the run completes, so a log under$TMPDIR/always means a run that died and holds the input that killed it; the harness's own exit test (ollin-mutation/ #expect() runs an unsafe decoder in a child process and reads the dying case back from the child's log, which the child shares throughprocessExitsWith: ) $TMPDIR. Seven traps found by the harness and six by the reading pass beside it, all fixed by the failure rule: a one-byte Firmata command (a program change) read a second data byte; a number off a wire narrowed withInt(_:)in nine places (OSCArgument.int,MQTTMessage.intandint(named:),RoomValue.int,Int.restored(_:), the OSCQuery stepper and menu apply, the remote menu apply, andTable.int, a file's), which now go through the packageDouble(.int( rounded: ) Sources/:Ollin/ Math/ Narrowing .swift nilwhen not finite or too large, the house rule for any number that arrived from outside); a WebSocket length one short ofInt.maxoverflowed the check that added to it (a frame pastmaxFrameBytes, 1 MiB, drops the connection); a Link beat or time pastLinkWire(2^50) overflowed the join's tempo math (the entry is skipped at the parser like one of the wrong size); a phone depth, matte, saliency or flow grid whose width times height overflows an.maxMagnitude Int, which every reader multiplies, is refused by its decoder (gridFits). What ran clean: every packet decoder proper, the phone's 18 message and 4 request decoders and the picture framing, both DMX formats and the receiver, the Record3D header and codec, MIDI and the timecode engine, the line assembler, the Bluetooth formats, the usbmux plist. Gotchas: a stateful reader under the harness is fresh per case or small (a room that kept every mutated block rebuilt a mesh of thousands per case, 439 s for one test); a decoder reached only through state (the Link pong, which lands on a measurement in flight) has that state set up in the closure; a message a stream parser reads as nothing (Firmata's protocol version) is not a seed; a run over a large input passessweeps: false, since the sweep is offsets times 121 values times a hex line of the whole input. The readers of files run under the same harness; see Bytes in a file never trap.Bytes in a file never trap (
Tests/, nine file suites beside the wire ones, 72 tests in the target, about two and a half minutes in parallel;OllinMutationTests/ Tests/README.md§ Files, and what a file declares). The wire harness over every reader of a file a sketch is handed:.cubelooks, palettes (hex lines, CSV, TSV, JSON, ASE), ICC profiles, takes, automations, cue sheets, formula text, Standard MIDI Files, IES profiles, SVG, glTF and GLB, OBJ and its material, PLY and STL (through Model I/O), USD as text, crate, and package,.r3drecordings, sound files (WAV, AIFF, CAF) through every loader, SFZ instruments, the GLSL importer, the shader include resolver, tables, JSON, and physics snapshots (whole, and the payload mutated and sealed again with a matching checksum so the edits reach the body readers). Each case is read the way a sketch reads it (a scene posed by its skins and morphs and animated across its length, a palette's colors turned through hue, a take stepped on a sketch, an instrument played). Two added invariants. The declared-size class: a count or a size in a file is checked against the bytes that remain before anything is set aside;MutationRunwatches the largest single block the decoding thread asks for through the allocator's logging hook (.run( allocations: ) AllocationWatch, C inCOllinAllocationWatch, since the hook runs inside the allocator and generic Swift allocates in a debug build) and names every case over itsAllocationBound, while a block past a gigabyte stops the process before it can be filled; the self-test's reserve-first twin goes red and its check-first twin stays green, and the.cubereader'sreserveCapacity(was the first real case (265 MB for an 856-byte file). The depth class: an input nested past a reader's limit is refused or read to the limit, never recursed until the stack runs out, measured inLUT_3D_SIZE³) DeepInputTestson a 512 KB stack (a background thread's, where a debug build's frames are large), and on 256 KB for a scene: a scene nests at most 256 levels in both formats (Scene.maxDepth, whichGLTFDocumentand.maxNodeDepth USDStage.maxDepthread), and every walk of a loaded scene keeps its pending nodes on a list (Scene.walk,Scene.visitWorlds,Scene.first,Scene.mutateFirst,Scene.mutateAll, the draw, the USD writer'sprimitiveTrees, the USD prim walks, and both readers' tree builders), so no code of Ollin's spends stack on a level. What does is the runtime's own release of a nested value when the scene is dropped, on whatever thread drops it last: the array destroy of each node's children runs inside the node's own destructor, about 440 bytes a level in the standard library's frames (measured from the frame pointers under lldb), which no walk removes and which is the same under any compiler of Ollin's code; a 1,024-deep tree took 450 KB to release, more than a background thread holds, so the limit is checked against that teardown: a scene at the limit is parsed, built, walked, merged, written out, and dropped on 256 KB, half a background thread's stack, and a stage one level past it is refused. A USD value (a dictionary in a dictionary, a tuple in an array) nests at most 64 levels (USDStage), since the value readers do recurse; a formula at most 1,024 tokens nested 64 deep. The glTF and USD scene builders never recurse while holding a node (a node is a large value: the recursing builders took 13 and 20 KB a level, so a 40-deep glTF or a 26-deep USD stage loaded on a background thread already overflowed); the automation plan walks its tracks with a stack of its own. Plus the text sweep (.maxValueDepth numberSweep:, every number in a text input replaced by each ofMutator), the named-file rule (.numberSpellings NamedFile.data(at:)/NamedFile.text(at:), package: a path a file names is read only when it is a regular file, so a model, a material, or a shader include naming/dev/zerois refused), and one mesh promise checked beside the no-trap invariant: a loaded mesh never names a vertex it does not have (GLTFDocumentdrops such a triangle; Model I/O's own normal generation is asked for only when every triangle fits). What the harness and the reading found, all fixed: by the harness, a NaN ASE swatch trapping in.triangles( _: vertexCount: ) Color(hue:), a curve of infinite length trappingPath's flattener (an SVGtranslate(1e999 …)),noise()at a coordinate past 2^63 (an automation looping over a 9.2e18-second length), a glTF node listing itself as a child, a PLY face index Model I/O's normals read past, a binary STL declaring four billion triangles (Model I/O asked for more than a gigabyte in one block before reading one), a negative USD face count, a USD text integer pastInt64, a crate section count pastInt.max, zip entries declaring gigabytes (.r3dand USDZ inflate, now held to deflate's 1032 to one), a CAF packet size of four gigabytes that ExtAudioFile sets aside a buffer for on opening,JSON.inton1e300, and in snapshots a 4 GB declared payload, an infinite ground, a velocity past what Jolt's single precision squares, 32-bit group and skin indices, and the bridge destroying a body Jolt never created; by reading, the glTF accessor arithmetic (negative indices, offsets that overflow, a buffer-less accessor's declared count,base + idxand out-of-range triangles), the crate reader's declared counts and LZ4 capacities and an exponential path walk, the SVG arc's narrowing, the audio loaders allocating a header's declared length (AudioFileFramesnow reads a stretch at a time and checks the rate, and the channel count againstmaxChannels, 1,024, the most the system's reader converts, before any buffer is made: a WAV declaring 32,768 made macOS 26's buffer initializer throw a C++ exception that no Swift code can catch; a stretch shrinks with the channels so its buffer stays at 4 MB), SFZ keys, tunings, and loop points past their ranges, and snapshot skin, ragdoll, and rope indices Jolt takes unchecked. What ran clean: MIDI, IES, takes, cue sheets, formula values, the GLSL importer, the include resolver, tables, ICC. Stays out: stepping a restored physics world, since Jolt's debug build asserts on configurations a world built by hand reaches too; Every loader fails one way: a file, a resource, or bytes handed toImage,Mesh,Scene,SVG,Palette,Table,JSON,IESProfile,ICCProfile, the three fonts, orComputeKernel(and theirload…sugar) throws aFileError(missingfor a path or resource that is not there,unreadablefor bytes that are not the format, with the path and a sentence), and the mesh and scene writers throwunwritablewhere they returnedfalseand printed; a name lookup (OutlineFont(name:)) and a wire packet staynil, since therenilmeans "not one of these" (FileErrorTests).Same seed, same pixels (
Scripts/+check-determinism .sh Scripts/; inexample-devices .zsh preflight, never a per-commit gate; 69 minutes for 671 examples on the M2 with the GPU to itself, 2026-11-13). Every example that runs alone is exported twice, in two separate processes, at the frame its media still is taken at (the manifest's.sh --milestone frame, else 480) under--seed 7 --photo, through the releaseOllinLiveloose-file route (no examples build), and the two pictures are compared by bytes, then by decoded pixels. Load-bearing: two processes, never two renders in one, because aSetorDictionarywalks its keys in an order hashed afresh per process (the self-test'sSetwalk is red across processes); the device hold rule lives inexample-devices.zsh, shared withmedia.sh, so a new device library is learned once;LIVE_WORLD(a live feed, today's weather) andOVER_UDP(the DMX and OSC loopbacks, whose frame draws whichever packet had landed) are held with their reasons, an example inRUNS_ALONE(it plays its own far end: a virtual MIDI source, a stand-in tracker, a dancer of its own) is checked like any other,NOT_EXACTholds the one detector that answers identical frames differently (TrajectoryTracking: Vision's trajectory fit varies a few millionths run to run, and over 900 frames that sometimes changes which sightings join an arc), two surfaces at one distance along a traced ray come out one way since 2026-11-29 (the 3D bullet's tie rule; before it a reflection could differ by a pixel between processes, the one difference three milestones each read once, and a glass block cut into touching pieces by thousands), and a sketch importingOllinVisionis checked like any other since 2026-10-02 (an export reads its detectors on its own clock; see Computer vision), where its difference used to be reported as filed; a "same" is not proof a detector answered: before that day most vision examples matched only because neither run had an answer, so read the pictures when a detector path changes; the render watcher reaps its ownsleep.--selftestplants aDate()read and aSetwalk (both red) beside four that must stay green: the same drawing from the seeded generator, a solid cut into touching pieces under the bounce, the same solid in glass under a traced reflection, and boxes doubled in one place over a mirror (the last three red with the opaque traversal planted back), 30 s.--stills DIRkeeps every example's first picture, which under--seed 1is the frame its still on the site was taken at, drawn by the framework as it is that day:Scripts/reads those against the hosted stills to say whose picture is out of date (the measure and its limits are inmedia-moved .py ARCHITECTURE.md§ Example media), so one pass answers both questions. The pass of 2026-11-29 (702 examples, 83 minutes,--seed 1): 652 the same, 50 held, none differed, none drew nothing, the first with nothing differing. What the first pass found (594 examples; 522 the same, 52 held, 1 too slow, 19 differed), each fixed at its cause: GPU work whose result followed thread arrival (theSpatialHashscatter under seven sims, the caustic photon append, theMeshFieldcull append; each now ordered underDrawer, true for an export or a playing take and false live and under.runsOnFixedClock --benchviaOllinApp, so a live frame never pays for an order no wall clock can use), four examples that opened the machine's camera under.isBenchmarking --photo(Camera.start()now throws there; the examples takeCamera.orStill), two live-world examples (held), and seven detector examples (filed then, fixed 2026-10-02 barTrajectoryTracking). No example read the wall clock or the system's dice where it mattered, bar one stand-in camera's launcher (seeded). A sort or a pick by a dictionary's values needs a rule for the tie, or two equal values come in the order that process hashed them: the pass of 2026-11-13 (619 the same, 50 held, 2 differed) foundVision/'s caption listing two tied counts either way round, and the same sort inObjectDetection Vision/SceneLabelsandPhoneFacewent with it (a tie goes by name, or by the listed order)..strongestBlendShapes The code in the prose compiles (
Scripts/, thecheck-snippets .sh OllinGuideSnippetstool,Guide/+Snippets/ known-gaps .txt Docs/; on a prose or framework change inSnippets/ known-gaps .txt preflight; about two minutes when every block compiles, seconds when little changed). Every Swift block in the Guide's chapters and in the reference pages underDocs/is wrapped by shape (a whole file as written, a declaration under an import, a fragment inside a probe sketch with members and statements told apart) and typechecked throughSketchLoaderagainst the built framework, across the cores. Load-bearing: a fragment that cannot stand alone is recorded, keyed on its own text, with the first error it gives, and the gate fails on a change (a block that starts failing, an error that becomes a different one, a recorded block that now compiles), which is what turns a public rename into a failure here instead of a reader's problem; the two trees keep separate gap lists and per-page preambles (Guide/,Snippets/ <chapter> .swift Docs/, the Docs key dashed because three pages share a stem); a block's imports are its own page's (Foundation, the preamble's, and any a block on that page writes), never a union across pages, since two chapters mean two types by one name (OllinPhysics' and OllinVision'sSnippets/ <Group>-<Page> .swift Body3D) and a union made both ambiguous, so a chapter's baseline never moves with another page's; a scoped--recordkeeps the lines of the pages it did not check; a block holding a bare...is illustration and passed over, and<!-- snippet:above a fence exempts one on purpose. Two name checks run with it: anskip why --> ollin docs Page#sectionin a shell block resolves to a real heading, and a backticked name beside anExamples/link names a real example. A block's answer is kept under a digest of what its compile read (Sources/, written toOllinGuideSnippets/ Remembered .swift .build/): the wrapped text, the compiler and the SDK, the checker's own sources, the C headers the module maps name (followed through their quoted includes, which is howsnippets/ results .json OllinShaderTypes.his in it), and the bytes of every module file its imports load, a list asked of the compiler once per distinct set of imports, so a run compiles only the blocks for which one of those moved. Nothing in it is guessed: a set of imports that does not all resolve, acanImporttest, or a module file that cannot be read back means no key and a compile every time, and only a real diagnostic is kept, never a compiler that died. A module file keeps its bytes across a change inside a function body, so such a change reuses every answer, and a change to one satellite's interface recompiles only the pages that import it (2,050 of the 2,918 blocks import the core alone).--no-cachecompiles every block, which a milestone does, and--inputslists what the digest covers. A block is compiled by the compiler process alone (DirectCompile.swift): through the loader a typecheck is four processes (the tool finder, the driver, the driver's question about the target, the compiler), so the driver is asked once, with-driver-print-jobs, for the command it would run for a probe compiled exactly asSketchLoadercompiles a block, and each block runs that command with its own file and module name in the probe's places, 1 min 44 s for all 2,918 against 2 min 26 s. A command of an unknown shape is not used; every twenty-fourth block a run compiles goes through the loader as well, and one disagreement throws the direct answers away and compiles everything through the loader (seen by planting a dropped flag: 6 of 122 sampled blocks disagreed, the verdict stayed right);.typecheck --compare-routescompiles every block both ways (0 of 2,918 differ) and--no-directis the loader alone. Each block's compile sits in its own autorelease pool (CompilePass.swift): the pipes to a compiler are let go only when a pool drains and the loop's threads never return to one, so without it the open files climb by about two a compile (3,731 after 84 s, against 33 throughout with the pool); a process here may hold 10,240, a run that compiled every block twice passed that near its end and could neither write a file nor start a process, and a single pass would have reached it at about 5,000 blocks. Checked by planting a rename (LinkClock.beat): the run that reused answers and a run that compiled everything reported the same three failures, on pages the diff never touched.Guide/AUTHORING.md§ The code in the prose.Checking the machine (
Sources/+ theOllin/ Core/ Doctor .swift OllinDoctortarget, behindollin doctor;Sources/+OllinCommandFlags/ CommandFlags .swift ShellCompletionsbehind.swift ollin completions;Sources/behindOllin/ Core/ ParamListing .swift --list-params). Three answers a broken setup otherwise gives somewhere else.ollin doctorreports the system against the 26 floor,swiftcand which one, the Metal device with ray tracing / mesh shaders / temporal scaling each said either way, the shader compiler asked by compiling (Ollin builds its library from source at start, so a findable compiler is not the question), whether theollinon thePATHis this checkout's, whether_ollinis on an fpath, and the camera / microphone / screen grants. Load-bearing: the report is the framework's (package, not public), so the tests read exactly what the command prints; every read is a preflight form that cannot raise a dialog (a doctor is run on a machine that is projecting); aproblemalways carries its fix line and is the only level that exits nonzero (a refused permission is a note, since it only stops a sketch that wants it); the CLI finds the checkout by walking up from its own executable to the directory holding bothPackage.swiftandScripts/ollin, since the build layouts differ. Completions:Scripts/is generated from one flag table (139 entries, each with scope, what follows it, and a one-line summary) and checked in, socompletions/ _ollin ollin installlinks it beside the command and agit pullcarries a new flag to the prompt; a flag a host spells with no table entry, a table entry nothing spells, and a stale_ollineach failScripts/(preflight), whose source set is the named list of files that parse a command line (a flag literal elsewhere belongs to git, xcodebuild, or a browser) with foreign flags inside those files listed incheck-flags .sh check-flags-allow; an internal flag is in the table marked.txt internalUserather than left out, so the table stays complete rather than curated. A value a flag may be left without takes zsh's::form, or offering it makes it required, and an apostrophe in a summary is closed and reopened ('\'') or it ends the quoting. A--paramvalue the parameter cannot hold (past its range, off its step, a list longer than the declaration) is refused by name, with the value it would have landed on and what the parameter takes, read back in the listing's spelling after the restore (ParamOverrideTests); the hosts' restore path still clamps and snaps, since a slider is a hand and a flag is a request, and a silent snap of.aValueTheParameterCannotHoldIsRefusedByName 12to10on a stepped parameter once rendered a twelve-second lap as ten and cost two sessions the investigation. A stepped value is the decimal its range and its step name (onGridonDouble, inMath/, the one snapDecimalGrid .swift Double.clamped, the bars row, and the web probe share): the sumlower + k * stepis rarely the number written (the 140th hundredth above 0.1 is 1.5000000000000002), and a value kept that way made the refusal above turn away every round decimal it landed on; the mark is read back at the digits of the longer of the two only when both are exactly short decimals, so a step of a third keeps its arithmetic bit for bit (ParamTests,.aSteppedValueIsTheDecimalItsStepNames ParamOverrideTests). The refusal counts a typed number as itself within a few rounding units of where it lands, so the sum's own spelling (.aRoundDecimalOnTheStepIsAccepted zoom=1.5000000000000002, in a listing or a command line written while a parameter held it) still asks for that step (ParamOverrideTests); and an old/new switch for such a change is never an environment variable when a sketch's picture is in question, since a variable nothing reads moved one sketch's late frame by itself (2026-11-11)..theSumThatFindsAStepIsAcceptedAsThatStep --list-paramsprints name / kind / value / what it accepts, grouped as the inspector groups its cards, aftersetup()and after any--param/--cue/--seedbeside it (so it describes that run), each value in the spelling--paramreads back and pinned by a round-trip test: exact for every kind but a color, which is said in hex and lands on the nearest 8-bit step.--help/-h(Core/,CommandLineHelp .swift CommandLineHelpTests4) prints the sketch's name, the usage line from the words before the first flag (a host's sketch file kept), that same listing without runningsetup()(the parameters by reflection, as declared, so no camera, model, or listener starts; ruled 2026-10-21), and every.runflag grouped from the shared table (Sources/, its own dependency-free target so the framework and the reference tools read one table without linking each other; the live hosts' group only when asked), and is read first inOllinCommandFlags runCommandLine, so it never opens a window, writes a file, or trips over the rest of the line (a planted miss turned all three checks red).DoctorTests(4) +ParamListingTests(5) +OllinReferenceTests(6);.CommandFlagsTests Docs/; Guide Ch 1 § What you need + Ch 1 § A shorter way to run things + Ch 45 § Passing the parameters back in.Tools/ Doctor .md The reference offline (
Sources/+ theOllinReference/ OllinDocscommand line, behindollin docs <topic>andollin examples <filter>). The written reference and the examples set read in the terminal, out of the checkout you build against, for anybody with no network or no wish to open a browser: a page by name / path / part of either,topic#headingfor one section,--searchacross every page, the examples with what each shows and the command that runs it,--sourceto print a sketch, andollin api <name>for one public name (every declaration it has from the listings underAPI/, each printed as its source writes it where it was found (the parameter names carry units,rotate(, and the defaults are real,_ radians: Double) phase: Double = 0; access level, the compiler-filled source-location parameters and the body dropped) and as the listing writes it otherwise, with the///comment above it inSources/and its file and line; then, per type the name sits on (the first three), up to three pages that write it as code and the three shortest examples that use it, each read the way that type's member is reached; a dotted name narrows by type from the inside out, a type lists its members (names only past sixty), a name nothing is called lists the public names containing it or a letter off it, two for a long one, fuzzy only when nothing matched exactly, and a bare name that is no sketch call leads with the sketch calls spelled like it, since a name carried from elsewhere can be a real member of another type (strokeWidthis an SVG element's; the call isstrokeWeight, found by the name's first camel-case word and ranked by the longest shared start). A source declaration pairs with one listing line only, so two lines the listing writes alike (one initializer for aParamOptionvalue and one forParamChoices) take their own declarations, each printed with what tells it apart: its extension'swhereclause, orrequirementinside a protocol. A type's page is ranked by how much the page writes it (an exact page name first), where a member's is ranked by a heading naming it, since a heading naming a type is as likely another page's section on binding it; and a type that finds no page or example by name is looked for through its cases and static members after an argument label the listing gives that type (style: .segmentedis aParamMenuStylebecause a call takesstyle:). Load-bearing: the folders are the truth about what exists and the indexes (ParamMenuStyle Docs/README.md, each category's ownREADME.md) are the truth about what each one is for, read separately so a page or a sketch added today is findable before anybody writes its line, and it simply arrives with none; the lookup runs exact → loose and stops at the first rank that finds anything, which is the whole reasoncoloranswers with the color page rather than the nine pages that mention color; a topic matching no page falls through to the search rather than failing, so a wrong guess still lands. Three renderer facts were defects first, found by rendering every page in the checkout in the test: the breadcrumb's---is dropped only when it is right under the trail (a page carries the trail and no rule, and hunting for one took the whole page with it); wrapped paragraphs are joined before anything is read (one page hard-wraps, splitting a link in half, and each half alone prints asfamily](#combining)), with fenced and four-space-indented lines never joined; and a page's title is the first#or##(both spellings are in the tree). Wrapping counts visible columns, so the escapes that color a line occupy none; plain output keeps an identifier's backticks and colored output drops them, since the color says the same thing. Example listings are read in both shapes the listings use (a category's table row, and the recreations' prose list under the artist, where the artist is the subject and a table would flatten that); the picture grid's name row is passed over (a row whose cells are nothing but links describes nothing, and it had described the first sketch of each grid row by its neighbors' names), and a row linkingSketch.swiftwins over one linking the folder. A search answers an exact name alone and unions everything looser in rank order (name prefix, folder, description, header credit, imports), socomplexlists ComplexPlane beside the sketches described as complex arithmetic rather than hiding them behind the name; the header credit (the//lines a sketch opens with, before its///documentation) is read into each entry, printed ascreditwhen it reads as one (Ported from,Inspired by,Recreation after,Based on), and searchable, so an article's author finds the sketches written after it.ExampleCatalogTestsreads every listing in the checkout for a description made of sibling names. The pager is the shell's job, not the command's (only the shell knows whether a person is looking), which is why.ownWords Scripts/ollinpipes into${PAGER:-less -FRX}and passes--colorthrough the pipe;--no-pager,--plain,--widthoverride, and a pipe gets plain text so--list | grepcomposes. It links no framework (OllinReferencedepends only onOllinProjects, forExampleSourcerather than a second walker), so the first run is a second or two..discover Scripts/ollinruns the reader straight from its build (0.08 s against 3.9 s throughswift run, which also holds the checkout's build lock, so a lookup through it waits out any build running there): a stamp at.build/records when it was last brought up to date, written at the time the build starts so an edit made during it still counts, and only a file under the reader's four source folders newer than the stamp builds again. The binary's own time cannot stand in for the stamp, because the build leaves a binary alone when a source changed and its output did not, and every lookup after would rebuild. A build that fails answers from the last one that worked, with a line on stderr, since a checkout shared with a session mid-edit still has pages to read.ollin-reference-<config> .checked ollin apipairs a listed declaration with its source by name, the types it sits in, and its argument labels (SourceComments): a reader for this tree's shape, not a Swift parser. It follows every brace outside strings (a shader held as Swift text has braces) and comments, and takes a declaration only at a type's member level or the top level, so a method's locals are never members; anextensionline never stands for the type's own declaration; a subscript's or an operator's parameter has no label unless it is given two names; acaselist may run over lines or sit on the enum's own line.APILookupTestspins that more than 99.9% of the public declarations are found (10,824 at the time), so a shape it cannot follow shows up as a drop rather than as comments quietly missing. A page counts as documenting a name only where it writes it as code in a Swift, Metal, or unlabeled fence, a code span, or a heading's code (a shell or output fence shows a lookup, not a use), and a member of a type other than.coverage Sketchcounts only reached with a dot, sotube:as a label is notMesh.tube. The commands print for a person; two maps serve a machine. No JSON and no server: whether Ollin runs a server of its own over these pages is the open question inROADMAP.mdunder A third-party extension ecosystem. What a machine gets is a map pointing at the same pages. The site writes one (below), andllms.txtat the checkout's root is its twin for a local assistant, written by the same generator (SiteBuilder, through the hidden.checkoutIndex OllinDocs llmsthatScripts/llms.shcalls): links are paths from the root, never addresses; a Start here section leads withDocs/andQuickReference .md Docs/Swift.md(neither sits under an index group, so neither would be listed otherwise), and the preamble names the three lookups by theirScripts/ollinspelling, which a site cannot run. A title's em dash is written as a colon in both maps. It is generated and committed, so every line derives from a page title, an index line, or a group, and an edit to any of them stales it:Scripts/is a standing preflight check for that reason, andllms .sh --check SiteTestspins that the committed file is current and that every link is a file in the checkout. The website (.checkoutIndex ollin site [folder],HTML.swift+Site.swift+SiteStyle.swiftin the same target, published by.github/) writes the same pages out as a static site: the README as the front page (its title and bold tagline lifted into a hero beside the ring, three cards, then part of the README, not all of it — its opening less the badge row and the navigation row the chrome stands in for, and the sectionsworkflows/ site .yml SiteHome.rowsnames by heading, Hello, circle / Run it / Install / What's in it, each in ahome-<slug>block the stylesheet lays out for the width of a page (Hello, circle is a.carouselrow rather than a.section, so its block ishome-band: the README's own program leads a band of sketches you page through, the rest named byshowcasein the manifest, each running beside the whole program that draws it. The band's heading is the site's own (Examples, carrying its own#examplesanchor as the README's sections do), since the README's heading names one sketch and cannot cover four; that heading is rendered a level down instead, inside the slide it came with, so it still names it and still carries#hello-circle, and every other slide is named by its example's own title. The run command under Run it names the sketch on screen: the page arrives spelling the README's own command, each slide carries the target that runs it, and the script rewrites that one word as you page. It is marked, never rewritten (the first occurrence of the lead's target in the first shown section that carries it), so the README's text stands untouched on the About page and in the markdown twin, and a README that changes its command simply keeps it. The moving is the browser's own (a snapping scroll container, so a swipe, a trackpad and the arrow keys work with the script off) and what the script adds is the buttons, the dots, and the rule that only the sketch on screen plays: the others carry neitherautoplaynor a preload, so a megabyte and a half is not fetched on arrival. One at a time is what puts the band back on a phone, where three stacked was a wall of code and the whole band had to be hidden), the spaced bullets of What's in it as a grid of cards, and a More about Ollin row linking every other section), the same README whole as the About page (about.html, kind.about, the same source file under a second site path;byRepoPathkeepsREADME.mdon the front page, aREADME.md#anchorlink from anywhere and a bare#anchoron the front page at a section it does not show both go to the About page, and the sidebar marks the current page by site path, since the two pages share a source), the Guide with the chapter list beside it, the reference with the index's groups beside it, every example on a page of its own with its highlighted source and the command that runs it, and the project pages the README links. Load-bearing: the site is a lens on the markdown, never a second copy (prose reaches the page exactly as the file spells it; only the chrome is the site's own); paths mirror the repository in lower case withREADME.mdas each folder'sindex.html, so every relative link resolves to the same neighbor it does on GitHub, and a link at something the site does not render (a source file, a folder of figures,CLAUDE.md) goes to that file on GitHub rather than dying; heading anchors follow the link checker's slug rule (tags and punctuation dropped, runs of space collapsed to one dash), which is what makes the corpus's#anchorlinks hold, and a run of dashes in a link's anchor is read as one (SiteBuilder.anchor), since GitHub keeps a dash per space (status--contributing) and nine links in the tree are written its way; the front page names its sections by heading and reports a heading the README no longer carries (Report.notes) rather than dropping it, and a README with no About page keeps its anchors on the front; the HTML renderer shares the terminal renderer's line joiner, list, link, and emphasis scanners, and the emphasis rule they share is CommonMark's (a*followed by a space opens nothing, so1 + F0 * (1/E - 1)stays a multiplication rather than an italic that swallows the line, a defect the corpus found on the attribution page); raw figure blocks pass through withsrc/srcset/hrefresolved and pictures copied to the mirrored path, so the<picture>dark variants switch with the reader's setting as the chrome does. Design: system type, hairline rules, a translucent bar whose active section hangs as a tab, light and dark schemes following the system, a sidebar of<details>groups (the current one open) that drops under the page on a phone, and an "On this page" rail; the only scripts are the front page's ring and the search. The examples menu lists a folder's own page, and the page is the folder's name: inside a category, a folder with aREADME.mdof its own (an artist, a part of the 3D set) is one row under that page's title, in the order of the titles shown (case and accents folded under a fixed locale, so the order is the same on every machine), and its sketches are listed on that page; a sketch in a folder with no page keeps its own row, since nothing else leads to it. The row carriesaria-current="page"on the folder's page andaria-current="true"on a sketch inside it, so every examples page marks exactly one row of its menu (realSitecounts it on every page). A sketch's trail and its search heading name each folder above it by that folder's page title (SiteBuilder); the title is the page's own.folders( above: plan: ) ##, never a second list of names, andlistingTrailsNameThePageholds each listing's hand-written trail to it. A list item holds what is indented under it (HTML.listItems): a line indented to where the item's text starts is the item's, blank lines included, and the lines are rendered as blocks with that indent taken off, so a paragraph, a table, or a fenced command under a bullet lands inside it and the command loses the spaces that nested it. A list with a blank line between two of its items, or between two blocks one item holds, is onespreadlist whose items carry paragraphs (the rule GitHub reads the same file by, so one such item spreads the whole list;.spread > likeeps the room separate lists had), a list with nothing between its items carries bare text, a numbered list a paragraph interrupted carries on at its own number (start), and an item's first line is text whatever it opens with. The search folds accents on both sides (processTermover the index and the query), sobonacicfinds Bonačić, and the accented text is marked where it stands. The floor under every page (2026-11-27;SiteTests.realSitewalks every page for it, withpicturesSayTheirSize,mediaPictureSizes,wrongAddressFromTheRoot,textContrast, andnothingRunsOffAPhone/aNameStaysWholeOnAWidePagein a real browser,HTMLTests): no page is wider than a phone (67 were at 390 px and all 1,059 at 320):.longNamesFold codeoutside a listing breaks anywhere, and a name of 20 characters or more carries<wbr>marks so it folds between its labels first (HTML.breakable: after a colon, a comma, a slash, or an opening parenthesis, and before a dot that opens a name; honored only under 860 px and never in a table,wbr { display:everywhere else, so on a wide page a name still moves whole to the next line; the marks do split a name's text into pieces, whose sub-pixel rounding re-wrapped one paragraph of the whole site at 1,280 px); any other overlong word breaks at the line's end (none } overflow-wrap:onbreak-word body), and a listing or a table keeps its lines whole and scrolls in its own box, so a table'scodeis set back tonormal, sinceanywherewould let a column shrink to a letter; under 350 px the bar drops the repository link. Every<img>says its size and all but a page's first wait (SiteBuilderin.sizingPictures SitePictures.swift, run after the clips are swapped in): a checkout file is read through ImageIO when the site is built (LinkLogmaps a site path back to its file), a picture on the media host is sized from the manifest (.pictureSources ExampleMedia: a still is the canvas, a.pictureSize( at: ) -640copy is fitted in 640 with its shorter side at the nearest even number, which is what the pipeline'scapwrites and was read off a file of every canvas shape, and a cover is a square), a writtenwidthis kept and gains the height that goes with it, and a picture from any other host (a badge) gets no size rather than a wrong one;img { height:is what keeps the shape in a narrower column. A wrong address getsauto } 404.html, written only when the site knows its address, throughlayout(rootedAt:): every path from the root (rootPath(of:),/or/Name/) because the host serves the one file at any depth, no menu, no canonical link, no markdown twin,noindex, and outside the sitemap,llms.txt, and the search index; its two lines arenotFoundTitle/notFoundLine, @eaviles's words, and its own button opens the search throughdata-search-open. The keyboard: the skip link is the first thing in<body>and<main>carriestabindex="-1"so it has somewhere to land;:focus-visibleis one ring in--text; a listing or a table that overflows takes a place in the Tab order throughSiteStyle, and one that fits takes none. Contrast: every text color reads at 4.5 to 1 or better on each ground the stylesheet sets it on, in both schemes, computed from the stylesheet's own variables; that is why.pageScript --mutedequals--text-2(a gray that passes on--surface-2is the secondary gray; ruled 2026-11-27) and why a link inside gray text is underlined (its hue alone was 1.0 to 1 against the words around it).theme-colorand--bgare written from the same two constants (SiteStyle.ground/groundDark). The lists beside a page follow the reader (SiteStyle, written to.menusScript assets/menus.js, loaded only by a page with a menu). The list of sections marks the last heading past a line 16 px under where an anchor comes to rest (scroll-padding-top); a page's last sections can never reach that line, so from where the last section that can has come to rest the line slides down and meets the last heading as the page ends: every section has its turn, in order. A section asked for by name (a click, an address ending in its anchor) stays marked until the page moves off where the asking left it. The mark isaria-current="location", a color and a bar on the list's hairline, never a weight (a bolder entry re-wraps the list as you scroll). The menu opens on the open page with no jump:menuPlaceScriptsits right after the menu and before<main>, so it runs before anything is drawn; nothing is stored between pages, and the reference's overview opens no group (ruled 2026-11-27). Near a page's end both lists are shortened by--cut, how far the layout's end has risen into the window, or the sticky box is pushed up under the translucent bar; a reader who asked for less motion gets every style change at once: the reset is a transition of no length and no delay (transition-duration:,0s transition-delay:), never one too short to see, since a 0.01 ms transition starts a frame later from the old value, and for that frame the phone's sheet was still0s visibility: hiddenwhen the script asked it to take the focus (the focus stayed on the tab) and a list just made shorter still had its old height. On a phone the menu is a sheet underhtml.js, which the head sets before the first paint (or the menu is drawn under the page and then taken away): what opens it is the active section's tab as a<button>twin beside the link (menu-toggle,aria-controls="menu"; beside the mark on a project page, which has no tab; ruled 2026-11-27), the sheet isposition: fixedwithalign-self: stretch(the column'sstartmakes a fixed box as tall as its content, which neither scrolls nor ends at the window's foot), andmainand the foot areinertwhile it is open. With no script the menu stays under the page and the repository link stays in the bar, which has no room for it beside the arrow under 480 px. The same list folds under the title below 1,100 px (onPage, the page's own markup, so it is there with scripts off and holds its room; it closes on a tap before the browser works out where the section is). A chapter's last line becomes two cards (pager(in:): the line's own words and links and nothing added; any other ending is left alone; chapters only, ruled 2026-11-27).[hidden] { display:keeps a control that waits on its script out of sight, since any rule that lays it out beats the attribute (the search button showed with scripts off and did nothing); undernone !important } html.jsthe button's room is held and only its sight withheld (visibility: hidden), or the bar's tabs move when it arrives, a layout shift of 0.002 on every page. The search button's spoken name holds the keys it shows, after a comma (Search, ⌘K, and the word alone where the keys are not shown): a name that leaves out what the button shows failslabel-content-name-mismatch, and that rule sets aside whatever a name says in brackets.menusFollowTheReaderandaPhoneOpensTheMenuFromTheBarrun the real stylesheet and both scripts in a browser, each under both motion settings (the browser's--force-prefers-reduced-motionand--force-prefers-no-reduced-motion, with the probe saying which it found): left to the machine, a desk with motion on and a build runner with it off each tested half, and the half the desk never ran held the defect above. One look across the sections (four rulings, 2026-11-27). One title size: a whole page goes throughHTML, which sets its headings at the levels.render( _: asPage: resolve: ) HTML.outline(_:)gives: where no heading stands above the first, the first is the title at level 1 and every other heading is set one level under the nearest heading before it that was written above it, or at level 2 when there is none (the reference and every examples listing write##and###where a chapter writes#and##, so 301 pages opened on a smaller title, had no first-level heading, and listed their sections all set in); so the nesting a file wrote is kept, its gaps are closed, and sections written at the title's own level are sections beside the ones written under it (thirteen reference pages mix the two, and set any other way their first sections sat two levels under the title); a part of a page (a section of the front page) keeps the levels it was written at, which is why the outline is asked for and never the default. A heading's level depends on the headings after it, so each is placed by a mark (headingMark, U+0001, taken out of the source first) and written once all are known; names and anchors are the file's. Trails: every page but the front one and the page for a wrong address has one, starting at a link to the front page called Ollin; a file's own first line is the trail when it writes one, andtrail(for:)gives its place otherwise (the project pages, the About page); an example's ends on the sketch; the section is named byname(of:)wherever the site names it (the bar, a menu's heading, a card, a trail), and the reference's files say Reference in their own first line (they said Documentation, one Docs, eight nothing). The examples menu reads every cell of the index that holds one link and nothing else, row by row (categories(): the grid of pictures is four across with the names on the row beneath, and reading only a row's first cell read the grid's first column. The reference's menu has a row for every page: the pages beside the index sit with the overview, and a group whose pages share one folder opens on that folder's index asreadingIndexAt: ) All <group>. The project pages go byaboutLabelsin a menu and a trail, and each keeps its own file's title as its heading. A list of sections (listed(_:title:)) names a heading that opens on a bracketed name by the name alone ([0.18.0] - 2026-11-14is0.18.0), and leaves out the second level when most of its names repeat one another (Added,Changed,Fixedunder every release). An example's first line is its listing's cell as written (ExampleEntry), with its code type, its links reduced to their words (.summaryWritten HTML.unlinked, since the cell's paths hold from the listing and not from the sketch's page), and a capital (HTML.sentence) unless it opens on a name somebody types. Every picture and clip has a hairline just inside its frame (outlinewithoutline-offset:, in-1px --border): it takes no room, and without it a sketch that is white at its edge has no edge on the white page. Every page unfurls with a card:og:urlandog:imageare written against the custom domain or, before there is one, the address GitHub Pages serves the repository at (SiteBuilder,.pagesAddress https:), and left out when neither is known; the card is/ / owner .github .io/ name/ Logo/(1200 by 630, the full mark in paper on an ink tile), copied in asollin-social .png assets/social.png, withLogo/beside it asollin-touch .png apple-touch-icon, both bitmaps written by.png Scripts/logo.sh(AppKit reads an SVG as an image) rather than at build time, since the text target draws nothing, and a missing one is aReport.notesline. A page with a picture of its own unfurls as that picture (2026-11-27,SiteBuilder): an example as its own still from the manifest, a Guide page as the first picture it renders (read before a clip takes that picture's place; only a.ShareCard .png/.jpgwhose size the site knows and whose shorter side is 300 px or more), every other page as the mark; a picture less than 3:2 wide is declaredsummary, since a feed cuts a large card to a wide strip and a square sketch would lose its top and bottom. The front page and the foot, composed (2026-11-27, three rulings and two extras). The opening is two boxes in the README's order (SiteHome:.openingColumns home-lede, thenhome-factsfrom the first list to the end, so the status note closes the facts): side by side from 1,180 px (437 and 479 px tall at 1,440), stacked under it, the facts as ruled rows with each fact's name hanging to the left and, at 480 px and under, over it. A row says how it is laid out (SiteHome):.Row .layoutClass .flowingis CSS columns (the browser ends the first column where the two come out even) and.splitputs each###part in ahome-partbox (SiteHome.parted), both two across from 1,000 px. In columns a block is spaced by its own padding, never a margin: WebKit carries a margin that meets a column's end to the top of the next column and Chrome drops it, so with margins the second column started 19 px lower in Safari and level in Chrome;SiteFrontAndFootTestsasserts the mechanism, since the test's browser cannot show the defect. On a phone the words come before the ring (stacked, the hero keeps its markup's order: the words, then the ring). The foot (SiteFoot.swift) is the mark drawn by<use>of the bar's own (SiteBuilder, so its outline is on a page once), the tagline, the newest release the changelog has a numbered section for (.markName latestRelease(, linked to that section's anchor), the three sections, and every project page ininChangelog: ) footGroups; a test fails when a file inaboutPageshas no row, and the bar's rule that hides the name beside the mark on a phone is scoped to the bar. A block of code stands in a frame (SiteBuilder, added in.framingCode layout(), the renderer's own markup untouched): the block scrolls and the frame does not, so the copy button and the fade at the edge a line runs past are set on the frame (SiteStyle,.pageScript assets/page.js, which also holds the Tab-order rule). The button is made by the script, shows on hover or focus, and where there is no pointer to hover with shows only once the block has been touched (and is not hit-testable before); the clipboard's older path is tried when the newer one refuses. A heading with an address ends on a link to itself (linkingHeadings, second to fourth level): the mark takes no room and the heading keeps 1.25em clear at its end under(hover: hover), because a mark hanging past a heading whose words reach the line's end made 60 pages wider than a 390 px window; it sits on the baseline at 1em tall, since any taller or lower and every heading grew by a pixel. A chapter's opening picture takes the frame a chapter's clip does (framingOpeningPicture), only when nothing stands between the title and the picture, so all 47 chapters open at the column's width and an appendix's first figure keeps its own. The search builds its index in steps of 500 (SiteStyle): at the library's ten, 478 timer waits were 3.1 s of a 3.4 s first search whose real work is 0.19 s (measured on the live site). The README's count of sketches is read by.searchBuildStep Scripts/against the sketches on disk (check-links .sh more than N hundredholds to the next hundred).SiteFrontAndFootTests(14: the boxes, the frame, the foot, the cards, and three browser tests that read the front page inside a frame of exactly 1,440, 1,000, and 390 px, which a headless window cannot be). The search (2026-09-07) is a button in the bar,/, or ⌘K opening a dialog over the page:SiteSearchwrites one entry per section of every page and one per example intoassets/(title, heading, the site path with the heading's own anchor, the first sentence as an excerpt, and the section's words, lower-cased and deduplicated, stop words and words under three characters dropped, minus the title's and heading's own words, and minus any word common to more than a tenth of the entries, which is what keepssearch-index .js colorfrom answering with 900 sections; a page'sContentssection is skipped, and the project pages beside the front page (.about) list headings and excerpts with no words, since their sections run to thousands of words each and would double the index), and the matching runs in the browser through MiniSearch (MIT), pinned to one release on cdnjs with its published SRI hash and loaded on the first search, never with the page, so a reader who never searches asks the network for nothing: boosts title 6 / heading 4 / excerpt 2 / words 1, prefix from two characters, one edit of fuzz from five, every word required, a page's own entry boosted over its sections, at most three rows per page of the thirty shown, the matched terms marked in what is shown. Load-bearing: the index is a script setting one global, never JSON fetched, so it loads from a folder opened off the disk (afetchof afile:URL is refused) and every<in it is written as\u003cso no excerpt can close the script that carries it; the sections come fromHTML.renderitself (Page.sections, the plain text of each block accumulated as the renderer walks, code and figures skipped, table cells and list items in), which is the only way an entry's anchor is the page's own (#ramps-1for a secondRamps); the excerpt's sentence rule ends at.only before a capital, a digit, or an opening quote, and never after a one-letter word or a dotted name (e.g.,p5.js), so0...1.ends and0.5does not; the button ishiddenuntil the script has run, so no script means no dead control; the dialog carriesdata-root, the path back up to the site root, and every result is prefixed with it. The library is the one thing on the site that comes from outside it: a folder opened offline has every page, and a status line says the search library did not load. This is a reader's search, not the machine-readable index the--jsonquestion (still open) is about.SiteSearchTests(6) pin the words, excerpts, anchors, pruning, and the file's shape;realSitechecks every entry against a written page and its ids and holds the index under 3 MB;searchInABrowserruns the shipped script in headless Chrome over a small index (prefix, fuzz, every word required, page over section, marks), skipped without a browser or the network. The mark and the favicon are the logo's own masters underLogo/, read from the checkout at build time (SiteLogo), never a copy: the masters are black ink on nothing with no color written in them, and the site sets the color three ways (inlinefor the bar, which shows the full mark at 30 px on every page (the small form is for icon sizes only: the favicon and Safari's pinned-tabmask-icon.svg, the master itself in ink), the ink ascurrentColorso one drawing follows both schemes and takes the page's text color;coloredfor a file that cannot take a color from a page, which is the README's dark twin on GitHub, written byScripts/logo.shand checked against the master bySiteTests;tiledfor the favicon, the small form in paper on an ink tile, since a tab bar is whatever color the browser makes it). A master still carrying a written-out black fill from an export is stripped of it on the way in, or the color set on the root would reach nothing;Scripts/logo.shis the one cleaning path (SVGO at five decimals, since three moves edges visibly), andSiteTestsfails on an export's leftovers. The picture the README opens with is lifted off the front page rather than rendered as prose (the bar shows the mark there; the About page shows the README's own<picture>), and a missing file is aReport.notesline, whichSiteTestsfails on. The front page's ring is the sketch's own web page (2026-09-04):Examples/recorded as the inline form ofWeb/ BreathingRing --export-weband committed as one raw string literal inSiteHero.swift, written only byScripts/(never by hand; the export is deterministic, so an unchanged input rewrites the file byte for byte, andsite-hero .sh Scripts/reruns the script when the sketch, the web exporter, the shader rewriter, or the shaders change, so the rewrite lands in the same commit). The builder pastes the fragment verbatim inside anpreflight .sh aria-hiddenwrapper and follows it with the site's own inline script (SiteStyle), which sets the ring's.heroScript inkandpaperthrough the handle from the stylesheet's--text/--bgand again on a color-scheme change; that script is inline right after the fragment, never a deferred file, or the recorded white paper paints first in the dark scheme. Reduced motion is the player's own rule (the first frame, still). An empty fragment builds a hero with no ring and aReport.notesline naming the script, andSiteTestsfails on it;ringFollowsTheSiteplays the hero in headless Chrome under the dark scheme's variables and reads the corner as the page's paper and the ring as its ink, against the recorded black on white. Every example can show what it does (2026-09-10):Scripts/media.shrenders a clip at the canvas size, a small clip for a grid, and a still at both sizes for one example (or--all), encodes each once from a ProRes master that is then deleted, uploads them to the host, and merges one row intoMedia/media.json(Scripts/, which keeps a per-examplemedia-manifest .py seconds/frameoverride across runs); the example's page plays the clip with the still as its poster (SiteBuilder.clip). Load-bearing: a sketch declaringloopDurationrecords one lap and everything else ten seconds, since a longer file of a looping sketch is the same lap again at N times the bytes while the page's ownlooprepeats it free; the clips are H.264 High 4.0,yuv420p, tagged bt709, faststart, no audio track, which is the combination an iPhone decodes, and the tagmuted+playsinlineis what keeps iOS Safari from taking a playing clip fullscreen; the poster is a real rendered frame, so low power mode, where nothing autoplays, still shows the sketch; 60 fps costs about 15% more bytes than 30, not twice, so the page clip runs at 60 and only the grid clip drops to 30; the manifest is the one place the address is written, an example with no row simply has no picture (which is what lets the set fill in a folder at a time), and both link checkers already skip an external address so no gate had to learn one. What is passed over is written down, never silently missing, and the three rules are read rather than remembered: a sketch whose imports name a camera / phone / controller / MIDI / serial / lighting rig / second machine waits on hardware; theInput/Live/Installation/Datafolders wait on a hand; everything else is measured (the master sampled once a second, the largest change between samples must clearMOTION_FLOOR1.0 — a static print scores ~0.2, a slowly growing sketch ~3). An unchanged example is left alone, media and verdict both (a digest of the whole example folder, notSketch.swiftalone, since a font/mesh/photo beside it changes the picture;--forceoverrides; noteshasumhashes the paths too, so a digest taken by hand must be taken the way the script takes it). Every listing opens on a picture grid (Scripts/, written from the manifest, idempotent, four across with names on the row beneath): the grid is markdown, never HTML (the renderer passes a few tags and escapes the rest, and GitHub shows the same file), a listing owns the sketches beneath it except those a nested listing owns (theexample-grids .py check-linksrule), andHTML.galleryrenders a first row of all-[![cells as figures in a grid rather than a table (a table scrolls sideways on a phone) with a hover swap to the small clip after ~120 ms, preloading nothing,(hover: hover)and reduced-motion gated, the clip's address derived from the still's name. A grid above a table of links broke the site's own reading of that table and both guards are load-bearing:categories(steps over a row whose first link is a picture, and dedupes by path, since the names under the pictures link the same folders and every category otherwise appeared twice in the sidebar. A page can open on a grid of sketches playing (readingIndexAt: ) heroesin the manifest,SiteBuilder): the markdown carries the still, since that is what GitHub and a plain clone show and a page should say something before a megabyte of video lands, and the site swaps an.playingHeroes <img>whose address matches a hero for that clip playing with the same picture as its poster, carrying the alt text over as the label; a page with no hero is untouched. The guide's is the sketch each of its thirty-two chapters builds (each figure marks its ownGuide payoffin source, which is what makes the selection the book's rather than a guess, and 32 chapters is what makes 8x4 the shape), the README's is thirty-two examples across every area. Each cell is filmed with a running start (--skip), or a sketch that accumulates opens on an empty canvas; three needed their age tuned individually rather than their content changed (a swarm that converges wants 2 s, a particle drift 30, and a grid simulation reads as isolated rings at 4 s and solid at 40, so it is caught at 10). Group covers (coversin the manifest, one per category / 3D group / artist) are a choice, not a rule, so they are written down;Examples/3Dwas split into ten topic pages because 137 sketches cannot take one grid. Measured over the whole sweep: 353 with media, 173 passed over, 1.49 GB at 4.32 MB per example, seconds of render each after a release build.ExampleMedia(Sources/);OllinReference/ SiteMedia .swift SiteTests(3: the manifest reads and its absence is not a failure, a clip carries what a phone needs, and no row names an example that has gone). An index and a markdown twin for every page (2026-09-10, thellms.txtconvention v2): the site writes/llms.txt(a title, a blockquote, then curated H2 link lists) and a.mdbeside every.htmlcarrying the markdown actually written, with its links rewritten through the same resolver the HTML uses and pointed at the twins, so a machine following one keeps reading markdown rather than falling into HTML halfway; every page's head carriesrel="alternate" type="text/andmarkdown" rel="describedby", the two relations the convention names. Load-bearing: the index is curated, never a sitemap (526 examples would bury the reference, so they are one link to their listing), each entry is cut to its first sentence and capped at 180 characters, since the whole point is fitting in context while the detail waits behind the links; an example's twin is its summary, its run command and its whole source in a fence, because an example is its source. A convention rather than a standard (proposed 2024; Anthropic, OpenAI and Gemini serve one for their own docs), so nothing fetches it automatically: it earns its keep when an agent with a browsing tool is pointed at the site.SiteTests.llmsIndexbuilds the whole checkout and fails if any link in the index is not markdown.SiteTestsbuilds the whole checkout into a temp folder and walks every page: no dead relative link, every picture in place, no markdown left in prose (code and attributes excluded), a canonical address per page;HTMLTestspin the anchors, the nesting, the figures, and the highlighter. The workflow skips its push trigger while the repository is private (a macOS runner bills 10x and Pages needs a paid plan there) and always runs by hand;SITE_DOMAINas a repository variable writes theCNAME.OllinReferenceTests(60, pure but for the reads of this repository and the browser run of the ring: every page renders and opens on its own heading, every page is linked from the index, every example carries a listing line, every example target the catalog prints is oneExamples/declares, and the whole site builds clean); no pixel snapshot (the output is text).Package .swift Docs/(§ In a browser); Guide Ch 1 § Looking something up without leaving the terminal. A type's cases print their comments in its members list (Tools/ Reference .md members(of:)prints eachenumCasemember's comment under its spelling, up to 8 lines, since a case's comment is the whole of its documentation, its units, its sign, what it hands back at zero; a function's keeps its own lookup, and the sixty-member cut still lists names alone).Installation mode (
Sources/+Ollin/ Core/ Installation .swift Live/+ the clock inInstallationHost .swift Core//SketchView .swift Core/Sketch.swift). The unattended-run tier:open var installation:declares a piece left running for days,Installation .onfilling the screen (native full screen, so the menu bar and Dock go with it and the window keeps the keyboard — a borderless one cannot become key without a subclass), hiding the pointer, and holding the display awake;--installation/--no-installationput any sketch either way with no edit. Load-bearing: the sketch clock is the sum of its own frame steps, each capped atSketchRunner(0.25 s), never.longestFrameStep now - startTime— a gap in the frames (a display asleep overnight, a drag, a stall) is then a pause rather than one eight-hourdeltaTimethat throws every integrator into the far distance; a capped step also never feeds the fps readout (a stall is not a frame rate). The GPU clock restarts (Sketch.shaderClock, the oneFloat(time)choke point inperformDraw): a 32-bit clock in seconds cannot hold a week (measured: at 604,800 s,Float(, so shader-driven motion stops dead; at 86,400 s the ULP is already half a frame step), sot + 1/ 60) == Float( t) .automaticwraps at a whole number ofloopDurationlaps (invisible by construction, capped near 1000 s), while a sketch with no declared loop keeps its clock running rather than take a silent jump;installationoff is identity, so nothing else changes.frameCountreaches the GPU withUInt32((a plain init traps after ~2.3 years at 60 fps). Power is both a heldtruncatingIfNeeded: ) ProcessInfoand a 30 s repeat of.beginActivity( [ .idleDisplaySleepDisabled, .idleSystemSleepDisabled]) IOPMAssertionDeclareUserActivity— the assertion alone stops display sleep but not the screen saver, which arms off the input-idle timer that declaring activity resets (verified live inpmset -g assertions:PreventUserIdleSystemSleep+PreventUserIdleDisplaySleep+UserIsActive). The hold is one (holdAwake(_:), idempotent, and the pointer hide the same throughhidePointer(_:)): the take-over and the schedule's first reading each began a hold of their own, the second's timer wrote over the first's, and the first kept declaring activity every half minute through the dark hours with nothing left to invalidate it, so the display never slept; a wake renews the one hold (renewAwake), and every path asks for a state rather than beginning another. The system calls go through thePowerseam, soInstallationHostTests(7) counts assertions begun and ended, timers made and invalidated, and hides against shows, through a take-over, a dark reading, a morning, a wake, and the release. A screen change arrives as a burst (a display waking reports many arrivals in a second), sodidChangeScreenParametersNotificationis debounced 0.5 s, then the window is put back on a screen that still exists andSketchRunnerretimes.displayChanged( to: ) preferredFramesPerSecond(read once at view build otherwise). The log flushes on the spot (stdout to a file is buffered, and a killed run then loses the whole trace). Applies on the standaloneOllinApp.runpath only — the live host and the gallery own their windows — and an export has no window for any of it; the shader-clock restart does follow the sketch into an export, landing on a whole lap there too. A loose single-file sketch reaches that path throughOllinRun(Sources/OllinRun/):ollin <file> --installationcompiles the file once throughSketchLoaderand hands the sketch toOllinApp.run, so the window, the supervisor, the checkpoint and the warp are the shipped ones and nothing downstream knows the sketch was loose; the script routes on the flag (--calibratetoo), and the live host, which cannot honor one, says so once per session when a sketch it is hosting declares an installation. It reloads nothing, by design: a wall runs the code it was started with, and the live host is where a piece is worked on. Load-bearing: the checkpoint is filed under the unqualified type name (whatString(describing:)gives), so the fresh per-compile module a loose load carries (OllinRuntimeSketch_<token>, different every time) never reaches the file name and a piece resumes across launches instead of silently starting over every morning; the compile runs beforeOllinApp.runso a broken file fails once with the compiler's own message rather than in each supervised child until the watch gives up.OllinRun --selftestpins the name across two compiles (printing both modules, so the check cannot pass for the wrong reason) and the declaration surviving one. Verified live on a loose file: full screen from the flag alone, a checkpoint every 2 s,kill -9on the child bringing the piece back resumed with its wall intact, and the watch stopping with no orphan left. Checkpoint and restore:Installation(writes the run down on a cadence,checkpoint: .every( seconds: )) @Saved(aCodableproperty wrapper found by the same mirror walk as@Param) marks what to keep, and a relaunch puts back the seed, the clock, every@Param, and every saved property. Load-bearing: the restore is two-phase — seed and parameters beforesetup()(so a sketch builds from the numbers it built from last time), state after (that is wheresetup()fills its properties in); each property carries its own JSON, so a renamed one finds nothing, a retyped one fails alone, and neither costs the properties behind it (pinned by a property declared after the failing one, verified red by sabotage); the file is atomic (a power cut cannot leave half of one), JSON a person can read (nested as real values, not escaped strings inside strings), keyed on the sketch type name + a format version, and nothing here ever stops a piece from starting — every mismatch is logged and skipped.--freshignores a file without deleting it;saveCheckpoint()/forgetCheckpoint()are the manual pair. Saves are timed by the sketch clock (a paused piece does not come back owing a pile), plus one onapplicationWillTerminateand one from aDispatchSourceSignalon SIGTERM/SIGINT (signal(_, SIG_IGN)first, or the default action kills the process before the source runs) — verified live: 10 tiles at the last cadence save, 14 in the file after akill -TERM. A save is never written before the run has read the file it replaces (didSetup): every save asked for from outside the frame loop (a schedule closing for the night, a quit, a stop signal) can arrive before the first frame, which is where the restore happens, and writing then puts an empty run over a piece that has been growing for days (found live, by launching a piece inside its own dark hours). Restoring is off even under.on(it changes what a piece does on launch), and the live host and gallery never checkpoint at all (restoring old state on every reload is the opposite of iterating). GPU-held state is out of reach by construction (accumulation, feedback, sim fields, compute buffers are framework textures) and the docs say so.Vector2/Vector3/Color/Rectangle/InsetsgainedCodablefor this. Restart on failure (Live/):Supervisor .swift Installation(turns the process into a supervisor that owns no window (the branch sits inrestarts: .onFailure) OllinApp.runbefore the window, so the process owning the window is the replaceable one) which runs the piece as a child and starts another when a run ends badly. Load-bearing: the child is marked by an environment variable (OLLIN_SUPERVISED), never an argument — the sketch's own flag surface stays untouched, and the round trip through the env the supervisor actually builds is what pins that a child never supervises in turn; a stall is found by a heartbeat written from the main run loop (Heartbeat, aTimerin.common), never from the frame loop, because anoLoop()still and a piece dark for the night both legitimately draw no frames while the run loop keeps turning, and a main thread stuck in a frame is exactly what stops it; a stalled child that exits tidily still counts as a failure (it can catch the SIGTERM, save, andexit(0), which by status alone is indistinguishable from somebody quitting the piece — read that way, the wall stays dark; sabotage-verified red); the first heartbeat gets a 120 s startup grace (a piece has not answered at all until its first frame, and killing a heavysetup()there makes such a piece unable to start at all; sabotage-verified red); the stop is SIGTERM then SIGKILL after 5 s (a hung main thread never services the signal, andCheckpointSignalshas already setSIG_IGNon it);RestartPolicycounts a run shorter than 30 s as a strike with a growing wait (1/5/15/30/60 s) and gives up after five, one real run clearing the record, so a nightly crash recovers for ever while a piece broken at launch does not spin all night; the supervisor forwards SIGTERM/SIGINT to the child (a signal sent to it by name alone would orphan the piece) from aDispatchSourceSignalbuilt non-isolated. Off even under.on(a piece that crashes while you work on it should stay crashed),--no-installationtakes it off with everything else, and it exists only on the standalone path. Verified live:kill -9andkill -STOPon the child each brought the piece back within a second or two, resumed from its checkpoint, with no orphan after the supervisor itself was stopped. Behavior by time of day (Core/Schedule.swift):Installation(is a list ofschedule: ) Periods (ExpressibleByArrayLiteral, so the call site never names the type), each a startTime(ExpressibleByIntegerLiteral,.at(9, 30)to the minute) + a name +shows, with.open(from:to:)the sugar for one showing period and one dark one; a sketch readsscheduledPeriod/scheduledProgressanywhere, at a desk as much as on a wall (the read is off the declared value, so only the darkening needs the installation). Load-bearing: the current period is the last one that has started, falling back to the last of the day when now is before the first — the small hours belong to last night, and read instead as "the first that has not started yet" a piece would come on at midnight in an empty building; that same rule is what makes a night crossing midnight one period rather than two.Time.wrappedMinutestreats a time to itself as zero, not a whole day (progress at a start must be 0), so the one-period case restores the day length explicitly, andTimeitself wraps into the day (.at(24)is midnight,.at(9, 90)is 10:30) because every reading compares minutes since midnight and a time outside the day would simply never come round. The host pushes the state to the runner on every reading, not only on a change, and holds the runner directly (InstallationHost) rather than through.attach OllinActiveSketch, which a piece only registers with on its first frame and a piece opening outside its hours has none — the defect in the first build, caught live: the log said dark while the frames kept advancing. Going dark pauses the frames (.runner SketchRunner:.setShowing isHidden+isPaused, and a still sketch keeps its own pause across it), so the clock stops with them and the morning resumes where the night stopped, writes the state on the way down, and releases the power assertions so the panel can rest. Verified live with a boundary a minute out: frames advanced, froze flat across the dark period (a screenshot of a black window), and advanced again when it opened. Fitting the wall (Core/+Projection .swift Core/+ProjectionCalibration .swift Live/+ProjectionCalibrator .swift Geometry/+ the projected present twins inHomography .swift ShaderEffects.metal):Installation(corner-pins the presented frame onto what it is thrown at (projection: ) showsthe part of the canvas this machine carries,cornerswhere that lands,blendhow far the edge fades reach,gammathe projector's own answer to the standard curve), with ⌘K raising four draggable handles over the running piece and the numbers kept per display. Load-bearing: the installation window always presents through the projected pass — fit corners reproduce the old SwiftUI letterbox exactly, so ⌘K has corners to drag on any piece and noifcan swap view identity (and the MTKView with it) mid-run; the geometry then renders at the canvas's own proportions (MetalRenderer, reusing the render-size seam the temporal upscaler opened) because the view now fills the display and a drawable-shaped target would carry oval dots and strokes of two widths. The fade is applied to light, not to a code value (after the tone map, before the encode), which is what makes two beams weighted.pictureSize wand1 - wsum to exactly one coat;gamma2.2 is the standard curve and yields exponent 1, no correction (sabotage-verified: weighting as a code value reads 0.87 coats mid-band).blendwidths are canvas fractions, the same units asshows, so both machines are told the same number about the same band and their two fades are the same function of the same wall. The warp runs in only the two paths that present into a drawable (encodePresent(), so an export, a frame grab and a Syphon feed stay unwarped (pinned by a test that diffs an export against itself with a warp set). The two present fragments are new functions, not a branch in the shipped pair (a grown fragment re-contracts under fast math, the rule the wide-gamut twin already carries).projected: ) fwidthis read in uniform control flow — a lane that returned early has no neighbors to read — so the behind-the-horizon guard multiplies the answer rather than returning. Corners are filed under the display's own UUID (CGDisplayCreateUUIDFromDisplayID, which survives a replug where the display number does not) because a keystone belongs to the room and not to the work, so every piece shown there opens square; nothing about reading that file may stop a piece from starting (the checkpoint's rule). A drag that folds the quad has no map, so the handles read from the corners themselves and the last good placement stays up: reading them back through the map throws all four across the display, and dropping the placement makes the picture vanish under the hand. The pointer takes the warp backwards, so a piece being lined up still readsmouseXin its own canvas, and a described part's frame goes through it forwards (the box around its four mapped corners, since a screen reader takes a rectangle) so an accessibility element still points at the piece of wall it is talking about.--calibrateopens with the handles up, and ⌘K is handled by a local key monitor (a full-screen window has no menu bar to hang a command on) that passes every other key through untouched.InstallationTests(11, the clock restart verified red by sabotage) +CheckpointTests(11, the per-property isolation verified red by sabotage) +SupervisorTests(15) +ScheduleTests(13) +ProjectionTests(22, both pixel claims verified red by sabotage: a flipped axis and a fade in the wrong space); no pixel snapshot (the warp is screen-only, so it is presented into an off-screen display texture through the sameencodePresentinstead). Where the canvas is on the desk (Sketch/.canvasOnScreen screenFrame, pushed each frame by the runner): the rectangle this canvas covers in screen points, and the screen it covers it on, so several windows of one sketch can look into one world (and, ahead, several displays can). Load-bearing: it is measured the way the canvas is (origin at the top-left of the primary screen, y down), because a sketch mixing a y-up desk with a y-down canvas draws its world upside down;NSScreenanchors that origin, never.screens .first .main, which is the screen with the key window and is a different screen on two displays. It reports the view's rectangle rather than the window's, so a host with a title bar or a sidebar says where the drawing is and not where its furniture is. It is read every frame (a window being dragged is current in the frames drawn during the drag), and isnilwith no window, which is what lets a piece fall back to being its own world in an export.PlacementTests(3, the turn-over verified red by sabotage). Several displays from one machine (Core/Displays.swift+Live/):DisplayWall .swift Installation((displays: ) .one/.spanning/.mirroring/.parts() puts one canvas on every display the machine drives, as a window and a drawable per display fed from one canvas render, presented once per display in the same command buffer, so every beam of a wall carries the same frame. Load-bearing: the placement travels with the display ([Projection]) encodePresent() and is never read off the renderer's own, or every beam carries the drawing display's part (pinned on pixels, sabotage-verified red);placement: ) .spanningderives each part from where the displays actually are (WallPlan, pure arithmetic over desk rectangles, so a wall of six is checked with none of them plugged in), dividing the machine's ownprojection.showsrather than the whole canvas (four beams over two machines is then two declarations of two), and the gap between two monitors carries canvas nobody sees, which is what the arrangement looks like from in front of it; exactly one part is the primary one and the piece's own window is moved to it, or a run whose display got no declaration would draw frames with nowhere to put them (sabotage-verified red); the canvas is drawn at the size the wall asks for (MetalRenderer, the largest drawable size over its own.wallDemand shows), capped atSketchRunner(16384) and the cap said out loud, since a wall quietly drawn at half the resolution somebody paid for is noticed at the opening; a wall window takes the keyboard only while the handles are up (.largestPicture OllinDisplayWindow, so a key-reading piece never goes deaf on the display it is drawn in), joins all spaces (a swipe must not take the piece off the wall), and never counts as a real window for the quit-on-last-close rule; ⌘K raises the handles on every display at once (the key monitor moved to.canBecomeKey InstallationHost, one per app) while the corner keys go to the window last clicked, each display still filed under its own UUID.--displays one|spanning|mirroringputs any piece on a wall, and--rehearse [n]lays that wall out asnwindows on one desk (it implies an installation, keeps the pointer and the title bars, and reads a.onedeclaration as.spanning, since asking for a rehearsal is asking to see a wall): the parts go side by side with a gap, never overlapped (two beams sharing a band add their light, two windows only hide each other), and a rehearsed display is filed under nothing, so nothing dragged there can reach the room's calibration. A display plugged in or unplugged rebuilds the wall on the debounce the window move already waits out; a rehearsal ignores it, its windows standing for displays that are not here.DisplayWallTests(16) +ProjectionTests(the per-display placement, sabotage-verified red). Examples.everyDisplayCarriesItsOwnPart Installation/+Unattended Installation/+Watched Installation/Hours+Installation/Fitted+Installation/(a long canvas spread over every display, and rehearsable on one desk) +ManyDisplays Installation/(one world through as many windows as are opened, kept in step with no messages at all: every window reads the time of day, so the world is the same function everywhere);ManyWindows Docs/+Output/ Installation .md Docs/Core/Sketch.md; Guide Ch 49 § Leaving it running:Installation+ § Several windows, one world:canvasOnScreen+ § Several displays, one machine:.spanning.Screen saver (
Sources/+Ollin/ Core/ ScreenSaver .swift Core/+Resources .swift OllinProjects/). A sketch wrapped as the machine's screen saver:ProjectGenerator .planScreenSaver ollin new <name> --kind screen-saverwrites the package, the@objcprincipal class, the property list, andbuild.sh, which assembles and signs the.saverand installs it to~/.Library/ Screen Savers SketchSaverViewis the host (anopenScreenSaverViewwhose one override ismakeSketch()), building anOllinMTKView+SketchRunneronstartAnimation(). It lives in the core rather than a satellite, behind#if canImport(, because it needs the internal seams (ScreenSaver) makeOllinMTKView,setProjection) and is the same class of thing asOllinApp.run; the framework it drags in is in the dyld shared cache, so every sketch linking it costs nothing. Load-bearing: the package builds a.dynamiclibrary product with-Xlinker -bundle, which is what makes the Mach-O anMH_BUNDLE(filetype 8) rather than a dylib — verified, and the reason no hand-writtenswiftclink step exists.Bundle.modulecannot serve a plug-in: the accessor SwiftPM generates checks onlyBundleand the machine's own build path, and in a plug-in.main .bundleURL Bundle.mainis the host's (legacyScreenSaver), so every core resource lookup goes through.appex OllinResourcesinstead, which adds.bundle Bundle(for:)'s ownresourceURLto the candidates and keepsBundle.moduleas the last of them (an ordinary run resolves to exactly the bundle it always did);build.shcopies every*.bundlethe build produced intoContents/Resources, so a satellite's resources travel too. Counterfactual-verified both ways: with the build path hidden the saver still renders (its own copy served it), and with both gone it stops atunable to find bundle named Ollin_Ollin. The script asksswift build --show-bin-pathrather than assuming.build/release(the two build systems the toolchain ships differ). The canvas takes no input (OllinMTKView:.ignoresInput hitTestnil +acceptsFirstResponderfalse) — a screen saver ends on a key or a click, and a canvas that answered would eat the one that gives the machine back.stopAnimation()is not the end: it fires for the System Settings preview and stays quiet when somebody wakes the machine, and the system builds a fresh view every time while releasing none, so teardown runs fromviewDidMoveToWindow(window gone → drop canvas, delegate, runner) plus thecomdistributed notification; a copy left drawing competes with its own replacement for the GPU. A sketch that is not.apple .screensaver .willstop .resizableis fitted, not stretched (setProjection(, the corner-pin path's.direct) .fitcorners), since a display is almost never the shape of a canvas; the generator writes.resizableinto the sketch unless a canvas was asked for. The plist name and the@objcname are the only link between the two files, and a mismatch fails quietly:Bundlehands back some class rather than nil, so the test compares the name (sabotage-verified red). The host disables library validation and holds a read-only exception for the whole filesystem, so an ad-hoc signature loads and any asset opens, but a saver cannot write (no export, take, or checkpoint)..principalClass ScreenSaverHostTests(7, the input opt-out and the teardown each verified red by sabotage) +ScreenSaverProjectTests(8, pure) +GeneratedProjectBuildTests(runs the emitted script, then loads the.aGeneratedScreenSaverBuildsAndLoads .saverand reads back its principal class — safe because that target links the generator and never the framework); no pixel snapshot (the output is files). Open: the real host has not run one —screenLock delay is immediateon this machine, so starting the saver locks the Mac.Docs/; Guide Ch 48 § Living in the system: a screen saver.Output/ ScreenSaver .md Sketch as an app (
OllinProjects/+ProjectGenerator .planMacApp ProjectKind.macApp). A finished piece wrapped as a signed, double-clickable.appfor a Mac without the toolchain:ollin new <name> --kind mac-appwrites the mac sketch's package unchanged (the sketch keeps@mainand its window; an ordinary executable target) plus the whole wrapper, which isInfo.plist+build.shand nothing else — the pair is self-contained by design, so it can be copied into any sketch folder of the same shape. Load-bearing:build.shcopies every*.bundlefromswift build --show-bin-pathintoContents/Resources(run from a bundle, the binary resolves the framework's resources through the app's own Resources folder; without them the app opens and renders nothing); the icon is the sketch — the freshly built binary renders itself (--export … --frame 120), sips squares and scales it,iconutilfolds the iconset intoAppIcon.icns— with an author's ownAppIcon.icnsbeside the script always winning and a failed render never failing the build; signing is ad-hoc by default (--sign - --timestamp=none) and the script states the this-machine-only limit at every build, while--sign <identity>applies--options runtime --timestamp(the two things the notary checks) and--notarize <profile>(refused up front without--sign— ad-hoc can never pass) submits the ditto zip vianotarytool --wait, staples, and re-zips to hand over; the plist isAPPLwithNSHighResolutionCapable(without it the canvas renders scaled on Retina), and camera/microphone usage lines follow the wired capabilities (vision →NSCameraUsageDescription, audio →NSMicrophoneUsageDescription; a bundled app that asks without one is killed, not prompted).AppProjectTests(8, pure) +GeneratedProjectBuildTests(runs the emitted script,.aGeneratedAppBuildsSignsAndRuns codesign --verify --strict, then renders from inside the bundle — the proof the resources traveled); no pixel snapshot (the output is files).Docs/Output/App.md; Guide Ch 48 § An app to hand somebody: signing and notarizing.The sketch on a phone (
Apps/OllinSketchAppthe reference app;OllinRuntime/+PhoneProject .swift Sources/OllinTetherbehindollin phone;Core/the touch twin;SketchCanvasUIKit .swift Core/the app). First light 2026-09-02 on an iPhone 15 Pro Max: the framework builds for iOS 26 and a sketch renders on the phone's own GPU throughSketchAppUIKit .swift SketchViewin aWindowGroup(some SwiftUI.Scene, because the framework has aScene), one finger drivingmouseX/mouseY/mouseIsPressedand a styluspressure.@mainon a sketch is the whole app there too (2026-10-22):Sketch.main()andOllinApp.run(_:)exist off the Mac (SketchTouchApp, the twin of the desk'sOllinSketchApp), the canvas full screen, the sketch'sInstallationbegun on the runner (Installation, so a declared checkpoint is kept, and.resolved( for: ) isIdleTimerDisabledwhen it runs unattended andkeepsDisplayAwake), and its@Params in a SwiftUI.inspectorholding the sharedParametersListView(a side panel on a tablet or a Mac, a sheet on a phone). The button that opens them is drawn only under#if DEBUG, whatever the sketch declares (ruled 2026-10-22: what is handed out carries no tuning control; first ruled hidden under a declared installation too, then not, since a checkpoint alone is one and a phone has no keyboard), and it stays in the tree, transparent and out of the touch path, because Command-/ belongs to a control that is there. Theios-appkind and the reference app write no hostApp, only the sketch with its@mainand a one-lineBundle+Module.swift(Bundle.moduleas.main, since an Xcode app target has no package bundle). Load-bearing: a phone loads no pushed dylib (refused outside the signed bundle since iOS 18, DTS-confirmed), so the live host's swap cannot run there andollin phoneis a rebuild and reinstall on every save (measured: the framework ~80 s once, then 5 to 7 s build + ~2.5 s install over Wi-Fi), with the runner's checkpoint (beginInstallation(, public now) carrying the clock, the seed, theInstallation( checkpoint: .every( seconds: 1))) @Paramvalues, and the@Savedstate across each relaunch, so it reads as a reload; an app's container survives a reinstall under the same bundle id, which is what keeps the checkpoint file. The build targetsgeneric/, never the phone by id (a phone that has left the network would otherwise fail the build rather than the install, which is the step that needs it); the sketch folder and the checkout are symlinked into the project folder (platform=iOS Sketch/,Ollin/) and the spec names everything through those links, because xcodegen's relative-path routine loops forever when a source path and the project folder share only the root (an absolute path to the sketch hung it from/var/foldersand from/private/tmpalike; measured 2026-09-02), the tether rewrites a diagnostic's link path back to the author's file, a sketch marked@main(every desk sketch) is compiled as a copy inSources/with the attribute blanked to spaces (PhoneProject, over.withoutEntryPoint SourceRegions.codeso a comment or a string keeps its@main; every line and column kept, the copy's path rewritten back too, the copy rewritten each save and removed once the sketch drops@main, or the class compiles twice), since the host keeps its own@mainfor the checkpoint andRemoteInspector, sibling assets are carried as resources through the same link, and the host definesBundle.moduleas.mainsoin: .moduleresolves; one bundle id (dev), so the phone holds one app that is the last sketch tethered, its display name the sketch's type; the parameters are the shipped.ollin .OllinPhone RemoteInspectoron 9330, proxied tolocalhostthrough usbmux when the phone is on the cable. Ten satellites reach the phone (Remote, Physics, OSC, MIDI, Controller, Video, Bluetooth, Audio, Vision, Haptics);OllinPhonelinks there too and reads that phone's own sensors (its own bullet, The phone's own sensors: built for a phone, not yet run on one); four are refused by nature (Camera, Syphon, Screen, Record3D); the rest link untried and are named. The app's property list carries the system's question for each sensor an import opens (PhoneProject: the camera for.usageKeys OllinPhoneandOllinVision, the microphone forOllinAudio, Bluetooth forOllinBluetooth), since an app that opens one without its line is closed, not asked. A canvas of a set size keeps its proportion on a phone (2026-12-02):CanvasProportioninSketchView, off the Mac only, fits it whole and centers it on black, at the SwiftUI layer so the pointer's map through the view's bounds stays exact; it had been stretched to the screen, unseen because the one sketch ever run there was.resizable, whose canvas is the screen. The simulator runs the 2D path and draws no 3D mesh (measured 2026-12-02). Its GPU reports Apple families 1 and 2 and the first of the common families: no MetalFX (compiled out,MetalRenderer+NoMetalFX), no cube-array textures (the two point-shadow factories return.swift nilundertargetEnvironment(; with them Metal stops the process on the first frame of any sketch), and a shader's textures end at index 30, wheresimulator) ollin_mesh_fragmentnames index 31, so the mesh pipeline is not built and its batches are left out. 2D, text, images, and a recording's video draw.pipeline(_:)now says a pipeline that cannot be built, once for each fragment, on standard error with Metal's reason; the skip had been silent, which is how the missing meshes went unseen.ollin phone --simulatorruns a sketch there (the simulator named by its id, which builds one architecture where the generic destination builds two) and says the limit before it builds;--no-openprints the parameters' address without opening it. Nothing gates the simulator build: animport MetalFXabove its file's ownos(macOS)guard had broken it unseen.devicectllaunches nothing while the phone is locked. Mac Catalyst runs it (an iPad app on the Mac, the shape a Playgrounds App Project previews in there), held by two invariants: a platform seam keys onos(macOS), nevercanImport(AppKit), since Catalyst imports AppKit and still cannot callNSWorkspace; and every runtime shader compile passesollinShaderCompileOptions(() Renderer/), since the Catalyst compiler defaults to Metal 2.2 where the desk defaults to 4.1, and the built-in library needs the ray-tracing namespace (2.3) and the mesh stages; the helper raises the version to 4.0 only when the default sits below it, so the desk and the phone compile exactly as before. Proven on the M2 (the rings sketch in a Catalyst window); no gate compiles for Catalyst yet.PlatformGPU .swift Scripts/compiles the framework for iOS on every framework change (a macOS-only SwiftUI call broke it within a day of the last hand check).preflight .sh PhoneProjectTests(19, pure) +PhoneProjectBuildTests(2, skipped without xcodegen: the emitted host, and a sketch that reads the phone with its recording inside the app, each compiled for generic iOS; the build is asked for by the scheme's own name and the app itself is looked for, since a build asked for by the target's name built the phone library and no app, and ended well); no pixel snapshot (a device).Docs/; Guide Ch 48 § In your pocket: the sketch on the phone. Failure shape (2026-09-22):Tools/ OnThePhone .md isRunning,unavailableReasonandstart(), the same shape asOSCQueryServer; a.failedlistener is dropped sostart()can try again, andstop()resetsboundPort(it used to keep the old port).RemoteWireTests..aPortAlreadyTakenIsSaidAndTriedAgain The phone as the sketch's screen (
OllinPhone:PhoneScreen.swift,PhonePictureEncoder,.swift PhonePictureSender, the shared.swift PhonePictureCoding; the app's.swift SketchScreen.swiftand Sketch mode).device.show(self)keeps the sketch on the Mac (its live reload, inspector, console) and shows its frames full screen on Ollin Capture, with nothing built or installed for the phone: it answers how a piece looks and plays in the hand, never whether the phone's GPU keeps up (the installed loop answers that). Load-bearing: the frame is copied from theframeRendered(texture into an IOSurface pixel buffer from the compressor's own pool by one Metal pass (an 8-bit canvas read through a plain view, bytes passed through; a float canvas clamped and sRGB-encoded in the pass) and the copy waits for completion inside the hook (the renderer takes the texture back on return, and hazard tracking does not reach another queue); HEVC in real time with no reordering, a keyframe at most a second apart, 709 primaries and matrix with an sRGB transfer tag, fitted under 1920 px and rounded to even, about 0.125 bit a pixel a frame clamped to 4 to 40 Mbps; pictures are sent over their own connection, port 1339 (_: texture: ) PhoneWire), in the request framing as request kind 4, so a picture never waits behind a sensor read and a mode request never waits behind a picture; a keyframe carries its parameter sets (VPS, SPS, PPS) and nothing else does, and a keyframe with no sets is refused at decode; a frame is skipped before it is compressed, never after (.picturePort wantsRenderedTextureasks for a frame only while the phone reports that its screen is the sketch's (isShowingSketch: Sketch mode, or the viewfinder of a camera mode), the sender is connected with nothing queued, and nothing is in flight; a P-frame already made is never dropped, since every later picture is built on it), and a picture too big for one wire frame is dropped with the next forced to a keyframe; keyframes are also forced on (re)connect and when the phone gives its screen back to the sketch; the sender dials only while a drawn frame wants it (keepWanted()frombeforeDraw, released after two seconds) and the phone's picture listener keeps only its newest client, which together hand the phone to a reloaded sketch without a ping-pong; every usbmux socket setsSO_NOSIGPIPE(a write to a phone that just unplugged otherwise ends the process). The first finger is the pointer through the purePhonePointerrule fed on the reader thread (so a tap between two draws still presses and releases): a second finger never moves it, a finger still down when the holder lifts never takes over, fingers resting at arming are passed, the fingers press only while the phone shows the sketch, and a held press is always let go; the phone's touch pad in Sketch mode is the picture view itself (aspect-fit, one view whatever the size so the display layer is never rebuilt), so -1…1 is the canvas;Sketch.setMouse/handleMouseButton/setPressurearepackagefor it. On the phone the sample buffer is rebuilt by the same shared file the Mac tests run and decoded byAVSampleBufferDisplayLayer's renderer on the server queue, starting at a keyframe after an attach or a failure.PhonePictureRoundTripTests(4, device phase besideSpatialVideoTests: rendered frames through the encoder, the wire in uneven chunks, the phone's rebuild and a decoder, mean error about 1.3 levels and 38.6 dB, the plain-view rule red by sabotage; a mid-stream join waits for a keyframe; the extension and its sender thread over a socket pair, the backpressure rule red by sabotage) +PhonePictureRequestTests(10) +PhonePointerTests(6) + 3PhoneTouchTests; the app built for generic iOS; the cable and the eyes are owed at the desk. Example3D/;Phone/ PhoneCanvas Docs/3D/Phone.md§ The sketch on the phone's screen +Docs/§ Without installing it; Guide Ch 48 § Leaving it on the Mac: the phone as the sketch's screen.Tools/ OnThePhone .md PhoneScreen.phasespeaks the sharedPublisherPhase(stopped, publishing while the phone shows the sketch, waiting otherwise), the vocabulary the Syphon and virtual camera servers use.Capture on the phone (
Sources/+Ollin/ Export/ CaptureKeeping .swift SessionRecorder; the control is.swift CaptureControlsinCore/; the lines inSketchView .swift OllinRuntime/,PhoneProject .swift OllinProjects/,IOSAppSource .swift Apps/; the viewfinder's Record inOllinSketchApp/ Info .plist Apps/). A sketch running on a phone or a tablet keeps what it shows:OllinPhoneApp/ Sources/ SketchScreen .swift saveFrame()andstartRecording()/stopRecording()go to Photos when no path is named, and an on-screen control does both (showsCaptureControls, default on, iOS only; a camera button and a red record button with the take's clock, at the foot of the screen over a letterbox's bar, never in its own picture since it keeps the canvas; it polls the recorder twice a second, so a take from code shows there too, and draws the recorder's sentence). Load-bearing: (1) a phone's.resizablecanvas is grabbed at the drawable's pixels (the canvas is points, a ninth of the pixels; the Mac's stays the canvas size), and a turn of the phone is a size change, which ends the take; (2) Photos is add-only and asked only with its line present (NSPhotoLibraryAddUsageDescription; asking without it closes the app), and a movie is handed over withshouldMoveFilefrom the app's temporary folder, so it is never on the phone twice; (3) a refused capture is kept, never lost: moved to the app's Documents (shown in Files throughUIFileSharingEnabled+LSSupportsOpeningDocumentsInPlace, which both generators and the reference app write), with the sentence why, where, and how to allow it inlastErrorand on the control; (4) a relative path on a phone is read from Documents, since its working directory is/; (5) the room's sound on a phone: the plist line checked before asking, the session set to.playAndRecord(speaker, mixing) before the engine, and an input with no channels refused rather than tapped (a tap on it traps);ollin phoneadds the microphone line when the sketch's text names.microphone/.sketchAndMicrophone. The control's take hears what the sketch's recorder hears (extend(for the room). The viewfinder's Record (capture app, a camera mode under the sketch shown from the Mac) records the camera's stream, never the picture sent back, so the piece is made again from it at full quality.SessionRecorder( audio: .sketchAndMicrophone)) PhoneProjectTests+IOSAppProjectTests(the lines, read back as property lists); proven in the simulator (a picture and two videos read back from its library at 1206 by 2622, the videos with sound; Photos refused, all three kept in Documents and the sentence drawn by a sketch readinglastError; a take there kept 40 to 73 percent of its frames, since the simulator encodes in software); unproven on a phone (P3: the control's buttons pressed and its note, the Photos prompt, what a take keeps at the screen's size, the room's sound beside an instrument, the viewfinder's Record).Docs/§ On a phone or a tablet.Output/ Recording .md Sketch as an app for the phone (
OllinProjects/+IOSAppSource .swift ProjectKind.iOSApp; the CLI's--team, the window's Signing team field).ollin new <name> --kind ios-appwrites a sketch as an iPhone and iPad app: the sketch (its@maindropped,.resizabledeclared, since the screen is the canvas), a host in the reference app's shape (<Name>App:.swift @mainon theApp,some SwiftUI.Scene,SketchView(, safe areas ignored, and<Name>( )) Bundle.moduledefined as.main, which an Xcode target never synthesizes), the property list (full screen, both device families,arm64+metalrequired, camera/microphone/Bluetooth usage lines following the wired capabilities), and theproject.ymlthatxcodegen generateturns into the project; no manifest and no script. Load-bearing: it is an Xcode project spec, not a package (an app is installed, never run), and the framework is named by its absolute path inpackages:the way the manifest kinds name it, which xcodegen takes in a second from any folder; only a cross-root source trips its relative-path loop, and every source here sits inside the project folder. Resources are named before the group and excluded from it (a folder entry named after the group adds nothing, measured; a folder is givenbuildPhase:so its files land flat where a name-and-extension lookup finds them), and aresources .metalgoes through acopyFilesphase (destination:), never the resources phase: Xcode runs its build rules over that phase too and compiledresources effect.metalinto a library (unknown type name 'ShaderInfo', 2026-09-07), while the framework reads a shader's source at run time; the built app now carries it as ASCII text, andPhoneProjectgot the same fix. A capability that wraps a Mac service is refused at plan time with its reason (Capability: Syphon, screen capture, the virtual camera, both ends of the phone link), an example's imports included; every template fits. The team is the one question no other kind asks: the.staysOnTheDesk --teamflag, thenOLLIN_TEAM(the variableollin phonereads), else the spec carries a marked, commentedDEVELOPMENT_TEAMline and the README says Xcode's own answer is lost on the next generate; never the reference app's team from the checkout, which is somebody's own. A--remoteframework pinsminorVersion:.IOSAppProjectTests(17, pure) +GeneratedProjectBuildTests(the spec generated and built for generic iOS unsigned in the tether's shared derived data, then the app checked for the framework bundle, the shader as text, and the flat folder; skipped without xcodegen); no pixel snapshot (the output is files); not yet run on a device (the desk backlog)..aGeneratedPhoneAppBuildsForIOS Docs/+Tools/ ProjectGenerator .md Docs/§ In an app of your own; Guide Ch 48 § In your pocket: the sketch on the phone.Tools/ OnThePhone .md Wallpaper (
Sources/+Ollin/ Core/ Wallpaper .swift OllinProjects/+ProjectGenerator .planWallpaper ProjectKind). A sketch run as the desktop wallpaper:.wallpaper OllinAppopens one borderless window per display at desktop level (.runAsWallpaper { Sketch( ) } CGWindowLevelForKey(— under the icons, over the system's picture), each display getting its own sketch instance from the closure;.desktopWindow) ollin new <name> --kind wallpaperwrites the project — the mac app's package, plist, andbuild.shplus aMain.swiftwrapper carrying@main(the kind strips the sketch's own entry point,carriesEntryPoint:, since two refuse to build). Load-bearing: the windows take no input at all (false ignoresMouseEvents+ignoresInput; borderless, so never key) — the desktop must stay the desktop;collectionBehavioris[so wallpaper never scrolls away with a space swipe; the app is an accessory (.canJoinAllSpaces, .stationary, .ignoresCycle, .fullScreenNone] LSUIElementin the emitted plist,.accessorypolicy in the host — it must NOT route throughOllinApp.run, whose delegate forces.regular), so the sparkle status item's Quit is the only way out and that menu is load-bearing, not chrome; panes rebuild ondidChangeScreenParametersNotificationonly when a screen frame actually moved (the notification also fires for changes that move nothing, and a rebuild restarts the piece); fitted-vs-filling followswindowModeexactly as the screen saver (sketchKeepsItsShape; the kind injects.resizableviafillsTheDisplay); the wrapper callshandleCommandLinefirst, which keeps every export flag working and is howbuild.shrenders the icon.WallpaperHostTests(5) +WallpaperProjectTests(5, pure) +GeneratedProjectBuildTests(runs the emitted script, checks.aGeneratedWallpaperBuildsAndRuns LSUIElementand the signature, renders from inside the bundle); no pixel snapshot (the surface is the desktop). Open: the eyes-on desk check — the piece visibly behind the icons — waits for an unlocked screen.Docs/; Guide Ch 48 § Wallpaper and a menu-bar strip.Output/ Wallpaper .md Menu-bar strip (
Sources/+Ollin/ Core/ MenuBar .swift OllinProjects/+ProjectGenerator .planMenuBar ProjectKind.menuBar). A sketch as a small live strip among the status items:OllinApp(56 pt default, height the bar's own) runs the canvas inside the item's button with the quit menu hung on the item;.runInMenuBar( width: ) { Sketch( ) } ollin new <name> --kind menu-barwrites the same app-shaped project as the wallpaper kind, pointed at this host. Load-bearing: the canvas isignoresInputso a click falls through to the button — the click opening the menu is the way out, and the strip never takes the keyboard from whatever is being typed; the strip draws at 30 fps and is never retimed to its display — arunnercall after the rate is set silently restores the display's maximum (a real bug, caught by.displayChanged theStripDrawsAtAWorkdayRate); under.resizablethe canvas is the strip's own points (the sketch sees ~56 by 22 andwidth/heightjust work), a declared canvas is fitted into the strip; with no Metal device the item still goes up with its menu, so the program stays quittable rather than kill-only.MenuBarHostTests(5) +MenuBarProjectTests(3, pure) +GeneratedProjectBuildTests; no pixel snapshot (the surface is the menu bar). Open: the eyes-on desk check — the strip beside the clock — waits for an unlocked screen..aGeneratedMenuBarStripBuildsAndRuns Docs/; Guide Ch 48 § Wallpaper and a menu-bar strip.Output/ MenuBar .md Overlay (
Sources/;Ollin/ Core/ Overlay .swift --overlay, read bySketch.main()). A sketch floating over the desktop:OllinAppopens one borderless, non-opaque window at the floating level on the main display (the whole display for a.runAsOverlay( hitTest: _: ) .resizablesketch, the canvas's fitted size centered on whole points otherwise), in an accessory app with the sparkle's Quit, like the wallpaper. Load-bearing: the window's own present keeps the canvas's coverage (MetalRenderer,.windowKeepsAlpha windowAlpha(for:):.premultipliedonly when the window is see-through and the canvas's background is; every other window stays.opaqueand byte-identical), with the canvas'sCAMetalLayernon-opaque and frame interpolation standing down (a held frame presents opaque); the window starts withignoresMouseEventson, andOverlayPaneflips it on every pointer move (a global monitor and a local one, since moves pass through to other programs) and on every frame read back; the piece is where the last read-back frame's coverage is over 0.05 (.apply( pointerAt: buttonsDown: ) OverlayHitTester), read from the frame-grab image every other frame (.threshold wantsRenderedFrame) at the byte the image's own layout puts its alpha in (four layouts pinned), an opaque frame counting as the piece everywhere, or it is where the sketch's ownhitTest:says, and then nothing is read back; a press that began on the piece stays the piece's while a button is down; the sketch'smouseXandmouseYfollow the pointer everywhere on the window, set from the system's pointer, since a window that ignores the mouse hears no moves; the window never becomes key.OverlayHostTests(10: the window, the keyboard, the two sizes, a rendered disk's rim within 1.5 points of its radius, an opaque frame, the four byte layouts, the click decision with a held press, the sketch's own answer, every other frame, and the present's alpha mode). Open: the feel by hand (a click through to the window below, a press on a firefly) waits for the desk.Docs/; Guide Ch 48 § Over the desktop instead of behind it:Output/ Overlay .md --overlay;Examples/.Installation/ OverDesktop A window for a layer (
Sources/+Ollin/ Core/ SketchWindow .swift Live/;LayerWindow .swift MetalRenderer)..ExtraDisplay .layer makeWindow(returns ashowing: title: ) SketchWindow(layer,title,isOpen,mouseX/mouseY/mouse/mouseIsPressedin the layer's points,close()); the run that draws the sketch opens a titled window the layer's shape for each (SketchRunner, every frame) and presents the layer into it from the frame's own command buffer, as a display of a wall is (.syncLayerWindows encodeExtraDisplays), so the two windows are never a frame apart. Load-bearing: in a frame that drew nothing into its layer a window shows an empty layer (ruled 2026-11-28, the layer's own rule:presentedTexture(hands the blank texture, never the one the handle still names, which is pooled and may be another layer's by now; the window used to keep its last picture while the canvas showed the layer empty); windows open only where the run draws in a visible window and takes input (never headless, never a wallpaper or a strip), and close when the sketch closes them, when the person does (for: drawer: ) isDismissed, never reopened), when the sketch is replaced (a reload), and when the canvas leaves its window; the layer window cannot become key (OllinDisplayWindow), so the keys stay with the sketch's own, andacceptsFirstMouselets a click land all the same; frame interpolation stands down while a sketch holds a window. A layer keeps a camera of its own (A camera for a layer, under 3D), so the second view can be the same world from another place, with the shadows the first one has. Lights are the frame's: set twice in one frame they are two lights.LayerWindowTests(10: the window's picture against the layer's own drawing and the canvas against its own, the window through the layer's own camera against the scene from above and the canvas against the scene from the stage, a layer the frame did not draw, an export, the pane's shape and its drawable, the pointer at two window sizes, both ways of closing, the run opening each once, a reload, and no window to stand beside).Docs/; Guide Ch 49 § A second view of the piece: a window for a layer;Output/ Windows .md Examples/. A window that goes away does so one way (Installation/ SecondView SketchWindow, from the sketch's.wentAway( dismissed: ) close(), the person's close, and the run's teardown): it stops being open and lets its mouse button go, since no release reaches a window that is gone.Widget (
Sources/+Ollin/ Core/ Widget .swift --export-widgetinCore/+SketchView .swift OllinProjects/+ProjectGenerator .planWidget ProjectKind.widget). A sketch shown as a desktop widget:ollin new <name> --kind widgetwrites an app with a WidgetKit extension packed inside it, and the framework draws the run the system shows. The design answer this surface forces, since a timeline refreshed in minutes cannot carry motion: a widget piece is one that changes rather than one that moves, so one picture is drawn per moment and the sketch says how far apart the moments sit (open var widgetTimeline:,WidgetTimeline .every(/minutes: count: ) .every(, 15 minutes by 4 the default). Load-bearing: the clock is the time of day (hours: count: ) timeis seconds since midnight of the moment being drawn,deltaTimethe spacing,frameCountalways 1) because the system throws a run away and asks for another whenever it likes, and an elapsed clock would jump the piece back to zero every time it did; the moments land on a grid counted from midnight (WidgetTimeline), so two passes agree and a quarter-hour piece steps at the quarter hours, with one short step at midnight for a spacing that does not divide the day. Each picture gets a fresh sketch, set up and drawn once, so a moment draws the same picture whether it opened a pass or closed one, and nothing carries between them (one renderer is shared across the pass, the contact sheet's rule)..gridMoment Sketch.dateis the moment the frame stands for (now at a desk, the future moment in a widget) andscheduledPeriod/scheduledProgressread it, since a widget's pictures are drawn before their moments come andDate()is then wrong, by up to 45 minutes under the default run. The generated project is three targets because a widget is two programs (the system finds a widget through its app) and two targets cannot share a folder of sources: the sketch is a library both reach through one generated public line (<T>Piece), never a public sketch class, which would force.make( ) public override func draw(on every override and make this kind's sketch unlike every other kind's.) build.shputs the extension atContents/and signs it before the app (signing the app seals what is inside it), withPlugIns/ <T>Widget .appex Widget.entitlementsdeclaring the sandbox an extension is refused without; both bundles get a copy of every resource bundle, since each is a running program. The generated file spellsWidgetKit.TimelineandSwiftUI.Colorout, because Ollin has aTimelineand aColortoo and all four are in scope there.--export-widget <dir> [--size WxH] [--frames N]writes the whole run as PNGs named by the moment, on any sketch, which is how a piece on this surface is judged in a second rather than a quarter of an hour.WidgetTimelineTests(10, the grid and the same-moment-same-picture invariant verified red by sabotage) +WidgetProjectTests(11, pure) +GeneratedProjectBuildTests+.aGeneratedWidgetProjectBuilds .aGeneratedWidgetBuildsAndRuns(milestone-gated: the appex inside the app, its extension point, its sandbox entitlement, the app's signature with it inside, and the run drawn from the bundled binary); no pixel snapshot (the output is files). Open: nothing here has been placed on a desktop — the widget gallery and how a picture reads at widget size want eyes.Docs/; Guide Ch 48 § A widget, and what it does to a sketch.Output/ Widget .md Single-file sketches (the
ollincommand,Scripts/ollin). One loose.swiftfile is a whole sketch, run from any directory:ollin <fileopens it in the live host (all flags pass through, so every export flag works on the loose file;.swift> --installation/--calibrateroute instead toOllinRun, which compiles the file once and hands the sketch toOllinApp.run— the only path that reads a declaredInstallation, so it is how a loose file goes on a wall, and it reloads nothing by design),ollin new [name]writes an executable starter file (class named from the file name),ollin install [dir]symlinks the script onto PATH. Load-bearing: the script resolves the repo from its own symlink-resolved location and execsswift run --package-path, so a PATH symlink is the whole install andgit pullself-heals on the next run — capture${0:A}at top level (inside a zsh function$0is the function name) — and sketch paths are absolutized before handoff (the host process runs with the repo as its package, not the caller's cwd). Hashbang:#!/+usr/ bin/ env ollin chmod +xmakes a sketch directly executable;SketchLoaderneutralizes a leading#!to//in place (same length, so diagnostics keep exact line/column) and compiles from the work-dir copy, since swiftc allows a hashbang only in a main file — applies to.fileand.sourceinputs (the live-coding editor buffer carries the line too). Pinned by two--selftestphases (hashbang renders; a broken hashbang sketch reportsSketch.swift:5:).Docs/; the Guide's Ch 1 points at it.Tools/ SingleFile .md A package's sketch, live (
SketchTarget,SketchChoice,SketchLoader.Scope, all inSources/andOllinRuntime/ SketchTarget .swift SketchLoader.swift). A sketch file inside a SwiftPM target's folder compiles with every.swiftfile of that target, under the target's Swift settings, and a save to any of them reloads;ollin <package folder>, a bareollininside a package, and--target <name>choose the sketch, read the same way by OllinLive, OllinRun, and OllinLiveCoding (SketchChoice/.arguments .resolve). Load-bearing:.targetis opt-in per loader, set only by the three hosts that run what a person names; the gallery, the Guide figures, and the generator preview stay.file. The manifest is read byswift package dump-packageunder a private--scratch-path(sharing the package's.buildwaited out a wholeswift build, 32 s against 0.25 s), cached per package root untilPackage.swift's modification date moves, and a read that fails fails the compile with SwiftPM's words rather than falling back to one file. Paths compare throughrealpath(Foundation's resolver strips/privatewhere the folder walk keeps it, and the sketch compiled twice: "filename used twice"). The walk is fresh per compile (a new file joins), skips hidden entries,exclude:, and resource paths, honorssources:, and leavesmain.swiftout (a library compile refuses top-level code, and the factory is the entry point). It callsskipDescendants()only on a folder: asked of an excluded file, the enumerator leaves the folder the file is in, and every file after it went uncompiled (found 2026-11-13 on a fetched package that excludes itsCMakeLists.txt, 2 files compiled of 30;anExcludedFileDoesNotEndTheWalkOfItsFolder). Flags:-package-name(the package folder's name as an identifier, one for every target of a package, without which apackagedeclaration does not compile),-swift-version(the target's setting, else the newest listed mode the compiler has, else 6 from tools 6.0),-D, upcoming and experimental features, default isolation (nonisolated spelled out), strict memory safety, the Swift tool's unsafe flags; a setting conditioned on another platform is dropped, one on a configuration follows the compile (.noneis debug). The factory shim is Swift 6 clean: both declarationsnonisolated, the address crossingMainActoras a.assumeIsolated UInt, since a pointer is notSendableand the old shim failed under a package's Swift 6 mode. Declared resources are linked into<work>/as the bundle lays them out (Resources .processflattened,.lprojwhole,.copywhole, the first name wins,embedInCodeskipped) andBundle.modulepoints there; a target declaring none keeps the sketch's folder. A compile that fails onno such module 'X'gets a sentence when X is a target of the package that the sketch's target does not list, or a dependency the manifest holds for another platform. Sketch classes are read with comments and strings blanked (SourceRegions,.code( in: ) SketchDeclarations), and a folder offers a target only when aSketchsubclass carries@main, or one exists and nothing else does (a host app's test sketches never surface). OllinLive watches the target's folder when the sketch sits below it; OllinLiveCoding carries the run only when the target's other files read as they did at the stage's build, and records an edit to one as the change itself (.restarts), so the toast says "restarted" rather than naming a block. Measured before the change on a generated project with a helper file:cannot find 'breath' in scope, and a.process(picture missing; after, both render."Images") SketchTargetTests(30),SketchCompileArgumentsTests, the OllinLive--selftesttarget phase and the--watchtestsave a folder below, the OllinLiveCoding--selftesttarget phase (red with the guard off).Docs/§ Growing into a package and § Where the live route stops; Guide Ch 1 § When one file isn't enough.Tools/ SingleFile .md The rest of a package, live (
SketchTarget,.dependencyOrder PackageWorkspace,DependencyErrorinSources/;OllinRuntime/ SketchDependencies .swift SketchLoader,.buildDependencies BuiltDependencyinSketchLoader+Dependencies). A sketch that imports another target of its own package, or a Swift target of another package (named by a path, or fetched), runs in the three.swift .targethosts, and a save to any of those files reloads it. Load-bearing: the host builds each dependency itself, from its Swift files, against the framework modules the sketch compiles against, and never asks the package build. Measured before the shape was chosen, on a project of two targets:swift build --targetin the project's.buildtook 36.7 s and 498 MB the first time (it builds the framework again), 1.4 s on every save to learn nothing changed, 1.8 s after a save to the library, waits out any build holding that folder, and compiles the library against the project's framework, which need not be the host's; the host's own compile took 0.7 s for 35 lines and 1.6 s for 2,000, with nothing written into the project. One framework in the process: each dependency is a dylib of its own whose install name is its own path, taken as an input by whatever imports it (the loader opens it with the sketch; nothing is opened first), its link leaving the framework's symbols to the host exactly as the sketch's does, and a module the host carries (hostModules(): every Swift and C module in the host's build folder) is never built and its package never read. Built once per fingerprint: the module compiles as<Name>_<12 hex>(SHA-256 over the target's root and name, its flags, the level, the names of the builds it needs, and every source's bytes) and importers get-module-alias <Name>=<that>, so two builds of one library share no symbol and no Objective-C class and the edited one loads beside the one it replaces; a fingerprint this process has built is handed back with no compile (a lock per fingerprint), so a save to the sketch compiles the sketch alone, a save to a dependency rebuilds it and everything above it, and a reverted file finds its earlier build. A dependency's stored globals live as long as its image (ruled 2026-11-13): they survive a save to the sketch and start over when the dependency is rebuilt. The order comes fromdependencyOrder, a walk kept on a list (the graph's depth is the manifests'), honoring platform conditions; a fetched package is found through SwiftPM's record (.build/), andworkspace-state .json swift package resolveruns only when that record is missing or older thanPackage.swift, once per manifest date per process (a resolve that changes nothing leaves the record's date alone, so the date is no proof it ran). Refused by name, each a sentence ending onswift run: a target with a C-family source or no Swift source, a system library, a binary, a macro, a plugin, a product withmoduleAliases:; a dependency nothing provides, two targets of one module name, and a cycle are said as what they are. A dependency that declares resources gets theBundle.modulethe package build would write. Compiler diagnostics have the build name put back to the real one. The framework-rebuilt refusal reads each dependency's module trace too. OllinLive watches every dependency folder someone could edit (never a checkout under.build) and asks again after each evaluation; OllinLiveCoding restarts the run when any file the buffer compiles with changed, a dependency's included, since a rebuilt dependency is a new module. Measured through the loader on a sketch over two libraries: first compile 2.1 to 2.8 s over three runs (two manifest reads are in it), a save to the sketch 0.7 s, a save to a library 1.3 s, a fetched package's first compile 2.9 s with its resolve. Still one file: the phone route, completion in the live-coding editor, and a shape drag in a helper.SketchDependencyTests(20), the OllinLive--selftestdependency phase (DependencyTest: the picture, the count of dependency compiles, and a count the library keeps, read after a save to each file; a fetched package through a local git repository; the C refusal; the watch), the OllinLiveCoding--selftesttarget phase.Docs/§ Code shared between sketches and § Where the live route stops; Guide Ch 1 § When one file isn't enough.Tools/ SingleFile .md Project generator (
ollin new+ollin generate). A ready-to-run project from a few questions, over three targets:OllinProjects(the model and emitters,Sources/),OllinProjects/ OllinNew(the CLI behindollin new), andOllinProjectGenerator(the SwiftUI window). Three catalogs are the extensible axes:ProjectKind(.singleFile/.macSketch/.macApp/.inPackage/.extensionPackage/.screenSaver/.wallpaper/.menuBar/.iOSAppavailable;.visionOSApp/.arEffectdeclared-but-gated, each carrying the platform leg it waits on),ProjectTemplate(10 ready-made starting points, each a whole small sketch), andCapability(asset folders + satellite links, contributing an import, a manifest entry, a folder, and one commented starter line insetup()). Load-bearing:OllinProjectsdepends on nothing butOllinShaderText, neverOllin(both only produce text), so it builds in ~1s and its tests are pure; the plan/write split (ProjectGeneratoris pure,.plan writeonly puts planned files down) is what lets the window preview the exact file list and the tests assert without disk;writerefuses any file that already exists rather than overwriting; a generated manifest points at the framework's own path (the CLI/window walk up from their binary to find it) so the project builds with nothing to fetch, with--remote/--framework-paththe overrides (--remotepins the newest tagged minor,FrameworkSource— bump it when a new minor is tagged); asset folders are.latestRelease .process(SwiftPM flattens a processed folder into the bundle root, which is what puts a dropped file within reach ofBundle, since Ollin's loaders pass no.url( forResource: withExtension: ) subdirectory:) while a.metalis a flat.copyfile (a processed.metalcompiles to a metallib, and a copied folder keeps its nesting) — so the per-folder placeholder note is named after its folder, never README.md, or two folders collide on one bundle name;@mainis inserted on the class, under the template's doc comment; a template that declares its owncanvasSizenever gets a second one. The window is three resizable columns (stage takes the slack) built to the design review: one sectioned source list (Templates group + the examples' own two-level catalog, one filter matching group names too, selection scrolled into view), the kind menu in the title bar with the gated kinds under a divider (a roadmap in a menu reads as a roadmap; in the main flow it reads as a broken control), a status line under the stage (built-in-Ns vs from-cache), the 3D chain as a strip under the stage laid along the constraint's own direction (Geometry → Finish → Extras, arrows, chips; a blocked chip names its cause and the blocker reportsblocks NviaThreeDRecipe/.blocker( of: ) blocks(_:); the reason line sits outside any scroll view, which is how the old clipped-hover-text gap disappears), everything else behind one Wire in disclosure that still reports what the starting point brought, the file list above the fold with the no-overwrite guarantee under it, and the dated serial as the field's placeholder rather than a value.OllinInspector(purple) is applied where it means something (list selection, chips, Create), never as a root.accent .tint, which would color every neutral native control. It previews a starting point by compiling and running it throughSketchLoader(the gallery's path, hence the satellite links +-export_dynamic), so one that stopped compiling shows up there. Starting from an example (--from Group/Name, the Examples tab) copies a maintained sketch instead of a template: the type is renamed by whole-word replacement (a sketch may name its own type inside itself), itsimports decide the linked satellites, its sibling files are copied (GeneratedFile) and declared.copiedFrom .copy, and the header comment travels verbatim (for a ported or homage sketch that is where the credit lives).ExampleSourcecompares path components after resolving symlinks (a.discover /vartemp dir walks out as/private/var, and a string-prefix test then matches nothing). Dated serial names (ProjectNaming) are the default when none is given:.nextSerial Sketch<year><nnn>, one past the highest already in the destination counting both folders and.swiftfiles, the year passed in rather than read from a clock so it is testable. The window remembers the destination (@AppStorage) and re-suggests the next serial after each Create. The 3D options surfaceDocs/as data (3D/ Combining .md ThreeDOption/ThreeDRecipe): each piece carriesrequires/conflictsplus the one-sentencerule, and the rules are a hierarchy, not a flat set (geometry is never blocked andsettle()fixes the finish and extras under it; a finish is blocked by its geometry; an extra by either) which is what keeps the panel navigable rather than refusing the first click;ThreeDSourcewrites the sketch from the recipe, andeveryGeneratedSketchCompilescompiles every extra on its own and every allowed geometry and finish with all its extras at once (18 recipes, in the one generated package that also holds the templates and the imported shader and scene sketches);ThreeDSourcewrites each extra as a fragment that reads neither the finish nor the geometry, which is what lets those 18 stand for every combination the rules permit (a rule that allows something uncompilable is the worst failure here, since the window would offer it). A fragment that starts reading the finish or the geometry needs the full sweep back. The build test is the load-bearing one (GeneratedProjectBuildTests): all 10 templates compile as targets of one generated package (one framework build), plus one full generated project built end to end.Scripts/ollin newroutes toOllinNew(a.swiftname still writes one loose file, unchanged),ollin generateopens the window. Joining an existing package (ProjectKind+.inPackage PackageHost) is the one path that changes a file rather than only creating them, so it is deliberately timid: it refuses a host that does not already depend on Ollin (a target added there could not import the framework), inserts one target by matching thetargets:array's own brackets (never the first], which would land inside a target'sdependencies:), preserves the closing line's indentation by inserting after the last entry rather than before the bracket, and when it cannot read the list confidently it writes the sketch and hands the stanza over to be pasted instead of guessing.GeneratedEditcarries the whole new text (worked out at plan time so the window shows it first) and edits apply after the new files. The CLI and the window both default to it whenever the destination sits inside such a package, since a folder of sketches is one package with a target each (the framework then builds once for all of them). Gotcha:relativePath(of:)compares twice, because symlink resolution only applies to path components that exist, so a folder about to be created keeps a/privateprefix its own parent has already lost and a single comparison silently yields an emptypath:. Two catalogs grow by different rules, and the difference is load-bearing: the examples list is discovered (ExampleSourcewalks.discover Examples/forSketch.swiftat launch), so a new example appears with no generator change, and an example'simportlines are read as the union with the capability catalog, never filtered by it (a filter drops a satellite that has noCapabilityentry yet, and since theimportis copied verbatim the new project then fails to build;unknownSatellitesSurvivepins it). The 3D catalog is hand-kept (ThreeDOption.all+ThreeDSource's fragments), mirroringDocs/: a 3D capability that changes what combines updates that page AND this catalog, the same hand-sync rule3D/ Combining .md ollin_sdf_distancecarries, andeveryGeneratedSketchCompilesthen compiles a new option alone and in every pair's full stack automatically.ProjectGeneratorTests(20) +ExampleAndNamingTests(12) +ThreeDRecipeTests(7) +PackageHostTests(8) +GeneratedProjectBuildTests(11); no pixel snapshot (the output is files).Docs/; Guide Ch 1 § When one file isn't enough.Tools/ ProjectGenerator .md Bringing a GLSL shader over (
ollin new --from-shader). A pasted fragment shader translated to Metal and handed over as a project (Sources/:OllinProjects/ GLSL/ GLSLTranslator/GLSLCompat/ShaderImport/ImportedShaderSourceover theShaderLexer/ShaderScanpair inSources/, the text target the web page's reverse rewriter shares, plusOllinShaderText/ ShaderSourceReaderon the CLI side). The shape read is the common web one —mainImage(over theout vec4, in vec2) iTime/iResolution/iMouse/iFrame/iChannel0-3values a site supplies — mapped onto Ollin's shippedshade(uv, info); how many channels it reads decides the routing (0 generator / 1 filter / 2 combine, the user-shader path's own rule), so no new render plumbing exists. Load-bearing: it is a lexer plus token rewriter, never a parser and never regex (a full grammar is far more to keep right than the rules need; blind substitution is the thrash trap), and every edit replaces the text of a token already there — nothing is inserted or removed — which is what keeps a pass's indices valid for the next one and preserves the author's spacing, blank lines, and comments (the property that makes the output editable source rather than machine output;theAuthorsLayoutAndCommentsSurvivepins it); a token carries its original bracket in a field beside its text (ShaderToken.bracket) so a rule may hang a whole argument off a)or turn a(into a{and every later structural walk still reads the shape the author wrote — matching on text breaks exactly this; an emptied token stops counting (hasText), or a blankedprecision …;swallows the statement after it and mis-attributes its line.modis the one rule that silently changes a picture rather than failing to build (GLSL floors the quotient, Metal'sfmodtruncates, so they disagree for negative operands — the ordinary case when tiling a plane reaching left of the origin): the flooring form is written out asollin_glsl_mod, never the built-in, measured at max 255 / mean 63.65 over 576k pixels on a tiled ramp — and note asin/costile spanning exactly one period cannot see the difference, so a counterfactual probe must not go through one (the first one did and read inert). A layer read turns the coordinate over (a texture is measured from its bottom edge, an Ollin layer from its top) or every imported filter arrives upside down;infotravels as a parameter only as far as it is needed (a supplied value is a global in GLSL and cannot be one in Metal, so a call-graph closure adds it to the functions that read one and the functions that call those, leaving pure sdf/noise helpers untouched); alpha is held at 1 (the source site shows every pixel opaque, so that is what reproduces the look). Nothing is dropped in silence — what cannot be carried lands in the file asNOTE(ollin)/TODO(ollin)and prints before anything is written (several passes, >2 channels, a self-declared texture, a written file-scope global (aconstone becomesconstant),texelFetch,iDate/iSampleRate, the mouse button, a 4x4 inverse). A plainmainwithgl_FragCoord/gl_FragColoror a declaredoutis reshaped into the same form. License hygiene is the point, not a footnote: nothing is bundled, the emitted header carries title/author/URL and says the terms travel with it, and a URL is fetched only through the site's own API with the user's ownSHADERTOY_API_KEY. A.macSketch/.inPackageproject keeps the shader as a flat.copyimported.metal(a processed.metalcompiles to a metallib — the shipped rule) so it hot-reloads with no swiftc pass; a single loose file carries it inline in a raw#"""literal (no target to declare a resource on, and a raw literal keeps a backslash a backslash).ShaderImportTests(17) +ImportedShaderProjectTests(4) inOllinProjectsTests(pure), andShaderImportRenderTests(10) inOllinTestscompiles every claimed shape throughcomposeUserShaderSource+makeLibraryon the real device — a rewrite that merely looks right is worth nothing (which is whyOllinTestsdepends onOllinProjects). No pixel snapshot (the output is files).Docs/; Guide Ch 18 § Somebody else's shader: GLSL import.Tools/ ShaderImport .md Bringing a 3D scene over (
ollin new --from-scene). A glTF or USD scene written out as the sketch that draws it (Sources/:OllinProjects/ Scene/ ImportedScene+ImportedSceneSource; the reader in the newOllinSceneImporttarget;ScenePlacementin the core). The split is the design: structure becomes source, geometry stays in the file. The camera prints as a.swift Camera3Dwith its own numbers, each light as its own factory, and each node as awithStateblock of the moves that put it where the file put it, nested as the file nests (so a group still turns as one thing) — while the sketch reads the file once for its meshes and places them itself through a generateddrawPart(_:), because a mesh is not something a person edits as text. Load-bearing:OllinProjectsstill depends on nothing, so the reader is its own tiny target (Ollin+OllinProjects) that both faces of the generator share, andImportedScenecarries plain numbers, never framework types; the placement split isSceneNode.placement(package,Sources/) reusing the shippedOllin/ 3D/ ScenePlacement .swift Scene.decomposeTRSrather than a second decomposition, and it reportsisExact == falseby recomposing and comparing, so a shear is said rather than silently mis-drawn; the emitted walk and the generator's naming walk must agree (each node before its children), which is why the part names are written into the sketch as a literal list rather than re-derived at runtime (a repeated or blank name still gets its own key); a move under 0.00005 is not printed (it would print as a call that does nothing), an axis-aligned turn reads asrotateX/Y/Z(with the negative axis flipping the angle), andscalealways takes the three-argument form (the one-argument one is the 2D call and would leave z alone).withStatesavesmodelMatrix, which is what makes the nested blocks reproducedrawScene's own composition exactly. What cannot come over is noted per node where it happens (a mesh with several materials draws in the first; a shear) and per scene in the header (animation, skins, blend shapes, and that materials come with their meshes, which is why nofillis emitted). A scene with no geometry needs no file at all. Verified againstdrawSceneon the bundledLoadedScene: identical but for the one multi-material slab, which is the documented loss.SceneSourceTests(13, pure) +SceneImportTests(11, against the loader; the placement probe verified red by sabotage, naming the node it moved) + aGeneratedProjectBuildTestscase compiling every light kind and both projections. No pixel snapshot (the output is files).Docs/; Guide Ch 28 § A scene you can take apart: the scene written as source (a pointer; the SceneAsSource figure is on the reference page).Tools/ SceneImport .md GUI / parameters (typed). The generic
@Paramwrapper/registry in the core (Param.swift) drives the shared inspector (Inspector.swift) in all three hosts; the control follows the property's type —Doubleslider /Intstepper /Booltoggle /ParamOptionenum menu /Colorwell /Vector2fields (+style: .pad) /Vector3/Rectangle/Insets/ClosedRange<Double>two-thumb slider /Stringfield /style: .segmented(the segments stay beside the label while they fit, wrap under it when they do not, and fall back to the menu row when even the wrapped control is wider than the panel, since a segmented control never shrinks below its names: five long names ran off the panel's edge, unreachable, and the wrapped child isfixedSize()on purpose soViewThatFitscan reject it) /Paletteswatch strip /Rampgradient band /ResponseCurvegraph and a list of numbers as bars (their own bullet below) / theParamChoicesnamed-catalog menu (Easingamong them) — through the type-erasedAnyParam/ParamControlsurface, so hosts never touchParam<Value>;ParamValueis public, so a user type can conform by mapping onto an existing control kind (no custom rows), wrapped through the publicconstraints:initializer, the primitive the built-in kinds' shorter spellings stand on (the bare form serves aVoidconstraints type;ParamOwnTypeTestsimportsOllinwithout@testableon purpose, since only a plain import sees what a sketch sees).icon:/group:decorate rows into titled group cards, andhelp:is a sentence the row's label shows when the pointer rests on it (under the whole name when the name may be trimmed;--list-paramsprints it under the row, the web page sets it as the label'stitle, OSCQuery'sDESCRIPTIONstays the label, and the phone's wire does not carry it, since a phone has nothing to hover); numeric value boxes scrub (Option fine, Shift steps on round marks, click to type), and while typed in the up/down arrows step them, all through the pureParamStepping(ParamNumberField): a plain drag covers the range in a 250-point track and a stepped box goes no slower than a step per 8 points (an Int over 0...10000 crossed in thousands of points before), Shift keeps the plain pace on marks leaving four to forty across the range (a power of ten, in whole steps on a stepped box, counted from zero when zero is on the step's grid), an arrow takes the next mark strictly past the value (the step, or a tenth of Shift's mark; binary noise on a mark counts as the mark) and starts from a half-typed number, and the Int −/+ buttons repeat while held (.swift buttonRepeatBehavior); a save's sentence (ParamSaveNote) clears on the next hand edit or any reset.ParamNumberFieldTests(the math) +ParamNumberBoxTests(arrow events through a real panel's event path). Rules:.theArrowsStepABoxToItsNextMark ParamChoicesneedsEquatableto find the current selection (a built-inEasingcarries its name as its identity, and a closure-built curve a serial of its own, which is what puts the curves on the menu and what a tuned choice persists under;LightingPreset,Material,Fog, andEnvironmentconform —Materialputs the whole curated finish library on the menu, while the parameterizedMaterialhelpers (.glass(...),.metal(...),.skin(radius:)) stay off it, since a menu needs fixed values;Environment's roster isallBuiltinsin browse order, so a.sky(...), an.hdri(...), or a built-in withlightingOnly()/highResolution(_:)applied is off it and reads as the first entry, which is why a sketch keeps the parameter on the plain built-in and applies the modifier at use;EnvironmentMenuTests); parameter values persist across reloads asParamStoredpayloads (syncParams; a property that changed type drops its stale value so the new default wins); OSC/MIDI bind toParam<Double>, and smoothing stays Double-only. The swatch strip (Palette/Ramp, oneParamControlkind,.swatches count:bounding its add/remove) draws a ramp's band by sampling the value itself, never by fading between the stops, so the row shows the blend the sketch draws whatever space it mixes in; a dragged stop stops at its neighbors, so strip order is ramp order; both persist as one.colors(payload (a palette's space isstops: space: ) nil, so a palette's payload restores into a ramp), and it has nothing between two values, so an automation holds it through a key. The SwiftUI layout gotchas (the scrub-pill.fixedSize(), the segmented ViewThatFits wrap) are in ARCHITECTURE.md. Headless gates:OllinLive --paramtest+ParamTests. A parameter read costs what a stored property costs (0.4 ns against 40.9 before, seven parameters read 160,000 times each on the M2, release): the getter is@inlinable, so a sketch compiles it for its own value type, and for aDouble, anInt, or aBoolit is one relaxed atomic load of the value's bits (ParamValue/.bits( of: ) value(fromBits:), stored by every writer inside the lock right after it movescurrent); a color, a vector, a palette, or text reads through the lock (lockedValue()). Every writer stores the value clamped and snapped, so no read clamps. Left generic across the module boundary the read cost 40 ns however it was stored, through the lock and the clamp or through the atomic alone, so the inlinable getter is the whole of the gain. The inspector answers posted events headless (OllinLive --inspectortest, run byScripts/): the parameters list is hosted in a window of the process, a click posted to the application's queue flips the toggle (a real AppKit switch under the SwiftUI row), and keys sent to the window type a value into the number row's field and commit it on Return, each read back from the handle, from the sketch, and fromhost-gates .sh onChange. A window behind the lock screen is never the key window, so the field is handed the keyboard bymakeFirstResponderand its keys go to the window rather than to the application (which routes key events to a key window only); a control SwiftUI draws itself is found through the accessibility tree, which SwiftUI builds only for a client that asked: settingAXEnhancedUserInterfaceandAXManualAccessibilityon the application is the ask (without it the tree holds one node), and each element then gives a role, a label, a value, and a frame on the screen, which is where the posted click or drag lands (the slider's thumb is itsAXValueIndicator; a drag is a mouse-down, a run ofleftMouseDragged, and a mouse-up, and SwiftUI's gesture follows it). Undo and redo are sent down the window's responder chain withtryToPerform, the route a menu item with no target takes; the grouped menu is read from theNSPopUpButtonit is and chosen from withperformActionForItem, since opening a menu starts a tracking loop a posted event cannot end; the pump callsupdateWindows()after each event, as the application's own loop does, which is what anything watchingdidUpdateNotificationhears. The curve and bars rows, the palette strip, and the timeline's lanes stay a desk check. The grouped menu: aParamChoicesroster folds into submenus throughparamChoiceGroups(ParamControl, laid out by.Menu .groups rows: every option reachable exactly once, a submenu standing where its first option stood);Easingdeclares its ten families, so thirty-two curves read as twelve rows. On the Mac it is an AppKit pop-up in a representable, because SwiftUI'sMenubuilds its items only while it is open, which leaves nothing to keep the pick checked in and nothing a test can read. A pop-up shows only an item of its first level closed, and the pick is usually inside a submenu, so the menu's first item is a hidden one that carries the pick's whole name and is always the selected one; the control's size and font are set from the row's environment on every pass, since SwiftUI sets the size itself and a font set once at a size change was skipped (the menu read 13 pt beside the flat menu's 11). The pick and the submenu that holds it are checked, and the pick goes through the same synchronous write the flat menu uses (ParamMenuGroupTests, 10). The Colors panel is moved off the list's column when a color row opens it there (ColorPanelPlacement: outside the window on the column's side, then the far side, then beside the column, kept on the screen;ColorPanelPlacerreads the panel's visibility atNSApplication, so the move is in the same pass as the click, acts on the rising edge only, and never touches a panel that is already up;.didUpdateNotification ColorPanelPlacementTests, 9).Undo in the inspector (
Live/, briefed byParamUndo .swift ParametersListViewon every body pass). The window's Undo and Redo cover a parameter turned by hand, a reset included. The steps go on the undo manager SwiftUI hands the list, the window's, so in the performance host they share one list with the editor's typing. One gesture is one step: edits to one parameter join the open step until it has sat still forquiet(0.3 s) with no mouse button held and no field of its row being typed in. The button is polled by a timer in the common run-loop modes, since a local event monitor never sees the mouse-up inside a control's own tracking loop; the typing is aholdeach row sets through the environment, because the number field writes the parameter as each digit lands, and without it a number typed slowly is a step a digit. A step that ends where it began is dropped: each step is its own target object, soremoveAllActions(forgets exactly that one, and the journal keeps every step alive because the manager does not keep its targets (anwithTarget: ) isolated deinitremoves them). A step names its parameter, never theParam, so it survives a reload, and a name the sketch dropped is skipped; another sketch in the same list (the name the list is given changes) starts with no steps, since itsradiusis not the one the last sketch's step was about. The journal never holds the view: what it is handed captures the save note's binding and the host's two calls, because the view's state holds the journal, and a journal that held the view back would outlive the list with its steps still on the window's undo manager. What a step puts back is a snapshot, taken when the parameters are adopted and on the list's 100 ms poll, because a row writes the parameter before it reports the edit. Each entry carries whether the row was turned, so undoing a first edit takes the mark with the value (the host's own reset, then the value set past it, sinceParamResetActionis the one call that forgets a mark), and a reset undone brings the marks back. Undo pressed inside the quiet time closes the open step without dropping it from under the manager that is running it. A manager that does not group by event has its group opened by hand. Beside it: a reset under a held clock asks for its frame (SketchSession, as.resetParams recordParamdoes), or the picture goes on showing the old value.ParamUndoTests(26),OllinLive --inspectortest(the responder-chain route, a typed number, a posted slider drag, a reset),OllinLiveCoding --sessiontest(the reset under a hold);Docs/§ Undoing a change.Helpers/ Parameters .md Curves and lists as parameters (
ResponseCurve,Math/; the list conformanceResponseCurve .swift Array:inParamValue where Element: ParamValue & Comparable, Element .Constraints == ParamNumericConstraints<Element> Live/Param.swift; the rowsCurveParamRow/BarsParamRowinLive/). TwoInspector .swift ParamControlkinds,.graphand.bars, with payloads.curve([Vector2])and.numbers([Double])(coding keyscurve,numbers).ResponseCurveis Fritsch-Carlson monotone cubic through its points: inner slopes the mean of the two secants (zero where they disagree in sign), a flat interval flattens both ends, a pair past the radius-3 circle scaled back, so it passes through every point, is C1, and never leaves a pair's band; out of range it holds the end heights; the final clamp is to0...1, never to the pair's band (a band clamp hid a planted slope error as a flat top); points are held to the unit square, sorted stably byx, and a later point at anxalready held is dropped; equality and hash are the points'. The graph draws by sampling the value itself (the ramp's rule), so the row shows whatcurve(t)returns. A dragged point, a typed place, an OSC point, and a phone drag all stop short of their neighbors (a handle's width, 0.001, 0.001, 0.01), because on a neighbor's place the curve keeps one of the two and the point an address names vanishes (an OSC test found it). A press away from every point inserts one on the curve and keeps dragging it;+inserts in the widest gap on the curve (curveGraphAdding), so nothing jumps;count:(default2...12) bounds the buttons, and a clamp past it keeps both ends and drops the last inner points. A list's length is the declaration's:restored(takes a longer payload's first values and keeps the current values past a shorter one's end; each element clamps and snaps through its own kind,_: keeping: ) Introunds on the way in (a whole list's bars step bymax(step ?? 1, 1),BinaryIntegertested on the element type), a payload with a value its element refuses restores nothing. Bars paint by drag and fill the bars a fast stroke skipped (barsPainting); a range holding zero grows bars from the zero line; beat marks only on a count of 8 or more divisible by four. Blends:Automation.blendandCueSheet.canFademove a list bar by bar and a curve point by point when the lengths match, and hold otherwise. Write-back (ParamWrite): a curve asResponseCurve(with bare whole numbers (the pairs' type is fixed by the call); a list by the scalar rule element-wise (whole stays whole while every value is whole and the literal had no point, otherwise a point on every value, since[( x, y), ...]) [1, 0]beside0...1reads as[Int]).--paramreads a curve asheight@placepairs (1@0,0.7@0.4,0@1, heights without places spread evenly, the color strip's spelling) and a list as comma-separated numbers (an empty field refused), and the listing writes both back pasteable. OSCQuery serves each as a container (fper bar,ffper point); the remote surface paints bars and drags points but adds none. The web page leaves both out (no control).CurveAndListParamTests,ParamWriteTests,OSCQueryTests,.aListAndACurveAnswerPerBarAndPerPoint RemoteWireTests,.aCurveAndAListTravelBothWays OllinLive --paramtestand--savetest(a curve, a fraction list, and a whole list written, recompiled, and read off a fresh sketch);Examples/;Live/ Parameters Docs/andHelpers/ Parameters .md#response-curve #bars,Docs/; Guide Ch 42 § Shapes you draw: a curve and a row of bars. The rows' drag by hand is a desk check.Helpers/ Animation .md#response-curve Performance stats (a shared
FrameStatsfeeding every host surface). The runner fills oneFrameStats(@Observable: fps, CPU frame time, draw counts, clock, canvas size) via the built-inStatsExtensionon the extend seam; the OllinLive sidebar, the gallery's right sidebar, and — standalone — a detached frostedNSPanel(⌘/ viaOllinHUDCommands) read it. A host with its own inspector sidebar opts the panel off (SketchView() and omitsshowsInspectorPanel: false) OllinHUDCommands. Stats are debug chrome, not in-canvas drawing — SwiftUI siblings of the Metal view, so they never land in exports. Gotcha: the CPU-ms must timeperformDraw()alone — timing acrossrenderer.render()includes the triple-buffer semaphore (vsync) wait and pins to ~1/fps, telling you nothing.SketchViewZStacks host chrome over a privateMetalCanvas— theNSViewRepresentableMTKView, still the AppKit/UIKit-portability seam.Writing an extension (
ollin new --kind extension;Sources/+OllinProjects/ ExtensionSeam .swift ProjectGenerator; in the window,.planExtension Sources/+OllinProjectGenerator/ SourceStage .swift GeneratorHarness;.swift SketchLoaderin.typecheck OllinRuntime). The third-party tier's convention half: a library other sketches import, namedollinx-<thing>with the moduleOllinx<Thing>(ExtensionNaming, a capital run staying one word —SVGTools→ollinx-svg-tools), written byplanExtensionover theExtensionSeamcatalog (the data-not-a-code-path shape the kinds and templates already use). Four--seamstarters, each a worked file plus real tests plus a publishing checklist: a drawing call onSketch, aShaderwrapped as aFilter, aFrameSource, aSketchExtension. Two surface facts run the other way from what the design note assumed:Draweris internal (so an extension extendsSketchand the public value types, and reaches the GPU through aShader; @eaviles has not ruled on opening it), andFilter/Generator/Sim/Combineare structs with no public initializer, so the effect catalogs take no new cases and.shader(_:)is the one way into the render graph (Filter.KindandShader.paramsare internal too, so an extension can build a filter and never read one back, which is what its tests can and cannot check). Load-bearing: the kind bypassestemplate.fits(_:)before the switch (a template's fit is about sketches, and asking would refuse a good library) and the CLI refuses every sketch-shaped flag (--template/--from/--3d/--canvas/--with) rather than writing a package where they went nowhere; a seam's shader constant is emitted internal, neverprivate(@testable importreaches internal and never private, so aprivate letmakes the generated test fail to compile). The generator window offers the kind through a source stage (shipped 2026-09-02): a library has nothing to run, so for the extension kind the left list holds the seams in place of the templates (no examples, since the plan ignores them), the stage shows the planned starter's text through a read-onlyNSTextViewcolored by the sharedSwiftTokensscanner (the performance editor's highlighter draws from the same eight patterns, so the two hosts cannot drift), a file strip under the stage switches between the files the plan will write (starter, tests, manifest, README,.gitignore; a non-Swift file is left uncolored), and typing a name re-plans, so the file renames itself on the stage as you type (the scroll position holds unless the file changes). The stage keeps the window's honesty promise: the starter is type-checked against the framework throughSketchLoader(.typecheck swiftc -typecheck -parse-as-libraryover the loader's own module discovery,moduleArguments()shared with the sketch compile; no dylib, no link, ~0.4 s) so the chip says Compiles, a seam that stopped compiling shows its log over the source, and the verdict is cached per seam, never per keystroke (a legal name cannot change whether a seam compiles). Canvas and wiring are hidden for the kind (a library declares neither; the CLI refuses the same flags), the name hint shows the two spellings the name becomes,--seam <id>opens the window set (and implies the kind), and the request carriesseam:only for this kind. Gates:OllinProjectGenerator --stagetestruns every seam through the stage's own check and requires a sabotaged starter to fail at its line (a check that cannot go red is worth nothing);--self-shot <png>captures the window (the source stage is AppKit text, so unlike a running sketch it comes out whole);everyExtensionSeamCompilesbuilds all four seams and their tests in one package,aGeneratedExtensionPackageBuildsrunsswift teston a real emitted package,ExtensionProjectTests(10 pure),SwiftTokensTests(5 pure, inOllinRuntimeTests). Discovery (a curated index, DocC, a Swift Package Index listing) waits on the repository being public and stays in ROADMAP. No pixel snapshot (the output is files).Docs/,Tools/ Extensions .md Docs/; Guide Ch 48 § Giving it to somebody else: an extension package + the ExtensionShape figure.Tools/ ProjectGenerator .md#an-extension-package-in-the-window Metal to GLSL for the web page (
Sources/:OllinShaderText/ ShaderToken/ShaderLexer/ShaderScan, the lexer the GLSL import shares, plusWebShaderTranslator/WebShaderCompat/WebShaderLibrary;Tests/). The first slice of the recorded web page (OllinShaderTextTests/ DESIGN-NOTES.md§ New output surfaces): the shader helper library rewritten from Metal to GLSL ES 3.00 by the import's lexer run the other way, so a translated unit keeps the author's layout and its line numbers. Load-bearing: it is a token rewriter, never a parser, and every edit replaces a token's text in place (the token count is the lexer's, pinned). The two rules that change a picture rather than failing to build arefmodandselect: Metal'sfmodtruncates where GLSL'smodfloors, so it becomesollin_fmodwritten out (nevermod), andselectbecomesollin_selectovermix(a, b, bvec)with its comparison turned into an overloaded helper call (c > 0.5inside it readsollin_gt(c, 0.5)), which is what lets a type-blind rewriter cross a vector comparison at all, since GLSL'sgreaterThanwants both sides the same width;any/alltake the same rewrite. Athread T¶meter isinout; a brace initializer becomes the constructor GLSL spells (vec3[12](…)with its trailing comma dropped, a struct's own name, the function's return type afterreturn); Metal's named constants stay names and arrive as#defines; a word GLSL reserves is respelled with a trailing underscore at its declaration and at every read;static/inline/constexpr, themetal::prefixes,using, includes, pragmas, and#linego; a#definebody has its types renamed;as_type<T>maps by the target's width. Nothing is dropped in silence: a pointer or buffer reference, a texture type or a.sample(read, an entry-point word, an attribute, a namespace, a template, an enum, and the Metal-only calls with no GLSL ES 3.00 form (sincos,ldexp, the bit tricks) each land as anunsupporteddiagnostic naming the line, andisCleanis false. The library crosses as its marked sections only (basealways,noisepullshash,visualboth), never the Metal preamble or the compute-only tail, since a page runs no kernel. Gates:WebShaderTranslatorTests(27, one per rule) andWebShaderLibraryTests(7): every section translates with no diagnostic at all, every defined function comes out the other side on the same line, and the browser gate compiles and links the whole library and each section alone in headless Chrome (--headless=new --dump-domon a file URL, read from the DOM; never pass--user-data-dir, which made the browser dump the DOM and then never exit; skipped where no browser is installed,OLLIN_CHROMEoverrides the path), proves itself live on a sabotaged shader (the log names the line), and reads pixels back to check thefmodsign and theselectshape against Metal's answers. The browser is waited on asynchronously through its termination handler, with stdout to a file, never a pipe read on a test thread: the first CI run parked three cooperative-pool threads in a blocking pipe read on a runner whose browser never exited (its children kept the pipe open past the kill), and the whole run stalled to its timeout. A probe finds once whether the browser yields WebGL2 (the GPU path, then--use-angle=swiftshader), the three browser tests skip with that reason where it does not, and a browser past its deadline is terminated and then killed. The framework's own segments mark sections for the page the same way (WebShaderLibrary:.segmentSectionNames shapesinShaderShapes.metal,presentinShaderCore.metal+ShaderEffects.metal; the closure addssdfundershapesandhashunderpresent), pinned bytheSegmentSectionsTranslateClean+ a browser compile. The user surface is the next bullet.A sketch as a web page (
Sources/:Ollin/ Export/ WebExport .swift OllinApp/.recordWebFrames captureWebFrame,WebTrack,WebShaders,WebPlayer,OllinApp/.web( of: frames: fps: skipSeconds: form: ) exportWeb,--export-web <path> [--frames N | --seconds S] [--fps F] [--skip S] [--inline]; the shared browser gate inTests/OllinWebGate/;Tests/). The recorder and the player of the recorded page (OllinTests/ WebExportTests .swift DESIGN-NOTES.md§ New output surfaces) through the primitives door: the export drives the sketch headlessly at a fixed rate like the video export, records what the renderer received each frame, and writes a WebGL2 page that draws it with the framework's own shape shader carried to GLSL, so a frame on the page is the Mac's frame. Load-bearing: the recorder reads the drawer afterperformDraw()and never renders (the call-orderedbatchesand theirsdfInstancesruns,backgroundColorwithaccumulates/backgroundSetThisFramefor the clear,toneMapMode/toneMapExposure), so it is noDrawerhook and nothing GPU-specific lands in the page; a.retainedbatch of shapes alone replays with the draw-time transform composed onto each instance's own. A refusal names the call family from the batch kind (webRefusalName: the rest of 3D,withClip,depth(at:), a live texture drawn as a picture, wide-gamut output; the doors since opened took the triangle and stroke paths, layers, blend modes,drawImage, the glyph atlas, gradient paints, and the two field kinds off the list) and the frame it was met at; nothing partial is written, and the flag exits nonzero. The shape coverage is one text in both places:ollin_sdf_coverageinShaderShapes.metal(the fragment's per-shape switch pulled into a function the Metal fragment calls, markedOLLIN_LIB_BEGIN shapeswith the coverage helpers andollin_sdf_distance,resolvePaintleft outside since it reads a texture) is what the page translates, so a new region shape joins that switch as it joinsollin_sdf_distance; the extraction was measured pixel-identical on five exports (HelloCircle, BreathingRing, StrokeAlignment, Polygons, Gradients: 0 bytes differing at 1080²). Thepresentsection carriesditherTriangle/finalizeColorandtoneMapACES. The wire record is 30 float32 per shape (WebInstance: the affine CTM's two axis columns and its translation, center, size, the two paints, the three params, stroke width, extra, band width, the tag as a float, the two gradient rows renumbered into the recording's strip), bound as ten instanced attributes; the page's vertex shader mirrorsollin_sdf_vertex, its fragment tailollin_sdf_fragmentwithresolvePaintwritten for the page, blendedSRC_ALPHA /+ONE_MINUS_SRC_ALPHA ONE /into anONE_MINUS_SRC_ALPHA RGBA16Fintermediate (EXT_color_buffer_float,RGBA8where absent), and the present pass writesfinalizeColor's encoded value straight to the canvas (an sRGB drawable re-encodes it on the Mac, the canvas takes it as is) with the dither'sfragCoordturned y-down. Weight, inWebTrack(Sources/): consecutive identical frames fold to one record (a still costs one frame); a stable cast (same count and tags every frame) stores the first frame as the base in float32 and travels only the moving columns, each one of three ways, tried in this order: live (an affine image of a formula-driven parameter's recorded values,Ollin/ Export/ WebTrack .swift affineFit, least squares with a max-error acceptance at 1e-4 of the column's range; the page then works it out every frame), fitted (on a lap recorded fromloopDuration,FourierFitover the column's period throughDiscreteFourier, an any-length mixed-radix transform with the plain sum for a prime factor; terms added biggest first until the reconstruction is within the same tolerance, refused past a frame-count/8 term budget; the Nyquist bin of an even length is one cosine at half weight; coefficients travel as float32 and the page evaluates them at the fractional frame, so the motion between records is the signal's own), or sampled (16-bit inside the column's own range,quantize, half a 65,535th of the range at worst, interpolated on the page); a changing cast travels every instance of every unique frame as 16-bit samples with a range per field (the tag column recovers exactly since its error is under a half). The meta JSON escapes<. A formula crosses as the formula (Sources/):Ollin/ Export/ WebFormula .swift webFormulas(of:)reads the automation's worked-out tracks (whole formulas and parts) in an order where a formula that reads a driven name comes after it (a ring stays behind, as it does on the Mac), skips a formula that reads noise, and carries a slider's or stepper's range and step (Fx.paramon the page applies the same clamp, the same step snap with half-away-from-zero rounding, and the integer rounding) while a part has none;FormulaJS.compilewrites the tree as JavaScript overv(the names) andFx(helpers) keepingFormulaNode.value's semantics (truth is a number that is not zero and not NaN,modfloors,roundis half away from zero,stepreads its edge first,&&/||short-circuit); the recorder reads each formula's value back from its parameter every frame (webFormulaValue, so what the sketch drew with is what a column is matched against), keeps the non-driven parameters as constants from the first recorded frame, the automation's clock (start/speed/loops/duration) so the page standstimewhere the Mac'sposition(at:)does,frameas index + skip + 1, and the pointer at the first frame as the page's starting mouse (apointermoveon the canvas moves it after). The formulas travel only when a column reads one live. Measured against Swift in the browser for seven expressions covering every function family: identical to 1e-9. Per-frame facts that never change (the clear, the tone map, the exposure, an identity frame map) travel once. Measured 2026-09-03: the ring's 60 s lap is 83 KB at 10 fps and at 30 (521 KB and 1.4 MB before the fit; 140 columns to 252 sines; 27 KB gzipped in transit), the breathing circle's 6 s is 75 KB with two sampled columns; the shaders and the player are about 70 KB of any page. The player interpolates between records when the cast is stable (frame k toward k+1, wrapping to 0 on a lap recorded fromloopDuration), draws every frame in order for an accumulating track, holds frame 0 underprefers-reduced-motion, pauses in a hidden tab, and leavescanvas.ollin/window.ollin(play,pause,seek,showFrame,frames,rate,duration,loops). The inline form is the whole of what the standalone wraps; the script finds the canvas just ahead of it. Gates (WebExportTests, 16): the recorder's frame (tag, radius, stroke, the identity transform), the lap flag with every column fitted and nothing sampled, the fit rebuilding a two-sine signal (and refusing a ramp), the transform against the direct sum at five lengths, a sampled column inside its range, the driven circle wired to its formula with its range, the fold and the stable cast, the changing cast, the refusals with their frames, the two forms, the shaders' provenance; and the browser gate: the page is played to a chosen frame inside the sharedHeadlessBrowser(a probe script callsshowFrameand writescanvas.toDataURLinto the DOM, so no screenshot flag, no window size, no device scale), decoded, and diffed againstOllinAppunder.image( of: frame: fps: ) Snapshot.tolerance(2.0) for HelloCircle, BreathingRing (sampled, and its fitted lap), a still, a moving disc, and a formula-driven circle, and the means print on every run (measured 2026-09-03 before the fit: 0.003 for the circle and the ring, 0.027 for the rounded rect and star, 0.013 for the moving disc, so a later drift is visible long before the line); the two forms compared byte-equal; the gate proven live (frame 0 against the Mac's frame 19 reads as different).OllinTestsdepends onOllinShaderTextandOllinWebGatefor it;OllinWebGateis a regular target underTests/because a test target cannot depend on another test target. The browser's clock is measured, not named (HeadlessBrowser): a test names what its page costs at a desk, the capability probe times its own launch (one browser, one trivial shader), and a page gets at least eight times that, capped at 600 s, with the number printed once per run. A run whose time ran out is tried once more at four times the budget. Both exist because the runner has no GPU, so every WebGL pixel is rasterized on the CPU and the wall clock swings with the load: the same one-page test takes 2.0 s here and took 229.7 s and 450.9 s there in runs that passed, while the eight-page.budget( _: launch: ) thePagePlaysWhatTheMacDrewsat at a flat 90 s per page and finally crossed it (CI run 35051898614; the page itself was correct, and the same commit went green on a re-run).WebGateTests(4) pins the budget; the retry was verified both ways by starving the first attempt. The shader door (2026-09-03): the layered effects cross. The recorder (WebGraphRecorder,Sources/) writes down each frame's pass graph beside the shape vector: the layers in the renderer's own fill order (generators, drawn targets, feedback, fields, then the filter and combine outputs in record order), what each was filled from, the canvas's items, and the whole-frame filters; a surface's items are shape runs and image quads (Ollin/ Export/ WebGraph .swift drawImage('s sixlayer .image) OllinImageVertex, 48 floats, under the batch's blend mode, drawn by the page's own image program with the Mac's factor table per mode); a pass's parameter rows join the frame's float vector, so a generator's phase fed the clock fits on a lap and samples otherwise, and a graph equal from frame to frame travels once (WebTrackreads stability as equal graphs plus equal tags; a changing cast stores shapes and quads as 16-bit samples by field and the rows as float32 inextra, with the graphs deduped). The pass description is one table for both sides:EffectPass(Sources/:Ollin/ Effects/ EffectPass .swift Filter.singlePass,Combine.singlePass,Generator.pass, theEffectQualitytap tables) is whatapplyFilter/applyCombine/encodeGeneratorencode from and what the recorder writes down, so the packing of a filter's numbers cannot drift between them; the refactor was measured 0 bytes differing on 25 exports (six FilterCatalog families, four GeneratorCatalog families, Glitter, SoapFilm, MeshGradient, Cellular, Chladni, DomainColoring, EscapeTime, Relight, Aside, PigmentMix, FlowStreaks, Ripples, Feedback, Layers, VisualSynth) before the exporter read it. A filter that is more than one pass answersniland keeps its orchestration in the renderer; the recorder refuses it by name (the diffuse filter), except.gaussianBlurand.bloom, which cross as the page's own passes (a separable Gaussian to three and a half sigma, normalized in the shader; measured on a one-pixel line against the Mac's hardware kernel, the same normalized Gaussian to within a level or two out past three sigma; bloom = the translated bright pass, the page's blur, the translated add-back). A wholefragmententry point crosses (WebFragmentTranslator,Sources/): the reachable closure over the file-scope declarations (functions with every overload, structs,OllinShaderText/ constantglobals,#definemacros, whose bodies are re-lexed for the texture rewrite) in the framework's order; the entry's parameter list is read by attribute (PresentOut in [[stage_in]]becomes the page'sin vec2 uvwithin.positiona macro overgl_FragCoordturned y-down,texture2d<float> x [[texture(an)]] sampler2Din binding order,samplerdropped and its uses0,constant float4 *params [[buffer(a0)]] uniform vec4array sized per fragment by#define OLLIN_PARAM_ROWS);t.sample(s, q)becomesollin_tex(t, q)andlevel(n)the LOD form,t.read(c)a fetch,get_widtha size query, every read turning the coordinate over because the page keeps its layers bottom-up (the effect vertex stage writesuv = (p.x, 1 - p.y)exactly asollin_present_vertexdoes, andollin_texreads(q.x, 1 - q.y)); a pointer walk over the params array (constant float4 *basis = params + 3and a helper takingconstant float4 *rows, the spectral family) becomes int offsets into the uniform array; a scalar initializing a vector (float2 p = 0.0) is wrapped in the constructor (a rule the cellular generator needed). All 129 door fragments compile in headless Chrome (WebFragmentTranslatorTests, which also found that the gate's compile page had to outputuvfrom its vertex stage or the very first program failed to link). A user shader crosses by the same rewriter (WebUserShaderGLSL): the wrapper is written for the page by hand (aShaderInfostruct without the texture members,sample_/sampleAux/sampleRawreaders overollin_src0/ollin_src1,paramoverloads, the clock, pointer, frame, and resolution as uniforms), the library sections the shader asked for and the user's body are translated (athread const ShaderInfo ¶meter becomes a value), andmainconverts straight sRGB to premultiplied linear asollin_user_fragmentdoes;sampleis a GLSL reserved word, so the reserved-word rule'ssample_is the name the wrapper declares. A compiledVisualchain is a user shader and crosses as one.info.timeis the track's clock,info.mousethe live pointer, and aShader'sparamsare recorded rows. Feedback and single-field simulations keep persistent pairs on the page (keyed per object, allocated at the rest state or the seed fill, flipped per frame; a sim's inject and its substeps run as translated fragments, itsagecounted per key); such a track isstatefuland the player draws every frame in order from the first, as it does for an accumulating one, and--skiprefuses it. Gates (WebEffectsTests, 10): the graph's shape per kind of pass (a generator's four rows and its moving phase column, a filter chain's inputs in order, a table traveling once, a combine's base and aux, a user shader's rows and its GLSL, feedback and field nodes, whole-frame filters), the refusals by name, and the browser parity of every kind of pass at a chosen frame againstOllinApp: a moving generator, a two-filter chain, a gradient map, a mix under a mask, a user generator, a user filter, a user combine with params, a chain, a.image( of: frame: ) composestack with a half-size layer and add/screen blends, a feedback tunnel at frame 11, reaction-diffusion at frame 15, whole-frame filters, and blur under bloom; measured on the first run at means of 0.006 to 0.16 (the feedback tunnel the largest) against the 2.0 line, and the gate proven live by playing the filtered page against the Mac's unfiltered layer. The examples, measured (2026-09-03,--export-web --frames 12 --fps 30against--export --frame 14, the still export counting at 60): Cellular 0.010, MeshGradient 0.012, Chladni 0.043 (a few sand grains land a pixel over, its max 127), DomainWarp 0.013, ShaderFilter 0.030, VisualSynth 0.030, Glitter 0.109, SoapFilm 0.091, every page 98 to 165 KB (the shaders and the player are most of it; a filter's rows add a few floats a frame), which is the effects examples that draw no caption; DiffusionCurves stops on its curve's stroke and Ripples on its radial-gradient dab, both named. A gotcha the gate met: the hash-driven passes (the plate's sand, a voronoi's jitter) are exact too, so a page that reads far from the Mac is a clock mismatch, not a shader one; the still export ignores--fpsand counts at 60, so its frame 14 is the page's frame 7 at 30. The triangle door (2026-09-03): strokes and fills cross as their vertices. The recorder reads a.trianglesor.fringebatch's run ofdrawer.vertices(the fringe expander's bands, libtess2's fills, outline text, the elliptical arc) asWebVertexrecords (7 float32: the position,aa.x, the straight color with its alpha; a gradient on this path was baked into the colors on the Mac, so it crosses as they are), a third region of the frame vector between the quads and the parameter rows (WebGraph/.vertexCount vertexOffset); a.retainedbatch of shapes, strokes, and fills replays run by run in the recording's order with the draw-time transform applied to each vertex on the CPU, as the replay's vertex stage applies it. A blend mode crosses on shapes, strokes, and fills (WebDrawItem.shapes/.trianglescarry theWebBlendindex; the page'ssetBlendmirrorsBlendMode,.blendState( premultiplied: ) SRC_ALPHAfor a straight fragment andONEfor an image). The page draws a run withollin_vertex's mapping and the two fragment tails (ollin_fragment's linearized color;ollin_fringe_fragment's paint alpha timesperceptualCoverageof the interpolated coverage), both cut from thebasesection. Multisampling is load-bearing, and its orientation is the trap: a fill's edge has no analytic coverage, so a track whose graphhasTrianglessetsmsaaand the page rasterizes every drawn surface (the canvas, a geometry layer, a feedback back, a sim seed) into a four-sample renderbuffer (RGBA16FunderEXT_color_buffer_float; four is what this Mac's canvas uses) and resolves it byblitFramebuffer; an accumulating canvas keeps its samples across frames, asaccumTargetdoes. The first parity run put 0.43% of a polygon's pixels more than 32 levels off the Mac along every diagonal edge while an axis-aligned rectangle with fractional edges matched exactly: the page keeps its pictures bottom-up, so in the GPU's own texture space the picture is mirrored and the fixed rotated-grid sample pattern meets a diagonal edge mirrored (each axis's offsets are their own mirror, which is why an axis-aligned edge cannot tell). The items are therefore rasterized upright into the multisampled buffer (ollin_flip= -1 on the three item vertex stages, 1 otherwise, so a page without triangles is unchanged) and the resolve flips on its way into the surface's texture through a same-size single-sample surface, since a multisampled read allows no flip; the polygon then matches to two levels with no far pixel. Weight, and the second trap: a stable cast's vertices travel once, the positions exact in float32 (WebTrack) and the coverage and color as 16-bit samples by field (.vertexPositions vertexBase+meta.vranges), moving vertex columns fit or sample like a shape's, a changing cast stores every vertex of every unique frame the same way (metabeside.positionOffsets offsets), and the exporter prints the fullest frame's vertex count. A position is never quantized over the frame's extent: the first pack quantized every field, and a 16-bit step over a canvas-wide drawing is a sixtieth of a pixel, enough to flip a multisample on a fill's edge once in about twenty edge pixels; on DeBruijn's captions that put a sixth of the glyph edge pixels a sample off the Mac (0.07% of the picture, under the line, and invisible, but not parity), while a caption alone read exact because its extent was the glyphs' own. Float32 positions cost four bytes a vertex more and made the captions exact. Gates (WebTriangleTests, 9): the runs per kind in call order and a vertex field for field, outline text as fills, blend indices on shapes and strokes, a recording's replay under its transform (the first vertex where the frame's turn puts it), the stable pack (the base holding the vertices as samples, the moving columns few) and the changing one, the pipelines' provenance; the browser parity of seven cases (joins and a round cap, a bezier, a gradient stroke, a concave polygon, a holed shape, a moving vertex, outline text, add and lightest, a turning recording, an accumulating canvas, a growing cast) at means of 0.004 to 0.042, under a second criterion the mean cannot feel, no more than 0.2% of the pixels past 32 levels (the figure gate's own line for a visible move), proven live twice on the pre-flip page: multisampling off read 0.25 to 0.66% far on the four fill-bearing cases (the stroke-only ones stayed under the line, as they should), the perceptual remap dropped 0.43 to 3.4% on every case but the accumulating one (its half-alpha strokes move under 32 levels); and the sabotage of a page's first frame against the Mac's fullest. The Patterns set, measured (2026-09-03, all 76 examples through--export-web --frames 4 --fps 60 --seed 1, the page's frame 3 played in headless Chrome against--export --frame 3): 71 cross and every one reads under both lines, 61 of them through this door at means of 0.005 to 0.160 with no pixel more than 32 levels off on any page (the ten shape-only pages at 0.005 to 0.129); the five that stop name a clip (Anamorphosis, Caustic, FordCircles) ordrawImage(Buddhabrot, FractalFlame). Weight is now the door ahead: 21 of the 61 pages are under 1 MB and the median is 3.3 MB, but a dense line drawing runs far past a page (Penrose 51 MB, Roses 72 MB, Spirograph 142 MB, ParametricLSystem 234 MB, Kleinian 309 MB, Guilloche 325 MB at 3.4 million vertices), a median of 36 times what the same frame weighs as SVG and 388 times at most, which is the measurement the WebAssembly expander option under the weight door (DESIGN-NOTES.md§ New output surfaces) was waiting for; the exporter writes the file and prints the size either way until that door lands. The asset door (2026-09-03): pictures, atlas text, and gradients on shapes cross. A picture travels once as an asset (WebAssetEncoder,Sources/;Ollin/ Export/ WebAssets .swift WebPictureon the recording): a file the sketch loaded travels as the file when a browser decodes its format (browserFormatreads the magic bytes for PNG, JPEG, GIF, WebP;Image.sourceURLis set byinit(contentsOf:)anddrawsSourceFilesays the pixels are still the file's), anything else as a PNG ofpremultipliedPixels((the buffer the Mac's texture is built from once pixels were written); the recorder keys an image by) ObjectIdentifier+Image(bumped on every pixel write) with a weak reference to catch a reused identifier, and dedupes by content, so two images with equal pixels are one asset and an edit is a second (.pixelGeneration Repaintedin the tests). A.imagebatch's run of quads (one, or one per symmetry copy) becomesWebDrawItemwith.image( source: quad: count: blend: ) WebImageSourcebeside the layer sources; a live texture (a camera, a video, a compute texture) refuses by name where it is read. Atlas text travels as its quads over the font's page (.picture( i) WebDrawItem;.glyphs( atlas: quad: count: blend: ) WebAtlason the recording): the recorder holds each atlas page it meets and reads it at the END of the recording (WebGraphRecorder,.finish GlyphAtlas: the rows down to the last packed shelf, 1024 wide), since a page fills as frames draw; a page is never cleared, so a font that fills one mid-recording crosses as several pages, each its own asset (.Page .webPage( ) WebAssetTests). The rows travel as an 8-bit gray PNG and land at the top of a page-sized.aFontThatFillsItsPageCrossesAsSeveralPages RGBA8texture (texStorage2D+texSubImage2D), read raw (colorSpaceConversion:) by the page's glyph fragment,'none' ollin_glyph_fragmentwritten for the page (the sampled distance to coverage throughfwidth,perceptualCoverage, straight alpha over the corner tint, so a gradient fill on atlas text crosses as its corner colors). A gradient on a shape is carried in its record: the two gradient rows are renumbered from the frame's per-frame, first-use-ordered table (and a retained batch's own table) into the recording's one strip (WebGraphRecorder, deduped by content), which the page uploads as an.gradientRows SRGB8_ALPHA8texture 256 wide (BakedGradient.width) bound to the shape program; the fragment tail carriesresolvePaintwritten for the page (the sametmapping,(,t * ( w - 1) + 0.5) / w (row + 0.5) / hthroughtextureSize) and passesfillKind == 3 || strokeKind == 3toollin_sdf_coveragefor the along-path coordinate. Three things the browser decided, all measured: (1) the decode is asynchronous, so the player draws its first frame whenPromise.allof the loads resolves (player.ready; the canvas is cleared to the first frame's paper meanwhile, encoded in JavaScript; a page with no assets starts synchronously as before;pause()before the start holds the autoplay) and the test probe awaitsready; (2) each asset loads through an image element from a data URL, nevercreateImageBitmap: an image element in flight holds the document's load event, which the headless dump waits for, where a bitmap decode holds nothing (measured on a 179 KB picture under two filter passes: the dump beat the bitmap decode two runs in six with--virtual-time-budget=30000and six in six without it; the image element read twelve in twelve with and without the budget, so the gate carries no budget), and a bitmap source ignores the upload flags where an image element honors them (UNPACK_PREMULTIPLY_ALPHA_WEBGLasked on a bitmap upload left a half-alpha pixel too bright, 1.4% of a test picture's pixels past 32 levels;UNPACK_COLORSPACE_CONVERSION_WEBGL = NONEandimage-orientation:on the element keep the decode raw, as ImageIO's is); (3) the browser's mip level 1 of an sRGB picture matches a box filter within two levels, as the Mac's does, so a picture drawn small reads the same level on both. A picture's edge is a raster edge:none WebGraph(triangles or image quads) is what sets.needsMultisampling msaanow, since a turned picture's edge on the Mac is multisampled and read 0.23% far without it; glyph quads keep their edge outside the field and need none. The Mac had a defect the gate caught: ImageIO decodes a PNG with alpha toalphaInfo == .last(straight) andMTKTextureLoaderkeeps it straight whileollin_image_fragmentblends premultiplied, so a translucent PNG pixel drew too bright;Image.texture(for:)now rebuilds a straight-alpha source through the premultiplying sRGB context (sRGBTexture(from:)), and a loaded PNG then matches the page at a mean of 0.011 with no far pixel. A JPEG is decoded twice (ImageIO on the Mac, the browser on the page) and the decoders disagree by a few levels along a sharp chroma edge (a checker of 8-pixel cells reads a mean of 0.71 and 2.4% of its pixels past 32 levels), which the far criterion sees and the mean does not; the file crosses as it is since a photo re-encoded as PNG weighs several times more, and the test asserts the mean alone for it. Gates (WebAssetTests, 9): a picture once across six draws (whole, small, tinted, multiplied, covering, turning) with the quad on the wire field for field, an edit as a second asset and equal pixels as one, a PNG and a JPEG file as their own bytes and a TIFF as a PNG, atlas text as glyph quads within the page's rows, a gradient's kind and row per shape with the rows one table on every frame, text and a picture in a recording turning, the page's assets and strip in the script, the browser parity of nine cases at means of 0.004 to 0.044 with no far pixel (the JPEG at 0.71 by its decoder), and the sabotage of the pictured page against the paper alone.OLLIN_WEB_DUMP=<dir>on that test writes each case's page and Mac frames to disk. The Text and Images examples, measured (2026-09-03, the same gate as the Patterns set): all 29 sketches ofExamples/TextandExamples/Imagescross and read under both lines, at means of 0.003 to 0.163 with at most 0.015% of the pixels past 32 levels (PhotoMosaic's 25 tiny pictures scaled), TextVolume's wall of atlas text at 0.126 with its whole page 9 KB, and Buddhabrot and FractalFlame, the two Patterns sketches the triangle door had stopped ondrawImage, at 0.057 and 0.092; the pages run 157 KB to 10.8 MB with a median of 774 KB, the heavy end a changing cast of outline glyphs (GlyphMosaic) and, for a picture that changes every frame, one PNG per version (Autostereogram, four frames, four pictures, 2 MB), which is the weight door's case. Two things the gate found on the way: a first run put the headless dump ahead of a 179 KB picture's decode on one page (LuminanceMelt), which is why the loader is an image element, and a gate script that grepsTest runfor a suite's end matchesTest run startedfirst. The field door (2026-09-03): composed and raymarched fields cross. The VM arithmetic is one text in both places:ShaderCombinatormarks.metal ollin_emod, the stairs and columns joint ops,ollin_sdf_combine, andollin_sdf_xformasOLLIN_LIB_BEGIN combinator, andShaderRaymarchmarks every.metal ollin_sd3_*distance function,ollin_sdf3d_eval,ollin_sdf3d_combine,ollin_sdf3d_unrotate, andollin_sdf3d_xformasraymarch(its closure pullscombinator,noisefor the roughening'svalueNoise, andsdffor the cone'sdot2); the instruction records the header declares (SDFNode,SDFNode3D) are declared again inside each section under#ifndef __METAL_VERSION__, which Metal never enters and the page's rewriter keeps, so a section compiles standalone in the browser gate. A fractal leaf's iteration count readsint(x + 0.5)on both sides now, since a count that crossed a wire a hair under its integer used to lose a level. The VM loops, the march, and the lighting are written for the page (WebShaders,.groupFragmentTail fieldFragmentTail,fieldLightingSource,upsampleFragment,groupVertex,fieldVertex): the program sits in alayout(block, four rows a node and 256 nodes at most (the framework's own cap, and the 16 KB WebGL2 guarantees), uploaded per field withstd140) uniform Nodes { vec4 nodeRows[1024]; } bufferSubData; the two stacks, the coverage tail, andresolvePaint(oneresolvePaintSourceshared with the shape tail) mirrorollin_sdfgroup_fragment; the field fragment mirrorsollin_raymarch_fragment(the ray through the inverse view-projection, the AABB slab test, the sphere trace with the pixel-cone coverage, the tetrahedron normal, the analytic self-shadow toward each caster, the leaf color or the screen-space gradient,gl_FragDepth = clipunder.z / clip .w LEQUAL) and itslitColoris the punctual half ofmeshLitColor(models 0 to 3, directional/point/spot with the wrap and the cone, the caster'sstrength,ollin_sss_translucency, both iridescence modes over the library'sfbm, the sparkle overhash33, the rim); a physically-based finish readsollin_pbr_essfrom the same split-sum table the Mac bakes, baked once per process on the CPU (WebBRDFLUT, 256 a side, 512 Hammersley samples a texel,ollin_ibl_brdf_lutsample for sample with the Mac's own tangent frame, stored as half floats throughWebHalfso a texel rounds as the Mac'srg16Floatdoes) and carried as anRG16Fasset only when a field uses one. The wire: four regions join the frame vector between the quads and the vertices (WebGroup26 floats in the seven rows the group stage reads,WebNode16,WebField36,WebNode3D16;WebGraph….groupOffset node3DOffset; the vertices stay last so the track's base split holds), items["g",andstart, count, blend] ["f",with the finish as nine parameter rows (start, count, blend, materialRow] WebMaterial), a program placed once per source range however many symmetry copies or replayed recordings share it, and the scene block travels apart from the vector, whole and exact (WebFrame.scene,WebGraphRecorder: the three camera matrices, viewport and the two step budgets, the march scale with the reduced pass's size and the scene scale, ambient, eye with the lit flag, counts, 20 floats a light, one row a caster;.sceneBlock WebTrack.scenewithmeta.sceneOffsets/sceneLengths; the page lerps it between records) because a camera matrix quantized inside its range moves a silhouette; the fold reads the scene too (a still field under a turning camera is a new frame every frame, though its vector never moves: the first gate played frame 0's camera at frame 3 and read 0.7% of RaymarchedShadow far). The stable-cast test also comparesWebGraph(a node's kind and op, a field's program length and boundedness). The scene resolves as the export's renderer would:.structuralColumns MetalRenderer/.raymarchBudget raymarchScale/fieldScreenCoveragearenonisolated staticnow (the instance methods call them withautomaticQuality; the recorder passes.detail, the export lift), so.defaultmarches at (192, 72),raymarchResolutionkeeps (128, 48) and traces at the coverage-adaptive fraction into ahalfSurfacewith aDEPTH_COMPONENT24texture, upsampled once by the page'supsampleFragment(bilinear color, point depth,gl_FragDepthre-emitted, premultiplied over,region=(on an exact-size target, which is the Mac's subrect clamp on a grow-only one); a page whose track( w-.5)/ w, ( h-.5)/ h) hasFieldskeeps a depth renderbuffer on the canvas (and on its multisampled buffer), cleared each frame. Only the primary caster reaches a field (finalizeShadowCasterskeeps slot 0 and drops every other slot that has no rendered map or cube, and a fields-only frame renders none), and its map term samples the 1×1 dummy map cleared to 1, so the page marches the analytic self-shadow alone and the caster row carriesshadowLightandshadowStrength. Refused by name where the page's lighting stops (sceneBlock,WebMaterial.refusal): an environment, fog and aerial perspective, an area light, a profile or cookie, contact shadows, GI, ray-traced reflections, the scene through glass, caustics, and a transmissive, clear-coated, sheened, thin-film, brushed, or scattering finish; the rest of 3D (a mesh, a point cloud, a field inside a layer) as before. Gates (WebFieldTests, 10): a composed field's quad and program field for field (the identity transform, a 3-point stroke, a linear fill on row 0, the second program following the first), symmetry copies and a turning recording sharing one program, a raymarched field with its scene (the export's (192, 72), a full-resolution march, one directional light, no caster), a still field under a turning camera as a new frame every frame, a reduced march's scale and a shadowed plane's caster, the split-sum table's presence and its half floats, the refusals by name, the shaders' provenance; and the browser parity of seven cases (a melt with a carve, a morph, a gradient, a stroke, and a tiling; symmetry, additive, a recording; a turntable blob; jade under a spot and a point with a gradient field beside it; a self-shadowing plane; a half-resolution march; a metal, a toon, and a Gooch) at means of 0.006 to 0.13 with no pixel past 32 levels (the reduced march read 0.38 with 0.1% far until the fold read the scene), and the sabotage of frame 0 against the Mac's frame 11. The Raymarching and Combinators examples, measured (2026-09-03, the same gate as the Patterns set, frame 3 at 60 fps): all five Combinators sketches and twelve of the seventeen Raymarching sketches cross and every one reads under both lines, at means of 0.051 (RaymarchedPlane) to 0.153 (RaymarchedDomain) with no pixel more than 32 levels off on any page, the five Combinators pages at 0.064 to 0.142 with their outline captions; every page weighs 220 to 306 KB, the shaders and the player nearly all of it, since a field's program is a few dozen rows and a still field under a turning camera travels one scene block a frame. The five that stop draw a mesh beside the field or outside a sculpt block (RaymarchedCastShadow, Distort, ReceiveShadow, SDF) or an environment (RaymarchedEnvironment), each named. The first run read RaymarchedShadow 0.7% far, RaymarchedClay 0.3%, and RaymarchedPlane 0.17%, with frame 0 exact and frame 1 already drifting: the fold, which is what found the missing scene compare (a camera probe on both drives printed identical eyes first, and was removed). Parameters as controls (WebControls.swift:WebControl/WebAxis/WebAxisColumn,OllinApp;.webControls --no-controls; the handle'sparams/get/set/reset). After the baseline, each part of each@Param(a number, an integer, a switch, a color's four channels, a point's parts, a pair of ends; a menu, text, a swatch strip, a rectangle, and insets are not offered) is set on a fresh sketch fromremake(the flag site passes the command-line factory underwithoutActuallyEscaping, so the seed, a replayed take, and the automation apply;web(of:)defaults totype() afterof: sketch) .init( ) runSetup(), recorded over the same frames throughrunWebFrames, and every column of the vector, the scene block, and the per-frame facts (the clear's channels, the exposure) that moved is fitted to a line in the setting at every frame, three settings a part (the range's ends, then two golden-section points,webProbeSettings, so no symmetric curve passes as a line; a switch has one), the tolerance a ten-thousandth of the column's spread or a few float32 steps at its size. Load-bearing: a discrete column that changes (a shape's tag or gradient rows, a program's kinds, a paint kind:webDiscreteColumns), or a graph, a length, the clear's presence, or the tone map, is a cast change and fails the part, except at an end of the range, which is passed over and the line fitted inside it (drawCircleskips a radius of 0 and a stroke with no alpha skips the shape, which tookradiusand every color's alpha out of the hero until the ends were passed over); a color channel is tried as itself first and then throughColor.srgbToLinear, per column, which is how a paper color reaches the clear while the same color reaches a fill straight; the wired parts are then moved together once, and a column that moved by other than the sum of its slopes drops every part touching it (webReasonCoupled: a stroke alpha written asink.alpha * fadeis exactly this, and the first fixture had it); a fresh unmodified run is compared to the baseline first, and a sketch that differs (unseeded randomness) loses every control with that reason; a part with no touched column is inert and the control is not offered, except a color's alpha, which the well drops. In the track, a column a formula drives is left to the formula when the formula's transitive reads include the axis (WebTrack), since the page evaluates formulas over the controls' values under their names; slopes pack as a moving column does (.formulaClosure packSlopes: one float, the sines of a lap, or a sample per frame) into@AXES@. On the page,applyAxesaddsslope × (after the base, the varying, the fits, and the drives, onto the vector, the scene block (copied first, sincevalue − base) sceneBasehands out a view), and the clear and exposure; a change on a sequential track replays from the first frame. The standalone page builds the panel under the canvas (PANEL;--ollin-panelsizes the canvas to leave room; the panel's text color follows the paper's luminance); the inline form never does and carries the handle. Gates (WebControlTests, 11): the wired slopes (a radius at one, a turning center at half the cosine, a color at one per stroke, the clear through linear light, a switch by the fill's difference, a point's part), each refusal by name (nonlinear, cast, coupled, inert, no control, driven, nondeterministic), a shader's row, the packing modes and the driven-column exclusion, the panel's presence per form, the probe settings, the browser parity of ten moved-control cases against the Mac run with--paramat the same values (means 0.003 to 0.067), the sabotage of a moved radius against the recorded one, and the handle's report through the DOM. Measured on the hero:inkandpaperlive (115 columns, each alpha fitted to one sine), 4 KB on the page, 26 more recordings of the lap. The weight limit (2026-09-04): a page pastOllinApp(25 MB, the largest file the static hosts serve and what a phone opens in seconds;.maxWebPageBytes --max-page-size MBraises it,0lifts it,maxBytes:onweb(of:)/exportWeb) is refused with aWebWeightRefusal: the weight, the heaviest part (WebTrack.weightscounts the shapes and passes, the stroke and fill vertices, the scenes, and the controls as the bytes they take written out, split into stored-once and per-frame;webInlineFragmentadds the pictures and the atlas pages; the remainder is the shaders and the player), whether it grows with the frames (per-frame > once, so the advice is--fps 10/ a shorter--seconds, else "would not help"), the video pointer, and the flag that writes it anyway. Load-bearing: the weight is worked out before the page's text exists (WebPlayerover the slot sizes plus the wrapper measured empty), and the recording bounds the page from below as it goes (.filledCount WebWeightBoundinrunWebFrames: the first frame's vertices and shapes once, every differing frame whole once the cast has changed, every picture, and, on a recording that is not a lap with no formula, two bytes per unique frame for every column that has moved so far plus twelve once; a lap or a formula leaves the moving columns out, since a fit or a drive can carry them for less), stopping at the frame the bound passes the limit withseen: (frames, of)and "at least" in the message, which is what keeps a 3-million-vertex drawing from taking 17 GB of frames it would never use on an 8 GB machine (the guilloche refuses at frame 1 in 0.4 s; the Penrose tiling at frame 5 where the old exporter recorded 2 min 16 s first). Two weight fixes found on the way: a sampled column's range and index travel as float32/uint32 base64 (WebTrack.ranges/.varying,@RANGES@/@VARYING@) rather than JSON text (43 bytes a column, which outweighed the samples on a short recording: a 2.5 MB scribble page became 1.5 MB), and the player's slots fill in one pass (WebPlayer.filled/slots(in:); eachreplacingOccurrencescopied the whole page through NSString, 0.7 s a frame on a 400 MB page, 0.05 s now). Gates (WebExportTests, 20): the refusal past a tiny budget naming the vertices with the frame count and the flag that then writes the page, a still's "would not help", the parts summing to the page with the vertices absent from a shapes-only sketch, the first-frame refusal of a dense still with the bound under the page's true weight, the within-frames refusal of a moving line with its moving columns counted against the same line as a lap weighed once assembled, and the one-pass fill (a lone@, a lower-case name, a value holding a slot's spelling). Measured 2026-09-04 on the six heaviest pattern examples (six seconds at 30 fps): all refused in under a second, vertices 15 to 70 times the same frame's SVG (the numbers are inDocs/Output/Web.md§ The weight limit).Docs/Output/Web.md§ Fields on the page, § Parameters as controls, and § The weight limit; Guide Ch 45 § A page that plays it: the web export. The points door (2026-09-06): strokes and fills cross as the points and the style the sketch gave, and the page expands them itself. The fringe expander's geometry stage moved out ofDrawer+Tessellationinto theOllinExpandertarget (StrokeExpander/.expand innerCrossings/spread/circleSegments;FillExpander.fan/.triangulateover libtess2;WebSourceLayout/WebSourceExpander, the wire's record and the walk that turns records into vertices), plain Swift over the C tessellator with nothing from Foundation, andScripts/compiles the same files plusbuild-web-expander .sh Scripts/with Embedded Swift forweb-expander/ Entry .swift wasm32-unknown-wasip1through the swift.org toolchain and its_wasm-embeddedSDK (Xcode's toolchain has neither the embedded stdlib for wasm nor a wasm linker) intoSources/(72,622 bytes: a reactor module,Ollin/ Resources/ WebExpander .wasm --strip-all, libtess2'ssetjmpshimmed to a trap inScripts/, its one importweb-expander/ shim/ random_get) besideWebExpander.json(toolchain, SDK, the SHA-256 of the sources in the script's order). Load-bearing: the Mac's expander is untouched by the move (a dump of 38,274 vertices over every join, cap, weight, transform, gradient, profile, and fold is byte-identical before and after;Drawerkeeps the measuring half, dropping repeats, subdividing for a gradient or a profile, the fringe width1/ctmScale, the half-width and the color per point, and hands the expanderPoint2Ds); the collinearity guard isStrokeExpander, a hundredth of a degree, because a point carried in single precision bends a straight run by a sine near a millionth and the old.collinear = 1e-4 1e-6made a gradient stroke's inserted subdivision points read as joins on the page (+360 vertices on the fixture) while the Mac's doubles stay collinear to 1e-16 either way (the dump stayed byte-identical under the new guard); the committed module must come from the sources in the tree (WebSourceTestsrecomputes the hash with CryptoKit, and.theCommittedExpanderWasBuiltFromTheseSources Scripts/runspreflight .sh build-web-expanderwhen.sh --check Sources/,OllinExpander/ Scripts/, orweb-expander/ External/CLibtess2/change, so an edit without a rebuild fails on CI without the toolchain). The record (WebSource,Sources/): whileOllin/ Export/ WebSources .swift Draweris on (armed by.recordsWebSources recordWebFramesand the controls probe beforerunSetup(), so a batch made insetup()carries its sources onBatch.webSources; off on the live path, one Boolean per stroke),appendFringeStrokeSinglekeeps each stroke as its deduplicated, subdivided points, closed/join/cap,fringe,ctmScale, one half-width or one per point, one color or one per point (a gradient, a varying opacity), the transform, and the vertex range it became;drawPolygonand the ellipticaldrawArckeep a fan,drawShapeits fillable contours with the winding rule, under a solid paint only (a fill under a gradient keeps its vertices, as do outline glyph fills and glyph strokes throughappendStrokedPath);replicatedcopies each record per fold withfold * transform, and the recorder passes over a record that expanded to nothing. On the wire a record is a 12-float header (kind, flags, count, fringe, ctmScale, the six transform floats, 0) and its body; the region sits between the 3D nodes and the vertices, always float32 (a position is never quantized), its header columns and a fill's contour lengths instructuralColumnsso a join that changes is a change of cast. The recorder walks each.triangles/.fringerun by binary search over the records (a running cursor breaks because items are gathered per surface) and interleaves.sources(items (start, floats, count, fringe, blend) ["x",in the meta) with the leftover vertex spans in draw order; a retained batch replays its records under...] retainedTransform * transform, so a turning batch moves six floats a frame. On the page the module is instantiated synchronously (new WebAssembly+.Module Instance, 5.5 ms in Chrome; a pending asynchronous compile holds no load event and raced the headless dump, so that path stays only as the fallback),drawSourcescopies an item's floats into the module (ollin_input/ollin_expand/ollin_output, eight floats a vertex: the position, a stroke's two edge distances, the color), keeps a buffer and a VAO per item until its floats change (a still expands once, a mover once a frame, a turning recording once per turn since the transform is in the record), and sweeps entries not drawn this frame. The page carries the module (97 KB as base64, its own weight part,the stroke expander, and the tessellator's SGI notice beside it in the script) only when a frame has points to expand; a missing resource throwsWebExpanderMissing. The bound and the track countstrokes and fills as pointsas a part beside the vertices. Gates (WebSourceTests, 9): the recorder (every stroke of a fixture with every join, cap, weight, transform, gradient, profile, and arc is a record and none is left as vertices; a fan, a holed shape as[[5, 4]], and arcs, with outline text's fills and strokes as vertex spans between them; twelve folds of a stroke and a fill are twelve records each and one moving point moves twelve floats; a turning batch moves only its transforms), the round trip on the Mac (WebSourceExpanderover the wire's region against.expand drawer.vertices: positions within 2e-3, coverage and color exact, with a culprit report naming the first record that expands to a different count), the track (a still's records in the base as float32, a changing cast's in the exact stream, a restyled join two unique frames), the provenance, the browser parity of seven cases at means 0.004 to 0.019 with no far pixel, and the sabotage (the same page withEXPANDERblanked draws no strokes).WebTriangleTestskeeps the vertex wire on outline text. The six heaviest Patterns, measured (2026-09-06,--export-web --frames 4 --fps 60 --seed 1, the page's frame 3 against--export --frame 3): all six cross under both lines where their vertices had been refused: Guilloche 5.2 MB (was 325 MB; 42 strokes, 3.4 M vertices expanded in Chrome in 74 ms) at 0.060, Spirograph 1.8 MB (was 142 MB) at 0.077, Roses 386 KB (was 72 MB) at 0.006, Penrose 452 KB (was 51 MB) at 0.057, Kleinian 1.2 MB (was 309 MB; 3.2 M vertices in 64 ms) at 0.136 with 0.0005% far, ParametricLSystem 8.7 MB (was 234 MB; 73,261 strokes, a still) at 0.100 with 0.0003% far; the expansion runs about 20 ns a vertex in Chrome on this Mac, against the Mac's own 50 ns in a release build. Over six seconds (--seconds 6 --no-controls --seed 1, the default 25 MB limit): Spirograph 24.5 MB at 30 fps and 9.0 MB at 10 (its 50,733 point columns all move and sample per frame), Roses 441 KB at 30 and 404 KB at 10 (its roses turn, so only the 20 records' transforms move), Penrose 1.2 MB at 30 and 709 KB at 10, Kleinian 2.1 MB at 10, ParametricLSystem 8.7 MB at 10 (a still, one distinct frame); Guilloche's 161,238 moving point columns are refused at 10 fps by frame 53 of 60 (a lower bound of 25.1 MB, the samples of a drawing whose every point moves) and cross over three seconds, which is the honest edge of the door: a dense drawing whose every point moves every frame still weighs its samples, and the refusal now charges those moving columns tostrokes and fills as pointsrather than to the vertices (the bound classifies a moving column by the region it sits in).Fabrication export (
Sources/+Ollin/ 3D/ MeshExport .swift MeshPrintCheck+.swift ZipWriter.swift). The write half of theMeshstory, the 3D counterpart of the plotter path:mesh.write(to:)/data(as:)/ theSketchsugarsaveMesh(_:to:)emitMeshFileFormat.stl(binary) /.obj/.threeMF, sized by a declaredModelUnit(3MF records it, STL/OBJ have nowhere to put it) withnormalized(scale:)the documented sizing step, plusprintCheck()→MeshPrintCheck(closed / consistently oriented / inside-out / boundary + non-manifold edge counts / degenerates / size / volume /problemsin plain words). Load-bearing: every format shares oneFabricationMeshpreparation (weld → drop degenerates → settle winding → turn z-up), so an STL and a 3MF of one mesh describe the same solid rather than each format's own idea of it; welding is a precondition, not a nicety (Ollin's generators are flat-shaded, so an unwelded mesh is 100% boundary edges and a slicer sees loose triangles, the same discovery the soft-body tier made, pinned by the raw-vs-prepared counterfactual); winding follows the normals, not the authored order, by area-weighted agreement over the whole surface flipping every triangle together or none (the subdivision-surface rule:Mesh.extrudewinds inward while shading outward), falling back to signed volume only when a mesh carries no normals; the z-up turn is the rotation(x, -z, y)(a quarter turn about x, determinant +1) so winding and normals are carried along untouched; the STL header must not begin withsolidor a sniffing reader takes the binary file for the text form; OBJ is geometry-only (a merged corner has no one normal, and writing an averaged one would round off the very edges the merge just joined);printCheck()describes the prepared mesh, never the raw arrays (on those every generator reads as broken, which is the whole reason the counts differ fromMesh.triangleCount); a failing mesh is written with a note, never refused (an open surface is a fine thing to draw). 3MF is an OPC package written byZipWriter(deflate-when-it-pays else stored, own CRC-32, fixed 1980 timestamps so output is byte-reproducible), the write counterpart ofUSDZipArchiveand verified against both it and the systemunzip; the spec's manifold + distinct-corner + counter-clockwise rules are exactly what the shared preparation leaves true. Deliberate v1 cuts: no vertex colors / uvs / materials (the 3MF materials extension is unwritten, so no multi-material or full-color print), no ASCII STL, and no CLI flag (a sketch draws many meshes, so there is no single "the mesh" for a flag to name). Example3D/(a tunable torus knot whoseGeometry/ Fabrication sealedparameter opens the tube's ends: the shape barely changes and the report turns red);MeshExportTests(20, the weld / winding / z-up treatments each verified red by sabotage, STL and OBJ read back through the shipped loaders, 3MF parsed through the shipped ZIP reader +XMLDocument); no pixel snapshot (the output is files, not frames). Guide Ch 46 § Something you can hold: a 3D print + the closed-versus-open figure;Docs/.Output/ Fabrication .md G-code export (
Sources/). The machine-facing vector sink beside SVG and PDF — the third reader ofOllin/ Export/ GCodeExport .swift recordVectorFrame'sVectorRecording:GCode(aMachineprofile —.plotter(pen:feed:)with a.zAxis/.servopen,.laser(,power: mode: feed: passes: powerScale: ) .mill(— plus explicit physicaldepth: depthPerPass: safeHeight: feed: plungeFeed: spindleSpeed: ) width,margin,ordered,joinTolerance, or a namedPaperSizethroughGCode(/_: paper: margin: optimizesTravel: joinTolerance: ) --gcode-paper a4[-landscape]:widthbecomes the sheet's less the margins,scale(for:)also holds the drawing to the sheet's height, scaling down never up, so a tall canvas fits the page instead of running off it, the header names the sheet, and the drawing keeps the margin corner as its origin rather than centering) plans aToolpath(toolpath(_:in:)/program(_:in:)/.program), withOllinApp/.gcode( of: settings: ) exportGCode/--export-gcode(--gcode-machine|-width|-margin, sharing--hatch) the sugar over it. Load-bearing: the whole pipeline stays in canvas space — millimeters and the y flip (a canvas grows down, a bed grows up from its origin at the canvas's bottom-left) enter only at emission;widthis explicit by design (the fabrication rule: a machine needs real units, and a silent default cuts at a silent size); strokes plot centerlines (strokeWeightdoes not travel) and fills contribute outlines unless aHatchingshades them (the SVG transform reused, not reimplemented); clipping is split by role — a fill clips as a region through the Clipper2 booleans (keeping the closing edge the render shows at a clip or canvas boundary) while a stroke clips as a line through the span clipper (segment crossings paired byShape.containsmidpoint tests), with the all-points-inside fast path only where the region is convex (the canvas rect); merge runs before order (open ends withinjoinTolerancemm weld so the pen stays down; a chain meeting itself closes into a loop) and the greedy nearest-neighbor walk may reverse an open path or enter a closed one at any vertex — ordering changes travel only, never ink (pinned bydrawnLengthequality); dialect facts are encoded once, not re-derived per machine: a laser fires only on feed moves, so travels are bare rapids with no off-word between paths (M4dynamic /M3constant, S scaled bypowerScale,M5only in the footer), a servo pen uses the spindle word with a settle dwell (G4 P0.15), and a mill's closed loop plunges deeper each lap without retracting while an open path retracts and returns;S/Fare modal (written only on change); every program is absolute millimeters (G21/G90/G17), endsG0 X0 Y0+M2, and is byte-deterministic for a seeded sketch (the recipe header carries the roll otherwise).Sketchis public so a preview sketch keeps its chrome (pen marker, caption, travel overlay) out of the plotted line work — it reads true during SVG/PDF/G-code recording. Example.isVectorExporting Export/Toolpath(draws its ownToolpath, walks a pen along it at machine speed, exports chromeless);GCodeExportTests(16, each program replayed through a small in-test interpreter asserting machine facts — pen up on every travel, power only on cuts, the depth ladder exact, nothing off the bed; the y-flip, clip, and depth-clamp treatments each verified red by sabotage; cross-checked by an out-of-project replay that reproduced the header's measured draw/travel mm); no pixel snapshot (the output is files). Guide Ch 46 § Driving the machine itself: G-code + the MachineRoute figure;Docs/.Output/ GCode .md DXF export (
Sources/). The drawing-exchange sink beside SVG, PDF, G-code, and embroidery:Ollin/ Export/ DXFExport .swift DXF((orwidth: margin: joinTolerance: ) DXF(over apaper: margin: joinTolerance: ) PaperSize, the same height hold G-code makes;--dxf-paper) plans aDrafting(drafting(_:in:)over contours on the default layer0;OllinApp/.drafting( of: settings: ) dxf(of:)/exportDXF/--export-dxf(--dxf-width,--dxf-margin, sharing--hatch) over a whole frame), whoseentities(.line/.polyline(closed:)/.circle) andlayers(name, color, the nearest of the nine standard color indices) stay in canvas space,sizein millimeters, andtextis the file. Load-bearing: each color is a layer named by its display bytes (color-1B1040), in the order first drawn on, since a shop program reads a layer as a job and the sketch's colors are the handle; the file is the R12 dialect (AC1009,$INSUNITS4,$EXTMIN/$EXTMAXthe drawing's size, anLTYPEtable withCONTINUOUS,POLYLINE/VERTEX/SEQENDfor a polyline, no handles, no objects, no text), group codes padded to three columns and lines ended\r\n, because the oldest dialect is the one every reader takes; millimeters and the y flip enter only at emission (the canvas's top edge is the drawing's top, the origin the canvas's bottom-left), as for G-code; the flattener is the embroidery one (stitchBlocks, strokes as centerlines and fills as regions, clips applied exactly) and the clip-and-merge is the G-code planner with ordering off, so nothing is reordered and touching ends merge only when consecutive; a circle stays aCIRCLEwhen its transform is a similarity (the images of the unit vectors equal in length and perpendicular), no clip is active, and it lies wholly inside the canvas, else it is flattened like everything else; a fill is a closed polyline unless aHatchingturned it into line work at record time.DXFExportTests(9 tests through a small reader: the skeleton, the flip and the extents with the margin, a layer per color with black as index 7, the circle kept and the squashed one flattened, touching paths merged and a two-point path aLINE, a clip cutting a line to its window, a fill as one closed polyline and hatched as lines, the public planner on layer0, the file written).Examples/;Export/ Drafting Docs/Output/DXF.md; Guide Ch 46 § A drawing for the shop: DXF + the LayerStack figure.Embroidery export (
Sources/). The thread-facing vector sink beside G-code, the fourth reader ofOllin/ Export/ EmbroideryExport .swift recordVectorFrame'sVectorRecording:Embroidery(explicit physicalwidth,margin,stitchLengthclamped to 0.3…12 mm,fillSpacing(nil sews a fill's outline),fillAngle,optimizesTravel,joinTolerance) plans aStitching(stitches(_:in:)/data(_:in:label:);stitchesasStitchvalues of kind.stitch/.jump/.colorChangein canvas space,threads,stitchCount/jumpCount/colorChanges,threadLength/jumpLengthin mm,size,dst(label:)), withOllinApp/.stitching( of: settings: ) embroidery(of:)/exportEmbroidery/--export-embroidery(--embroidery-width|-margin,--stitch-length,--fill-spacing, 0 = outlines) the sugar over it. Load-bearing: the pipeline stays in canvas space; millimeters, the tenth-millimeter grid, and the y flip enter only indst(label:), which rounds absolute grid positions and takes their differences (accumulating rounded deltas walks the design off its drawing); a record moves at most ±121 grid steps (81+27+9+3+1 on its own bits, the jump and color-change flags in the third byte), so a long jump is split into equal records and a stitch never exceeds the pitch; the design starts at the canvas center, so a centered hoop sews it whole; every corner is a penetration (each segment is divided into equal steps no longer than the pitch); a hop between paths within the pitch is sewn and beyond it is a jump; a fill is rows through the shippedhatchLinesscan-fill, serpentined by the same nearest-neighbororderedPathswalk G-code uses so the rows connect without lifting, or its outline whenfillSpacingis nil; each color is a thread in draw order (a new block whenever the color changes, never regrouped, so what was drawn on top is sewn on top; a gradient sews as the middle of its ramp; the optimizer never crosses a block); the header'sSTcounts every record before the end,COthe color changes, and the extents are the sewn extents; no lock stitches or trims are written (the machine's own settings or the embroidery program add them, said in the Docs). Written from the published Tajima record layout, credited inATTRIBUTION.md.EmbroideryExportTests(10, CPU-only, through a reader that decodes every record back onto the grid); no pixel snapshot (the output is a file).Examples/;Export/ Embroidery Docs/; Guide Ch 46 § Thread instead of ink: embroidery.Output/ Embroidery .md Spatial export (
Sources/+Ollin/ 3D/ SceneExport .swift SceneWriterUSD+.swift Sources/). The write half of the USD story, per-scene where fabrication is per-mesh:Ollin/ Export/ SpatialExport .swift scene.write(to:)/data(/ theas: metersPerUnit: ) SketchsugarsaveScene(_:to:)emitSceneFileFormat.usdz(package) /.usda(text layer), andOllinApp/.spatialScene( of: frame: ) exportSpatial/--export-usdz <path>(--frame,--meters-per-unit) drive a sketch headlessly and collect the frame's 3D draw calls. The architecture is one writer with two ways in: the frame recorder's output is an ordinaryScene(the same valueloadScenehands back, so a recorded frame can be read, edited, and redrawn), which is what makes it structurally impossible for the frame path and the file path to drift. Ollin writes the USD itself (Model I/O is out of the USD path entirely, and both halves of a writer were already here): a.usdatext layer plusZipWriter, which gainedstored:/alignment:(defaulted, so the 3MF path is byte-identical) for the spec's zero-compression, 64-byte-aligned, layer-first package. Every mapping is the stated inverse of the reader's and the tests hold the two against each other, because a writer that drifts from its reader is wrong in a way nothing else notices: colors sRGB→linear,focal = aperture /, ortho2tan( fov/ 2) verticalAperture = height × 10, spot cone as a half-angle in degrees, texturev → 1 − v, and a USD matrix's four rows are the simd matrix's four columns. Load-bearing, each a real defect the system validator caught: a Mesh needssubdivisionScheme = "none"or every schema-honoring viewer shows a smoothed, shrunken cage; a prim that binds a material mustprepend apiSchemas = ["MaterialBindingAPI"]; a primvar reader'svarnameis astring, not atoken. A preview surface has one diffuse slot, so whichever of the mesh's base color and its per-vertex colors is present carries the composed product (vertex colors go out asdisplayColorfed to diffuse through aUsdPrimvarReader_float3; a texture's tint is carried inUsdUVTexture) and the other steps aside with a note..inputs: scale MeshMaterialgrew the format-expressible finish (metallic/roughness/opacity/ior/clearcoat/clearcoatRoughness, spec defaults, carried-not-rendered) so aScenecan hold what USD can say; a non-PBR finish mapsspecularSharpness → roughnessthrough the shipped area-light curve(2/(s+2))^(1/4), andDrawer.activeLightswas extracted frommakeLightingso the renderer and the export can't disagree about which lights a frame had. Nothing is dropped quietly: 2D drawing, point clouds / GPU particles / raymarched fields (skipped at their own funnels,isosurface/particleSurfacenamed as the way through), stylized finishes, animation and skinning, and the environment (deliberate, and usually right: a viewer lights a model with its own surroundings, which in AR is the actual room) each note once. Textures package as PNG entries in a.usdzat an anchored relative path and are noted-and-skipped for a bare.usda(one text file has nowhere to put an image). Output is byte-reproducible. Example3D/;Geometry/ SpatialExport SceneExportTests(29: round trips through the shipped reader for geometry / materials / textures / cameras / every light kind / transforms, the written-color-is-linear and half-angle checks that a matching pair of mistakes would slip past, package layout, determinism, the 3MF-untouched guard, andusdchecker --arkitover a package carrying every light kind, a texture, per-vertex colors, and a PBR material, tool-gated like theusdcatcross-check); no pixel snapshot (the output is files). Guide Ch 46 § Something you can walk around: USDZ + the drawn-versus-reopened figure;Docs/.Output/ Spatial .md Spatial video (
Sources/+Ollin/ Export/ SpatialVideoExport .swift Sources/). The moving counterpart of the USDZ model:Ollin/ 3D/ Stereo .swift --export-spatial <path/.mov> OllinApprenders a stereo pair per frame and muxes it as MV-HEVC spatial video, the format Apple's platforms play with real depth. A sketch declares.exportSpatialVideo stereoGeometry(StereoGeometry(,interocular: convergence: ) .automatic), either number derivable and either overridable per export (--interocular,--convergence,--meters-per-unit, plus the video export's--frames/--seconds/--fps/--skip/--bitrate/--quality);Camera3D/.stereoPair( _: aspect: ) stereoEye(/_: interocular: convergence: ) StereoGeometryare the public geometry. Load-bearing: the pair comes out of one.resolved( for: aspect: ) performDraw()rendered twice withDrawerswapping the camera between renders, never two draws (a second draw rolls the rng and steps every sim again, and the artificial-life tier is documented as not frame-exact even at one seed, so the eyes would see different worlds); the repeat render is free because.aimStereoEye( _: previous: ) statefulEncodeIsRepeatalready exists for the live frame grab, andprevious:moves with the eye or motion blur reads the eye separation itself as a sideways lurch. A layer that set a camera of its own has two eyes as well (Drawer.layerViews,aimStereoEye(): each plain layer's camera is re-aimed to its own pair, resolved from that camera at the layer's shape, so a number the geometry leaves out is measured against the view it applies to and never taken from the canvas's; a layer that keeps its picture (a feedback layer, an accumulator, a simulation field's seeds) is filled once a frame whatever is rendered twice, so it stays on the camera it set, with a note (re-aimed, it would show both eyes the left eye's picture, half a separation off). The convergence lean is one matrix entry,_: previous: layers: ) [2][0], correct for all three projections by two separate routes (perspective/intrinsic: clip w is the view distance, so a constant NDC shift collapses into it, the asymmetric frustum a parallel rig is defined by, thejitteredidentity; orthographic: no such w, so it needs a depth-proportional shear, which works out to the same value), andstereoLateraldefaults to 0 so an ordinary camera's projection is untouched by construction. The eyes step along the camera's own right axis and stay parallel (toeing in leaves unfusable vertical parallax at the corners). The derived spacing is a stated criterion: 1% of the frame width at the convergence plane, which for a camera with a vanishing point is also 1% at infinity, the cinema comfort figure; the frame width is read off the built projection's[0][0]so an intrinsic lens measures the same way. Five metadata keys are what make the system call it spatial (HasLeft/HasRightStereoEyeView,HorizontalFieldOfViewin millidegrees,StereoCameraBaselinein micrometers,HorizontalDisparityAdjustment, which is 0 because convergence is already in the pictures); drop one andAVAssetPlaybackAssistantreports.stereoMultiviewVideobut not.spatialVideo, so that near neighbor is not the test. All three ofMVHEVCVideoLayerIDs/MVHEVCViewIDs/MVHEVCLeftAndRightViewIDsare written: naming the middle without the last hangs the encoder rather than refusing. Buffers must be IOSurface-backed, from the receiver's own pool; the write path uses the macOS 26TaggedPixelBufferGroupReceiver, not the adaptor already deprecated at the deployment floor; settings are built at frame 0 because the lens and the spacing are only known once.appendImmediately draw()has set the camera; and the video input isexpectsMediaDataInRealTime = true(the ordinary video export does not need it) because a file-paced multi-layer input stops accepting frames at the end of the first ~1 s chunk and never recovers (measured at frame 36 of a 30 fps export: status still.writing, error nil, readiness false forever), the same exemption the soundtrack input already takes. Envelope, stated not faked: an accumulating sketch (one persistent surface) and a 2D sketch read flat with a one-time note, and anything the sketch flattened duringdraw()(project(),depth(at:), a billboard) lands on the screen plane in both eyes. Sound comes along via the shipped soundtrack path. Example3D/;Geometry/ SpatialVideo SpatialVideoTests(11: the geometry against counterfactual twins, the system's own.spatialVideoreading, the metadata numbers, and a wider-eyes-disagree-more probe over both decoded layers; the convergence-lean sabotage is red in three), and three inLayerCameraTestsonrenderStereoFrames(a layer's squares displaced between the eyes by what the declared separation predicts for their depths, a left-out separation derived from the layer's own camera beside a canvas camera that derives 2.4 times as much, and a kept layer's one picture); no pixel snapshot (the output is a file). Mechanism:ARCHITECTURE.md§ Spatial video. Guide Ch 46 § Something you can look into: spatial video;Docs/.Output/ Spatial .md#spatial-video Variations & seed exploration. A sketch is a generator, so its seed is first-class:
Sketch.initrollsvariation(a five-digitInt, 1…99_999) and seeds bothrandomandnoisefrom it, so an unseeded run still varies yet always names the number that brings it back (every export's recipe now carries aseed). Load-bearing:seed(_:)setsvariation(it's the one host-navigable seed);randomSeed/noiseSeedare partial reseeds that leavevariationalone (so the recipe still splits them). Two unseeded exports of a randomness-free sketch differ only in the recorded seed (SVGExportTestspins body-equality; snapshot pixels unaffected, none re-recorded). Live navigation isSketchRunner, an in-place restart on the same instance (reseed →.restart( variation: ) frameCount = 0→resetAccumulation()→ re-runsetup()next frame), so@Paramvalues survive; it must callsketch.loop(), not just unpause the view — a stillnoLoop()sketch's freshnoLoop()is only a change (and only re-pauses) if the running state was restored first. The sharedVariationCardView(coreLive/) drives it from all four inspector surfaces viaOllinActiveSketch; its seed box fills while focused-but-empty, and the detached panel drops the keyboard it is handed on becoming key (AppKit gives an ordered-front window's first text field the keyboard whether or not the window is key, and SwiftUI's default focus agrees, so a standalone run's seed box used to open empty, take the first click into the panel whatever was clicked, and keep the keyboard until another field was clicked;.runner InspectorPanelFocusTestspins the sequence against a real panel, verified red by sabotage), a click on any inspector's bare surface ends typing (endsTypingOnBackgroundTap, on all four surfaces), and a value pill's scrub surface stays in the tree while the pill is typed in rather than being removed (a hover view taken out from under the pointer never pops the cursor it set, which left the resize cursor on the whole screen); andSketchSessioncarries a navigated seed across hot reload the way tuned parameters do (applied in.recordSeed syncParamsbeforesetup(), so a sketch that pins its own seed still wins; pinned byOllinLiveCoding --sessiontest). Export side:--seed Nreseeds beforesetup()on every export path (onemake()wrapper inhandleCommandLine), and--export-grid/OllinApp/.contactSheet( of: seeds: ) exportContactSheettile one frame per seed into a labeled proof sheet, with--export-sweep/contactSheet(the same sheet along one namedof: sweeping: values: seed: ) @Paraminstead (or by key path,sweeping: \.$radius/\.$rings, the projectedParambox found by identity amongparameters()so the compiler checks the name and the sheet is the named one;VariationTests; values apply via the hosts'.sweepingByKeyPathIsTheNamedSweep ParamStoredrestore path so a tile matches the dragged parameter; every tile pins one seed — given, or rolled once and recorded — so the parameter is the only thing changing; unknown name → nil + the sketch's actual parameter list on stderr; both sheets share one private tiling core; the framing is deliberate, don't re-blend it: seeds = a piece's identity (the Variations story, matching the generative-art seed culture — @eaviles keepsDocs/seed-pure) while the sweep is a tuning tool, documented on the Parameters/Export pages) — a fresh sketch per tile (no state leak) over one reused renderer (Core/ Variations .md OllinApp, factored out of.renderImage( of: frame: fps: renderer: ) image(of:)),resetAccumulation()between tiles, and the renderer's same-frame stamp keyed onDrawer.serial, never the drawer's address (a tile's drawer can be handed the freed address of the tile before it, at the same frame, and read as a repeat: its feedback served empty textures, so every tile from the third drew black;PersistentLayerExportTestsforces the reuse), tile width floored at 64px, the sheet's own recipe carrying the seed list (ExportMetadata). Example.sheetRecipe Randomness/(a whole composition per seed — the decisions live inVariations setup());VariationTests.Docs/,Core/ Variations .md Docs/.Output/ Export .md Record & replay. A run written down as a
Take(Sources/, versioned Codable JSON: theOllin/ Core/ Take .swift variationseed, per-frame clock samples exactly as the display drove them — live jitter included, every input event and@Paramchange frame-stamped, plus the starting parameter values) and played back exactly, to the byte. Load-bearing: both halves live on two choke points — every driver (live window, all export loops, benchmark) funnels throughSketch.advance, where the player overrides the caller's clock after applying that frame's events and parameter changes and the recorder writes down whichever clock applies; and all input entersSketchthrough its internal handlers, each of which taps the recorder and gates external calls off while a player is attached, with the player re-ingesting through the same paths so the hooks (mousePressed()et al.) fire again on replay. The stamp contract: an event or change stampedkwas received after framekdrew and applies at the advance where pre-incrementframeCount == k(frames[k]is that advance's clock) — recording and playback must share the pre-increment stamp or replays shear by a frame.Take.install(on:)must land beforesetup()(seed and starting parameters first, so setup builds from them);--seedbeside--replayre-seeds after install on purpose (same gestures, different variation; pinned). Windowed:--record-take <file>(standalone + OllinLive — the recorder attaches in the runner's first-frame block ahead ofsetup(), autosaves on a doubling cadence since a growing take re-encodes whole, value-copy written off-main; quit writes the final file, and a reload or seed-restart ends/restarts the take) and--replay <file>(live input gated, keyboard becomes the transport: space pause/start-over, arrows step, shift-arrows jump 30, Home/End; a backward scrub rewinds and re-simulates,stepReplayFramemirroringrenderImage's stateful-GPU stepping; a rewind swaps in a fresh instance (type(through the reload path,of: sketch) .init( ) reloadedsuppressed) because stored-property state (a rate gate, a particle array) otherwise carries the first pass's end into the second and the re-simulation cannot walk the recorded path, which is exactly how reseeding the same instance measured wrong; a scrub's crossed frames are held quiet through theTransportMutableseam (SynthdropsnoteOns; releases pass) except a forward jump of at most the shift step (30), and the landed frame always speaks — accumulate/feedback frames render offscreen, everything elsestepComputes). Headless:--replaycomposes with every export flag through the onemake()wrapper plus the advance override (video-shaped exports default their length to the take's). Determinism scope: time, inputs, parameters,random/noisereplay; live feeds, OSC/MIDI, andDate()reads do not (documented). Verified byte-identical through the CLI (replay-export twice, hashes equal; non-replay differs) andTakeTests(12: exact trace + hook replay, input gate, parameter landing on its frame, past-end advance, seed-override, file round-trip + version refusal, GPU byte-identity, and the runner-level transport: End-then-space restarts, the end reached twice (the first of which is a rewind from past the end replaying the whole run), rewound scrub quiet with the landed frame loud, short forward jump audible, long jump quiet, the five transport claims verified red against the stale-instance rewind; player sabotage verified red) +TransportMuteTests(a mutednoteOnnever starts the engine).Docs/Core/Replay.md. The window's title is the replay's only while a take plays (settleReplayTitle(), called wherever a replay can end without playing out: a seed restart, a swap; the title the window had is kept and put back).isRecordingTakeis the public twin ofisReplaying, andfinishTake()gives up the take's destination with the take.Keyframed parameters. A sketch's
@Paramvalues written down over time as anAutomation(Sources/, versioned Codable JSON): oneOllin/ Core/ Automation .swift Trackper parameter, each a list ofKeys (time +ParamStoredvalue + theCurvethat leaves that key), read every frame atstart + time * speed(a negative speed runs it backwards,loopswraps atduration,lengthholds past the last key before the wrap). Written in code asautomate((the projected value names the property by identity; a second call replaces that parameter's track) or read from a file ($parameter) { track in track .key( at: _: curve: ) } --automation <file>, honored by standalone runs and by every export path, throughconfigureTransportplus the exportmake()wrapper). Load-bearing: the player applies insideSketch.advance, after the take player resolves the clock and beforetakeRecorder— a run recorded under an automation has to write down the values the curves actually held, or a plain replay shears by a frame (sabotage-verified red); the parameter is.recordFrame set, not retargeted, so asmoothing:parameter never glides twice (the curve is the glide); the parameter handles are cached once (the@Paramset is fixed and reflecting per frame costs real time), which is why theautomationsetter mutates the existing player rather than building a new one. Blending is by kind: number/color/vector/vector3/rect/insets/range interpolate (color throughColor.mix's even path), while boolean/option/text and any mismatched pair hold what they left; both ends short-circuit, so a key reads back as exactly itself.Curveis.hold/.linear/.easeIn/.easeOut/.easeInOutover the shippedEasingcatalog plus.bezier(, the editable one, solved by Newton with a bisection fallback — its handles bend the clock, not only the value, so reading it means inverting x for the parameter first and only then taking y (the test measures against an independent bisection; a symmetry-only test cannot see the difference and passed under sabotage). Keys sort on construction with ties keeping declaration order; outside its span a track is a constant.x1: y1: x2: y2: ) AutomationTests(20 tests: curve monotonicity and endpoints, the Bezier inversion, hold, per-kind blending, span clamping, sort ties, speed/direction/loop/length, file round-trip and version refusal, the sketch reading the curve including a smoothed parameter, the recorder stamp, an unknown parameter skipped). ExampleMotion/Automation(four kinds of track, with the sketch plotting its own tracks under the stage).Docs/,Core/ Automation .md Docs/.Output/ Export .md Parameter timeline. OllinLive's authoring surface over
Automation(Sources/+Ollin/ Live/ TimelineModel .swift TimelinePanel.swift; the clock transport onSketchRunner): a floating resizable panel (the Timeline chip / ⌘T,OllinHUD), one lane per track — number lanes plot the track's sampled value normalized over the span, color lanes draw the blend as a band sampled from the track itself, switches step, and a formula track shows its rule and takes no keys — plus a per-row keyframe diamond in every inspector row (.showTimelineKey KeyframeDiamond, rendered only where a host injects\, so the gallery and other hosts show nothing, and only while the panel shows or the parameter already has a track or a rule (.automationTimeline showsMark(for:)overisPanelShown, set bybeginFollowingClock/endFollowingClock), so a sketch that never keyframes keeps a clean inspector; ruled 2026-10-13). The authoring loop is scrub → adjust the parameter → click the diamond (places a key at the playhead holding the parameter's value; on a key it re-keys a changed value and removes an unchanged one, compared against what the track gives at that moment); keys drag in time, double-click removes, a click on a key selects it and scrubs to it (select(), a ruler scrub within 6 pt of a key snaps to it (track: index: ) snapped(_:within:)), a selected key's value shows in the footer beside its moment and curve (readout(of:param:), a whole number with no decimals),.beziergrows drag-handles on the lane, and every edit registers on the model's ownUndoManager(groupsByEventoff; a lane drag is one group, opened by its first edit throughbeginDrag(span:)/endDrag; the panel's delegate hands the manager to the Edit menu, so ⌘Z/⇧⌘Z work while the panel is key, for an edit made from a row too). A hand edit under a hold draws a hand pass (2026-10-13):SketchSessionasks.recordParam refreshClockFrame(, a nudge pass whosekeepingHandValues: true) advance(skips the player, so the picture follows the inspector and the track does not take the value back before the diamond keys it; the next scrub, step, or plain refresh applies the tracks again (the first audit found step 2 of the loop blind and a re-key impossible). Every edit reads the clock, never the ticked playhead (appliesAutomation: false) toggleKeysyncs first,hasKeyAtPlayheadreadslivePosition): the ticker runs only while the panel shows, so a diamond clicked with the panel closed keyed the moment the panel was closed. The scale includes the playhead (Scale(, so a clock run past the last key stays on the ruler, where it left it and the panel read as frozen) and holds its span through a drag on the ruler or a lane (contentDuration: playhead: lockedSpan: ) lockedSpan; the last key dragged past the span grew the ruler under the pointer and jumped ahead of it, and a scrub back from a far playhead shrank the ruler under the pointer).loopRegionis observed (as@ObservationIgnoredstate the region and the loop button appeared only on the next playhead change). The panel's hosting view accepts the first mouse, so a drag coming from the inspector acts on its first click. The diamond sits at the trailing edge of every row (KeyframeDiamondafter the control,KeyframeDiamondGapunder it on a second line of fields), one column whatever the control's width, where before controls of differing widths zigzagged it. Load-bearing: the transport is the runner's own (setClockPaused/scrubClock/stepClock/clockLoopRegion,package): a hold stops the display link and is enforced at the top ofdraw(in:)like the replay pause (a queued tick must not advance a clock the panel just placed, and an accumulating canvas must not composite the held frame twice), while a reload's first frame, a setup rerun, and a camera snap still pass under a zero step; a scrub or step is one deliberate pass (pendingClockNudge) that waits for the frame ring rather than dropping (the take exception's shape — a dropped pass ate a backward step, caught red) and drops any interpolator-held frame first (also caught red); a backward nudge places the clock and handsadvancea zero step, never a negative one; a take owns the whole transport (beginTake/replayrelease the hold). The panel's axis is the automation's position, never the raw clock (position(at:)forward,clockTime(invertingforPosition: ) start + time * speedfor scrubs), so a looping pass shows the playhead coming around while the clock runs on — the first live run had the playhead silently off the ruler's right edge — andtoEndlands a frame short underloops, since the exact end wraps to zero. The loop region lives on the transport in position space, mapped onto the clock; it is never written into the file. Edits land on the sketch's own automation (tracks rebuilt throughAutomationso the sort invariants hold; a worked-out track is refused), debounce to the file (.Track( name: keys: ) <Sketch>sibling by default,.automation .json --automationoverrides; OllinLive reads it on launch andSketchSessionre-installs it before.automation setup()on every swap, keeping the documented file-before-setup precedence), andrefreshClockFrameredraws the held frame so an edit made while paused shows. The model holds its runner weakly (the session owns it — a test must keep the harness alive). The row is also the field that takes a rule (RuleLineinInspector.swift, overTimelineModel/.setRule checkRule/removeRule/beginRule/rule(param:)/takesRule): right-click the diamond of a number, whole number, or switch for Write a Rule, a monospaced field opens under the row, Return installs the text as aformulatrack through the sameapply(file, reload carry, held-frame refresh), an emptied field removes it, Escape reverts, and a ruled parameter shows thefunctionmark with its control disabled (the sync pull keeps it following; a hand would be undone next frame). The refusals happen where the text is, never at play time: the parser'sFormulaError.offset(a Character index,Array(source)) puts a caret under the character in the field's own column grid (same mark, padding, and monospaced face); a name nothing supplies is refused at the name (its token offset, since a discovered variable would read as 0) rather than reported on stderr asdrivedoes; a self-reference and a ring through another parameter are refused at the closing name by building the candidate automation and askingAutomation.rings()(package, over the player's own plan) before anything is written; a kind no formula can drive (menu, text, color, the parts kinds) and a track that already holds keys are refused outright, and the menu never offers them. Never install a formula parsed against the declared name list (Formula(): its_: variables: ) variableswould be every readable name, soreadNameswould make every ruled parameter depend on every other and the plan would see rings everywhere; parse discovered, then check.writingRuleis model state (the row open with no rule yet), never a write. A track the sketch writes itself reaches the row: the diamond and the rule line observe onlyeditCountandplayhead, and adrive/automateinsetup()bumps neither (the panel's ticker runs only while it shows), which left every slider row hollow and ruleless on the first capture while the stepper and switch beside them showed theirs; the model now watches the sketch's automation from the moment a runner is attached (250 ms, anAutomation ==) and bumpsautomationVersion, which the rows read besideeditCount.ParameterTimelineTests(38: the transport tests including the ring wait and the reload hold, the edit tests, the position mapping, the scale and plot tests, six rule-field tests, three of them verified red under a zeroed offset, and the hold-loop tests: the hand pass, the re-key, the clock read without the ticker, the scale with the playhead and under a drag, the snap, the select, undo and redo with a drag as one step, the marks' visibility, and the readouts) + the rule phase ofOllinLive --paramtest(the write, the file, four offsets, the refusals).Docs/§ Writing a rule in the row; Guide Ch 47 § Writing the parameter as a rule: formulas.Tools/ Timeline .md Cues (
Sources/,Ollin/ Core/ Cues .swift Sources/, the carry inOllin/ Live/ CuesCard .swift OllinRuntime). A.SketchSession Cueis one named set of every@Param's value ([String:, the inspector's own payloads, so every kind is carried);ParamStored] saveCue(_:)stores the parameters as they stand (replacing a same-named cue where it stands),cue(_:over:)by name / by index from 0 /nextCue/previousCue(wrapping) /cue(calls one back at once or over an ease-in-out fade run fromCueRequest, over: ) Sketch.advanceafter the automation and before the take recorder (so a track still wins its parameter and a take holds the fade); a kind with nothing between two values (bool, option, choices, text, colors) jumps on the fade's first frame, the rest blend throughAutomation.blend; a cue called mid-fade starts from where the parameters are; a name the sketch no longer declares is skipped and a parameter not in the cue keeps its value.CueSheetis the ordered list with a version (a newer file is refused),Sketch.cueSheetthe one carried,currentCuethe last called,isCueFading,loadCues(from:)/saveCues(to:)for a sketch on its own,--cues <file>/--cue <name>on every export path and the window (applied inapplyCommandLineParamsaftersetup(), before--param; without--cuesthe sketch's own sheet is searched, which is how OllinLive's sibling file serves an export: its export path loadsSketch.cues.jsonbeside the automation and installs it on the loaded sketch). Load-bearing: the hosts keep the sheet inSketch.cues.jsonbeside the sketch (the automation's precedent), throughSketchSession, which re-installs the sheet on every freshly loaded sketch before.adoptCueFile( _: ) setup()and files every save and delete through the sketch'spackage var cuesChangedhook (a path with no file yet is where the first save lands; an untitled performance buffer keeps its cues in memory until saved);CuesCardView(a public inspector card in both hosts, under the parameters and above the Controls card) lists the cues, calls one over the fade it keeps underCuesCardViewin the defaults (read by the performance host's controls too), saves the parameters under a typed name or "Cue N", updates a cue whose name is typed, deletes, and polls.fadeKey currentCueevery 100 ms so a cue the sketch calls itself lights up; the performance host answers a MIDI program change withcue(on any channel with nothing learned,.number( program)) /ollin/cuewith a name or a number and an optional fade argument, and two press actionscueNext/cuePrevious(/ollin/cue/next,/ollin/cue/previous, learnable). "Snapshot" was not used (the render-image tests and the remote surface's wire image own it), nor "preset" (a named built-in value of one type).CueTests(11 tests), the--sessiontestcue-carry phase, the--controltestcues phase;Examples/Live/Cueswith itsSketch.cues.json;Docs/; Guide Ch 47 § A look you come back to: cues.Helpers/ Cues .md Parameters driven by a formula. A
@Paramset from a rule read as text rather than from Swift source (Sources/+ the formula leg ofOllin/ Math/ Formula .swift Automation.swift):drive(, for$radius, "190 + sin( time * tau / 6) * 80") Double/Int(rounded) /Bool(on for anything but zero).Formulais a public,Sendable, pure value: a hand-written tokenizer plus recursive descent, names resolved at parse time to positions (so a per-frame evaluation touches no dictionary),variablesreporting the free names in discovery order,value(_:noise:)taking them positionally or by name, and a second initializer taking a declared name list so an unknown name is refused with what was available.FormulaErrorcarries amessageand the characteroffset, which is what a typed-in field needs to point at the spot. Vocabulary: the arithmetic/comparison/logic operators, ~45 functions spelled and argument-ordered to match the framework's own and the shader library's (clamp/lerp/mix/step/smoothstep/map/fract/saturate, variadicmin/max,if(c, a, b),noise/signedNoise), andpi/tau/e. Two spellings are load-bearing because they change a picture rather than fail to build:^binds tighter than unary minus and associates right (-2^2 == -4,2^3^2 == 512) — the ordinary calculator table, and deliberately notLSystemExpression's, which binds unary tighter per its published formalism (the test asserts both sides); and%/modfloor (-1 % 3 == 2), matchingfractand the shader spelling, not Swift's%. There is norandom(a formula must answer the same number for the same moment, or a directed run stops rendering twice the same);noisereads a suppliedNoiseField, andSketch.noiseField()hands over the sketch's own sonoiseSeed()reaches it. A formula is aTracklike a keyed one (sameAutomation, sameloops/speed/start/length, same--automationfile, encoded as its source text so a person edits it there; formatversionwent to 2 and the load guard relaxed to<=so v1 files still read). It namestime(always overridden to the automation position, insideTrack.value),frame(frameCount + 1, because the player runs before the sketch steps its counter),width/height/mouseX/mouseY, and the sketch's other number/switch parameters by name — built-ins win a spelling clash. Load-bearing: tracks apply in dependency order, not declaration order (a depth-first plan cached per track set), so a parameter worked out from another lands on the same frame — a snapshot-then-apply design was built first and rejected, because its one-frame lag makes the picture depend on the frame rate and a 30 fps export stops matching the 60 fps window; a parameter read back fromparam.storedafterrestoreso the next formula sees the clamped value; and a ring (two parameters naming each other, or"n + 1") cannot settle on one frame, so the whole ring is reported once and left alone rather than played at a frame-rate-dependent value.drivenever throws: a parse error or a name nothing supplies is reported on stderr and costs that one parameter (pass atry Formula(...)to handle it yourself). A parameter of more than one number takes one rule per part (drive($eye, x:y:), plusVector3,Color,Rectangle,Insets,ClosedRange<Double>;Track.parts, formatversion3): the part names areAutomation's keys (.parts( of: ) x/y/z,red/green/blue/alpha,x/y/width/height,top/right/bottom/left,lower/upper) andAutomationwrites them back into the parameter's current stored value, which is what leaves a part with no rule alone (the hand keeps it while the part beside it plays)..applying( _: to: ) parameter.partis a readable name too ("frame), so the tokenizer joins a dot to the name it follows (a dot with no letter after it is still an error, and.x + frame .width / 2" 1.5is still a number), the plan follows a dotted name to the parameter it names (Automation) so ordering and ring detection both hold, and the player feeds every part of a multi-number parameter back as.baseName( of: ) name.part— including one a keyed track is carrying. Three rules that only a test can pin: one call carries the whole parameter (a seconddrivereplaces the first, so give every part at once), a pair of ends stays ordered (upperis lifted to meet alowerthat climbs past it, becauseClosedRangerefuses a crossed pair outright and the parameter would silently freeze), and a part naming its own parameter is a ring (refused whole, since parts read one shared snapshot). A rule that cannot be read costs that one part; a call naming no part at all writes no track..restored FormulaTests(20 tests) +FormulaTrackTests(10) +FormulaPartTests(14); sabotages verified red for the numbers (precedence, floored%, the NaN guard, eagerifcounted through the noise field, declaration order, the ring,frame, thetimeoverride) and four more for the parts (a misnamed part inapplying, the dotted-name-to-parameter mapping, the crossed-pair lift, the joined dot). ExamplesMotion/Formula(six driven parameters, printing the text that drives each) andMotion/FormulaParts(a ruled size over an unruled place, a dot reading its rectangle back part by part). No pixel snapshot (the claims are numbers).Docs/,Helpers/ Formula .md Docs/.Core/ Automation .md