Ollin

D. The complete toolbox

This appendix lists everything Ollin can do, one row for each capability, in the order the guide teaches it. The rows are grouped by part and chapter. Each row says what the capability is in plain words, links the section that teaches it, and links its page in the reference.

Use it as an index when you remember a technique from the guide and want to find it again. You can also read it as a list of what you haven't tried yet. A capability taught in more than one chapter sits with the chapter that teaches it most fully. Its row also links the other sections, each marked with its chapter. If something you want isn't here, it isn't in the framework yet, and the roadmap lists what's ahead.

Contents: The ideas underneath · Part I: Seeing something move · Part II: Systems that come alive · Part III: Shapes, lines, and marks · Part IV: Pixels and light · Part V: The third dimension · Part VI: The world coming in · Part VII: Out into the world

The ideas underneath

The capabilities all assume a few ideas. These seven pages in the reference explain them, one screen each, and sit between a chapter and a function signature.

IdeaWhat it saysTaught inReference
The frameA drawing call records rather than paints, call order is draw order, and nothing is kept for youCh 1: Once, then every frame, Shapes and inkThe frame
Where a point isThe canvas frame and its units, transforms as a change of frame, and the other frames a sketch meetsCh 1: Where things go, The canvas is not the window; Ch 6: Moving the paper: translate, rotate, and scaleWhere a point is
LayersAn off-screen picture you draw into and then read back: what one costs, and when you need oneCh 19: A drawing you can hold: render targetsLayers
What survives a frameWhat carries into the next frame, and what a batch, a reload, and a checkpoint holdCh 19: The canvas that keeps everything: noClear, Record it once: batches; Ch 45: Picking up where it left off: checkpoints and @SavedWhat survives a frame
Why a run repeatsThe seed and the fixed export clock, and the four things that break a repeatCh 4: Seeds: randomness you can keep, Finding a seed to keep; Ch 3: When a frame takes too long; Ch 41: The recipe in the fileWhy a run repeats
Light and colorWhy the middle of a frame is linear light, and what tone mapping and dithering do at the end of itCh 9: A picture made of pictures; Ch 19: Brighter than the screen: toneMapLight and color
Values and bare callsThe typed values under the short calls, and when to keep the value rather than make the callCh 10: An arrow you can draw: Vector2; Ch 15: Shapes you can holdValues and bare calls

Part I: Seeing something move

Chapter 1: Hello, Ollin

CapabilityWhat it isTaught inReference
Checking the machineollin doctor checks the toolchain, the GPU, the command, and the permissions, and prints the line that fixes each problem; shell completions; --list-params for the parameters a sketch declaresWhat you need, A shorter way to run things; Ch 41: Passing the parameters back inDoctor
The examples galleryswift run OllinExamples shows the examples in a tree and runs the one you pick, with its parameters beside itThe galleryExamples/
Live reloadswift run OllinLive Sketch.swift watches the file, and each save swaps the change into the open windowYour first sketchSketch
Swift itselfAs much of the language as a sketch needsYour first sketch; Appendix ASwift quick reference
The sketch lifecyclesetup() runs once, and draw() runs every frame at the display's rateOnce, then every frameSketch
Canvas and windowcanvasSize and its presets, and windowMode (auto, fixed, resizable)The canvas is not the window; Ch 44: Filling the screen or fitting in it: windowModeCanvas
Looking closerviewControl() lets you drag to pan and scroll to zoom the live view, and leaves the canvas as it isLooking closerDrawing
Normalized coordinatesuv(u, v) gives the canvas point at fractions from 0…1 across and down, and scale, the shorter edge over 1000, sizes marks to the canvasPlacing things without pixelsCanvas
The shape catalogCircles, rectangles, lines, ellipses, triangles, stars, hearts, arcs, rings, and n-gons, drawPolygon and drawPolyline through points you give, and about twenty moreShapes and ink; Ch 6: Grids that aren't square: hexGrid and triangleGrid; Ch 7: The diagonal tile: ten printDrawing
Ink statefill, stroke, and strokeWeight, then caps and joins; the reference adds hollow band mode and stroke alignmentShapes and ink; Ch 5: Putting it together: a meadow in the wind; Ch 7: No coins at all: kolam and sonaDrawing
Rounded rectanglesdrawRect with cornerRadius:, or cornerRadii: for a different radius at each cornerShapes and inkDrawing
MousemouseX, mouseY, and mouseIsPressed, the press and release hooks, and mouse and previousMouse as pointsThe mouse joins inInput
@Param parametersA property marked @Param becomes a control in the inspector, chosen by its type: a slider, a stepper, a color well, a pad, and morePutting it together: a breathing ring; Ch 38: One parameter, three hands: binding and smoothingParameters
Saving tuned valuesThe inspector's Save parameters button writes the values you tuned back into your .swift fileSaving the values you tunedParameters
Dragging a shapeHold Command in the live window and drag a shape, and the numbers that placed it change in your fileMoving something by hand; Ch 43: Moving a shape on stage: the Command-dragDragToEdit
One frame on requestredraw() draws one more frame of a sketch that noLoop() stopped, so a still sketch answers a click and costs nothing betweenOne more frame when asked: redraw()Sketch
The pointerpointerShape(_:) picks one of the system's pointer shapes over the canvas, and hidePointer() and showPointer() take it away and bring it backThe pointer's shape, or noneInput
The open panelchooseFiles(withExtensions:) shows the system's open panel without stopping the frames; the pick arrives in chosenFiles() and filesChosen()A file the person picks: the open panelInput
The frame on the clipboardcopyFrame() puts the frame the window shows on the clipboard as a PNGThe frame on the clipboard: copyFrame()Recording
Single-file sketchesollin new <file>.swift and ollin <file>.swift: one file is a sketch, and it runs from any folderA shorter way to run thingsSingleFile
Project generatorollin new <Name> and ollin generate write a folder from a template, and you can watch the template run firstWhen one file isn't enoughProjectGenerator
A package's sketch, liveollin in a package's folder runs its sketch in the live window, every .swift file of the target compiled together and a save to any of them reloading it; --target picks one of severalWhen one file isn't enoughSingleFile
The reference offlineollin docs, ollin api, and ollin examples read these pages, the calls, and the examples in the terminal, with a search across them; ollin site writes them out as a websiteLooking something up without leaving the terminalReference
Ollin on one pageThe lifecycle, the calls by area, units and conventions, the command line, and the mistakes that fail with no errorGo deeperQuick reference

Chapter 2: Color that works

CapabilityWhat it isTaught inReference
Color valuesNamed colors, hex, RGB, HSB, and alphaNaming a color, Thinking in hueColor
Perceptual colorThe OKLab family, and Color.mix, which blends the way your eye expectsMixing you can trustColor
Lightness and related colorsOKLCH and OKHSL keep hues at one lightness, and lighter(by:), darker(by:), and complement make colors related to one you haveHues that weigh the same: lightnessColor
Palettes and rampsColorBrewer sets, harmonies built from one color, smooth ramps, and cosine palettesKits you carry: Palette and RampColor
ColormapsViridis, magma, and turbo: ramps for turning data into colorKits you carry: Palette and RampColor
Gradient paintLinear, radial, conic, and along-path gradients for any shape's fill or strokeGradients as paintColor
Palettes from a fileloadPalettes reads every palette in a file of hex codes, CSV or TSV, JSON, or Adobe .ase swatches, and loadPalette reads the firstPalettes from a fileColor
AccessibilitySee your colors as the three kinds of color blindness see them, check that a palette's colors stay apart, and read the reduce-motion settingWill everybody see it?; Ch 3: When somebody would rather it stopped: reduced motionAccessibility
Spectral colorSpectrum: color as light by wavelength, .paint mixing where blue and yellow make green, blackbody light, and thin-film, diffraction, and paint-mix effectsBlue and yellow make green: mixing in .paint, Light by wavelength: SpectrumSpectral color
Shades that driftPalette.shades and Ramp.shades build a ramp of one color whose hue warms toward the light and cools into the shadowShades that drift: Palette.shadesColor
Color distancedistance(to:) measures how far apart two colors look, in OKLab or by CIEDE2000; CIELab brings a swatch's numbers in; nearest(to:) finds the palette entry most like a colorHow far apart two colors look: distance(to:)Color

Chapter 3: Motion and time

CapabilityWhat it isTaught inReference
The clocktime, deltaTime, frameCount, and frameRate; noLoop() for a stillThe clock; Ch 1: It moves on its own; Ch 44: Wallpaper and a menu-bar stripSketch
Everyday mathmap, lerp, clamp, fract, step, smoothstep, and .taumap and lerp: moving between ranges, The circle behind sin, Shaping time; Ch 11: Putting it together: the wrecking ballMath
Loop phasesloopProgress and pingPong turn the sketch clock into a cycle from 0 to 1map and lerp: moving between rangesMath
EasingThe catalog of curves, and @Eased and @Sprung values that glide or spring to what you assignA catalog of curves, Values that chase a target: @Eased and @SprungAnimation
Perfect loopsDeclare loopDuration, and --export-loop renders one lap that ends where it beganPutting it together: a loop that never ends; Ch 41: Motion: video and GIFExport
Swaysway moves a value from one end of a range to the other and back once per lap, along one of five paths; wave names the parts of a sineThe sway you write over and over: swayAnimation
TimelineKeyframes with easing on each segment, for sequences you choreographChoreography: TimelineAnimation
Timersevery, after, and everyFrames say whether a moment has arrived, for events like adding a dot every two secondsDoing something now and then: every, after, and everyFramesAnimation
Knowing an exportisExporting is true from setup() to the last frame written in any export, so work spread over live frames is done at onceWhen every frame is written: isExportingSketch

Chapter 4: Randomness

CapabilityWhat it isTaught inReference
RandomSeeded random, Gaussian values, choices plain and weighted, and shufflesRolling dice, Seeds: randomness you can keep, Letting chance decide, Two shapes of chance: uniform and GaussianRandom
Variationsvariation: the seed a run grew from, stepped and rolled from the inspector's Variation cardFinding a seed to keepVariations
Keyboardkey, keyCode with its typed KeyCode values, isKeyDown(_:), and the press and release hooksFinding a seed to keep; Ch 31: Someone to be in there: the character controllerInput
Contact sheets--export-grid tiles one frame per seed into a labeled sheet, and --seed renders the one you keepFinding a seed to keep; Ch 41: Picking a keeper: a contact sheet and a fixed seedVariations
Random walksrandomWalk, a tangle that pools in one patch; levyFlight, tight clusters joined by long jumps; and selfAvoidingWalk, a path on a grid that never enters a cell twice and fills its regionThree walks, three rules: randomWalk, levyFlight, and selfAvoidingWalk, The random walk, by handWalks
Markov chainsMarkovChain from a drawing sketch: a pick whose odds follow the last pick, with the table declared by handA roll that remembers the last one: MarkovChain; Ch 40: What comes next: a MarkovChainRandom
Blue noisePoisson-disk scatter: points at random, but kept a set distance apartDarts that keep their distance: poissonDiskBlueNoise
Low-discrepancy samplingHalton and Sobol points: even at any count, and adding points never moves the ones already placedPoints that never move: haltonPoints and sobolPointsLowDiscrepancy
Breeding by eyePopulation and Genome: a handful of genomes, bred from the ones you pickSixteen things and no opinion about them: PopulationEvolution

Chapter 5: Noise

CapabilityWhat it isTaught inReference
Noisenoise, signedNoise, the loop: forms that come back to their start (a value, a line, a field, or a volume), and layered fbm; curlNoise and curlField; noiseFields for work off the main threadRandom that remembers: noise, Drift that swings: signedNoise, Coming home: the loop: argument, Layering shape and detail: fbm; Ch 14: Points the field carries: advectionNoise
The noise familysimplexNoise, cellular worley (the nearest point, the second nearest, or the border between), ridgedFbm, turbulence, and warpedFbm, all pinned by noiseSeed; gaborNoise, which takes a seed: of its own; and tilingFbm for a texture that wrapsA family of fields; Ch 27: A picture from three sides: triplanarNoise

Chapter 6: Grids and repetition

CapabilityWhat it isTaught inReference
GridRows, columns, padding, and gutters in one loop instead of twoOne loop, not two: gridGeometry
Transforms and the state stacktranslate/rotate/scale, scoped with withState { }Moving the paper: translate, rotate, and scale, Symmetry by hand: rotating around the centerDrawing
Kaleidoscope symmetrysymmetry(n, mirrored:) repeats your 2D drawing in n wedges around the origin, with a mirrored copy in each when you askThe fold, done for you: symmetryDrawing
Rectangles and circlesRectangle and Circle as regions: a clip, a text box, insetting, and hit testingDrawing inside a shape: withClip; Ch 8: Both edges flush: the box form and justificationGeometry
ClippingwithClip(shape) { }: drawing inside the block lands only within the region; nesting intersectsDrawing inside a shape: withClipDrawing
A view boxwithViewBox clips to a region and moves the coordinates too, so the block inside draws as though the region were the canvasA cell that is a whole canvas: withViewBoxDrawing
Hex and triangle gridsThe other regular grids, with hex distance, neighbors, and picking the cell under a pointGrids that aren't square: hexGrid and triangleGridTiling
Recursive subdivisionsubdivide: uneven panels from splitting the canvas again and again, in halves or in quartersUneven panels by recursion: subdivideTiling
Ulam spiralThe counting numbers written in a square spiral, so a test on each one becomes a picture, and the primes fall on diagonalsWalking a grid: numbers in a spiralUlamSpiral

Chapter 7: Tiles that cover the plane

CapabilityWhat it isTaught inReference
Truchet tilesdrawTruchet puts one tile in each cell at a random turn, and loops and mazes appear; truchet hands back the strands as valuesTiles that agree at their edges: Truchet, Strands as values: truchetTruchet
Ten printOne of two diagonals in each cell by a coin flip, joined into the long paths they formThe diagonal tile: ten printTenPrint
Hitomezashi stitchingOne bit per grid line sets where its dashes start; stitches and a two-tone cloth appearOne coin per line: hitomezashiHitomezashi
MazesPerfect mazes, with one route between any two cells, carved three ways and drawn as line workOne route between any two: perfect mazesTiling
Kolam and sonaOne line bounced around a field of dots until it closes, in gcd(rows, columns) loops, with walls to steer the countNo coins at all: kolam and sonaKolam
Celtic knotworkThe same line given width and an over-under rule, its bands broken where each cord passes underThe same line, woven: Celtic knotworkKnotwork
PolyominoesPieces of joined squares, the twelve pentominoes, and a search that fits a set of them into a region exactly or says it cannotPieces that have to fit: polyominoesPolyominoes
Wave Function CollapseTiles with labeled edges solved by constraint propagation, or a texture learned from a small sample pictureEvery neighbor must agree: Wave Function Collapse, Or hand it a picture instead: overlapping WFCWaveFunctionCollapse
Aperiodic tilingsPenrose kites/darts and rhombs with matching-rule arcs, Wang edge-matching quilts, girih star patterns over any polygons, and the spectre (the einstein)Tiles that never repeat: aperiodic tilingsAperiodic tilings
De Bruijn sequencesA cyclic run holding every window of a given length exactly once, with the reader that turns a window back into a positionEvery window once: de Bruijn sequencesDe Bruijn sequences
Hyperbolic tilingRegular polygons meeting more to a corner than flat paper allows, drawn in the Poincaré disk, with a checkerboard by parity, rings by depth, and a viewpoint you can panMore room than the page has: hyperbolic tilingHyperbolic tiling
Parquet deformationsA tiling whose tile changes shape as you read across it, the geometry carried on the lattice's shared edges so nothing comes apartA tile that changes as you read: parquet deformationsParquet deformations

Chapter 8: Words

CapabilityWhat it isTaught inReference
Drawing textdrawText with size, alignment, wrapping in a box, justification, and text along a pathSaying something: drawText, Both edges flush: the box form and justification, Letters that move: drawText with a closureText
Three font kindsOutline (any installed font), bitmap, and plotter stroke fontsThree kinds of letters: outline, bitmap, and stroke fontsText
Text as geometrytextToShapes: letters become Shapes you can warp, resample, and rebuildText as geometry: textToShapesText
Letters one at a timedrawText with a closure runs your code once per letter, so each one can move, turn, or change colorLetters that move: drawText with a closureText
Every script, and columnsArabic, Devanagari, Thai, and Japanese shaped by the system; columns down the page that fill right to left, as Japanese does, or left to right, as Mongolian does; and hanging punctuation at the edge of a boxShaping and direction: text in any script, Down the page: vertical text, Both edges flush: the box form and justificationText
Missing lettersfontsUsed(for:) names the faces a line of text borrowed, and textMissingCharacters lists the characters the current font cannot drawWhat the font could not do: fontsUsed and textMissingCharactersText

Chapter 9: Pictures and data

CapabilityWhat it isTaught inReference
ImagesLoad PNG, JPEG, HEIC, and more; draw, tint, scale, and crop them, fit one into a box of another shape, and draw one cell of a sprite sheetA picture on the canvas: loadImage and drawImage, A working copy: resized and cropped, The box is never the right shape: fitImages
Sample photographsTwenty bundled pictures and a short film, with their credits, to try a technique onA working copy: resized and cropped; Ch 34: When there is no camera: stills and footageSample photographs
PixelsRead and write a pixel with image[x, y], and build an image from nothingAn image you can ask: image[x, y]Images
Atlas texttextMode(.atlas) draws a lot of text quicklyPutting it together: a picture painted with typeText
Files dropped on the windowfilesDropped() runs when files land on the window, and droppedFiles() hands over their pathsA picture you drop on the windowInput
Seam carvingA picture made narrower or wider by taking away or duplicating the paths that carry the least, so what carries texture keeps its shapeMaking it narrower without squashing it: seam carvingSeamCarving
Palettes from a picturePalette(extractedFrom:) pulls a palette out of a photographPalettes from a photographColor
Histogramshistogram(of:) counts a picture's pixels by lightness or by one channel, and percentile(_:) reads its working black and whitePalettes from a photographColor
Ditheringdithered rebuilds a picture in fewer colors, scattering the ones it has so the eye reads the tones betweenFewer colors than the picture needs: ditheringColor
A small picture drawn bigimageSampling(.nearest) keeps every pixel a hard square when a picture is drawn larger than it is, with no enlarged copyDrawn big, cell by cellImages
Glyph mosaicA picture rebuilt as a grid of characters, each chosen by its measured ink in the active fontOne mark per cell: drawGlyphMosaic and drawHalftoneGlyphMosaic
HalftoneA picture as a print's dot screen: each dot sized to its tone on a turned grid, drawn as circles a plotter can followOne mark per cell: drawGlyphMosaic and drawHalftoneHalftone
Photo mosaicA picture rebuilt out of many smaller pictures, each cell taking the nearest by average colorA picture made of picturesPhoto mosaic
StipplingDots packed to match a picture's tone (weighted Voronoi)A picture as one line: stippling, singleLine, and spanningTreeStippling
Single-line drawingOne unbroken tour through a stipple: the picture as a single closed line (TSP art)A picture as one line: stippling, singleLine, and spanningTreeSingleLine
Spanning-tree drawingThe same stipple joined by the minimum spanning tree: the picture as branching veinsA picture as one line: stippling, singleLine, and spanningTreeSpanningTree
Hilbert orderThe same stipple sorted along a space-filling curve: one line by a single sort, neighbors kept togetherA picture as one line: stippling, singleLine, and spanningTreeHilbert order
String artOne continuous thread over rim pins, each chord wound toward the darkness that remainsA picture wound from thread: StringArtStringArt
Pixel sortingRuns of a picture's own pixels, bounded by brightness, reordered into streaksSorting the pixelsPixelSorting
AutostereogramA depth map hidden in a repeating pattern, so a surface nobody drew stands out of the pageA picture that hides a shapeAutostereogram
Tables and JSONloadTable reads a CSV or TSV with typed reads by column name and numbers(_:) for a whole column; loadJSON reads a document by name and indexReading a table: loadTable, From numbers to marks, Documents with a shape: loadJSONData

Part II: Systems that come alive

Chapter 10: Vectors, gently

CapabilityWhat it isTaught inReference
VectorsVector2 and Vector3, with operators for adding and scaling, length, normalized, lerp, rotated, and with(x:) for a copy with one part changedAn arrow you can draw: Vector2, Arrow arithmetic: adding, subtracting, scaling, and dividing, A point part of the way: lerp(to:), Length and direction: length, normalized, and limited(to:), Position, velocity, acceleration; Ch 26: Where things are in the world: Vector3 and world unitsGeometry
ArrowsdrawArrow(from:to:) draws a vector as an arrow, with a head you can sizeAn arrow you can draw: Vector2Drawing

Chapter 11: Forces and physics

CapabilityWhat it isTaught inReference
Soft physicsVerlet particles and springs, with disk collisions: ropes, cloth, and blobsA world that pushes back: World and particles, Springs: connect, rest length, and pinPhysics
Rigid physicsBodies, colliders, and joints in the same World: stacks, chains, and hinged armsRigid bodies: Body and colliders, Hinges and a handle: .revolute and grabPhysics
Grabbinggrab: pull a rigid body with the mouse, through a jointHinges and a handle: .revolute and grabPhysics
FractureBreaking a shape or a solid into pieces that fit back together, evenly or crowded around a point of impact, each piece ready to be a rigid bodyBreaking things; Ch 30: What hit what: contactsFracture
Inverse kinematicsIKChain: a segmented limb that reaches for a target, or a rope dragged by its tipA limb that reaches: IKChainMotion
Gravity at scaleNBody: thousands of bodies pulling on each other, with seeded disk and cluster scenesGravity at scale: NBodyMotion
Force-directed layoutForceLayout: a graph that untangles itself into an even web you can grow, pin, and drag, drawn with drawGraphA graph that lays itself out: ForceLayoutForceLayout
Soft bodies from outlinesaddSoftBody(from:): any closed Shape as a squishy body that keeps its area, springs back toward its shape, and keeps other outlines outA squishy thing from any outline: addSoftBody(from:)Physics

Chapter 12: Flocks and swarms

CapabilityWhat it isTaught inReference
Steering vehiclesSeek, flee, arrive, pursue, wander, follow, and contain, as forces you add togetherA creature that steers: Vehicle, Seek and arrive: aiming at a target and stopping there, Roaming: wander, and trails from noClear; Ch 10: Steering: the chaseSteering
FlockingBoids from separation, alignment, and cohesion, which can also follow a fieldThe flock, assembled: Boids, Three rules make a flock: separation, alignment, and cohesionBoids
Spatial indexWhat is nearest, what is within reach, and what is inside a box, found without reading every pointThe trick that keeps it cheap: SpatialIndexSpatial index
PursuitRunners that each head at the one they chase: the ring of dogs, whose paths are logarithmic spirals, and a pursuer after a quarry that runs straightEveryone chasing somebody: pursuit curvesPursuit
CrowdsCrowd: walkers that avoid each other by each taking half of every swerve, walls no walker passes, even in a jam, and lanes that form on their ownA crowd that makes room: CrowdCrowds
Coupled oscillatorsKuramoto: oscillators that fall into step past a critical coupling, with coherence to watch it happen; each one listens to the whole crowd, or to its neighbors on a ring, a square or hex lattice, or a graph of your ownFalling into step: Kuramoto; Ch 24: In step with the neighbors: oscillators on a latticeCoupled oscillators

Chapter 13: Growing things

CapabilityWhat it isTaught inReference
L-systemsGrammar rewriting drawn by a turtle, for ferns and other plants, and parametric rules that carry numbersRules that rewrite: L-systems, When the rules need arithmetic: parametric L-systemsLSystem
Space colonizationBranching growth toward scattered attraction points, as in the veins of a leafGrowth that claims space: space colonizationSpaceColonization
Diffusion-limited aggregationWalkers that freeze on contact into dendrites and frostGrowth by chance: diffusion-limited aggregationDiffusionLimitedAggregation
Shape grammarsRules over labeled shapes in place: ice-ray lattices, building fronts, nested figuresRules over shapes, not symbols: shape grammarsShapeGrammar
Dielectric breakdownLightning grown where the solved field is strongest, with eta choosing between a bush and a boltGrowth by voltage: dielectric breakdownDielectricBreakdown
Differential growthA line that folds like coral as it grows, because it pushes away from itselfGrowth by crowding: differential growthDifferentialGrowth
Crack growthPerpendicular cracks subdividing the plane into city blocks, with a wash of translucent grains beside each crackGrowth by collision: crack growthCrackGrowth
MeanderA river migrating by curvature, cutting off oxbow lakes, and keeping its past channels as scarsGrowth by wandering: meanderMeander

Chapter 14: Fields and flow

CapabilityWhat it isTaught inReference
Flow fieldsDirection fields, streamlines (free and evenly spaced), advectionA direction at every point: FlowField, Following the flow: streamlines, Lines that keep their distance: evenly spaced streamlines, Points the field carries: advectionFlowField
IsolinesLevel curves of any field or an image's tone (marching squares): metaball outlines, contour mapsWhere the field equals something: contoursIsolines
Chladni figuresThe standing-wave patterns of a driven plate in closed form, as a field, a generator, or nodal contoursStanding waves: Chladni figures; Ch 18: Closed forms at every pixel: the pattern fieldsChladni
Line integral convolution.lineIntegralConvolution(length:field:) and .streaked(along:length:field:) brush a layer's grain, or a picture, along a direction field, so the whole field shows at once as fine streaksThe whole field at once: line integral convolutionEffects
FittingRadialBasis, a smooth field of numbers, vectors, or colors that passes through values you know at a few scattered places, and Fit.minimize, a downhill walk that finds a few numbers against a cost you writeA field you pin down yourself: radial basis functions; Ch 15: The circle they were scattered around: Fit.minimizeFitting
SlopesA fitted field's exact gradient(at:) and derivative(at:along:), and gradient(at:field:) and derivative(at:function:) for any function you writeA field you pin down yourself: radial basis functions; Appendix B: A number field's slope: the gradientFitting, Math

Part III: Shapes, lines, and marks

Chapter 15: Shapes as material

CapabilityWhat it isTaught inReference
Paths, shapes, and contoursCurved outlines you build, hold, and edit, and respace with resampledContours, shapes, and holes; Ch 8: Text as geometry: textToShapesGeometry
Shape booleans and offsetsUnion, intersect, subtract, xor; grow and shrink regionsShape arithmetic: the booleans, Growing, shrinking, and thickening: offset and strokedGeometry
Stroke as shapeTurn a stroked line into a filled region for booleans and plottingGrowing, shrinking, and thickening: offset and strokedGeometry
Voronoi and DelaunayTerritories and neighbor networks from points, with Lloyd relaxationTerritories and neighbors: Voronoi and DelaunayVoronoi
Power diagramsVoronoi cells for points that carry a weight, so the line between two circles falls where a point is equally far outside both, and a circle that touches no other sits inside its own cellTerritories and neighbors: Voronoi and DelaunayVoronoi and Delaunay
HullsThe convex hull, the rubber band around a point set, and the tighter wraps: the concave hull and the alpha shape, with its islands and holesWhat shape are these points? Hulls and alpha shapesGeometry, Hulls
Medial axisA shape reduced to its skeleton, each point carrying the radius of the largest circle that fits thereThe skeleton inside: the medial axisMedialAxis
HatchingHatching(spacing:angle:crossHatches:) fills a shape with lines a pen can drawLines for a pen: hatchingExport
Outline questionsTangent, normal, nearest point, the piece between two fractions, crossings, simplify, and rounded or cut cornersAsking an outline where it goes: contour questionsGeometry
Bending outlinesAn outline bent along a curve, pulled toward a point with its ends held, smoothed with its corners kept, cut into pieces at its corners, and traced into a few cubic curvesBending an outline: warped, pulled, split, and fittedGeometry
A curved patchA four-sided region whose sides are curves (or four corners, the bilinear map), and an outline bent into it from a rectangle, such as lettering on a waving bannerBending an outline into a patch: CoonsPatchGeometry
Enclosed regionsEvery patch a drawing's lines wall off, each as its own Shape, holes included, with Circle.contour(segments:) and Rectangle.contour as the ways inThe regions a drawing encloses: regions(enclosedBy:)Geometry
Points inside a shaperandomPoints(in:count:) and poissonDisk(in:radius:) scatter points inside an outline, and randomPoints(along:count:) along itChance inside an outline: points in a shapeGeometry, BlueNoise
Shapes that crossLineSegment, Arc, and Ellipse as values beside Circle and Rectangle, each with its measures and its nearest point, and crossings(with:) between any two of them through PlaneCurveShapes that know where they cross: segments, arcs, and ellipsesGeometry
Circle packingCircles that grow until they touch, seeded so a run repeatsPacking: circles that grow until they touchPacking
Apollonian gasketA circle filled with circles that touch, smaller and smaller down to a size you setPacking: circles that grow until they touchTiling
Ford circlesA circle for each fraction, touching its neighbors and overlapping none, over the Farey sequence, with a Fraction typeA circle for every fraction: Ford circlesFord circles
Shape packingPacking measured against the shapes' outlines, so small shapes settle into a star's notches, all at once or filled in over timePacking shapes, not circlesShapePacking
Rectangle packingRectangles of given sizes fitted into one bin at their own sizes, the placed and the ones that did not fit, with rotation as an option, for a contact sheet, a collage, or an atlasPacking rectangles: packRectanglesRectanglePacking
Straight skeletonThe ridges a shrinking outline leaves, with mitered insets cut from one buildThe straight skeletonStraightSkeleton
SVG importVector artwork read into shapes: draw it as authored, or use its outlines as geometryShapes from a file: SVG importSVG
Crease patternsThe flat sheet a folded or cut thing comes from: the Miura fold, folding rigidly in three dimensions, rotating-squares kirigami, and the two local rules a flat fold must obeyMountains and valleys: CreasePattern and the two laws, A sheet that opens all at once: the Miura fold, Origami allowed to cut: rotating squaresCreasePattern

Chapter 16: Curves and figures

CapabilityWhat it isTaught inReference
Hobby's splinedrawCurve(_:closed:spline:) with .hobby draws a curve through your points that reads as drawn by hand, and HobbySpline(through:) hands it back as a pathA curve that reads as drawn: Hobby's splineGeometry
Classic curvesPhyllotaxis, Lissajous figures, roses, superellipses, supershapes, spirograph gears, guilloche rosettes, the harmonograph, spirolaterals, Chaikin corner-cut smoothing, and a moving average that keeps every point, none of them randomCurves you can write down: the classic curves, A walk that comes home: spirolateralsClassic curves
ClothoidThe curve whose bend grows at a steady rate (the Euler or Cornu spiral): easements into a turn, smooth paths through waypoints, corners a vehicle could take, and the curve that fits two points and two headingsA corner a car could take: clothoidsClothoid
Envelopes and causticsThe curve a moving line leans on, the bright curve reflected or bent light crowds along, and where a wavefront gets to nextThe curve a family of lines leans on: envelopes and causticsEnvelopes and caustics
Fourier epicyclesA closed outline rebuilt as a chain of spinning circles, with the number of terms setting the detailCircles on circles: Fourier epicyclesEpicycles
Shape morphingOne shape turned into another; holes grow in and out, and each in-between is a shape you can useOne shape becoming another: shape morphingMorphing
AnamorphosisA plate that reads only in a mirrored cylinder standing on the page, from one viewing spot: points, contours, and shapes mapped to the page, and the arc of the cylinder an eye can seeA drawing only a mirror can read: anamorphosisAnamorphosis
TurtleA pen you drive from code: forward, back, left, right, pen up and down, and a remembered pose for branches, every run an ordinary contourA pen you drive: the turtleTurtle

Chapter 17: Marks and media

CapabilityWhat it isTaught inReference
Variable-width strokesstrokeProfile(_:): width shaped along the path, so a line tapers, swells, or carries a profile you wroteA width that changes along the path: strokeProfileDrawing
Stroke dynamicsStrokeMark and drawMark: width and opacity set by how fast and how hard a mark is made; pressure reads a Force Touch trackpad or a tablet, and stylus a pen's tilt and twistPainting as it happens: stroke dynamicsMarks, Input
BrushesstrokeBrush(_:): a stamp repeated along the path instead of one continuous ribbon, with its own tip, spacing, jitter, and angleStamps along the path: brushesMarks
Dashed strokesstrokeDash(_:): a line with gaps, the pattern walked along the path so corners and curves keep their rhythmA line with gaps: strokeDashDrawing
Paper marblingInk floated on a bath and raked: drops, tines, combs, and vortices, each a transform of vector outlinesInk on water: marblingMarbling
WatercolorPigment from one polygon, deformed and stacked at low opacity: dense cores and uneven edgesPigment from a polygon: drawWatercolorWatercolor

Part IV: Pixels and light

Chapter 18: Your first shader

CapabilityWhat it isTaught inReference
User shadersWrite shade(uv, info) and run it as a generator, a filter, or a two-input combine; #include pulls in a helper file several shaders shareThe first shader: shade, uv, and generate, Drawing with distance: smoothstep as an edge, Time, mouse, and parameters: info and params, One helper, two shaders: the include lineShaders
The shader libraryHashing, noise, SDFs, palettes, and OKLab, spliced into each shader and kernelThe shader library: fbm, hash12, palette, and the distance functionsShaderLibrary
A shader as paintfill(shader) and stroke(shader) run shade at every pixel a shape covers, uv across the shape's own box, with the edge distance, the fraction along a stroke, and the canvas position in info; a mesh takes it as its surfacePaint, not a layer: fill and stroke with a shaderColor
Design generatorsTen built-in shaders that draw a finished graphic at their defaults, among them mesh gradients, god rays, spirals, orbiting dots, grain gradients, and pulsing bordersBackdrops that come composed: the design generatorsEffects
Pattern fieldsClosed-form fields that move only by the phase you pass: quasicrystal, moire, gyroid, phyllotaxis, hex pulse, and ChladniClosed forms at every pixel: the pattern fieldsEffects
Post-process anti-aliasing.antialias smooths the stepped edges a shader leaves, as a filter on the layerThe edges a shader leaves: post-process anti-aliasingEffects
Visual chainsPer-pixel composition written as a chain: oscillators, warps, blends, and modulation, in one passPatching without typing Metal: Visual chainsVisuals
Bringing a shader overollin new --from-shader: a GLSL fragment shader translated into Metal, with a project written around itSomebody else's shader: GLSL importShaderImport
Checking a shaderollin check: compile a .metal file on the GPU and see the errors at your own line, what the shader is, and the parameters it readsTrying a shader on its own: ollin checkShaderCheck

Chapter 19: Layers and effects

CapabilityWhat it isTaught inReference
Render targetsOff-screen layers: draw into one with withTarget, then draw it back onto the canvasA drawing you can hold: render targetsEffects
The filter catalogThe built-in GPU filters: blurs, glows, color, stylize, retro, distortion, and design; postProcess applies one to the whole finished frame, and drawSheet lays labeled tiles out to compare themFilters; Ch 20: More from the shelf: ink lines, flat regions, chromatic aberration, a lens, a wall, and a mixerEffects
Generator fillsgenerate(_:) fills a layer with a built-in pattern such as .noise; the plain fills .checkers, .gridLines, .bars, and .cellular are in the referenceFilters; Ch 14: The whole field at once: line integral convolutionEffects
Blend modesAdd, subtract, multiply, screen, lightest, darkest, as drawing stateHow new paint meets old: blend modesDrawing
AccumulationnoClear(): the canvas keeps what earlier frames drew, in single precision with .float32 for a long faint exposure; Accumulator: a layer that keeps the running mean, so faint samples settle into a pictureThe canvas that keeps everything: noClear, Converging instead of brightening: the running mean; Ch 12: Roaming: wander, and trails from noClearAccumulation
HDR and tone mappingLight past full brightness, brought back by toneMap (clamp, Reinhard, ACES, or the hue-preserving neutral curve)Brighter than the screen: toneMapHDR
FeedbackA layer that sees its own last frame: trails, tunnels, and video feedbackThe canvas that remembers itself: feedbackEffects
The compose blockcompose { layer { } … }: a stack of layers, filters, and blends written as one blockThe whole stack in one block: composeEffects
ProfilingThe inspector's cost row: CPU against GPU on one frame's scale, the draw, pass and batch counts, and a frame handed to XcodeWhich half is slow: the cost row; Ch 3: When a frame takes too longProfiling
Retained batchesmakeBatch { } records static drawing once into a Batch, and drawBatch draws it again each frame at little cost, placed by the transform in forceRecord it once: batchesRetained batches

Chapter 20: Pictures restyled

CapabilityWhat it isTaught inReference
Brushwork.brushwork repaints a picture in strokes that follow its edges (an anisotropic Kuwahara filter)Paint that follows the picture: brushworkEffects
Hatching a picture.hatching draws a picture's tones as strokes that follow its shapesStrokes that follow the picture: hatchingEffects
A look from a fileColorLUT reads a .cube color lookup table, the grade a color tool exports, and Filter.lut applies it; a look built in code writes out as a .cubeA look from a colorist's suite: ColorLUTLooks
A film lookFilter.halation puts film's warm fringe around highlights, and Filter.filmGrain lays grain that follows the tone and keeps the meanA film look: halation and grainEffects
Design filtersFluted glass, water, and paper that transform a picture; liquid metal, heatmap, and gem smoke that read a shape's silhouetteThe design filters: paper, glass, water, and a material from a silhouetteEffects
Ink lines.xdog draws a line wherever the picture has an edge (an extended difference of Gaussians)A line where there is an edge: xdogEffects
Flat regions.shock flattens a picture into regions with crisp edges (a shock filter)Regions with crisp edges: shockEffects
Chromatic aberration.chromaticAberration pulls the color channels apart, so a white edge grows a colored rim, with a mode for each kind of pictureOne filter, five pictures: chromatic aberrationEffects
Lens distortionA layer bent into a barrel or a pincushion by a lens's radial model, with the corners left empty or the frame kept full: the .lensDistortion filterThrough a lens, onto a wall, and through a mixer: lensDistortion, cornerPin, and channelMixerEffects
Corner pinA layer laid onto four points with its straight lines kept, the .cornerPin filter, the same map installation mode fits a projector withThrough a lens, onto a wall, and through a mixer: lensDistortion, cornerPin, and channelMixerEffects
Channel mixer.channelMixer mixes each output channel from all four input channels plus an offset, through a ColorMatrix: a gray made to your own recipe, or two channels swappedThrough a lens, onto a wall, and through a mixer: lensDistortion, cornerPin, and channelMixerEffects
Relight, two tones, and warps.relight reads a picture's brightness as height and lights it, .dither(dark:light:) screens it into two colors, and .swirl, .bulge, and .ripple bend it around a center you giveHeight, tone, and a center: relight, the two-tone dither, and the warpsEffects
Droste.droste makes a picture contain a smaller copy of itself, again and againA picture inside itself: drosteEffects
Luminance meltA picture liquified by a warped noise field and poured through a palette, the .melt filterThe picture poured: meltEffects

Chapter 21: Pictures you solve

CapabilityWhat it isTaught inReference
Diffusion curvesA few marks held as color sources and the color let out between them, so a curve can carry a different color on each sideA picture made of a few marks: diffusionEffects
Measured distance fieldsHow far each pixel is from the nearest drawn edge and which way it lies, read back as contours, grown or shrunk shapes, outlines, and a Voronoi built from the drawn shapes rather than from pointsA field you measure: the distance fieldMeasured distance fields
Layer stylesA layer given an edge of its own from its alpha: an outline inside, outside, or centered on the edge, a drop or inner shadow, an outer or inner glow, and a lit bevel, each one filter that stacks in the order it is chainedA field you measure: the distance fieldLayer styles
Combinescombined(with:_:) runs an effect that reads a second layer, such as a mask, a displacement, a mix, depth of field, ambient occlusion, and screen-space reflectionsA field you measure: the distance field; Ch 26: What the depth buffer is for: ambient occlusion and defocus; Ch 33: Mirrors that see off screen: ray-traced reflectionsEffects
Light in a flat sketchDraw a scene in one layer and the lamps in another, and get back the light that reaches each pixel: shadows that soften with distance, falloff, beams through a gap, and the color a lit wall gives backLight that works itself out: .lightLight in a flat sketch
Seamless clone.seamlessClone sets a piece of one picture into another so the colors meet with no seam (Poisson image editing)Putting a piece of one picture into another: .seamlessCloneEffects
The frequency domainA picture read as a sum of waves instead of a grid of pixels: filtering by scale is a shape drawn over the spectrum, and a field can be built from a description of its energy (Filter.fourier/.inverseFourier/.spectrum)A picture read as waves: the Fourier transformThe frequency domain
Local averagesThe average of the square around each pixel at a price that does not grow with its size: a box blur of any radius, and a threshold that compares each pixel with its own neighborhood, so uneven light stops matteringAverages of a neighborhood, at a flat price: the summed-area tableLocal averages

Chapter 22: Iterated forms

CapabilityWhat it isTaught inReference
FractalsIFS chaos games, fractal flames, the Buddhabrot, circle-inversion lace, Kleinian limit-set curves, and Schottky circlesThe same fern, played as a game: the chaos game, Circles used as mirrors: inversion limit sets, A group drawn as one curve: Kleinian limit sets, The chaos game with a twist: fractal flames, Circles that pair off: Schottky groups, What the escapers leave behind: the BuddhabrotFractals
Strange attractorsLorenz, Clifford, de Jong, and others, drawn as orbits, and as a field a million particles followA formula that folds the plane: chaotic maps; Ch 25: A million following the same field: attractor flowAttractors
The bifurcation diagramIteratedMap: the logistic map and its one-dimensional relatives on their way into chaos, watched through bifurcation diagrams, cobweb staircases, and Lyapunov exponentsOne dial away from chaos: the bifurcation diagramBifurcation
BilliardsBilliard: a ball bouncing in a circle, an ellipse, a polygon, or a stadium, with posts standing in it, and its path as geometry you can strokeA ball in a room: billiardsBilliards
Double pendulumDoublePendulum: two weights on two hinged arms under gravity, stepped by advance(); a run repeats exactly, yet a start a ten-thousandth of a radian off soon swings somewhere elseThe classic chaos machine: DoublePendulumMotion
Escape-time fractalsThe Mandelbrot set and Julia sets, colored by how fast each point escapes, zoomable; orbit traps color by the closest pass to a shape insteadIteration without memory: escape-time fractals and orbit trapsEffects
Newton's basins.newton colors each point by the root Newton's method carries it toWhere it lands: Newton's basinsEffects
Domain coloring.domainColoring paints a complex function over its own plane: color for direction, rings for size unless you ask for .phase alone; placeable zeros and poles, and the named functions with their branch cutsA picture of a function: domain coloringEffects
Complex numbersComplex, a point of the plane that multiplies: the polar form, exp, log, pow, sqrt, and the trig functions, and ComplexPlane to place it on the canvas; the shader library has the same in its complex sectionMultiplying turns: the complex plane, Iteration without memory: escape-time fractals and orbit trapsComplex

Chapter 23: Simulations on a grid

CapabilityWhat it isTaught inReference
Simulation fieldsSimField and withField: the Game of Life, Gray-Scott reaction-diffusion with feed and kill that can vary across it, and fluid, as state on the GPU that you seed by drawing into itState that lives on the GPU: SimField and withField, The Game of Life: a first field, Two chemicals: reaction-diffusion, Water you can stir: fluidEffects
Reading a field as data.gradientMap, .levels, and .relight read a field's numbers as color, contrast, and heightA field is data: gradientMap, levels, and relightEffects
Predator-prey field.predatorPrey: prey and predators on one land, with predators released where you draw green, an invasion front, and the spiral waves behind itTwo species: predator and preyEffects
Multi-scale Turing patterns.multiScaleTuring runs one activator-inhibitor rule at several sizes at once, with a TuringScale for eachThe same rule at many sizes: multi-scale TuringEffects
Ripple pool.ripples: the wave equation as an interactive water surface; drawn marks add height, rings spread and reflectA pool you can drop things into: ripplesEffects
Self-warp.selfWarp measures which way each part of a picture moved and carries what it showed along that motion, so moving things smear and still ones stay sharpThe picture dragging its past: self-warpEffects
Falling sand.fallingSand with SandMaterial: sand that falls, rolls, and piles, water that spreads flat and lets sand sink through it, and walls that hold still, settled in 2x2 blocks each passSand that falls: the falling-sand automatonEffects
Watercolor washwatercolor(pigments:): wet paint on rough paper, with darkened edges, backruns, dry brush, and glazingPaint that behaves: watercolorWatercolor
A simulation of your ownSim.shader runs a kernel you write as a Shader, whose shade returns each cell's next state from its neighbors; inject: decides what a drawn mark doesLife rewritten as a kernel: Sim.shaderEffects

Chapter 24: Automata

CapabilityWhat it isTaught inReference
Percolationpercolation: a grid of coin flips whose open cells join into one cluster across the grid once the probability passes about 0.5927When chance acts as a crowd: percolation, Putting it together: the wildfirePercolation
Forest fire.forestFire: bare ground, trees, and fire, a field that finds its own critical density, or with growth and lightning at zero burns only what you plant and lightA forest that keeps burning: the forest fire, Putting it together: the wildfireEffects
Cellular automataelementaryCA and totalisticCA rules, and Turmite ants: small rules run for a long timeA single row of cells: Wolfram's elementary rules, An ant on a grid: turmitesCellular automata
Lenia.lenia: the continuous Game of Life, smooth mass that grows colonies and creaturesLife made continuous: LeniaEffects
SmoothLife.smoothLife: Life's own rule on a continuous field, a disc for the cell and a ring for its neighbors, with the paper's glider as the default regimeLife with soft edges: SmoothLifeEffects
Grid automata.cyclic, .excitable, .briansBrain, .hodgepodge, .wireworld, .schelling, and .ising: state automata as fields, from spirals and gliders to a circuit, a neighborhood sorting itself, and a magnet against the heatThe medium that has to rest: excitable media, A circuit made of cells: Wireworld, A neighborhood sorting itself: Schelling's board, Spins against the heat: the Ising modelEffects
Sandpile.sandpile: grains dropped on a grid, each cell toppling onto its neighbors when it holds fourA pile of sand: the Abelian sandpileEffects

Chapter 25: Simulations made of particles

CapabilityWhat it isTaught inReference
Compute kernelsYour own GPU code, written in the chapter as the Particles step snippet and the Simulation step over a texture; .metal files that reload as you edit and the typed ComputeKernel are in the referenceA million grains: GPU particlesCompute
GPU particlesParticles: a million particles moved by a Metal snippet run once per particle and drawn on the GPU, with stepParticles and drawParticlesA million grains: GPU particlesCompute
Artificial lifeParticleLife, PPS (the Primordial Particle System), Physarum, ParticleLenia, and SwarmChemistry, most of them on the public SpatialHash neighbor searchParticles that see their neighbors: Particle Life, the Primordial Particle System, Physarum, and the flock at scale, Agents that talk through the floor: Physarum, Matter that decides what shape to be: Particle Lenia, A rule that spreads by winning arguments: swarm chemistryArtificial life
Steering at scaleSwarm: separation, alignment, cohesion, seek, flee, arrive, wander, and flow as weights over tens of thousands of agentsThe flock, a thousand times bigger: SwarmSwarm
Particle fluidsParticleFluid: SPH liquid with a free surface, splashes, and grabbingLiquids and jellies: SPH and soft bodiesFluids
JelliesSoftBodies: shape-matched jellies that squash and pileLiquids and jellies: SPH and soft bodiesFluids
Ant colonyA colony laying pheromone trails, narrowing a web of possible routes down to a short tourA search you can watch: ant colony optimizationAntColony
EvolutionEvolution: GPU populations bred toward a target past obstacles, by tournament selectionLetting the sketch find it: evolutionEvolution
Kernel simulationsSimulation runs a Metal step once per cell of a texture, the grains' kind of snippet over a grid, stepped with stepSimulation(_:custom:), with substeps for several steps a frame and a kernel of your own for the first stateOne step per cell: SimulationCompute

Part V: The third dimension

Chapter 26: 3D, gently

CapabilityWhat it isTaught inReference
The cameracamera(_:) with a fixed pose such as .orbiting(...), perspective(eye:target:) to aim the eye from one point at another, and ortho(eye:target:height:), where far things keep their sizeA camera and a sphere, Placing things: transforms compose3D
Camera control and movesOrbiting with the mouse, the self-driving cameraShowcase, and snap views such as cameraView(.front); the cinematic CameraMove values are in the referenceA camera and a sphere, Keeping your bearings: views, the axis, and the ground gridCamera
Spherical coordinatesspherical(azimuth, elevation, radius, around:) places a point by two angles and a distance, in the camera's own orbit convention; a Vector3's azimuth and elevation read the angles backAppendix B: Two angles and a radius make a point in spaceMath
Axis and ground gridcameraAxis() shows a small x-y-z compass and groundGrid() a faint floor, drawn in the live window and left out of exportsKeeping your bearings: views, the axis, and the ground gridCamera
The depth testSolids nearer the camera hide the ones behind, in whatever order you draw them, over a floor from drawPlane or drawGround()Depth that hides things: the depth test3D
Solid primitivesBox, sphere, torus, knots, Platonic solids, lathes, extrusions, and moreA catalog of solids3D
Wireframewireframe() draws a mesh as its triangle edges, which take no light; each vertex also carries a normal, the way the surface faces there, in the mesh's normalsWhat a solid is made of: triangles and normals3D
LightsDirectional, point, spot, and ambient lights, glowing panels, disks, and tubes, and lighting presetsLight: presets and the kinds of light, A light with a body: area lights3D
Light shapingA fixture's measured throw on a light (IES files), and an image projected through a spot (a cookie, the stage gobo)Light: presets and the kinds of light, Air you can see: fog and volumetric light3D
Several rigs in one framewithLights gives a block its own lamps, and withoutLights draws it flatLight: presets and the kinds of light; Ch 27: One solid, two shadows: shadow art3D
ShadowsCast shadows that harden near contact, with a softness setting, ray-traced for point lights on capable GPUsShadows, and what they tell you, Two lights, two shadows3D
MaterialsStylized finishes (toon, iridescent, velvet, glitter), and physically based metal and gloss from metallic and roughnessMaterials; Ch 28: Two numbers for most real surfaces: PBR3D
What stacks with whatThe compatibility map across the 3D featuresMaterials; Ch 32: The light this needs: materials and shadows on a fieldCombining
Contact shadowscontactShadows(length:) darkens the seam under a thing resting on anotherThe seam under a resting thing: contact shadows3D
AtmosphereFog that fades surfaces with distance and pools low with a height falloff, aerial perspective that turns far ground blue and brightens the air toward the sky's sun, and volumetric light that turns spot cones, cookies, and cast shadows into visible beams and shaftsAir you can see: fog and volumetric light; Ch 28: Distant air: aerial perspectiveAtmosphere
The cartoon lookoutline(width:color:) draws a line around a mesh's silhouette, and headlight() is a light that follows the cameraThe cartoon look: outlines, and a light that follows the camera3D, 3D
Hidden-line solidsfeatureEdges(creaseAngle:) draws a mesh's faces in the fill and over them only its creases, its boundary, and its silhouette in the stroke, near solids hiding the edges of far ones, every copy of an instanced draw in one more drawA draughtsman's drawing: hidden-line solidsHidden-line solids
MatcapsShading read from a picture of a lit sphere, such as chrome, clay, or car paint, with no lights in the sceneShading from a picture: matcaps3D
Depth compositingFlat 2D drawing placed inside the 3D depth buffer, so nearer solids hide it: depth(at:), project, and billboardsFlat drawing that knows where it is: depth compositing; Ch 35: Flat marks at a depth: depth compositingDepthCompositing
Lines in 3DdrawLine and drawPolyline over Vector3: the 2D stroke laid on the camera's picture, a depth at every point so solids hide it and it hides what lies behind, a color per point, a weight on screen or in world units with strokeWeight(_:in:), and drawAxes and drawGrid built from itFlat drawing that knows where it is: depth compositingLines in 3D
Type as a soliddrawText3D, over the Mesh.text and Mesh.textGlyphs builders: a word extruded into a lit solid that throws a shadow, or the same word a letter at a time, each letter knowing where it sitsA mesh from a word: type as a solid3D

Chapter 27: Meshes and maps

CapabilityWhat it isTaught inReference
Meshes from fileOBJ, glTF, USDZ, STL, and PLY, with materials and textures; normalized(scale:) recenters and fits whatever arrivesA mesh from a file3D
TexturesA mesh wrapped in an image through its UVs, or, with no UVs, through a triplanar projectionA picture wrapped around it: textured, A picture from three sides: triplanar3D
Subdivision surfacessubdivided(levels:): a rough cage of few faces refined into a smooth solid (Catmull-Clark, or Loop for triangle meshes), with welding and open edges handledSmooth from a cage: subdivision surfacesSubdivision surfaces
Height mapsA height map carves depth, as shading with parallaxMapped or as geometry with displaced(by:scale:)Depth from a picture: height maps, Putting it together: the raked garden3D
Detail maps and decalsA detail map keeps texture sharp in a close look, and a decal stamps a picture onto the sceneTexture that survives a close look: detail maps, A picture stamped onto the scene: decals3D
Maps on a surfacenormalMapped adds relief the light sees, and surfaceMapped sets metal, roughness, occlusion, and glow texel by texel (glowing(_:) for a mesh's own colors)Relief from a picture: normal maps, What the surface is, per texel: surface maps3D
Scenes from fileloadScene reads a glTF or USD scene: named nodes drawn in place with drawScene, the file's camera and lights as values, a node reached by name, and the animations, skins, and morph targets it holdsA scene with its camera and lights: loadScene, Motion the file remembers: animations, skins, and morph targetsScenes
Bringing a scene overollin new --from-scene: a glTF or USD scene written out as the camera, light and placement calls that draw itA scene you can take apart: the scene written as sourceSceneImport
Cutting and joining meshesunion, intersection, subtracting, and symmetricDifference combine two closed solids, and Mesh.joined(_:) makes one mesh from several placed onesCutting one solid with another: mesh booleans, One mesh from several: joined and placed3D, 3D
Shadow artshadowArt(fromFront:fromSide:) carves the largest solid that throws the silhouettes you ask for, and shadow(from:) shows the shadow it throwsOne solid, two shadows: shadow artShadow art
Mesh growthMeshGrowth: a surface that grows more area than it has room for and folds, driven evenly, by curvature, by your own field, or by a reaction-diffusion pattern in the surfaceA surface that outgrows itself: differential growthMesh growth
Sweeps and stripsMesh.sweep carries a Shape along a Curve3D, whose frames never twist, sized and turned on the way; Mesh.loft carries several shapes placed along it and blends the surface from each to the next; Mesh.strip is the ribbon between two lines; Pace spaces points along a curve by length, or along a strip by areaA shape along a path: sweeps and stripsSweeps and strips
The Hopf fibrationA sphere's worth of circles, no two of which meet and every two of which are linked once, handed back as 3D paths to sweepA shape from four dimensions: the Hopf fibrationThe Hopf fibration

Chapter 28: Materials and surroundings

CapabilityWhat it isTaught inReference
EnvironmentsHDRI image-based lighting (eight bundled, twelve to download) and a procedural sky that needs no files, with its own sun as a light and clouds; the surroundings become the lightSurroundings as the light: environments, Weather in the sky: clouds3D
Brushed metal, clearcoat, sheen, and skinAnisotropy stretches a highlight into a streak, clearcoat and sheen give paint and cloth, and subsurface scattering lets light into skin, wax, and stoneA streak instead of a dot: anisotropy, Paint and cloth: clearcoat and sheen, Skin, wax, and stone: subsurface scattering3D
GlassA material that bends and tints the light passing through itGlass3D
The scene through glasssceneThroughGlass() draws the frame once more with the glass taken out, so a bottle in your scene shows what stands behind it on any Mac, with no ray tracingGlass3D
VolumesVolume, a box of density samples, drawn by drawVolume as smoke, cloud, fire, or ink: the medium blocks light, scatters the scene's lights, and glows, and solids inside it are veiled by what lies in frontA cloud in the scene: volumesVolumes
Thin filmthinFilm and thinFilmThickness color a surface the way a soap bubble is colored, with no pigmentColor with no pigment: the thin film3D

Chapter 29: Landscapes and multitudes

CapabilityWhat it isTaught inReference
TerrainHeightfield: landscapes grown from noise or diamond-square, weathered by simulated rain and gravity, read out as a mesh, an image, or samplesA landscape you grow: heightfields and erosionTerrain
Instanced meshesOne mesh drawn thousands of times in one draw call: MeshInstance placements the GPU applies to each copy, or a buffer a compute kernel writesTen thousand of the same thing: instancingInstancing
Points on a surfaceScatter a mesh's skin by area, not its vertex list, each spot carrying its normalWhere the copies go: points on a surfaceSurfaceSampling
Mesh fieldsA world of placed meshes kept between frames and drawn by one call, each copy culled on the GPU against the camera (MeshField, drawMeshField)A world the camera trims: MeshFieldInstancing
Strand fieldsGrass grown inside the draw call: bending, swaying blades with no geometry buffers, camera-culled and distance-graded (StrandField/drawStrands)Grass that was never built: strand fieldsStrands
DrainageRivers worked out from a Heightfield rather than drawn: hollows filled so water always has a way out, flow counted per cell, the rivers above a minFlow as polylines you can stroke, Strahler ordering, and basinsWhere the water goes: drainageDrainage
The oceanA sea built from its own wave spectrum: one inverse Fourier transform makes the surface, drawn as water with no stored geometry, its wave height a measurement in world units (Ocean/makeOceanField/drawOcean)The sea, from what a sea is made of: an ocean spectrumThe ocean
How far a light carriesreach: bounds a lamp to its own neighborhood, with no light past it, which lets a frame carry up to 256 lamps: past eight, the lights are culled per screen tileA courtyard of lamps: many lights3D

Chapter 30: Worlds with weight

CapabilityWhat it isTaught inReference
3D physicsWorld3D: rigid bodies that stack, tumble, and swing inside the 3D scene, picked up and thrown with the mouseThings with weight: World3D and bodiesPhysics3D
Motors, gears, and racksdrive(at:strength:) turns a hinge or a slider at a speed and drive(to:) holds it at a pose; .gear(teeth:and:) makes two hinges turn together, and .rackAndPinion turns a hinge's turning into a slider's travelMachines out of joints: motors, gears, and racksPhysics3D
Collision groupsgroup: and ignoreCollisions(between:and:) let chosen bodies pass through each otherThings that pass through each other: collision groupsPhysics3D
Asking the worldworld.contacts says what hit what, a body made with isSensor: counts what is inside it, and raycast(from:to:), sweep, and bodiesOverlapping ask what is in the wayWhat hit what: contacts, A region that counts what is inside: sensors, What is in the way: rays, sweeps, and overlapsPhysics3D
Holding a body backfreedom: takes a direction of motion away, gravityScale gives a body a pull of its own, and checksPath keeps a fast body from passing through a thin wallTaking a direction away: degrees of freedom, A pull of its own: gravityScale, Too fast for a thin wall: checksPathPhysics3D
More jointsA cart on a track with .path(through:looping:alignment:), a pulley, and .allowing(_:at:travel:), a joint written as a list of freedomsA cart on a track: the path joint, A rope over two hooks: the pulley, The joint that is a list of freedoms: .allowingPhysics3D
TensegrityTensegrity and addTensegrity: struts held apart by cables in their balanced forms, standing in the world as capsule struts joined by .cable jointsStanding on cables: tensegrityTensegrity
Buoyancyworld.water with Water(level:): bodies float by the weight of the water they push aside, on waves if you askWater, and what it holds up: buoyancyPhysics3D
Ground and scenery from elsewhere.heightfield turns a landscape into ground, and addStaticBodies(from:) and addBodies(from:) read colliders from a scene or a USD fileGround from a landscape: the heightfield collider, Scenery and bodies from a file: scenes and USD physicsPhysics3D
Physics snapshotssnapshot() and restore(_:) keep a world as it stands, save(to:) writes it to a file, and assetName saves a large collider by nameA world saved as it stands: snapshot and restore, A large collider saved by name: assetName; Ch 31: Snapshots of figures, vehicles, and clothPhysics3D

Chapter 31: Characters, vehicles, and cloth

CapabilityWhat it isTaught inReference
A characteraddCharacter(radius:height:at:): a capsule steered by walk(at:), often from moveAxis, that jumps, climbs steps, and stops at slopes too steep for itSomeone to be in there: the character controllerPhysics3D
VehiclesaddVehicle: wheels with suspension, an engine, steering, and a hand brake; isTracked: makes a machine that turns by driving its two sides at different speedsSomething to drive: the vehicle, Turning without steering: tracksPhysics3D
Cloth and soft bodiesaddSoftBody(from:at:): cloth that drapes and balloons that hold their air, pinned where you say, touching the rigid world and floating like any bodyCloth that finds its own shape: soft bodies, A cloth among the contacts, A raft made of cloth: soft bodies that floatPhysics3D
RagdollsaddRagdoll(from:at:): a figure that falls, and with drive(toward:strength:), one that tries to standLetting a figure fall: the ragdoll, A figure that tries to stand: powered ragdollsPhysics3D
Cloth a figure carriesskinnedTo: and carriedBy: hang cloth on a moving figure, with sway and a limit on how far it stretchesA cape on someone's back: cloth a skeleton carriesPhysics3D
RopesaddRope(through:at:radius:pinned:): a rope that knows how far it is twisted as well as where it bendsA line that knows how it is turned: ropesPhysics3D

Chapter 32: Sculpting with fields

CapabilityWhat it isTaught inReference
2D SDF combinatorsShapes as distance fields that merge, melt, morph, and repeatA shape as a question: the signed distance field, Melting: the smooth minimum, Carving, overlapping, and halfway: the other verbs, Folding space: domain repetitionCombinators
Raymarched 3D fieldsSDF3D drawn by sphere tracing through the camera, sharing depth with meshesInto space: SDF3D and drawSDF3D, How the picture gets made: sphere tracingCombinators
Field distortionstwisted(_:), bent(_:), displaced(amplitude:frequency:), and roughened(amplitude:frequency:) bend a whole field at onceBending the whole form: distortionsCombinators
Joins like joinerychamferUnion, stairsUnion, and columnsUnion join shapes with machined edges, and smoothUnion(k:) { } merges ordinary draw callsJoins like joinery: the machined family, Merging ordinary draw calls: the block formCombinators
The sculpt { } blockAdd, carve, and blend shapes with stateful verbs, in 2D or 3D, made for live codingBuilding up and carving away: the sculpt blockCombinators
Fractal fieldsmandelbulb, mengerSponge, and mandelbox as leaves of a raymarched field, each a distance estimateInfinite detail: the fractal leavesCombinators
Isosurfaces and metaballsThe surface where a field over space crosses a level, built as a Mesh by marching cubes, or by dual contouring to keep sharp corners: soft spheres that fuse, and noise volumesAny field as a mesh: isosurface, Soft spheres that add up: metaballs, Corners that stay sharp: dual contouringIsosurfaces

Chapter 33: Traced light

CapabilityWhat it isTaught inReference
Ray-traced reflectionsrayTracedReflections(): surfaces that reflect the scene's geometry, off-screen parts and hidden faces included, on a ray-tracing GPU; glossyReflections() blurs them, and reflectionBounces(_:) lets mirrors face mirrorsMirrors that see off screen: ray-traced reflections, The floor that shows the room: glossy reflections, Mirrors facing mirrors: reflectionBounces3D
Global illuminationglobalIllumination(intensity:) lets light bounce off one surface and color the next, on a ray-tracing GPULight that bounces: global illumination3D
CausticsThe light glass and polished metal focus, photon-traced: a lens's bright spot inside its own shadow, a chrome ring's folded fan, prism rainbows via dispersionThe light the glass takes, given back: causticsCaustics
Temporal anti-aliasingtemporalAntialiasing(): 3D edges refined past the fixed samples per pixel by shifting the projection a fraction of a pixel each frame and averaging the frames; withMotion { } keeps a moving mesh's edges smoothEdges that settle: temporal anti-aliasing3D
Motion blurmotionBlur(shutter:): the streak a shutter leaves, worked out from how far each surface moved since the frame beforeThe streak a shutter leaves: motion blur3D
Lens flareThe light the camera adds: the ghosts a lens prescription throws from a bright source and the star on the source, both shaped by the iris blades, fading as something covers the sourceLight in the camera: lens flareLens flare
Path-traced export--path-traced renders the 3D scene by tracing light: soft shadows, bounce color, mirror in mirror, glass, glowing meshes as lights, textures in the bounces, and a lens; --pt-noise lets a settled pixel stop early and spends the count where the grain is; --pt-clamp bounds what one bounce may add to a sample, so a polished scene's fireflies go, at a bias the recipe states; --pt-reuse carries the earlier frames' samples into each frame of a sequence, so the grain settles and holds still; --pt-seconds gives each frame a time in place of a count, and the recipe records the count it reached; --denoise filters out the grainLight followed path by path: the path-traced export, Grain filtered out: denoisingPath-traced export
Specular anti-aliasingspecularAntialiasing(): highlights that hold still instead of crawling and sparkling as a surface turnsHighlights that hold still: specular anti-aliasing3D
Bokeh.defocus(blades:catsEye:) shapes the out-of-focus blur by the iris blades, with the cat's-eye shape toward the edgesThe shape of a blur: bokehEffects
Depth of field on the canvasdepthOfField(): the 3D frame blurred by its own depth through the camera's lens (aperture, focusDistance, apertureBlades), a blurred foreground turned into a veilThe frame through the camera's lens: depthOfField()3D
The overlaywithOverlay { }: a block drawn over the finished frame after every pass, so a caption or a readout stays sharp under the lens, the edge average, and the motion blur, and never joins an accumulating canvasThe frame through the camera's lens: depthOfField()Effects
Depth of field from lightLineSpray and Bokeh: lines drawn as millions of scattered points through a lens into a running mean, until the lens's blur appears; the .light particle style and the develop print underneathA lens made of samples: depth of field from light; Ch 25: Grains as light: the light style and the running mean; Ch 19: Converging instead of brightening: the running meanDepth of field from light
Motion for a changing meshdrawMesh(_:previous:) hands motion blur and anti-aliasing the mesh's shape from the frame beforeA mesh that changes shape: drawMesh(_:previous:)3D
Temporal upscalingtemporalUpscaling(_:): render fewer pixels and let MetalFX build the frame back at full size, in the live windowRendering fewer pixels: temporal upscaling3D
Frames between the drawn onesframeInterpolation(): draw() runs every other refresh and the platform builds the frame in between, so a heavy scene drawn at thirty frames a second moves at the display's sixty, one refresh laterDrawing fewer frames: frame interpolation3D

Part VI: The world coming in

Chapter 34: Seeing

CapabilityWhat it isTaught inReference
Camera feedsThe webcam, or any frame source, drawn with drawFrame and read by trackers as it runsThe webcam is an image, Trackers: attach, then readVision
Video playbackVideo files as live textures you play, seek, and loop, frame for frame the same under an exportWhen there is no camera: stills and footageVideo
A feed with no cameraCamera.orStill and StillFrames, so a sketch that reads the world runs with nothing plugged inWhen there is no camera: stills and footageVision
Motion trackersObject tracking, the paths of thrown things, and dense optical flowThe picture as a field: optical flow, A patch you point at: ObjectTracker, Things that fly: TrajectoryTrackerVision
People trackersFaces with landmarks, hands, 2D and 3D body poses, and person segmentationThe body as a controller: hands, faces, and bodies, The person as pixels: lifting the subjectVision
Still analysisMost trackers also run once on an ImageThe body as a controller: hands, faces, and bodiesVision
Scene trackersContours, rectangles, barcodes, text (OCR), saliency, classification, and the subject lifted from a picture, whole or at a point you giveReading outlines and print: contours, rectangles, text, and codes, Words for the scene: ImageClassifier, Where an eye would go: SaliencyTracker, The person as pixels: lifting the subject, A click cuts it loose: PointSegmenterVision
ModelTrackerA Core ML model of your own: classifiers, detectors, image-to-image maps, and segmenters, with sketchResource(_:) to find the model fileBringing your own model: ModelTracker, Models of your ownVision
Depth from a pictureDepthTracker estimates depth from one camera and holds it steady from frame to frame; DepthClip reads a whole recorded clip first, so an export gets the same depth each runDepth that holds still: DepthTracker, A clip read whole for an export: DepthClipVision
Words as numbersConceptTracker scores phrases you type against the picture, as numbers a sketch can useWords as numbers: ConceptTrackerVision
The camera in a 3D sceneEnvironment.feed lights a 3D scene with the camera's picture, and textured(_:) wraps a mesh in the live frameThe room as the light: Environment.feed, The room as the surface: textured3D
Screen captureScreenCapture: a display, an app, or one window on the Mac as a live frame source, with nothing asked of the app it captures; a tracker reads it like a camera, and excludesOwnWindows = false puts the sketch's own window in the picture as a feedback tunnelDrawing with the screen: ScreenCaptureScreenCapture
Slit scanA rolling frame history read back through a per-pixel time delay: time as a spatial dimensionEvery pixel its own moment: SlitScanSlitScan

Chapter 35: Depth

CapabilityWhat it isTaught inReference
RGBD framesColor plus depth plus intrinsics; unproject turns a pixel into a point in metersWhat a depth camera sees, Standing the picture upRGBD
Point cloudsPoints drawn as instanced splats that face the camera, in the hundreds of thousandsStanding the picture up3D
World fusionWorldCloud fuses depth frames into one world cloud by their poses, and ScanGraph recognizes a place the scan comes back to, so the scan agrees with itselfOne world from many frames, When the camera loses its place: correcting drift, Coming back to where you started: closing the loopPhone
A depth frame as the stagedrawDepthScene(_:) puts a depth frame behind the 3D scene as both backdrop and depth, with camera(.intrinsic(_:)) matched to its lensSolids behind the scene: drawDepthSceneDepthCompositing
Surface reconstructionreconstructSurface and particleSurface: a scanned or generated point cloud turned back into a Mesh, with holes in the data left open, and particle sets skinned as one blended bodyA solid from a sweep: reconstructSurface, Points as their own material: particleSurfaceSurface reconstruction

Chapter 36: The iPhone as a sensor

CapabilityWhat it isTaught inReference
Recorded capturesOpen .r3d depth recordings as point clouds, with the intrinsics of the camera that made themDepth footage: Record3D clips and the live streamRecord3D
Live USB depthA tethered phone's RGBD stream, frame by frameDepth footage: Record3D clips and the live streamRecord3D
The capture appOllin's own iPhone app runs ARKit on the phone and streams typed results through PhoneDevice, starting with LiDAR depth and the phone's pose as it movesOllin's own app: Ollin CapturePhone
A body in solidsThe phone's skeleton in meters, each joint with an orientation, dressed in capsules, and read from a film with BodyTracker3D when no phone streamsA pose you can dress in solids: the body, When no phone is streaming: the film, Putting it together: the dancer in solidsPhone, Vision
The room from the phoneThe phone's labeled room mesh, the flat surfaces it found, and the light it measured in the roomThe room from the phone: its mesh, its surfaces, and its light, A surface the phone already built: the room mesh, Somewhere to stand: flat surfaces, The light in the room: PhoneLightPhone
More of a person from the phoneHands measured in meters, and where a look landsMore of a person from the phone: hands and a gaze, A hand you can reach in with: hands, Where a look lands: gazePhone
The picture from the phoneText read and placed in the world, where an eye would go, how the picture is moving, and pictures the phone was told to look forThe picture from the phone: words, attention, motion, and a known print, The words on the wall: text, What draws the eye: attention, How the picture is moving: flow, A picture it knows: markersPhone
The phone in your handThe phone as a pointer, its Ray3 hitting things in the scene, the sounds it hears named, touches on its glass, and the air pressure around itThe phone in your hand: a wand, its ears, the glass, and the air, Pointing at it with the phone: the wand, What the phone hears: sound events, Playing the glass: touches, The air it is standing in: the barometerPhone, Geometry

Chapter 37: Listening

CapabilityWhat it isTaught inReference
Audio analysisAmplitude, spectrum, waveform, and log-spaced bandsLoudness from the microphone: amplitude, What the analyzer hears: waveform, spectrum, and bandsAudio
Audio sourcesThe microphone, audio files (the same numbers under an export), test tones, and a video's soundtrackFour sources: the microphone, a file, a tone, and a videoAudio
Feeding the analyzer yourselfAn AudioAnalyzer fed samples you make with analyze(samples:count:), one frame's worth at a time, so its numbers are the same on every run; the chapter's StageMic feeds it a made-up band this wayA band that plays the same every run: StageMicAudio
Beat detectionOnsets as events: beat, beatCount, timeSinceBeatHearing the beat: onsetsAudio
Pitch trackingThe note being sung or played as pitch (its hertz, confidence, nearest note, cents, and MIDI number) and nearestPitch, and the twelve pitch classes as chroma, with the octaves folded togetherOne note at a time: pitch, Every note in the air: chromaAudio
ListeningSpeech as a caption that corrects itself, phrases you can trigger from, and about 300 everyday sounds named as they happenWords as they are spoken: SpeechListener, Sounds with names: SoundClassifierListening

Chapter 38: Controls and signals

CapabilityWhat it isTaught inReference
MIDIKnobs, notes, and messages from hardware controllers, sent as well as read, and each held note's own bend, pressure, and slide from an MPE surfaceParameters from anywhere: MIDI and OSC; Ch 39: A note under the finger: expressionMIDI
OSCOSCReceiver reads network control messages from tablets, DAWs, and other machines, and OSCSender sends them outOver the network: OSCOSC
MIDI clockTempoClock(from:) follows the beat a drum machine, a DJ mixer, or a DAW sends as MIDI clock, as beats, bars, and a phase to animate withMusical time: MIDI clock and LinkMIDI
LinkLinkClock joins the shared tempo session on the network, so every app that joins keeps one tempo and lands the same downbeat, with the reads TempoClock hasOne beat for the whole room: LinkLink
Parameter bindingOne @Param driven by MIDI (a knob or the pitch wheel), OSC, serial, Bluetooth, and the inspector alike, with smoothing, and show-rules that hide a parameter while another leaves it nothing to doOne parameter, three hands: binding and smoothingParameters
Game controllersSticks, triggers, and buttons read in draw(), plus motion and a touchpad on hardware that has them, with several players at once and centered sticks and unpressed buttons when nothing is plugged inSomething to hold: game controllersController
The weather outsideWeather reads the sky over a place or a name in plain units, and Place.sun(at:) puts the sun where the clock saysThe weather outside: WeatherWeather
HapticsA pattern of taps and hums played from draw(), put together like a phrase, and turned into a trackpad's three feelings and one strengthTouch as an output: hapticsHaptics
Pinch and turnTwo fingers on the trackpad, or on the phone showing the sketch, read in draw() as this frame's change of size and turn, with a hook for each, recorded into a take, and zooming viewControl() and cameraControl()Two fingers on the trackpad: pinch and turnInput
Typed textThe keyboard read as a text field reads it: a dead key's accent, the emoji viewer's pick, and an input method's confirmed word arrive through typedText(), the reading still being composed in composingText, with a hook as text arrivesText the way a text field takes it: typed textInput
TUIOTouches, tagged pieces, and shapes from a marker table, a touch wall, or a phone appA table you put things on: TUIOTUIO
SerialA USB microcontroller's sensor lines read in draw() or bound to a parameter, lines written back to drive the hardware, a port that waits through unplugs and reopens itself, and FirmataBoard for a board running FirmataA wire to the physical world: serialSerial
BluetoothA Bluetooth Low Energy sensor read in draw() or bound to a parameter, BluetoothScan listing the devices in range, the formats that turn bytes into values, and a connection that waits and reconnects by itselfThe same loop, without the wire: BluetoothBluetooth
OSCQueryThe sketch's parameters published as a tree a control app browses and builds its own controls from, the values coming back over OSCThe sketch that says what it takes: OSCQueryOSCQuery
Curves and barsA ResponseCurve parameter shaped by dragging its points and read like an easing, and a list of numbers painted as a row of bars, both saved into the sketch and held by a cueShapes you draw: a curve and a row of barsParameters
Smoothing@Smoothed calms a jittery input, such as the mouse, a tracker, or a sensor, as it arrivesA value that is not a parameter: @SmoothedAnimation
Live dataDataFeed reads one address over and over in the background, counting only the answers that changed; PushFeed holds a connection open for messages that arrive on their ownNumbers that keep arriving: DataFeed, Messages that arrive on their own: PushFeedLiveData

Part VII: Out into the world

Chapter 39: Making sound

CapabilityWhat it isTaught inReference
SynthesisA Synth the sketch plays: notes by name or number, voice presets, envelopes, and filtersA sketch that playsSynthesis
Physical modelsA plucked string worked out sample by sample, a shape you strike that rings in its own modes, and a bowed string and a blown tube you keep playingA string worked out sample by sample: the plucked string, A shape you can hit: modal synthesis, A note you keep playing: bowed and blownSynthesis
The effects chainsynth.effects: distortion, delay, reverb, chorus, and a limiter in a chain after the note, in the order you list them, and a room of your own from a recording or a rule (convolution reverb)After the note: the effects chain, A room you can draw: convolution reverbSynthesis
Patches and FMPatch builds an instrument from oscillators, and modulated(by:amount:) lets one oscillator push another's frequency back and forth (FM)Building an instrument instead of choosing one: patches and FMSynthesis
Sampled instrumentsSampledInstrument: an instrument played from recordings, the built-in one or an SFZ set you loadAn instrument somebody recorded: sampled instrumentsSynthesis
Wavetables and grainsA wavetable read by position, and a grain cloud cut from a sound, so a moment can be held and dragged throughA wave you can draw: wavetables, A sound in pieces: grainsSynthesis
More effectsThe four effects that move a sound (chorus, flanger, phaser, tremolo), the three that hold its level (compressor, limiter, gate), pitch shift, freeze, and stretch, and an effect you write yourselfSomething that moves: chorus, flanger, phaser, tremolo, Something that holds a level: compressor, limiter, gate, Something that takes the sound apart: pitch shift, freeze, stretch, An effect nobody wrote for you: custom effectsSynthesis
Per-note expressionnoteOn returns a PlayingNote, and bend(_:semitones:), press(_:_:), and slide(_:_:) shape that one note while it soundsA note under the finger: expressionSynthesis

Chapter 40: Music by rule

CapabilityWhat it isTaught inReference
Tempo and stepsTempo turns the clock's seconds into beats and a NoteLength into seconds, and StepCounter hands back each step number the beats have passedBeats and note lengths: Tempo and NoteLength, One step at a time: StepCounterComposition
Euclidean rhythmsRhythm spreads hits as evenly as it can over a number of steps, rotated to start where you sayHits spread evenly: Euclidean rhythms with RhythmComposition
SwingEvery second step played late by the same fraction of its pair, through the wait a synth's play(_:velocity:for:after:) takesLate on purpose: swingComposition
ScalesScale turns a degree into a note that stays in keyStaying in key: ScaleComposition
Chords and arpeggiosChord names a chord by its root and kind, chord(on:) builds one on a degree of a Scale, and Arpeggio plays its notes one step at a timeChords from the key: Chord and ArpeggioComposition
Markov chainsMarkovChain counts what followed what in a motif and picks each next element by those counts, the same line for the same seedWhat comes next: a MarkovChain; Ch 4: A roll that remembers the last one: MarkovChainComposition
Chord progressionsProgression plays a key's chords by Roman numeral, or chords named by symbol from any key, with named progressions and wandering(_:) for a longer run that makes only the moves the original madeChords that come out of a key: ProgressionComposition
MIDI filesA Standard MIDI File read into notes a sketch plays or draws, and written back out so a phrase opens in a sequencer; its tempo map read from beats to seconds and back; a take recorded from a Synth as it playsKeeping what it played: writing a MIDI file, Music that travels between programs: MIDI filesMIDI files
A step sequencerStepSequencer: a grid of steps with swing, velocity, chance, and ratchets, read at the beat you hand itA grid with a feel: StepSequencerComposition
An arpeggiatorArpeggiator plays the notes you hold as a pattern, one step at a timeA chord played as it is held: ArpeggiatorComposition
TuningsTuning: equal temperament, just intonation, Pythagorean tuning, other divisions of the octave, and Bohlen-PierceOther divisions of the octave: TuningComposition
Playing along with the roomBeatFollower finds the beat in the sound it hears, so the music keeps time with the roomPlaying along with the room: tempo syncComposition
SonificationNumbers read out as notes: a table column, a terrain profile, or a picture row spread over a range of pitch and snapped to a scaleNumbers you can hear: sonificationSonification
Spatial audio and sound in an exportplace(at:heardFrom:) sounds a synth from a point in the 3D scene, heard from the camera; an export renders what the synths play into its soundtrack, the same on every run, with the placing keptSound from a place in the scene: spatial audio, Putting it together: the music boxSynthesis, Sound in an export

Chapter 41: Finishing a sketch

CapabilityWhat it isTaught inReference
Stills and sequences--export writes a frame as PNG or HEIC, and --export-sequence a folder of themEvery export runs without a windowExport
Paper sizescanvasSize as a sheet such as .a4, .a3, or .usLetter, turned .landscape, at a .dpi(_:) you chooseSized for the output: fractions of the canvas, and paper sizesCanvas
Video and GIF--export-video (H.264, HEVC, ProRes) and --export-gif, the same frames on every runMotion: video and GIF; Ch 3: Putting it together: a loop that never endsExport
SVG and PDF for plotters--export-svg and --export-pdf write the drawing as vector paths, and --hatch turns fills into line workLines for a pen: SVG and PDF; Ch 15: How a plot runsExport
Describable outputdescribe(_:) and describe(_:as:in:): the sketch says what it shows and what its parts are, so a screen reader has something to readSaying what it shows: describable outputAccessibility
Reproducibility metadataPNG, SVG, PDF, and video files carry their recipe: the seed, the @Param values, the git commit, and the frame; --capture-source keeps the code tooThe recipe in the fileExport
Setting a parameter for one run--param name=value sets a parameter for an export, and --list-params shows what a sketch declaresPassing the parameters back inExport
Headless captureOllinApp.image(of:frame:) renders a sketch to a CGImage in code, with no window; the export flags wrap it, and the guide's figures are made with itRendering from code: OllinApp.image(of:frame:)Export
Drawing finer than you save--render-scale draws each frame larger and averages it back down, for finer edges on filled shapes and outline textDrawing finer than you save: supersamplingExport
Linear frames for a compositor--export-exr writes the frame before the tone map: light past white, the frame's coverage, and, for a 3D scene, the distance from the eye as a Z channelThe frame before the tone map: OpenEXRExport
Wide gamut and HDR outputcolorOutput: Display P3 on screen, highlights brighter than white, HDR10 video, and HEIC stills with a gain map; Color(displayP3:green:blue:) for colors outside sRGBBrighter than white: HDR outputWide gamut & HDR output
Transparent outputbackground(.clear) keeps the canvas see-through, and PNG and the two video codecs that carry alpha, proRes4444 and hevcWithAlpha, keep that transparency, so the sketch lands over another layerLeaving the background behind: transparent videoExport
Frame rates--fps by number or by name (ntsc, film), a FrameRate in code, the broadcast fractions kept exactThe grid a broadcast asks for: named frame ratesExport
Slow motion in an export--slow-motion renders the extra frames a slowed shot needs, so the motion stays smooth rather than stepping, and --made-frames has the GPU build the ones between for a heavy 3D sceneSlower than it happened: slow motionExport
Settled frames--settle lets a running mean settle before each frame of a video is writtenSettled, then written: a running mean in a videoExport
Motion blur from subframes--subframes draws each frame at moments across the open shutter and averages them, so anything a sketch draws streaks, 2D included, at that many times the render costBlurred the slow way: subframesExport
A web page--export-web records what the sketch draws and writes a page that plays it back in a browser, with the framework's shape shader rewritten in GLSL, as one file or a fragment for your own pageA page that plays it: the web exportWeb page

Chapter 42: Making it physical

CapabilityWhat it isTaught inReference
G-code for machines--export-gcode writes the frame's line work as a machine program: pen plotter, laser, or mill, with the pen-up travel planned shortDriving the machine itself: G-codeG-code
A named sheetGCode(.plotter(), paper: .a4) and DXF(paper: .a3) size a drawing for a sheet with a margin clear on every side, holding its height as well as its width; --gcode-paper, --dxf-paperDriving the machine itself: G-codeG-code
Line drawinglineDrawing(of:): a 3D scene written down as 2D line work, with what the surfaces hide taken out: the silhouettes, creases, and boundaries a draftsman would draw, so a plotter, a laser, or a vector file can have the sceneA 3D scene on the plotter: lineDrawing(of:), Putting it together: the printed knotLine drawing
Print separations--export-separations: one grayscale master per spot ink, screened into dots with --screen if you ask, with an overprint previewPrinting one ink at a time: separations, Putting it together: the printed knotPrintSeparations
3D printingmesh.write(to:) as STL, OBJ, or 3MF at the size you set, with printCheck() reporting whether the surface is a solidSomething you can hold: a 3D printFabrication
Embroidery for a machine--export-embroidery writes the frame as the stitches an embroidery machine sews: strokes as running stitch, fills as rows, each color its own threadThread instead of ink: embroideryEmbroidery
A drawing for the shop--export-dxf writes the frame as a DXF drawing a CAD program or a laser's software opens: lines, polylines, and circles in millimeters, each color on its own layerA drawing for the shop: DXFDXF
Print colorSoftProof and Filter.softProof: the canvas as a press profile will print it, the colors it cannot reach flagged, and --export-plates for the process platesSeeing the print before you print it: soft proofsPrintColor
Spatial models--export-usdz writes a 3D frame, and write(to:) any Scene, as USDZ that Quick Look and Messages open and that stands in a room in ARSomething you can walk around: USDZSpatial
Spatial video--export-spatial writes the motion as a stereo pair per frame (MV-HEVC), with stereoGeometry naming how far apart the eyes stand and how far away they agreeSomething you can look into: spatial videoSpatial

Chapter 43: Performing

CapabilityWhat it isTaught inReference
Live codingswift run OllinLiveCoding: the code shown over the visuals, evaluated while it moves, with names completed under the text cursorPerforming the code itself: live coding, Finishing a name as you type: completionLiveCoding
Live recordingstartRecording() or ⌘⇧R keeps a run as it happens, sound included, through evaluationsKeeping the takeRecording
CuesEach parameter's value saved under a name and called back at once or over a fade: saveCue, cue(_:over:), nextCue, the inspector's Cues card, a .cues.json file named after the sketch, and --cueA look you come back to: cuesCues
The host on a controllerThe live-coding host's own actions, such as evaluate and record, answer to fixed OSC addresses and to MIDI you teach itThe host on a controller: OSC and learned MIDILiveCoding
Record & replay--record-take writes down a run's seed, clock, inputs, and parameters; --replay plays it back the same, steps through it frame by frame, and renders it through any exportPlaying the night again: replayReplay
Keyframed parametersautomate($parameter) { } writes a parameter's values down over time, with named or Bezier curves, looped or at any speed, and rendered the same by any exportA value at each moment: keyframesAutomation
Parameter timelineOllinLive's panel: drag the playhead, set a parameter, and click its diamond to place a key; lanes, curves shaped by eye, a rule typed in the parameter's own row, and an automation file OllinLive reads and other exports take with --automationDirecting by hand: the timeline panelTimeline
TimecodeTimecodeClock follows the MIDI Time Code a deck or an editing system sends, so a sketch keeps to the show's position rather than its own clockFollowing another timeline: timecodeMIDI
Parameters driven by a formuladrive($parameter, "190 + sin(time) * 80") reads a parameter's rule from text rather than from Swift source, so it can arrive from a file or a typed field, and one parameter can be worked out from anotherA rule instead of keys: formulas, A rule for each part: parameters that hold several numbersFormula
SyphonPublish frames to (and read frames from) other Mac apps, GPU to GPUInto another app: SyphonSyphon
Virtual camerapublishVirtualCamera() makes the sketch a camera any app can pick, a video call or a web page included, once the Ollin Camera extension is installedThe sketch as a webcam: the virtual cameraVirtualCamera

Chapter 44: Handing it over

CapabilityWhat it isTaught inReference
A sketch as the screen saverollin new --kind screen-saver wraps a sketch as a .saver the system loads when the machine goes idle, with one script to build, sign, and install itLiving in the system: a screen saverScreen saver
A sketch as the wallpaperollin new --kind wallpaper runs a sketch as the desktop: one window per display at desktop level, behind the icons, quit from its menu-bar markWallpaper and a menu-bar stripWallpaper
A sketch in the menu barollin new --kind menu-bar runs a sketch as a small live strip among the status items, at 30 frames a second, since it stays on screen all dayWallpaper and a menu-bar stripMenu bar
A sketch as a widgetollin new --kind widget shows a sketch on the desktop as a widget: widgetTimeline says how far apart the pictures sit, one is drawn for each moment on the day's own clock, and --export-widget shows the run without waiting for itA widget, and what it does to a sketch, A widget's clock: the time of day, How far apart the pictures sit: widgetTimeline, Seeing the run without waiting: --export-widgetWidget
A sketch as an appollin new --kind mac-app wraps a finished sketch as a .app, signed for this Mac, or with --sign and --notarize for any Mac without the toolchain, with a frame of itself as its iconAn app to hand somebody: signing and notarizingA sketch as an app
The sketch on the phoneollin phone puts a sketch on a paired iPhone or iPad and installs it again on each save, its clock and parameters carried across, with the parameters live on the MacIn your pocket: the sketch on the phoneOnThePhone
The phone as the sketch's screendevice.show(self) keeps the sketch running on the Mac and shows its frames full screen on the capture app, sent down the cable as video, with the first finger on the glass as the sketch's pointer and nothing built for the phoneLeaving it on the Mac: the phone as the sketch's screenPhone
Extensionsextend(_:) registers a SketchExtension that hears about setup and each frame before and after draw(), and can ask for the rendered image, for recorders, overlays, and guidesAdding behavior from outside draw(): SketchExtensionSketch
Writing an extensionollin new --kind extension: a library other sketches import, the ollinx- naming convention, and the four seams to build onGiving it to somebody else: an extension packageExtensions

Chapter 45: Installations

CapabilityWhat it isTaught inReference
Running unattendedInstallation puts a sketch on a wall: full screen, no pointer, the display kept awake, and, with a loop declared, a shader clock that starts over at the end of a lap so it stays exact for weeks (every sketch already treats a gap in the frames as a pause)Leaving it running: Installation, The clock over a long run: gaps and precisionInstallation
Resuming after a stopInstallation(checkpoint:) writes the @Saved properties, the seed, the clock, and every @Param value to a file on a cadence you set, so a relaunch carries on near where the sketch wasPicking up where it left off: checkpoints and @SavedInstallation
RestartingInstallation(restarts: .onFailure) starts the sketch again after a crash or a stallWhen it falls over: restartingInstallation
Opening hoursInstallation(schedule:) with .open(from:to:), or parts of the day named with .from(_:_:) and read back as scheduledPeriod, with .dark(from:) for the hours with nothing on screenGallery hours: the scheduleInstallation
DMX lightingLights driven from draw() over Art-Net or sACN: a 512-channel universe filled through the fixtures you patch with DMXFixture and sent each frame, and a lighting console driving the sketch backLight instead of pixels: DMX and LED maps, A console that drives the sketch: DMXReceiverDMX
LED mapsLEDMap lays strips and matrices of LEDs over the canvas and sends each frame's pixels under them out as DMXLight instead of pixels: DMX and LED mapsDMX
Show lasersLaserProjector sends line work to a show laser through an Ether Dream: points spaced evenly, held at corners, the beam dark between shapes, and no light until arm()Drawing with light: a show laserLaser
Fitting a projectorCorner pinning with Command-K fits the picture to a wall, and Installation.Projection blends the edges where two projectors overlapFitting a projector: corner pinning, Two projectors, one picture: edge blendingInstallation
Several displaysInstallation(displays: .spanning) spreads one canvas over several displaysSeveral displays, one machine: .spanningInstallation
Several windows, one worldcanvasOnScreen tells each window where its canvas sits in the space all the screens share, so several windows show one worldSeveral windows, one world: canvasOnScreenInstallation
RoomSeveral machines drawing one sketch: they find each other by a name with no server, share values and @Param parameters, agree on one clock so motion stays in step, and take a seat each across a wallSeveral machines, one sketch: RoomRoom
Remote surfaceRemoteInspector serves the sketch's @Param parameters to a phone on the same Wi-Fi as touch controls, live both ways, for tuning an installation from in front of itTuning it from the floor: RemoteInspectorRemote
MQTTThe message bus a building speaks: a house's sensors subscribed to and read in draw() or bound to a parameter, lamps and machines published back to, retained values, a last will for when the sketch is cut off, and a connection that resubscribes and resends on its ownWhat the building already says: MQTTMQTT

Contents · Previous: Appendix C, Coming from p5.js and Processing · Next: Appendix E, Coming from openFrameworks and OPENRNDR

↑↓ move ↩ open