# Writing a driftype piece

driftype draws type as a signed distance field on the GPU: a phrase is one
continuous surface, and a shader you write decides every pixel from it. A
piece is a small JSON file: one or more phrases that cross into each other,
the WGSL (WebGPU's shading language) that shades them, and the pipeline of
render and compute passes that runs it. The lab, https://driftype.com/lab, opens, plays,
edits and exports pieces.

This file is the lab's reference panel as plain text, for anyone (a person or
an AI) writing a piece without the lab open. Read it in order: the piece's
JSON, the pipeline as JSON, then shade(p), view, the prelude, passes, the
scene's light and layers, the engine's fixed clock and its warp and light
grids, the limits, the lab and the page around a piece, and five whole pieces
to start from.

To hand a piece to someone:

1. Give them the JSON to save as `<name>.lab.json`.
2. They open it in the lab by dropping the file on the page, or with
   **open a file…**.
3. It opens paused: its shader has not run on their computer, and a shader
   that never ends can freeze a browser, so nothing of it runs until they
   press **run** (in the bar at the top, beside **open a file…**).
4. A piece the lab will not open, or one that does not build once run, shows
   the problem with a **copy for your AI** button: it copies the problem and
   the piece, to give back to whoever wrote it.

## A piece: the JSON

A piece the lab opens is one JSON object. Every field is below, marked
required or optional, with what leaving it out means. The lab is strict about
the shape: it refuses a piece with a field it does not know, at any level (the
piece, a phrase, `type`, `inputs`, the pipeline), or a known field of the
wrong shape, and says which field. A typo, `input` for `inputs`, would
otherwise turn something off without a word.

- `format` (required): `"driftype-lab/6"`. A file without it is not read
  as a piece.
- `id` (optional, default `null`): the piece's title, one line of at most
  80 characters, or `null` (untitled: the first phrase stands in).
- `about` (optional): a few plain sentences on what the piece is and how
  to play with it (move the pointer, press), at most 600 characters,
  no markup. Say it here, not in a comment at the top of the WGSL: the WGSL
  starts with code, and its comments explain how it works. The lab shows it
  above the code; the gallery's pages and an exported page do not, though
  anyone who opens a published piece in the lab can read it.
- `sequence` (required): the phrases, in order, at least one and at most
  64: `[{ "text": "CALM", "hold": 2, "transition": 1, "font": 0 }, ...]`,
  each phrase with these fields and no others. `text` (required) is one
  line, no line breaks, at most 200 characters (4000 in all the
  phrases together). The phrase is held `hold` seconds (required), then
  crosses into the next over `transition` seconds (required; 0 is a cut).
  `font` (optional, default 0) is an index into `fonts`. The shader draws
  each cross: `view.transition`, `view.from_item`, `view.to_item`, and
  `field_from` / `field_to` (below).
- `loop` (optional, default `false`): `true` to cross from the last
  phrase back into the first; `false` holds the last once reached.
- `type` (required): `{ "em_per_height": 0.45, "overflow": "fit_width" }`,
  both fields required. em_per_height is one em (the font's size) as a
  fraction of the canvas's height (with `aspect`, the letterboxed
  canvas's), above 0 and at most 10; overflow is
  `"clip"` or `"fit_width"`, what a phrase wider than the canvas does (fit_width
  shrinks the type until the widest phrase fits 85% of the width).
- `inputs` (required): `{ "pointer": false }`. `true` hands the shader
  the viewer's pointer (`view.pointer`, `view.pointer_down`, …); with
  `false` `view.pointer` stays at the canvas's centre, never pressed.
- `aspect` (optional, default: fill the frame): `[16, 9]`, the canvas's
  shape, letterboxed wherever the piece plays; two numbers above 0, width
  over height between 0.1 and 10.
- `reach` (optional, default 0.1875): how far each glyph's distance field is
  exact past its outline, in em, 0.1875 to 1. `field()` goes on past it
  anyway, close to exact (`field` below), so leave it out unless an effect
  needs the exact distance further from the letters. Each glyph's box grows by
  the reach on every side, so its memory grows with about the square: at 0.5
  about 2.5 times the default's, at 1 about 5 to 7 times ("Settings" below).
- `settings` (optional): knobs a visitor turns while the piece plays,
  shown as a panel wherever it plays (the lab, under an exported page's
  piece, the page that made it): `[{ "id": "speed", "label": "speed",
  "kind": "range", "min": 0, "max": 3, "step": 0.1, "default": 1 }, ...]`,
  at most 8. `kind` is `"range"` (min, max, step optional),
  `"toggle"` (default true or false) or `"choice"` (`"options": [{
  "value": "sea", "label": "sea" }, ...]`, two or more, the default one of
  the values). The shader reads them from the piece's own uniform
  `settings`, which the page writes: in the pipeline, `"settings": {
  "kind": "uniform", "host": true, "members": ["v: array<vec4f, 1>"] }`
  (1 holds four settings, 2 eight), in the reads of each pass that reads
  it. Setting i, in this list's order, is `settings.v[i / 4][i % 4]`
  (the first `settings.v[0].x`): a range its number, a toggle 0.0 or
  1.0, a choice its option's index. Leave the uniform's `value` out (the
  defaults are written into it), or make it the defaults.
- `presets` (optional, with settings): named sets of their values, a
  button each above them: `[{ "id": "calm", "label": "calm", "values": {
  "speed": 0.3 } }, ...]`; a setting a preset leaves out goes to its
  default.
- `fonts` (optional, default `["Anton"]`): the fonts by family, in
  order: `["Anton"]`, or any family on Fontsource
  (https://fontsource.org: the Google Fonts catalogue and more, open
  licences only), written as Fontsource lists it: `["EB Garamond"]`,
  `["Inter", "Anton"]`. Each item names one by index (`"font": 0`; no
  `font` is 0); the first sets the line. The lab reads the outlines it
  needs from the font when it opens the piece (Anton from its own file, any
  other family fetched from Fontsource then), and keeps them in the piece
  from then on (a piece the lab saved holds embedded font blocks here,
  `{ "mode": "embedded", "family": "Anton", "glyphs": "…", "metrics": {…} }`;
  don't write those by hand).

  Weights and styles: a family's name alone is its regular (weight 400,
  normal style). For another, write an object:
  `{ "family": "Inter", "weight": 700, "style": "italic" }` (weight a CSS
  weight, 1 to 1000, 400 regular and 700 bold, though Fontsource's files come
  in hundreds, 100 to 900; style `"normal"` or `"italic"`; either may be
  left out). Never `"Inter 700"` or `"Inter Bold"`: a family's
  name is only its name, and some end in digits (`"Jersey 10"`). A weight
  the family lacks becomes the nearest it has (CSS's rule), a style it lacks
  the other, and the lab says which it took. Two weights or styles of one
  family are two fonts: `["Inter", { "family": "Inter", "weight": 700 }]`.

  Scripts: Fontsource splits each family into files by script (latin,
  latin-ext, cyrillic, greek, vietnamese, …), and a font with many
  characters (a Chinese, Japanese, Korean or emoji font: Noto Sans JP has
  about 120, Noto Emoji 11) into numbered slices of a few hundred
  characters each. The lab fetches only the files the phrases set in a
  font need ("ŁÓDŹ" takes latin and latin-ext; "東京" two slices of Noto
  Sans JP), and later only the files new letters need. A character none of
  the family's files has (Japanese in Roboto) is left out and said: set it
  in a family that has the script (fontsource.org lists each family's
  subsets: Noto Sans JP, SC, TC and KR for Chinese, Japanese and Korean).
  A family with no latin letters (Noto Emoji) is taken too, for the scripts
  it has. A joined script's letters are still separate glyphs, each laid at
  the last one's advance: they connect only where the font's own shapes
  overlap. A family Fontsource
  does not have, or one not under an open licence, is refused when the lab
  opens the piece, saying so; check the spelling on fontsource.org. System
  and commercial fonts are not on Fontsource: Arimo for Arial, Inter for
  Helvetica, Tinos for Times New Roman, Cousine for Courier New, Gelasio for
  Georgia. These lookalikes are approximate, matched to the regular weights
  (Arimo stops at 700, and is no Arial Black). An icon font is named by its
  family as any other (`"Material Icons"`, `"Material Symbols Outlined"`),
  its icons written as codepoints (U+E838 as the character itself), which
  draw; a ligature name (`"star"`) draws its letters, or nothing.
  Names ignore case and spaces at either end (`"anton"` is the
  site's own Anton, which is never fetched). A font no phrase is set in is
  left out, never fetched; a piece names at most 8 fonts to fetch. A
  character the font lacks is left out.

  Overlapping shapes: a font whose letters are built from overlapping
  shapes (Roboto's H, a handwriting family's ç) draws them whole, like any
  other, and inside the ink `field()` is the distance to the letter's own
  outline: the edges buried where its shapes overlap are not edges, so
  bands or outlines drawn inside the letters (`abs(d) < w`) follow the
  letter, not the shapes it was built from. One limit, in every font: a
  notch narrower than the baked field's texel, about 1/64 em (the tip of
  A's counter, where an accent meets its letter), reads as ink.

  Size: a piece the gallery takes is at most 512,000 bytes, outlines
  included. That is roughly 800 distinct characters of a plain face (Inter,
  Roboto) and about 160 of a rough-cut one (IM Fell English): real phrases
  stay far below it, a whole alphabet of a detailed face may not. CJK
  costs more: about 530 kanji of Dela Gothic One fit, about 155 of Zen Old
  Mincho. A font's outlines are kept for the characters its phrases use
  when the piece is saved, kept, exported or published, and the lab says
  when a piece passes the gallery's size. Write text in precomposed characters
  (Unicode NFC, `É` as one character): a combining mark is placed after
  its letter, not on it. A font that is on no catalogue (the person's own
  file) cannot be named: write the piece in another and tell the person how
  to change the font in the lab (see "The phrase and its font" below).
- `code` (required, in a piece written now): the shader code as code units, an object
  from a unit's name to `{ "uses": [...], "wgsl": "…" }`. Each pass of the
  pipeline names the unit it runs (`"code": "draw"`), and several passes may
  run one. A unit's `uses` are the engine's capabilities its WGSL calls
  (`[]` for none): `"glyphs"` (`field()`, `field_slope()` and the rest
  of the text's field, the placed glyphs), `"warp_grid"`, `"steps"`,
  `"light_grid"` (reads the light grid), `"light_grid_add"` (lays light,
  a compute pass's unit only) and `"page"` (the page's boxes, the type laid
  into its anchor box); see "Code units and what they use" below. A pass
  gets a capability's names only through its unit's uses, and the engine
  makes a capability's memory only when some unit uses it, so a piece costs
  what it uses. Passes that use different resources run different units,
  because each pass's module declares only the resources that pass reads or
  writes. A unit calling what its uses do not give fails to build at that
  line ("unresolved call target 'field'"), and the lab says which use to add.
- `wgsl` (required): `null` with `code`. An older piece's WGSL, in
  place of `code`: one text every pass runs, or an object from pass name
  to that pass's text. Such a piece is given every capability its pipeline
  configures, used or not.
- `pipeline` (required, with `code`; with `wgsl`, default `null`): the
  passes and resources as the JSON document the engine runs (the next
  section), each pass naming its unit; `null`, for a piece with `wgsl`,
  is the default: one render pass that calls your `shade(p)` for every
  pixel. This is what plays.
- `pipeline_js` (optional): the JavaScript the lab's pipeline pane shows,
  written with the builder documented below, ending `return pipeline({...})`.
  The lab evaluates it on each edit, into `pipeline`, but never runs it to
  open a piece: `pipeline` is what plays, whatever `pipeline_js` says.
  The builder's passes name no unit: in a piece with `code` the lab gives
  each the unit of its own name, and `pipeline` names them.
  So if you write `pipeline_js`, write the `pipeline` it returns too (or
  `null` when it returns the default; the lab saves its default pipeline's
  JavaScript with `"pipeline": null`). Left out, the lab's pane shows the
  pipeline as `return {…}`, or the default's JavaScript when `pipeline` is
  `null`. With one render pass, leave out both. The whole pieces below give
  both.
- `host_js` (optional): the lab's host pane, a script standing in for the
  page around the piece, writing into its `host: true` resources (see
  "host.js: the embedding page's part" below, and the whole piece that ends
  this file). Lab only: an exported page, an export's kit and the gallery's
  pages never run it, so the piece must look right without it. One from a
  file waits for its own **run host**.
- `engine` (optional): written by the lab, the engine build it saved the
  piece with. Leave it out.
- `engine_level` (optional): written by the lab with `engine`, the engine
  level the piece was made at, 1 to 15 (a piece with `engine` and
  no level is level 1). The lab keeps such a piece at its level: its pipeline
  takes only the keys levels 1 to that one brought, until "play at level
  15" raises it; this engine plays every level alike. Leave it out:
  a piece without `engine` is at level 15.

The smallest piece that plays, the required fields alone:

```json
{
  "format": "driftype-lab/6",
  "sequence": [
    {
      "text": "HELLO",
      "hold": 2,
      "transition": 1,
      "font": 0
    }
  ],
  "type": {
    "em_per_height": 0.45,
    "overflow": "fit_width"
  },
  "inputs": {
    "pointer": false
  },
  "wgsl": null,
  "code": {
    "draw": {
      "uses": [
        "glyphs"
      ],
      "wgsl": "fn shade(p: vec2f) -> vec4f {\n    let inside = smoothstep(-0.01, 0.01, field(p, 0.0));\n    return vec4f(vec3f(inside), 1.0);\n}\n"
    }
  },
  "pipeline": {
    "passes": [
      {
        "name": "draw",
        "kind": "render",
        "vertex": "graffito_vs",
        "fragment": "graffito_fs",
        "draw": {
          "vertices": 3
        },
        "code": "draw"
      }
    ]
  }
}
```

## The pipeline as JSON

`pipeline` is one object. The lab's pipeline pane writes it with the builder
(further down); a piece written by hand, or by an AI, gives the JSON itself.
Each field and what the builder call becomes, all from the one pipeline at
the end of this section. Every name below is the field's exact spelling, and
the lab refuses any other field, or a list where an object belongs.

- `version` (optional): `1`. The builder writes it.
- `types` (optional): structs the WGSL uses, by name, each a list of
  `"member: type"` in order: `{"Particle": ["pos: vec2f", "vel: vec2f"]}`.
  `struct({ pos: vec2f, vel: vec2f })` named `Particle` in `types`.
- `constants` (optional): a LIST of `"NAME: type = value"`, a scalar type
  (u32, i32, f32) and a number: `["GRID_W: u32 = 64", "SCALE: f32 = 0.5"]`. Each is a WGSL
  `const` in every pass. Not an object: the builder's `{ GRID_W: u32(64) }`
  is written `["GRID_W: u32 = 64"]`.
- `resources` (optional): an object from name to resource, each with a
  `kind`. The WGSL refers to a resource by its name and never declares it.
  The name is a WGSL global in each pass that reads or writes it (a function
  or constant of yours with the same name is a redeclaration), and a word
  WGSL reserves (`meta`, `patch`, `filter`, `target`, …) is refused.
  - `"storage"`: `array<element>` in a storage buffer. `element` is a
    type: a scalar, vector or matrix (`"f32"`, `"vec4f"`, `"mat4x4f"`),
    a struct from `types` (`"Particle"`), `"array<f32, 4>"`, or
    `"atomic<u32>"` / `"atomic<i32>"` (storage only). Sized by `length`,
    a number or another storage's name (the same length as it), or by
    `init`, a list of element values (numbers, lists for vectors, objects for
    structs; the rest is zero). `{"kind": "storage", "element": "Particle", "length": 4096}`, `{"kind": "storage", "element": "atomic<u32>", "length": 2048}`,
    `{"kind": "storage", "element": "f32", "length": "particles"}`, `{"kind": "storage", "element": "vec4f", "init": [[1, 0.4, 0.2, 1], [0.2, 0.6, 1, 1]]}`. `host: true` lets the page around
    the piece write it while it runs.
  - `"uniform"`: one struct, its `members` a list of `"name: type"`,
    and its `value`, an object with every member (none at all is zeros):
    `{"kind": "uniform", "members": ["speed: f32", "tint: vec3f"], "value": {"speed": 0.5, "tint": [1, 0.5, 0.2]}}`. In WGSL its struct is the name capitalised (`Sim`) and
    the variable the name (`sim.speed`). `host: true` as for storage.
  - `"texture"`: a 2D RGBA8 texture, `size` [width, height] in texels,
    and `init` (optional), a list of [r, g, b, a] texels from 0 to 1, row by
    row: `{"kind": "texture", "size": [1024, 512]}`. Read as `texture_2d<f32>`; a compute pass that
    writes it gets write-only storage. (`image` needs files a piece has not
    got.)
  - `"sampler"`: `filter` `"linear"` (default) or `"nearest"`, and
    `address` `"clamp"` (default), `"repeat"` or `"mirror"`:
    `{"kind": "sampler", "filter": "linear", "address": "clamp"}`.
- `groups` (optional): bind groups, a list of lists of resource names,
  `[["particles", "bins"], ["sim"]]`. Left out, a piece's resources share
  one group; the engine adds two of its own, and WebGPU allows four.
- `canvas` (optional): [width, height], which only defines `CANVAS_SIZE`
  in the WGSL: render passes draw at the canvas's size whether it is given or
  not. Leave it out.
- `passes` (required in a pipeline): a list, run in order every frame, each
  with a `name`, a `kind` and, with `code`, the unit it runs (`"code": "draw"`;
  an older piece's `wgsl` per pass is keyed by the name).
  - `"compute"`: `reads` and `writes` (lists of resource names),
    `entry` (the entry point's name), `workgroup_size` (default `64`; a
    number, or `[x, y]` or `[x, y, z]`, any sizes within WebGPU's
    limits: x and y at most 256, z at most 64, 256 in all), and `dispatch`:
    `{ "over": "<resource>" }` (one invocation per element or texel, along
    x alone: give it a one-number workgroup_size and index by `id.x`) or
    `{ "size": [w, h] }` (by `id.xy`); either may run past the end to fill
    the last workgroup, so return past it. The pass's WGSL has
    `WORKGROUP_SIZE` (x) and `WORKGROUP_SIZE_X`, `_Y`, `_Z` (1 for an
    axis not given) for its `@workgroup_size`:
    `{"name": "clear", "kind": "compute", "writes": ["bins"], "dispatch": {"over": "bins"}, "entry": "clear"}`, `{"name": "step", "kind": "compute", "repeat": 4, "reads": ["sim"], "writes": ["particles", "bins", "heat"], "workgroup_size": [8, 8], "dispatch": {"size": [64, 64]}, "entry": "step"}`.
  - `"render"`: `reads`, `vertex` and `fragment` (entry points;
    `"graffito_vs"` and `"graffito_fs"` call your shade(p)), `draw`:
    `{ "vertices": n, "instances": n or "<storage>" }` (instances, a count
    or a storage's length, default 1), `blend` (`"replace"` default;
    `"alpha"`, straight alpha, so its fragment returns color not multiplied
    by alpha; `"additive"`, color and alpha added as returned), `load` (`"clear"` default, `"keep"` to
    layer over the pass before), `target` (a texture to draw into instead
    of the canvas), `topology` (`"triangle_list"` default,
    `"triangle_strip"`, `"line_list"`, `"point_list"`):
    `{"name": "text", "kind": "render", "vertex": "graffito_vs", "fragment": "text_fs", "draw": {"vertices": 3}, "target": "layer"}`, `{"name": "dots", "kind": "render", "reads": ["particles", "heat"], "vertex": "dot_vs", "fragment": "dot_fs", "draw": {"vertices": 6, "instances": "particles"}, "blend": "additive", "topology": "triangle_list", "load": "keep"}`.
  - Either kind: `once: true` runs it on the first frame only (a seed):
    `{"name": "seed", "kind": "compute", "once": true, "writes": ["particles"], "dispatch": {"over": "particles"}, "entry": "seed"}`; `repeat: n` (1 to 64) runs it n times in a row
    where it stands (see repeat, below).
  - A compute pass with a dispatch, not `once`: `step: {}` (or `{ "hz":
    120, "max": 8 }`, the defaults) runs it once per step of a fixed clock,
    120 steps a second however fast the screen draws (engine level 9; "step:
    a fixed clock" below).
- Beside `passes`, what the pipeline may ask the engine for (engine levels
  6-10; each is explained in its own section below):
  - `seed` (a whole number) and `ranges` (`{ "NAME": [lo, hi] }`,
    each a WGSL constant drawn from the seed): "seed, ranges and
    graffito_range".
  - `light` and `layers` (up to 3 shaped layers and a fill, drawn by the
    render pass whose fragment is `"graffito_layers_fs"`): "The scene".
  - `warp_grid` and `light_grid` (each an object of knobs, `{}` for
    the defaults) and `reduced_motion` (`"own"`, for a piece that calms
    itself): "The engine's clock and grids".

What the builder calls become: `render("draw", {…})` is
`{ "name": "draw", "kind": "render", … }`, a resource object is its name,
`over: trail` is `"dispatch": { "over": "trail" }`, `size: [w, h]` is
`"dispatch": { "size": [w, h] }`, `workgroupSize` is `workgroup_size`.
This pipeline, written with the builder,

```js
const Particle = struct({ pos: vec2f, vel: vec2f });
const particles = storage(Particle, 4096);
const bins = storage(atomic(u32), 64 * 32);
const heat = storage(f32, { length: particles });
const palette = storage(vec4f, [[1, 0.4, 0.2, 1], [0.2, 0.6, 1, 1]]);
const sim = uniform({ speed: f32(0.5), tint: vec3f(1, 0.5, 0.2) });
const layer = texture({ size: [1024, 512] });
const soft = sampler({ filter: "linear", address: "clamp" });
return pipeline({
  types: { Particle },
  constants: { GRID_W: u32(64), SCALE: f32(0.5) },
  resources: { particles, bins, heat, palette, sim, layer, soft },
  passes: [
    compute("seed", { writes: [particles], over: particles, entry: "seed", once: true }),
    compute("clear", { writes: [bins], over: bins, entry: "clear" }),
    compute("step", { reads: [sim], writes: [particles, bins, heat], size: [64, 64], workgroupSize: [8, 8], entry: "step", repeat: 4 }),
    render("text", { target: layer, vertex: "graffito_vs", fragment: "text_fs", draw: { vertices: 3 } }),
    render("show", { reads: [layer, soft, bins, palette], vertex: "graffito_vs", fragment: "show_fs", draw: { vertices: 3 } }),
    render("dots", { reads: [particles, heat], vertex: "dot_vs", fragment: "dot_fs",
      draw: { vertices: 6, instances: particles }, blend: "additive", load: "keep", topology: "triangle_list" }),
  ],
});
```

is this JSON:

```json
{
  "version": 1,
  "types": {
    "Particle": ["pos: vec2f", "vel: vec2f"]
  },
  "constants": ["GRID_W: u32 = 64", "SCALE: f32 = 0.5"],
  "resources": {
    "particles": {
      "kind": "storage",
      "element": "Particle",
      "length": 4096
    },
    "bins": {
      "kind": "storage",
      "element": "atomic<u32>",
      "length": 2048
    },
    "heat": {
      "kind": "storage",
      "element": "f32",
      "length": "particles"
    },
    "palette": {
      "kind": "storage",
      "element": "vec4f",
      "init": [
        [1, 0.4, 0.2, 1],
        [0.2, 0.6, 1, 1]
      ]
    },
    "sim": {
      "kind": "uniform",
      "members": ["speed: f32", "tint: vec3f"],
      "value": {
        "speed": 0.5,
        "tint": [1, 0.5, 0.2]
      }
    },
    "layer": {
      "kind": "texture",
      "size": [1024, 512]
    },
    "soft": {
      "kind": "sampler",
      "filter": "linear",
      "address": "clamp"
    }
  },
  "passes": [
    {
      "name": "seed",
      "kind": "compute",
      "once": true,
      "writes": ["particles"],
      "dispatch": {
        "over": "particles"
      },
      "entry": "seed"
    },
    {
      "name": "clear",
      "kind": "compute",
      "writes": ["bins"],
      "dispatch": {
        "over": "bins"
      },
      "entry": "clear"
    },
    {
      "name": "step",
      "kind": "compute",
      "repeat": 4,
      "reads": ["sim"],
      "writes": ["particles", "bins", "heat"],
      "workgroup_size": [8, 8],
      "dispatch": {
        "size": [64, 64]
      },
      "entry": "step"
    },
    {
      "name": "text",
      "kind": "render",
      "vertex": "graffito_vs",
      "fragment": "text_fs",
      "draw": {
        "vertices": 3
      },
      "target": "layer"
    },
    {
      "name": "show",
      "kind": "render",
      "reads": ["layer", "soft", "bins", "palette"],
      "vertex": "graffito_vs",
      "fragment": "show_fs",
      "draw": {
        "vertices": 3
      }
    },
    {
      "name": "dots",
      "kind": "render",
      "reads": ["particles", "heat"],
      "vertex": "dot_vs",
      "fragment": "dot_fs",
      "draw": {
        "vertices": 6,
        "instances": "particles"
      },
      "blend": "additive",
      "topology": "triangle_list",
      "load": "keep"
    }
  ]
}
```

## Drawing: shade(p) and the field

### The WGSL pane: shade(p) (`wgsl-pane`)

The shader code, in WGSL, WebGPU's shading language, after the engine's prelude. A piece's code is its code units, a file each, named for the unit (draw.wgsl), with what the unit uses above it (Code units and what they use); a piece made before them has one file, shade.wgsl, or one a pass, named for the pass. Define shade(p: vec2f) -> vec4f: the prelude's fragment stage graffito_fs calls it for each pixel, with p the pixel's point in em (baseline y = 0, one em is the font's size). field(p, k) is the phrase's signed distance in em, positive inside, fused over k; view.time is seconds, view.px_per_em the scale. To light it (a bevel, a highlight, glass), take the slope from field_slope(p, k), whose yz is field()'s gradient, smooth everywhere; dpdx and dpdy of field() step every 2x2 pixels and every sample of a glyph (1/64 em), which a sharp highlight on large type shows as stairs. No name of yours may be a word WGSL reserves, and it reserves many plain ones besides its keywords: active, meta, mod, smooth, filter, target, type, set, get, from, pass, shared, … (a build that uses one says which). What it returns is written to the canvas as it is: no color conversion and no tone mapping, each channel clamped to 0..1 and stored in 8 bits, and shown as sRGB (0.5 lands as 128 of 255), so mix() blends sRGB values, not light. Alpha below 1 lets the page behind show through; return color already multiplied by alpha, vec4f(rgb * a, a). Hack at your own risk: a shader that runs too long makes the GPU reset, which can blank other tabs and apps for a moment. The lab then opens your code paused. What the lab allows: What a piece costs.

Names: `shade`

```
fn shade(p: vec2f) -> vec4f {
    return select(vec4f(0.0, 0.0, 0.0, 1.0), vec4f(1.0), field(p, 0.0) > 0.0);
}
```

WGSL spec (W3C): https://www.w3.org/TR/WGSL/

### Code units and what they use (`code-units`)

A piece's WGSL is its code units: each a file of WGSL and the list of what it uses, the boxes above its text. Each pass runs one unit (its code key in the pipeline), and several passes may run one. What a unit uses are the engine's capabilities its WGSL calls, and a pass gets their functions only through its unit's uses: the engine makes a capability's memory only when some unit uses it, so a piece costs what it uses. view and the prelude's helpers that read only view are every unit's. glyphs: field, field_from, field_to, field_cross, field_cross_from, field_cross_to, field_slope, field_slope_from, field_slope_to, graffito_field, graffito_placed_distance, graffito_distance, graffito_texel, graffito_atlas, graffito_glyphs, graffito_placed. warp_grid: graffito_warp_grid, graffito_warp_grid_jacobian, graffito_warp. steps: graffito_restart, graffito_steps, graffito_step_time, graffito_step. light_grid: graffito_light, graffito_light_slope, graffito_light_cell, graffito_light_FADE, graffito_light_FADES, graffito_light_grid, graffito_light_layout. light_grid_add: graffito_light_add, graffito_light_line. page: page_join, page_join_slope, graffito_page. glyph_direction: field_direction, field_direction_from, field_direction_to, graffito_distance_direction, graffito_placed_distance_direction, graffito_direction_texel, graffito_atlas_direction. glyph_index: graffito_no_index, graffito_index_texel, graffito_distance_index, graffito_placed_index, graffito_field_index, graffito_atlas_index. glyph_outline: field_exact, field_exact_from, field_exact_to, field_exact_smooth, field_exact_smooth_from, field_exact_smooth_to, graffito_distance_exact, graffito_placed_distance_exact, graffito_outline. glyphs is the text: a unit that draws or measures the letters uses it, and one that needs none (a ground, a simulation, light) leaves it out; with no unit using it the engine makes no glyph memory at all. warp_grid and light_grid need their keys in the pipeline, steps a pass that steps, light_grid_add a compute pass (a render pass reads the light with light_grid). A unit that calls what it does not use fails to build at that line ("unresolved call target 'field'"), and the lab says which use to tick. A piece made before code units has none: its WGSL is given everything its pipeline configures, and it plays, edits and exports as it always did.

Names: `code`, `unit`, `uses`, `capability`, `capabilities`, `glyphs`, `warp_grid`, `steps`, `light_grid`, `light_grid_add`, `page`, `glyph_direction`, `glyph_index`, `glyph_outline`, `unresolved`

### graffito_vs and graffito_fs (`vs-fs`)

The prelude's full-screen render stages: graffito_vs draws one triangle over the target (draw 3 vertices), graffito_fs calls shade(p), and graffito_layers_fs draws the pipeline's layers (layers, below). A render pass that names them as its vertex and fragment gets them; stages of its own can have any other name.

Names: `graffito_vs`, `graffito_fs`

### field(p, k), field_from, field_to (`field`)

The text's signed distance at em point p, in em: positive inside. Letters are unioned smoothly over k em; k = 0 is a plain union. smooth_max(a, b, k) is that union for two distances. In a sequence, field_from(p, k) is the phrase being left and field_to(p, k) the one being entered (the same phrase while it holds); field mixes them linearly by view.transition. Write your own crossing from the two. The distance is exact within each glyph's reach of an outline (about a fifth of an em: 0.19 em at 64 texels an em), and goes on past that with no flat edge, within about 0.016 em of the exact distance out to 2 em (where two parts of the text are as near, the crease is read slightly rounded), so a glow, contour rings or a ground gradient fade all the way out. Beside a long thin glyph (a long bar, a wide bracket) it can read up to about 0.1 em nearer than exact: don't count on the exact distance far from one. Inside the ink it is not clamped: it grows to half the stroke's width. Where a letter is built from shapes that overlap (an accented letter whose cedilla or ogonek is drawn into the base letter, Anton's Ç, Ę or Ǫ; Roboto's H), the edges buried in the ink are not edges: inside, the distance is to the letter's own outline, so an outline, band or bevel drawn from it follows the letter, not the shapes it was built from. A notch narrower than one texel of the baked field, about 1/64 em (the tip of A's counter, where an accent meets its letter), reads as ink.

Names: `field`, `smooth_max`, `field_from`, `field_to`

```
let t = smoothstep(0.0, 1.0, view.transition);   // eased
let d = mix(field_from(p, 0.05), field_to(p, 0.05), t);
```

### Where the phrase sits (`placement`)

Each phrase is one line on the baseline, y = 0, starting at x = 0, each centred by its advances within the widest. The canvas's centre is the middle of the widest phrase's advances across (one under 1 em wide is taken as 1 em, so it starts half an em left of centre), and up, the middle of the first font's line, ascender to descender. For Anton (ascender 1.176 em, descender -0.329, cap height 0.859) that is y = 0.424 em, so its capitals sit nearly centred: at em per height 0.5 the baseline is 0.288 of the canvas's height up from its bottom and the cap tops 0.717 (measured). One em is em per height × the canvas's height in pixels, unless overflow fit_width shrinks it until the widest phrase's ink fits 85% of the width. The canvas's own bounds come from view, as below.

Names: `baseline`, `centre`, `center`, `origin`, `bounds`, `cap height`, `ascender`, `uv`

```
let size = view.resolution / view.px_per_em;               // the canvas in em
let lo = view.origin - vec2f(0.0, size.y);                    // its bottom left (y is up)
let centre = lo + size * 0.5;
let uv = (p - lo) / size;                                     // 0..1 across it, y up
```

### Added to a pass (`added`)

view is in every pass's reads without being listed or declared. graffito_atlas, graffito_glyphs and graffito_placed are added to a pass whose code unit uses glyphs, and each other capability's resources to a pass whose unit uses it (graffito_page for page; the step's only to a stepped one; see code units); in a piece without code units, every pass gets the glyphs' and those of each capability its pipeline configures. The names view and graffito_* are reserved for them.

Names: `view`, `graffito_atlas`, `graffito_glyphs`, `graffito_placed`

### field_slope(p, k), field_slope_from, field_slope_to (`field-slope`)

field() and its slope, for lit surfaces (engine level 4): a vec3f, x the distance and yz its gradient in em per em, about unit length near an outline and pointing inward. Each glyph's samples are read through a quadratic B-spline, so the slope is continuous everywhere, and x is within 0.005 em of field()'s (fill with field(), light with this). It joins the page's shapes and crosses phrases as field() does; field_slope_from and field_slope_to are field_from's and field_to's. It covers the glyphs where the page placed them: a glyph drawn somewhere else (graffito_placed_distance(i, p - offset)) has no public slope, so take differences of that distance (continuous only to its 1/64 em sample). Light a bevel, a highlight, wet or glass surfaces from it, not from dpdx and dpdy of field(): those are flat across each 2x2 block of pixels and across each sample of a glyph (1/64 em), and a sharp highlight shows both as stair steps once the type is large (full-window, a sample is 7 px or more; at 800x400, 3 or 4, where they hide). A height h(d) has slope h'(d) times yz. Through a warp, with q the warped point and s = field_slope(q, k).yz, the slope in p is vec2f(dot(s, dpdx(q)), -dot(s, dpdy(q))) * view.px_per_em: q is smooth from pixel to pixel, so its own derivatives are fine. smooth_max_slope(a, b, k) and round_box_slope(p, center, half, radius) are smooth_max and round_box with slopes, for shapes of your own. It costs more than one field() call (9 samples a glyph to 4), far less than four.

Names: `field_slope`, `field_slope_from`, `field_slope_to`, `smooth_max_slope`, `round_box_slope`, `slope`, `normal`, `gradient`, `bevel`, `highlight`, `light`

```
let q = p + 0.02 * vec2f(sin(p.y * 9.0), sin(p.x * 7.0));   // a warp
let f = field_slope(q, 0.03);                                // f.x the distance, f.yz its slope in q
let depth = clamp(f.x / 0.13, 0.0, 1.0);                     // a rounded bevel 0.13 em deep
let dh = select(0.0, 2.0 * (1.0 - depth) / 0.13, f.x > 0.0 && f.x < 0.13);
let slope = dh * vec2f(dot(f.yz, dpdx(q)), -dot(f.yz, dpdy(q))) * view.px_per_em;   // in p
let n = normalize(vec3f(-slope * 0.06, 1.0));
```

### field_direction(p, k), field_direction_from, field_direction_to (`field-direction`)

A code unit that uses glyph_direction (engine level 15; it brings glyphs): x is field(p, k), the same bits, and yz the unit inward direction to the closest point of the outline, which the glyph bake keeps for each sample beside its distance. The four samples round p are mixed and normalized, so the direction is smooth except where the closest point jumps (a stroke's middle, a corner's inside): there it turns within one sample (1/64 em), and its crease follows the samples' grid. Where the mix cancels, as midway across a thin stroke, yz is (0, 0): handle that before dividing by it. Past a glyph's box, the far record's slope. The page's shapes join and phrases cross as for field(). graffito_distance_direction(slot, p) is one glyph's in its own em, graffito_placed_distance_direction(i, p) a placed glyph's in page em, graffito_direction_texel(slot, x, y) one stored sample. The engine bakes the directions only where a unit uses glyph_direction: 16 MiB more in the lab, about 5% more bake, and one more storage buffer in the pass. For a crease placed exactly, use field_exact.

Names: `field_direction`, `field_direction_from`, `field_direction_to`, `graffito_distance_direction`, `graffito_placed_distance_direction`, `graffito_direction_texel`, `glyph_direction`, `direction`

```
let f = field_direction(p, 0.0);              // f.x field(p, 0.0), f.yz a unit direction inward
let n = normalize(vec3f(-f.yz * 0.8, 1.0));       // a facet turned toward the outline
let lit = max(dot(n, normalize(vec3f(-0.4, 0.5, 0.75))), 0.0);
```

### field_exact(p, k), field_exact_smooth(p, k, width) and their _from, _to (`field-exact`)

A code unit that uses glyph_outline (engine level 15; it brings glyph_index and glyphs): the distance from the outline itself, not from its samples. x is the signed distance (positive inside) and yz the unit inward direction. Both come from the outline's pieces that the four samples round p name, each evaluated at p, the closest kept, so a crease (a stroke's middle, a corner's inside) is where the outline puts it, to the pixel. On a crease the direction is one side's (the same every time). field_exact_smooth(p, k, width) mixes it with the other side's in a band width em wide centred on the ridge, half and half on it, x unchanged; width 0 gives field_exact's numbers. Past a glyph's box, the far record's. The page's shapes join and phrases cross as for field(). graffito_distance_exact(slot, p) and graffito_placed_distance_exact(i, p) are one glyph's, as for field_direction. The engine keeps the outlines only where a unit uses glyph_outline: about 18 MiB in the lab, the outline table's 2 MiB (Anton's a-zA-Z take 42 KB) and the 16 MiB index it brings, and two more storage buffers in the pass (the outline and the index). Each point evaluates up to four pieces of the outline; _smooth looks for the other side within width as well.

Names: `field_exact`, `field_exact_from`, `field_exact_to`, `field_exact_smooth`, `field_exact_smooth_from`, `field_exact_smooth_to`, `graffito_distance_exact`, `graffito_placed_distance_exact`, `glyph_outline`, `exact`, `ridge`

```
let f = field_exact_smooth(p, 0.0, 0.01);       // x the distance, yz inward, its ridge eased over 0.01 em
let chisel = f.x > 0.0 && f.x < 0.1;                // a chisel 0.1 em deep, its ridge along each stroke's middle
let n = normalize(vec3f(select(vec2f(0.0), -f.yz, chisel), 0.6));
```

### graffito_field_index(p, begin, end) and the index readers (`field-index`)

A code unit that uses glyph_index (engine level 15; it brings glyphs): which piece of the outline is closest. An index is contour << 16 | segment of the outline as the font decodes it, so index >> 16 is the contour (a letter's hole is a contour of its own) and index & 0xffff the piece along it. graffito_field_index(p, begin, end) takes the placed glyphs [begin, end) (field_from's are [0, view.from_glyphs)) and gives, in x, the one with the largest distance at p and, in y, its index. Both are graffito_no_index where none is ready. An index is never mixed: it is the nearest sample's, so its edges step every 1/64 em. graffito_distance_index(slot, p), graffito_placed_index(i, p) and graffito_index_texel(slot, x, y) read one glyph's; each is graffito_no_index past its box and before it is baked. 16 MiB more in the lab and one more storage buffer in the pass.

Names: `graffito_field_index`, `graffito_no_index`, `graffito_index_texel`, `graffito_distance_index`, `graffito_placed_index`, `glyph_index`, `index`, `segment`, `contour`

```
let ix = graffito_field_index(p, 0u, view.from_glyphs);
let hue = select(0.0, f32((ix.y >> 16u) % 5u) / 5.0, ix.y != graffito_no_index);   // a tint a contour
```

### field_cross(p, k), field_cross_from, field_cross_to (`field-cross`)

The same numbers as field(), field_from and field_to: each glyph's distance goes on past its reach with no floor, so there is nothing to ease. Kept for pieces that use them.

Names: `field_cross`, `field_cross_from`, `field_cross_to`, `reach`, `bevel`, `crease`

```
let e = 0.002;
let d = field_cross(p, 0.0);
let n = normalize(vec2f(field_cross(p + vec2f(e, 0.0), 0.0) - d, field_cross(p + vec2f(0.0, e), 0.0) - d) + 1e-6);
```

### round_box, page_box, view_frame (`boxes`)

Boxes as signed distances in em, positive inside as field() is, so they join the text with max (a plain union) or smooth_max (melted together). Exact everywhere: unlike field(), they have no reach, so a ring or melt around one goes as far as asked. round_box(p, center, half, radius) is the box centred on center, half its size in half, its corners rounded by radius (at most the shorter half). page_box(p, rect, radius) is a box on the page: rect is x, y, width, height in CSS px from the viewport's top left (getBoundingClientRect), radius in CSS px. view_frame(p, inset, radius) is the canvas itself, shrunk by inset em on every side, its corners rounded by radius: 0 on that frame, positive inside the view. With an aspect, the view is the canvas, not the frame shown around it. -view_frame(...) is the wall outside it, which letters can melt into, as below.

Names: `round_box`, `page_box`, `view_frame`, `box`, `rounded`, `frame`, `edge`, `border`

```
let d = field(p, 0.03);
let wall = -view_frame(p, 0.05, 0.1);           // the canvas's edge, 0.05 em in
let melted = smooth_max(d, wall, 0.15);         // letters run into the edge
let card = round_box(p, vec2f(0.0, 0.3), vec2f(0.6, 0.2), 0.08);
```

## view: time, the sequence, the pointer

### view (`view`)

The engine's uniform, written every frame; its WGSL struct is below. Compare the u32 members as integers (view.pointer_down != 0u, not > 0.5). origin: the em point at the canvas's top left. resolution: the canvas in pixels (with an aspect, the letterboxed canvas, not the frame around it). The canvas spans x from origin.x to origin.x + resolution.x / px_per_em, and y from origin.y - resolution.y / px_per_em at its bottom up to origin.y at its top: y goes up, pixel rows down. px_per_em: pixels per em. time: seconds, the piece's one clock: the sum of every frame's time_slice since the restart. Nothing else moves it and it never jumps. It does not wrap when the sequence loops; the pointer's times and the phrases are on the same clock. It stands still while paused and while the page is hidden (another tab in front, a minimised window), and carries on from there. transition: 0..1 across the sequence's current transition, uneased, 0 while a phrase holds. from_item, to_item: the indices of the phrases being left and entered, equal while holding; vary the look per phrase with them. from_glyphs: where field_from's glyphs end (the engine's). pointer: the pointer, in em where p is (distance(p, view.pointer) is how far a pixel is from it). With the piece's "pointer" setting off it is always the canvas's centre (pointer_down 0, the times -1); on, the canvas's centre until the pointer first moves over it. pointer_down: 1 while it is pressed. One pointer at a time, and a press starts only on the canvas (The pointer, touch, keys and reduced motion). canvas_rect: the canvas on the page, x, y, width and height in CSS px from the viewport's top left (where a page measures its own elements). px_per_css: canvas pixels per CSS px: the device's pixel ratio, capped at 2 (a 3× phone draws at 2×, and this is 2); a fullwindow <graffito-piece> caps it at 1. pointer_down_time, pointer_up_time: view.time when it was last pressed and last let go (the frame that first sees it), -1 before the first: hold a mark while pressed, fade one after (view.time - view.pointer_up_time). pointer_inside: 1 while the pointer is over the canvas (a finger: while it touches), 0 before it first moves and once it leaves, where view.pointer stays parked. seek: always 0: the time never jumps, and the lab has no scrubbing. pointer_down_pos, pointer_up_pos: where the pointer was at the last press and the last let-go, in em as view.pointer is, so a mark stays where it was made; the canvas's centre before the first (the times' -1 says never). pointer_enter_time, pointer_leave_time: view.time when pointer_inside last went to 1 and to 0, -1 before the first: fade in on arriving and out on leaving. pointer_presence_from, pointer_press_from (engine level 13): graffito_presence() at the last arrival or leave, and graffito_press() at the last press or let-go: where each eases on from, so a quick flip goes on from where it was. 0 before the first and on a restart. pointer_pressure (engine level 14): how hard the pointer presses, 0..1: a pen's own pressure; 1 for a mouse, a finger and a pen that reports none (the web's 0.5 for a press without pressure never reaches view). It is not eased: graffito_press() * view.pointer_pressure eases in on a press and out after it. After a let-go it keeps the last press's; 0 before the first press since the restart; reduced motion leaves it as it is. time_slice: the seconds this frame adds to view.time: the seconds since the last frame drawn, at most 0.1, and a tenth of that under reduced motion. The same for every pass and the host script's onFrame. 0 while paused and on a restart (a build's first frame, the restart button). A hidden page's first frame back is a frame on from its last, and a frame stalled past 0.1 leaves the piece behind the wall clock, which nothing reads. Other engines call it dt or delta; view has no member of either name. A piece with state marks its passes "step" and moves by view.step_dt instead (engine level 9), the same at any frame rate. frame_count: frames drawn since the restart, 0 on the first. A new build starts it again, with the piece's resources, and so does the restart button; a pause does not: frames run on while paused. item_elapsed_time: seconds since the phrase being entered (to_item) began arriving, from the start of the cross into it (a cut, or phrase 0 before the sequence has looped: from when it appeared). It holds with view.time. The last phrase of a sequence that does not loop holds for good, so this runs past its hold. item_hold_time: that phrase's hold, in seconds. item_transition_time: the length of the cross into it, 0 for a cut and for phrase 0 on the sequence's first pass (during the cross from the last phrase back into phrase 0 it is that cross's length). loop_count: how many times a looping sequence has wrapped (onFrame's loop), 0 if it does not loop. It goes up when phrase 0 arrives, at the end of that cross, not as the cross begins. reduced_motion: 1 while the viewer asks for reduced motion (prefers-reduced-motion: reduce, followed live). The engine then slows the piece's clock to 1/10 and the pointer's answers appear at once, at every engine level; a piece saying "reduced_motion": "own" (engine level 9) calms itself. pointer_type: the last pointer's kind, 0 a mouse, 1 a touch, 2 a pen. Also 0 before any pointer, so 0 alone does not say a mouse: view.pointer_enter_time < 0 is "no pointer yet". The first frame: view.time 0 and view.frame_count 0, in the lab, an exported page, <graffito-piece> and the MCP tools alike. Set up state when graffito_restart() is true in a "step" pass (engine level 9), or on view.frame_count == 0u, not on time being 0: a paused piece stays there.

Names: `view`, `origin`, `resolution`, `px_per_em`, `time`, `transition`, `from_item`, `to_item`, `from_glyphs`, `pointer`, `pointer_down`, `canvas_rect`, `px_per_css`, `pointer_down_time`, `pointer_up_time`, `pointer_inside`, `seek`, `pointer_down_pos`, `pointer_up_pos`, `pointer_enter_time`, `pointer_leave_time`, `time_slice`, `frame_count`, `item_elapsed_time`, `item_hold_time`, `item_transition_time`, `loop_count`, `reduced_motion`, `pointer_type`, `dt`, `delta`, `step_dt`, `step_count`, `steps_now`, `step_restart`, `slowed`, `pointer_presence_from`, `pointer_press_from`, `pointer_pressure`, `pressure`

```
// Declared for you (never write it); read as view.time, view.pointer_down != 0u.
struct View {
    origin: vec2f,              // em point at the target's top left
    resolution: vec2f,          // target size, pixels
    px_per_em: f32,
    time: f32,                  // seconds
    transition: f32,            // 0..1 across a cross, uneased
    from_item: u32,             // phrase being left
    to_item: u32,               // phrase being entered
    from_glyphs: u32,           // where field_from's glyphs end
    pointer: vec2f,             // em, where p is
    pointer_down: u32,          // 1 while pressed
    canvas_rect: vec4f,         // canvas on the page: x, y, width, height, CSS px
    px_per_css: f32,            // target pixels per CSS px
    pointer_down_time: f32,     // view.time of the last press, -1 before one
    pointer_up_time: f32,       // view.time of the last let-go, -1 before one
    pointer_inside: u32,        // 1 while over the target
    seek: u32,                  // 0 (one clock: no jumps)
    pointer_down_pos: vec2f,    // em, at the last press
    pointer_up_pos: vec2f,      // em, at the last let-go
    pointer_enter_time: f32,    // view.time pointer_inside last went to 1, -1 before
    pointer_leave_time: f32,    // view.time it last went to 0, -1 before
    time_slice: f32,            // seconds this frame adds to view.time, <= 0.1; 0 while paused, on a restart
    frame_count: u32,           // frames drawn since the restart, from 0
    item_elapsed_time: f32,     // seconds since to_item began arriving
    item_hold_time: f32,        // to_item's hold, seconds
    item_transition_time: f32,  // the cross into to_item, seconds; 0 for a cut
    loop_count: u32,            // times a looping sequence has wrapped
    reduced_motion: u32,        // 1 when the viewer prefers reduced motion
    pointer_type: u32,          // last pointer: 0 mouse, 1 touch, 2 pen
    page_shape_count: u32,      // the page's shapes, 0 unless the page sets some
    page_shape_blend: f32,      // how far they melt in, CSS px
    page_shapes: array<vec4f, 64>, // two a shape: rect; radius, kind, hover, press
    field_runs: array<vec4f, 2>, // the engine's own (field()'s culling): don't read it
    step_dt: f32,               // a fixed step, seconds; 0 unless a pass steps or warp_grid is on (level 9)
    step_count: u32,            // fixed steps since the restart, this frame's in
    steps_now: u32,             // the fixed steps this frame takes
    step_restart: u32,          // 1 on a frame that restarts the stepped passes' state
    slowed: u32,                // the engine's own (reduced motion, level 9): read reduced_motion
    field_runs_y: array<vec4f, 2>, // the engine's own (field()'s fold, level 11): don't read it
    pointer_presence_from: f32, // graffito_presence() at the last enter or leave (level 13)
    pointer_press_from: f32,    // graffito_press() at the last press or let-go (level 13)
    pointer_pressure: f32,      // 0..1: a pen's; 1 a mouse's or finger's press; held after a let-go (level 14)
}
let aa = 0.7 / view.px_per_em;   // one pixel, in em
let fade = select(0.0, exp(-2.0 * max(view.time - view.pointer_up_time, 0.0)), view.pointer_up_time >= 0.0);
state[0] += speed * view.time_slice;   // a stateful step: still while paused, the same at 60 and 120 Hz
```

### The pointer, touch, keys and reduced motion (`pointer-input`)

With inputs.pointer on, a piece has one pointer; view has no second. With two fingers down, the first pressed is followed until it lifts; the other is not heard, and its lift lets nothing go. A pen's pressure is view.pointer_pressure (engine level 14); a mouse and a finger read 1 while pressed (a phone's touch "pressure" is the contact's size, not its weight). There is no tilt or contact size: a pen or a finger is a point. A press starts only with a press on the canvas. A mouse lets go at the edge (pointer_down 0, pointer_inside 0); dragged in, or back in, with its button held it moves the pointer unpressed, and pointer_down_time does not change. A finger or a pen keeps steering past the edge until it lifts, with pointer_inside 1 meanwhile, and is gone (pointer_inside 0) as it lifts off the canvas. A finger has no hover: pointer_inside is 1 only while it touches. While inputs.pointer is on, the canvas keeps its touches, so on a phone a finger on the piece does not scroll the page (elsewhere it does): mind a piece as wide as the screen. Keys never reach the shader. In the lab a host script can listen for them on window once a click on the canvas has put focus in its frame, and write them into a host: true resource. An export drops the host script, so there the page around the piece writes them (el.write). The viewer's prefers-reduced-motion is the engine's, at every engine level (Reduced motion, by the engine): it holds a piece nearly still, its clock and the sequence's at a tenth. view.reduced_motion says it is asked, for a piece whose pipeline says "reduced_motion": "own" and calms itself.

Names: `pointer`, `touch`, `pen`, `mouse`, `multi-touch`, `finger`, `pressure`, `tilt`, `keys`, `keyboard`, `scroll`, `reduced_motion`, `accessibility`

### graffito_presence(), graffito_press() (`presence-press`)

0..1, eased: graffito_presence() how present the pointer is (in over 0.4 s as it arrives, out over 0.6 s after it leaves, 0 before it first arrives), graffito_press() how pressed (most of the way up in about 0.3 s; after a let-go down as exp(-2.5 t), 0.08 at 1 s, never 0: gate on a floor, not > 0). Each eases on from its value at the last change (view.pointer_presence_from, view.pointer_press_from), so leaving and coming back, or pressing again, quickly never jumps it. A layer's sample carries both (s.presence, s.press); any pass may call them. Multiply a pointer's effect by them so it neither pops in nor stays parked. While the engine slows a piece for reduced motion (reduced-motion) they are 1 or 0 at once, with no ease.

Names: `graffito_presence`, `graffito_press`

### Counting a press once (a compute pass) (`press-once`)

A compute pass runs every frame, so a pass that adds while view.pointer_down != 0u adds once a frame for as long as the press lasts. Count presses by view.pointer_down_time instead: it changes once per press. Keep the last one counted in storage, and start again on a restart (view.frame_count == 0u: a new build, the restart button), without counting the press from before (one still on is stamped 0 there). Run it as one invocation, size [1, 1] with workgroup_size 1: with over, every element's invocation would count. Below: the pipeline's pass and resource, then the pass's WGSL; a render pass reading count draws the score. A pass that instead moves something (a position, a trail's fade, a drop's fall) is marked step and moves by view.step_dt, as in pos += vel * view.step_dt (engine level 9; step: a fixed clock).

Names: `press`, `click`, `count`, `once`, `score`, `pointer_down_time`, `seek`, `time_slice`, `frame_count`, `step`, `state`

```
// "resources": { "count": { "kind": "storage", "element": "f32", "length": 2 } }
// { "name": "tick", "kind": "compute", "writes": ["count"], "entry": "tick",
//   "workgroup_size": 1, "dispatch": { "size": [1, 1] } }

// count[0]: the last press counted, as view.pointer_down_time + 1 (0: none yet,
// as storage starts); count[1]: presses counted.
@compute @workgroup_size(1)
fn tick() {
    let press = view.pointer_down_time + 1.0;   // 0 until the first press
    if (view.frame_count == 0u) {               // a restart: start again,
        count[1] = 0.0;                         // and don't count a press from before
        count[0] = press;
    }
    if (press != count[0]) {                    // a press not counted yet
        count[0] = press;
        count[1] += 1.0;
    }
}
```

## The prelude: what every pass can call

### graffito_rand(seed), graffito_hash(x) (`random`)

Randomness in the prelude, the same every run (a hash, not a generator): graffito_hash(x: u32) -> u32 is the PCG hash; graffito_rand(seed: u32), graffito_rand2(seed: vec2f) and graffito_rand3(seed: vec3f) -> f32 are uniform in [0, 1). A float seed hashes its bits: floor a point for one value per cell, add a frame or step count for one that changes. Named graffito_ so they can't clash with a hash or rand of your own. There is no noise function: for smooth noise, write your own from these, as below (value noise; sum a few octaves for fbm).

Names: `graffito_hash`, `graffito_rand`, `graffito_rand2`, `graffito_rand3`, `random`, `rand`, `hash`, `noise`

```
let cell = floor(p * 8.0);
let v = graffito_rand2(cell);                      // one value per cell
let w = graffito_rand3(vec3f(cell, floor(view.time * 4.0)));   // a new one 4 times a second

// value noise: a random value at each cell's corners, mixed smoothly
fn noise(p: vec2f) -> f32 {
    let i = floor(p);
    let u = smoothstep(vec2f(0.0), vec2f(1.0), fract(p));
    return mix(mix(graffito_rand2(i), graffito_rand2(i + vec2f(1.0, 0.0)), u.x),
               mix(graffito_rand2(i + vec2f(0.0, 1.0)), graffito_rand2(i + vec2f(1.0, 1.0)), u.x), u.y);
}
```

### seed, ranges and graffito_range(lo, hi, key) (`seed-ranges`)

A pipeline's seed (a whole number, 0 to 4294967295; 0 when left out) is what its draws come from. The lab and the AI's tools stamp one, from the piece's phrases, once a piece has ranges or a layer, and keep it from then on. ranges: { NAME: [lo, hi] } puts each NAME in every pass as a const f32 drawn once from lo to hi from the seed, so the piece picks its own numbers and keeps them; another seed draws others. graffito_range(lo, hi, key: u32) -> f32 draws the same way at run time, one value per key (an element's index): the same every frame and every run. graffito_seed is the seed as a u32 const. A range's name is UPPER_CASE and is no constant's.

Names: `seed`, `ranges`, `graffito_range`, `graffito_seed`

```
// pipeline({ seed: 60331, ranges: { DROP_R: [0.02, 0.05] }, ... })
let r = DROP_R;                                    // one radius, the piece's own
let x = graffito_range(-1.0, 1.0, i);              // one per drop i
let speed = graffito_range(0.08, 0.16, 100u + i);  // another draw for the same drop
```

### page_point(page), page_length(css) (`page`)

A point on the page, in CSS px from the viewport's top left (what getBoundingClientRect gives), as an em point where p is; and a length in CSS px as one in em. For shapes the page writes into a host: true resource. In the lab, the host script's page is its frame over the stage, and the canvas is measured in the same terms, so a script measures its own elements just as it would on a real page.

Names: `page_point`, `page_length`

```
let d = distance(p, page_point(s.center)) - page_length(s.radius);
```

### graffito_placed (`graffito-placed`)

The glyphs the page placed. graffito_placed.count says how many; graffito_placed_distance(i, p) is placed glyph i's distance at page point p, in page em. field() is these, unioned. Indices follow the text, inked glyphs only: a space gets none, so i counts letters, not characters. During a transition 0..view.from_glyphs are the phrase being left and view.from_glyphs..count the one entered. graffito_placed.glyphs[i].to_glyph (mat3x3f) takes a page point into glyph i's own em, and .slot is its graffito_glyphs record; as the engine places a phrase it is a uniform scale and a shift (no rotation), so glyph i's pen, its origin in page em, is -to_glyph[2].xy / to_glyph[0].x. To draw glyph i somewhere else, ask at a moved point: graffito_placed_distance(i, p - offset) draws it moved by offset.

Names: `graffito_placed`, `graffito_placed_distance`, `count`, `to_glyph`

```
for (var i = 0u; i < graffito_placed.count; i++) {
    d = max(d, graffito_placed_distance(i, p));
}
// glyph 0 again, half an em to the right
d = max(d, graffito_placed_distance(0u, p - vec2f(0.5, 0.0)));
```

### graffito_distance(slot, p) (`graffito-distance`)

One glyph's signed distance in em at p, in that glyph's own em space: positive inside, exact within its reach (graffito_glyphs[slot].reach, about a fifth of an em) and going on past it (within about 0.016 em of exact out to 2 em; beside a long thin glyph, up to about 0.1 em nearer); graffito_far (-1000) before the glyph is ready.

Names: `graffito_distance`, `graffito_far`

### graffito_texel and graffito_glyphs (`graffito-texel`)

graffito_texel(slot, x, y) is one stored texel, unconverted (the distance in texels, positive inside): x below width, y below height. Every texel of the box is exact. graffito_glyphs[slot] is a glyph's record: offset, width, height, ready, origin, texels_per_em (64, or 128 for a glyph with hairlines), reach, ink_min, ink_max, advance (em). graffito_atlas holds the glyphs' fields; past them nothing is defined, and a played piece's (an exported page, the graffito-piece element) is sized to its own glyphs.

Names: `graffito_texel`, `graffito_glyphs`

## Passes and the pipeline

### pipeline.js: the passes (`pipeline-pane`)

JavaScript that ends return pipeline({...}): which passes run, and the resources they read and write. Every builder function below is in scope (render, compute, storage, uniform, vec4f, …). view and names starting graffito_ are the engine's; a render pass that names graffito_vs and graffito_fs draws with shade(p). In a piece with code units each pass runs the unit its code key names, and a pass that names none (the builder's never do) runs the unit of its own name, a new one made for a new pass. It runs in a worker on each edit, stopped after 2s, and its result is the piece's pipeline; opening a piece never runs it: the pipeline saved with it is what plays. While it throws or is refused, the last version that built keeps running, and that is what exports. A piece that has not built in this tab yet (one opened from a file is paused until run) shows the lab's default shader, and exports and publishes nothing until it builds.

Names: `return`

```js
return pipeline({
  passes: [render("draw", { vertex: "graffito_vs", fragment: "graffito_fs", draw: { vertices: 3 } })],
});
```

### pipeline({ ... }) (`pipeline`)

The document. Options: canvas, types, constants, resources, groups, passes; and seed, ranges, light, layers, warp_grid, light_grid and reduced_motion (their own entries say what they do), passed through as written. Every struct and resource is named here, once; elsewhere you pass the object itself.

Names: `pipeline`

```js
const sim = uniform({ dt: f32(1 / 60) });
return pipeline({ resources: { sim }, passes: [/* ... */] });
```

### passes (`passes`)

compute(...) and render(...), run in order every frame. once: true runs a pass on the build's first frame only (not again on a restart, the restart button: state a restart must lay again goes on view.frame_count == 0u, or graffito_restart() in a stepped pass).

Names: `passes`, `once`

### compute(name, { ... }) (`compute`)

reads, writes (storage, read-write in WGSL), over (one invocation per element or texel) or size: [w, h], entry, workgroupSize, once. workgroupSize is 64 (the default), or [x, y] or [x, y, z]: any sizes within WebGPU's limits (x and y at most 256, z at most 64, 256 in all). over dispatches along x alone, enough workgroups for every element (a texture's texels counted as one row), so give it one number and index by id.x; size: [w, h] dispatches enough for w by h, by id.xy. Either may run past the end, to fill the last workgroup: return when id is past it. At most 65535 workgroups along each axis: over with workgroupSize 64 reaches 4194240 elements, 256 reaches 16776960; past that, give a bigger workgroupSize or dispatch by size: [w, h]. A pass binds at most 8 storage buffers (WebGPU's limit a shader stage), the engine's among them: 2 where its code unit uses glyphs (so 6 of your own), one more each where it uses warp_grid, light_grid (or light_grid_add), page, glyph_direction or glyph_index, two more for glyph_outline (its table and the index it brings), and one more in a stepped pass whose unit uses steps (in a piece without code units, every pass has the glyphs' and those of each grid its pipeline configures, and every stepped pass the step's). A render pass's count is its vertex stage's too. More fails to build with WebGPU's own message, which names no pass. Put several arrays in one storage of a struct, or in textures.

Names: `compute`, `reads`, `writes`, `over`, `entry`, `workgroupSize`

```js
compute("advance", { reads: [sim], writes: [particles], over: particles, entry: "advance" })
```

### render(name, { ... }) (`render`)

reads, vertex, fragment, draw: { vertices, instances } (instances a count or a storage's length), blend, topology, load ("clear" or "keep", to layer passes), once. blend: "replace" (the default) writes what the fragment returns; "alpha" is straight alpha, color × alpha + what is there × (1 - alpha) (alpha: alpha + what is there × (1 - alpha)), so a fragment in an alpha pass returns its color NOT multiplied by alpha: vec4f(rgb, a), unlike shade(p)'s premultiplied answer in a replace pass; "additive" adds color and alpha as returned (one + one), the alpha no weight.

Names: `render`, `vertex`, `fragment`, `draw`, `instances`, `vertices`, `blend`, `topology`, `load`

```js
render("dots", { reads: [particles], vertex: "dot_vs", fragment: "dot_fs",
  draw: { vertices: 6, instances: particles }, blend: "additive", load: "keep" })
```

### Chaining render passes: target (`chain`)

A render pass with target: a texture draws into that texture instead of the canvas, and a later pass reads and samples it: a glow, a blur, a palette, anything that needs the whole frame first. It is how to make a glow or halo wider than field()'s reach (about a fifth of an em unless the piece raises reach, which costs glyph memory): draw the text into the texture, then sample around each pixel, as below. A pass can't read its own target. The texture keeps its size when the canvas changes, so a pass drawing the text into it maps texels to the canvas's pixels itself (view.resolution), and one reading it takes its size from textureDimensions. The pass drawing into it cannot ask its size (the texture is not bound there: textureDimensions on it is an unresolved value), so give the size as a constant, as LAYER below. Give each pass its own fragment: a fragment that samples the texture can't be in the pass that draws it. Below: the pipeline, then the text and show tabs.

Names: `target`, `textureDimensions`

```
const layer = texture({ size: [1024, 512] });
const soft = sampler({});
return pipeline({
  resources: { layer, soft },
  passes: [
    render("text", { target: layer, vertex: "graffito_vs", fragment: "text_fs", draw: { vertices: 3 } }),
    render("show", { reads: [layer, soft], vertex: "graffito_vs", fragment: "show_fs", draw: { vertices: 3 } }),
  ],
});

// text.wgsl, uses glyphs
// The layer has its own size, so map its texel to the canvas's pixel
// before asking for the field: graffito_fs would assume they match.
const LAYER = vec2f(1024.0, 512.0);

@fragment
fn text_fs(@builtin(position) texel: vec4f) -> @location(0) vec4f {
    let pixel = texel.xy / LAYER * view.resolution;
    let p = view.origin + vec2f(pixel.x, -pixel.y) / view.px_per_em;
    return vec4f(vec3f(step(0.0, field(p, 0.0))), 1.0);
}

// show.wgsl, uses nothing
@fragment
fn show_fs(@builtin(position) pixel: vec4f) -> @location(0) vec4f {
    let uv = pixel.xy / view.resolution;
    let r = 12.0 / vec2f(textureDimensions(layer));
    var glow = 0.0;
    for (var i = 0; i < 16; i++) {
        let a = f32(i) * 0.3927;   // 16 taps around a circle
        glow += textureSample(layer, soft, uv + r * vec2f(cos(a), sin(a))).r;
    }
    let ink = textureSample(layer, soft, uv).r;
    return vec4f(mix(vec3f(1.0, 0.45, 0.1) * glow / 16.0, vec3f(1.0), ink), 1.0);
}
```

open this example in a new tab: https://driftype.com/lab?example=chain

### repeat: n (`repeat`)

On a compute pass with over or size (or a render pass): runs it n times in a row where it stands, every frame, 1 to 64, each run seeing what the one before wrote. Its WGSL has REPEAT_INDEX (0 to n - 1, this run) and REPEAT_COUNT (n), both u32 constants: a simulation stepped n times a frame is one pass and one source. To ping-pong, the pass writes both buffers and picks by REPEAT_INDEX's parity; with n even the last run wrote the first. Each run compiles on its own, so a build takes n times as long.

Names: `repeat`, `REPEAT_INDEX`, `REPEAT_COUNT`

```js
compute("step", { writes: [a, b], size: [W, H], workgroupSize: [8, 8], entry: "step", repeat: 16 })
// fn src(i: u32) -> f32 { if (REPEAT_INDEX % 2u == 0u) { return a[i]; } return b[i]; }
// fn put(i: u32, v: f32) { if (REPEAT_INDEX % 2u == 0u) { b[i] = v; } else { a[i] = v; } }
```

### resources (`resources`)

{ name: storage(...) | uniform(...) | texture(...) | sampler(...) }. The WGSL refers to each by this name and never declares it. Each name is a global in the WGSL of every pass that reads or writes it, so a function, constant or variable of your own of the same name is a redeclaration error; and a name WGSL reserves is refused (WGSL reserves many plain words besides its keywords: meta, patch, filter, target, type, set, smooth, shared, resource, module, pass, …: rename it).

Names: `resources`

### storage(element, sizing) (`storage`)

array<element> in a storage buffer. sizing: a length (1000), an init list ([0, 1, 3]), { length, init }, or { length: other } to follow another storage's length. host: true (here, in uniform's options, or texture's) lets the page write it while the piece runs; until it does, it holds what is declared.

Names: `storage`, `length`, `init`, `declare`, `host`

```js
const particles = storage(Particle, 10_000);
```

### uniform({ ... }, { host }) (`uniform`)

A struct of values, var<uniform>. Give every member a value or none (zeros). In WGSL its struct is the name capitalised: sim is Sim.

Names: `uniform`

```js
const tint = uniform({ color: vec3f(1, 0.5, 0.2) });
```

### texture({ size, init }) (`texture`)

A 2D RGBA8 texture: texture_2d<f32> where read, write-only storage where a compute pass writes it. A compute pass with it in both reads and writes gets the write-only one alone: it cannot read it there (textureLoad on it fails to compile), so read last frame's values from a second texture or a storage buffer. init lists [r, g, b, a] texels row by row. The builder's image option needs files, which the lab has not got.

Names: `texture`, `size`

```js
const noise = texture({ size: [256, 256] });
```

### sampler({ filter, address }) (`sampler`)

filter "linear" (default) or "nearest"; address "clamp" (default), "repeat" or "mirror".

Names: `sampler`, `filter`, `address`

### types (`types`)

{ Name: struct(...) }: the structs the WGSL uses, emitted into every pass.

Names: `types`

```js
const Particle = struct({ pos: vec2f, vel: vec2f });
pipeline({ types: { Particle }, /* ... */ })
```

### constants (`constants`)

{ NAME: u32(2), SCALE: f32(0.5) }: a WGSL const in every pass.

Names: `constants`

### canvas (`canvas`)

[width, height]: defines CANVAS_SIZE (a vec2f) in the WGSL, and nothing else: render passes draw at the canvas's size whether it is given or not (view.resolution says that size). Leave it out.

Names: `canvas`, `CANVAS_SIZE`

### groups (`groups`)

[[a, b], [c]]: bind groups, by position. Left out, your resources share one group. The engine adds two groups of its own, and WebGPU allows four.

Names: `groups`

### Scalars and vectors (`scalars`)

f32, u32, i32, and vec2f to vec4i as in WGSL. Each is a type (f32) and makes a value (f32(0.5), vec2f(1, 2) or vec2f([1, 2])).

Names: `f32`, `u32`, `i32`, `vec2f`, `vec3f`, `vec4f`, `vec2u`, `vec3u`, `vec4u`, `vec2i`, `vec3i`, `vec4i`

### Matrices (`matrices`)

mat2x2f to mat4x4f: matCxRf has C columns of R rows. A value is its columns.

Names: `mat2x2f`, `mat2x3f`, `mat2x4f`, `mat3x2f`, `mat3x3f`, `mat3x4f`, `mat4x2f`, `mat4x3f`, `mat4x4f`

```js
mat2x2f([1, 0], [0, 1])
```

### array(element, count) (`array`)

A fixed-size array<element, count>, and a function making a value: a list of exactly count. In a uniform, elements must be 16 bytes apart: array(vec4f, 16), not array(f32, 64).

Names: `array`

### atomic(u32), atomic(i32) (`atomic`)

A storage element only: storage(atomic(u32), n), not in a struct, an array or a uniform. A pass that writes it sees array<atomic<u32>> (atomicAdd, atomicStore, atomicLoad, atomicMax, atomicMin, atomicExchange, and atomicCompareExchangeWeak, which claims a cell only if it still holds what you expect: grains that must not share one, as in the gallery's Sand); a pass that only reads it, a render pass too, sees array<u32>, plain numbers, since WGSL allows atomics only in read-write storage. It keeps its counts from frame to frame: clear it with atomicStore in a pass before the one that adds.

Names: `atomic`, `atomicAdd`, `atomicStore`, `atomicLoad`, `atomicMax`, `atomicMin`, `atomicCompareExchangeWeak`, `atomicExchange`

```js
const bins = storage(atomic(u32), 64 * 32);
compute("clear", { writes: [bins], over: bins, entry: "clear" }),
compute("count", { reads: [particles], writes: [bins], over: particles, entry: "count" }),
// count: atomicAdd(&bins[cell], 1u); a render pass reading bins: bins[cell]
```

### struct({ ... }) (`struct`)

Members in order, each a type (structs nest). Name it in types. As a function it makes a value for a uniform: S({ a: 1 }).

Names: `struct`

```js
const Light = struct({ pos: vec2f, power: f32 });
```

### A pass's WGSL (`one-module`)

WGSL checks every function, used or not, and a pass only has bindings for what it reads and writes, and for what its code unit uses. That is why passes that read different resources run different code units: a compute pass and a render pass can't share a source. Within one unit's WGSL, a function that uses a resource needs it in the reads or writes of every pass that runs the unit.

### What is written for you (`declarations`)

Each pass's module starts with its structs and constants, each uniform's struct, a binding for every resource it reads or writes, then for a compute pass WORKGROUP_SIZE, WORKGROUP_SIZE_X, WORKGROUP_SIZE_Y and WORKGROUP_SIZE_Z (u32; all four always, an axis not given 1, WORKGROUP_SIZE the same as _X), then the prelude, then your WGSL. So a piece holds no directive (enable f16;, requires, diagnostic(...);), which WGSL wants before every declaration: the build says "directives must come before all global declarations" at your line 1.

Names: `WORKGROUP_SIZE`, `WORKGROUP_SIZE_X`, `WORKGROUP_SIZE_Y`

```
@compute @workgroup_size(WORKGROUP_SIZE)                       // workgroupSize 64, over
fn advance(@builtin(global_invocation_id) id: vec3u) { /* ... */ }
@compute @workgroup_size(WORKGROUP_SIZE_X, WORKGROUP_SIZE_Y)     // [8, 8], size: [w, h]
fn step(@builtin(global_invocation_id) id: vec3u) { /* ... */ }
```

### wgsl (`wgsl-option`)

In a page, a pass's wgsl option lists its files. In the lab it has no effect: a pass's WGSL is its code unit's tab in the WGSL pane.

Names: `wgsl`

### The language (`wgsl-language`)

WGSL is WebGPU's shading language: types, built-in functions (mix, smoothstep, fract, length…), and the rules for entry points and bindings are all in its specification.

WGSL spec (W3C): https://www.w3.org/TR/WGSL/

### Errors (`errors`)

A builder error names the call; a document error names the resource or pass; a WGSL error names the pass and your line:column. Nothing replaces the running pipeline until it builds clean.

## The scene: light and layers

### light: the scene's one light (`light`)

A pipeline with layers may declare its light; the layer's color reads it as s.light: dir (unit, toward the light, z out of the page), color, ambient. azimuth: degrees counterclockwise from +x (135, the upper left, when left out); elevation: degrees above the page, above 0 and at most 90 (45); color [r, g, b] (white); ambient 0..1 (0.3). follow: "pointer" makes it a lamp lamp_height em (0.8) over the pointer, eased in and out with its presence. fn names fn(p: vec2f, rest: GraffitoLight) -> GraffitoLight of your own, called once a pixel after follow (a moving sun, a press that dims). shadow: { from: [the layer's name], height (em, 0.1), soft (6: larger is sharper) } marches the layer's group (its joined distance: drops joined into the letters cast with them) once a pixel toward the light, as far as the ray takes to rise to height, or to the lamp when a lamp_height below height is passed first, and hands the color s.shadow. Inside the casting group's shape it is 1: the shadow darkens what is around the caster, never the caster, so a color may multiply its own light by s.shadow.

Names: `light`, `GraffitoLight`, `azimuth`, `elevation`, `ambient`, `lamp_height`, `shadow`

```
light: { azimuth: 135, elevation: 40, color: [1, 0.96, 0.9], ambient: 0.3, follow: "pointer", lamp_height: 0.8,
         shadow: { from: ["ink"], height: 0.1, soft: 6 } }
```

### layers: a layer's warp, distance and color (`layers`)

Instead of shade(p), a pipeline may declare up to 3 shaped layers, and beside them one fill (a layer with no distance or slope: the ground first, or an overlay above everything), and the functions that make them; a render pass whose fragment is graffito_layers_fs (vertex graffito_vs) draws them, back to front, the ground first. Alone, a layer's color paints the whole pixel, the ground where s.cover is 0 and the shape where it is 1. With several, each is put over what is behind it by the alpha its color returns, and graffito_under() is that picture behind it at the pixel (premultiplied; 0 for the first). join: { with: an earlier layer, op: "union" | "smooth" | "subtract" | "intersect", k (smooth's: em, or a range's name) } makes them one group: one shape (s.shape, the joined distance), one cover; each member's color gets its share (s.weight, summing to 1) and the group's gradient (s.grad, the members' mixed by share), and their colors are mixed by share, drawn where the first member stands. Subtract keeps what is in the first and not the second, in the first's color. A fill joins nothing. Its fields name functions in that pass's WGSL: warp fn(p: vec2f) -> vec2f (the point the shape is sampled at; none: p); distance fn(q: vec2f) -> f32, positive inside, as field() is; slope fn(q: vec2f) -> vec3f, the distance and its gradient (field_slope's), for lit edges; extra fn(q: vec2f) -> vec4f, any four numbers for the color (a grid read, a matter value); color fn(s: GraffitoSample) -> vec4f, required, its alpha straight (not premultiplied): the engine multiplies. height (em) is how tall it stands. With neither distance nor slope it is a fill (cover 1). The engine evaluates the warp, the distance (the fill's edge) and the slope (the gradient) before anything branches, so the color may call dpdx, dpdy and fwidth. layer_<name>(p) is a shaped layer's warp and distance, group_<its first>(p) a joined group's, scene_distance(p) every shaped group's, to call anywhere in that pass's WGSL (they are generated there alone; each call is another lookup). warp_grid: true (engine level 8) draws a layer through the pipeline's warp grid (warp-grid), its slope taken into p through the grid's Jacobian; a layer's own warp leaves s.grad the slope at q, not taken through the warp.

Names: `layers`, `graffito_layers_fs`, `GraffitoSample`, `layer_`, `scene_distance`, `graffito_cover`, `graffito_grad`, `join`, `graffito_under`

```
// pipeline({ layers: [{ name: "ink", warp: "ink_warp", distance: "ink_d", slope: "ink_s", color: "ink_color", height: 0.1 }],
//            passes: [render("draw", { vertex: "graffito_vs", fragment: "graffito_layers_fs", draw: { vertices: 3 } })] })
fn ink_warp(p: vec2f) -> vec2f { return p + vec2f(0.01 * sin(p.y * 9.0 + view.time), 0.0); }
fn ink_d(q: vec2f) -> f32 { return field(q, 0.02); }
fn ink_s(q: vec2f) -> vec3f { return field_slope(q, 0.02); }
fn ink_color(s: GraffitoSample) -> vec4f {
    let ground = vec3f(0.1, 0.12, 0.18) * (s.light.ambient + (1.0 - s.light.ambient) * s.shadow);
    let n = normalize(vec3f(-s.grad * 0.35, 1.0));
    let ink = vec3f(0.74, 0.85, 0.97) * (s.light.ambient + max(dot(n, s.light.dir), 0.0) * s.light.color);
    return vec4f(mix(ground, ink, s.cover), 1.0);
}

struct GraffitoSample {     // declared for you
    p: vec2f,               // the pixel, em
    q: vec2f,               // warp(p)
    d: f32,                 // distance at q; 1e9 for a fill
    shape: f32,             // the distance cover is taken from: d, or its group's joined
    cover: f32,             // 0..1, antialiased over a pixel
    weight: f32,            // its share of its group: 1 alone
    grad: vec2f,            // the gradient, em per em, inward: slope's, else screen derivatives; a group's mixed by share
    height: f32,            // the layer's, em
    px: f32,                // one pixel, em
    presence: f32,          // graffito_presence()
    press: f32,             // graffito_press()
    light: GraffitoLight,   // the scene's light at p
    shadow: f32,            // 1 lit .. 0 in the light's shadow; 1 inside its caster
    extra: vec4f,           // extra(q), else 0
    layer: u32,             // its index in layers
}
// Three: pipeline({ layers: [{ name: "ground", color: "sky" },
//   { name: "ink", distance: "ink_d", slope: "ink_s", color: "ice" },
//   { name: "drops", distance: "drops_d", color: "water", join: { with: "ink", op: "smooth", k: 0.04 } }], ... })
// ice and water return alpha s.cover; sky paints everything, alpha 1.
```

## The engine's clock and grids

### step: a fixed clock (`step`)

On a compute pass with over or size (engine level 9): step: {} runs it once per step of a fixed clock, 120 a second and at most 8 a frame (the rest dropped), or { hz: 60, max: 4 }. The stepped passes stand together and run, in their order, once per step where they stand; none while paused, so what they move lands at the same place at 30, 60 or 144 Hz. On a restart (a build's first frame, the restart button) they run once with graffito_restart() true, taking no step: lay the state afresh then. graffito_steps() is the whole steps taken since (in a stepped pass, before this one; elsewhere, this frame's included) and graffito_step_time() that in seconds: the simulation's own time, never view.time. view.step_dt is the step. A stepped pass whose code unit uses steps (every stepped pass without code units) reads one more storage buffer of the 8 a stage may bind (graffito_step, the step's place).

Names: `step`, `fixed step`, `hz`, `graffito_restart`, `graffito_steps`, `graffito_step_time`, `step_dt`, `simulation`

```js
compute("fall", { writes: [ball], size: [1, 1], workgroupSize: 1, entry: "fall", step: {} })
// fn fall() {
//     if (graffito_restart()) { ball[0] = Ball(vec2f(0.0, 1.5), vec2f(0.9, 0.0)); return; }
//     var b = ball[0];
//     b.vel.y -= 4.0 * view.step_dt;
//     b.pos += b.vel * view.step_dt;
//     ball[0] = b;
// }
```

### Reduced motion, by the engine (`reduced-motion`)

A piece holds nearly still while the viewer asks for reduced motion, with no code of its own for it and at every engine level: the engine runs its clock at a tenth of the speed (view.time, view.time_slice and so the fixed steps), a press too: the rate of the slices after the change, never a jump in time. What the pointer does appears at once instead: graffito_presence() and graffito_press() are 1 or 0 with no ease (view.slowed, the engine's own, says so; a piece's own ease reads view.reduced_motion), and <graffito-piece> sets the page's boxes' hover and press at once. The pointer's times are stamped on the slowed clock and never move, so view.time - view.pointer_down_time is the time since the press on it: what a press sets off starts in its frame and plays at a tenth. The phrases are on the same clock and slow too. A piece that holds itself still (it reads view.reduced_motion, 1 either way) says "reduced_motion": "own" beside passes, and the engine leaves its clock and its pointer helpers alone; the key came with engine level 9, so a piece the lab keeps at an older level takes it once raised. The gallery plays a piece in the engine it was published with, so one published before level 9 plays there as it did.

Names: `reduced motion`, `still`, `own`, `prefers-reduced-motion`, `accessibility`

```
// pipeline({ reduced_motion: "own", passes: [...] }): this piece calms itself
let sway = 0.1 * sin(view.time) * (1.0 - f32(view.reduced_motion));
```

### warp_grid: the engine's displacement grid (`warp-grid`)

A pipeline key (engine level 8): "warp_grid": {} and the engine keeps a displacement over the canvas that taps, drags and the hover write into and that settles back to 0 by its own damping. A tap lays a few rings that run out through the letters (slower inside them, so they bend at the outline), a drag pushes what is under it along and lets it spring back, the hover leaves a light wake and magnifies what is under the pointer. It is one grid, not a list of ripples: no tap ends another's, and the engine holds it back where it would fold the letters over. A pass whose code unit uses warp_grid reads it (in a piece without code units, every pass): graffito_warp_grid(p) is how far the picture moves at p, in em, so draw what is at q = p + graffito_warp_grid(p); graffito_warp_grid_jacobian(p) is the Jacobian of q, and a slope s at q (field_slope(q, k).yz) is s * graffito_warp_grid_jacobian(p) in p, so light and antialiasing follow the moved letters. A layer with "warp_grid": true is drawn through it, its slope taken through the Jacobian. Knobs, each a number or a range's name: speed (em a second, 0.85), damping (per second, 1.05), ring (how fast struck water keeps rising and falling, radians a second, 2.5), medium (the speed inside the letters as a share, 0.73; 1 the same), tap (em, 0.034; 0 none), radius (of a tap, a push and the lens, em, 0.18), push (the share of a drag's motion, 0.575), spring (radians a second, 6.5), spring_damping (0.285), wake (em per em moved, 0.0075), lens (0.29), opening (the drop as the piece starts, in taps, 1.1; 0 none). Reduced motion: no opening drop, no hover wake, waves die 3 times as fast. It costs about 0.1-0.2 ms a frame whatever the canvas, and one more storage buffer in a pass that reads it (compute).

Names: `warp_grid`, `graffito_warp_grid`, `graffito_warp_grid_jacobian`, `ripple`, `tap`, `drag`, `displacement`

```
// pipeline({ warp_grid: { damping: 1.5 }, passes: [render("draw", { vertex: "graffito_vs", fragment: "graffito_fs", draw: { vertices: 3 } })] })
fn shade(p: vec2f) -> vec4f {
    let q = p + graffito_warp_grid(p);
    let s = field_slope(q, 0.0);
    let g = s.yz * graffito_warp_grid_jacobian(p);           // the slope in p
    let ink = smoothstep(-0.7, 0.7, s.x * view.px_per_em / max(length(g), 0.05));
    let lit = 0.7 + 0.3 * dot(normalize(vec3f(-g * 0.4, 1.0)), normalize(vec3f(-0.5, 0.6, 0.6)));
    return vec4f(mix(vec3f(0.08, 0.12, 0.15), vec3f(0.93, 0.9, 0.84) * lit, ink), 1.0);
}
```

### light_grid: the engine's light grid (`light-grid`)

A pipeline key (engine level 10): "light_grid": {} and the engine keeps light over the canvas that the piece's compute passes lay and that only the engine's fade lowers. Its cells follow the canvas in device pixels (cell px each, 1), so it is as sharp at any size and on a 2x screen; at most cap MiB (32; past it the cells grow). A compute pass whose code unit uses light_grid_add lays light: graffito_light_add(p, light) is a point (light a vec3f, shared among the four cells round p), graffito_light_line(a, b, light) a segment, light a cell of its length, so a path laid a frame at a time is as bright as one laid at once. A render pass only reads. A pass whose unit uses light_grid or light_grid_add reads graffito_light(p) -> vec3f, the cells through a smooth B-spline, and graffito_light_slope(p) -> mat3x3f, that light and its change along x and y per em; graffito_light_cell() is a cell's side in em, graffito_light_FADE the fade's time constant, graffito_light_FADES each channel's (a vec3f). The fade (fade: seconds, 0.6, or a range's name; or, on 3 channels, a list of three, a fade a channel: [2.4, 0.9, 0.3] keeps red longest, so light laid warm cools to red as it fades) runs in 1/120 s steps (with stepped passes, once a step before them: light they lay is the same at any frame rate) and reaches 0; nothing fades while paused, and the grid starts again on a restart (a build's first frame, the restart button) and follows a resize. So nothing drawn from it vanishes faster than the fade, however fast the presses come: sparks or drops in a list only lay light, and one overwritten under fast presses just stops. channels 3 (colored light) or 1 (one number a cell, a third the memory). One more storage buffer in a pass that reads it (compute). In a piece without code units every pass reads it and every compute pass may lay light.

Names: `light_grid`, `graffito_light`, `graffito_light_slope`, `graffito_light_add`, `graffito_light_line`, `graffito_light_cell`, `graffito_light_FADES`, `fade`, `trail`, `sparks`

```
// pipeline({ light_grid: { fade: 0.8 }, passes: [compute("lay", { workgroup_size: 64, dispatch: { size: [3, 1] }, entry: "lay" }),
//   render("draw", { vertex: "graffito_vs", fragment: "graffito_fs", draw: { vertices: 3 } })] })
// pass "lay": three comets, each laying the arc it swept this frame
@compute @workgroup_size(WORKGROUP_SIZE)
fn lay(@builtin(global_invocation_id) id: vec3u) {
    if (id.x >= 3u || view.time_slice <= 0.0) { return; }
    let c = view.origin + vec2f(0.5, -0.5) * view.resolution / view.px_per_em;
    let a = view.time * 1.7 + f32(id.x) * 2.0943951;
    let b = a - view.time_slice * 1.7;
    graffito_light_line(c + vec2f(1.6 * cos(b), 0.45 * sin(b)), c + vec2f(1.6 * cos(a), 0.45 * sin(a)), vec3f(1.0, 0.5, 0.2));
}

// pass "draw": the light, and the letters over it
fn shade(p: vec2f) -> vec4f {
    let sky = vec3f(0.03, 0.03, 0.06) + 1.0 - exp(-graffito_light(p) * 1.5);
    let ink = clamp(field(p, 0.0) * view.px_per_em + 0.5, 0.0, 1.0);
    return vec4f(mix(sky, vec3f(0.85, 0.82, 0.76), ink), 1.0);
}
```

## What a piece can hold

### What a piece can hold (`limits`)

A phrase is one line, no line breaks, of at most 200 characters; a piece holds at most 64 phrases and 4000 characters in all. While a phrase crosses into the next both are placed, and the two share 256 glyphs (spaces, and characters the font lacks, take none): past that the entering phrase's last glyphs are not drawn while it crosses, and the status says so. Each other character is one glyph, laid left to right with no shaping: Arabic letters don't join, Hebrew and Arabic run the wrong way unless typed in visual order, and Devanagari conjuncts don't form. A character the font lacks is left out. For randomness the prelude has graffito_rand(seed) and friends (see that entry): the same every run, so an export draws what the lab did. field() is exact within the piece's reach of an outline (0.1875 em, about a fifth, unless the piece raises reach: Settings) and close to exact past it (field(p, k), field_from, field_to). For a soft glow or haze, which is cheaper and softer blurred, draw the text into a texture and blur it in a later pass (see Chaining render passes, and the chain example). A storage buffer holds at most 128 MiB, a piece's buffers and textures 512 MiB in all (the engine's own not counted). An init holds at most 33554432 numbers, 128 MiB of f32: a list of numbers, or of equal lists (vec4fs, texels). An init of objects (structs) or of unequal lists holds at most 4194304 values, each number, list and object one. A pass binds at most 8 storage buffers, the engine's among them (6 of your own in a pass whose unit uses glyphs, fewer with a grid, page or a step), and a compute pass dispatches at most 65535 workgroups along an axis (see compute).

Names: `limits`, `glyphs`, `characters`, `line`, `shaping`, `random`

## The lab around a piece

### about this piece (`about`)

Above the code, "about this piece": a few plain sentences on what the piece is and how to play with it (move the pointer, press, wait for the next phrase). Plain text, at most 600 characters, saved with the piece as typed. Put that here rather than in a comment at the top of the WGSL: the code starts with code, and its comments say how it works. The lab shows it, and so does a piece opened from a file or the gallery; the gallery's pages and an exported page do not.

Names: `about`, `description`, `comment`, `how to play`

### The phrase and its font (`text-font`)

A new piece starts with one phrase in one font. The lab reads the outlines out of the font file and the piece carries them from then on, so it plays with no font file. Its font: search Fontsource's families by name (the form's font field), or pick a font file of your own; with neither, Anton. The search's list, about 2,100 families under open licences, is fetched from api.fontsource.org when you first focus the field, never before. It narrows as you type and by script and kind, shows each family's licence, then a weight and style where the family has several. It shows no previews (fonts load only from this site): the new piece is the preview. If Fontsource cannot be reached the search says so, and a file still works. Change either in the phrases table under the timeline: type a phrase, choose its font in its menu, or add a font with the two buttons beside it ("by name…" searches Fontsource the same way, "file…" takes a file). A character the piece holds no outline for is read from its font's file. Anton's is fetched, and so is a Fontsource font's (the files those characters need, at the version the piece was made with); any other file is asked for, and one that draws the letters the piece holds differently (another font, or another version of it) is refused. A piece written elsewhere (by an AI, say) may leave the outlines out and name its fonts. In its file: "fonts": ["Anton"], or no "fonts" at all, which means the same; or any family on Fontsource (fontsource.org: the Google Fonts catalogue and more, open licences only), written as Fontsource lists it: "fonts": ["EB Garamond"]. "open a file…" makes the outlines for its phrases: Anton's from the site's own file, any other family's from the files the lab fetches from Fontsource (api.fontsource.org and cdn.jsdelivr.net) as it opens the piece. The piece then carries them, so a saved, exported or published piece never fetches. Name a weight or style as an object, { "family": "Inter", "weight": 700, "style": "italic" }, never "Inter 700": some families' names end in digits. A weight is a CSS weight, 1 to 1000 (Fontsource's files come in hundreds, 100 to 900); one the family lacks becomes the nearest it has, and the tab's note says which. Names ignore case ("anton" is the site's own Anton, never fetched). A font no phrase is set in is never fetched. A piece names at most 8 to fetch. Fontsource splits a family into files by script (latin, latin-ext, cyrillic, …; a font with many characters, such as a Chinese, Japanese, Korean or emoji font, into numbered slices of a few hundred characters). The lab fetches only the ones the phrases need, merges them into one font, and fetches more only when new letters need them. A character none of the family's files has is not drawn, and the status says so. A family with no latin letters (Noto Emoji) is taken for the scripts it has. A joined script's letters are still separate glyphs, each laid at the last one's advance: they connect only where the font's own shapes overlap. The piece does not open, saying which, for a family Fontsource does not have, one not under an open licence, or no network. For a font on no catalogue, open the piece in Anton and pick that font's file here. A piece opened from a file is in a tab of its own, its phrases table read-only: to add a font to it, "keep as my piece" first (it replaces the piece you had: save that one first if you want it), then the row's "by name…" or "file…". A font whose letters are built from overlapping shapes (Roboto's H, a handwriting family's ç) draws them whole, whether a file of your own or fetched by name: bands or outlines drawn inside the letters (abs(d) < w) follow the letter, not the shapes it was built from. One limit, in every font: a notch narrower than about 1/64 em reads as ink (field(p, k), field_from, field_to). Type precomposed characters (Unicode NFC: É as one character). A combining mark is a glyph of its own, placed where its font draws it: on the letter before in STIX Two Math, DejaVu Math and Libertinus Math, beside it in most fonts (the status says when). Math (operators, arrows, Greek, math alphabets such as 𝑥 𝔄 𝕏) reads right in STIX Two Math or Libertinus Math, on one line: no fractions, roots over an expression, stretchy brackets or big display operators, and super- and subscripts are the few Unicode has (² ₙ). Anton lacks most of it and draws ≠ as =; the status says when a font draws a character exactly as another. An icon font (Material Icons, Material Symbols Outlined) is named by its family like any other, and its icons are written as codepoints (U+E838), not ligature names ("star" draws its letters, or nothing). It may have no space, so spaces in its phrase vanish and are reported missing. The font search leaves icon fonts out: name one in the piece's file ("fonts": ["Material Symbols Outlined"]), or give its font file to a row's "file…". The lab's own labels show such a character by its codepoint (U+E838), which the page's font cannot draw.

### The phrases: hold and transition (`sequence`)

Under the timeline, "phrases" opens the table: each phrase is held for its hold, then crosses into the next over its transition, both in seconds. The shader draws each cross (view.transition, view.from_item, view.to_item). The last phrase crosses into the first only when the sequence loops. A hold may be 0 (the phrase is there only as its cross begins) and a transition 0 (a cut); either under 1 ms counts as 0. Edits play as typed and are saved with the piece; they run no code. An edit to a hold or transition while playing moves the phrases under the same view.time (the time never jumps): view.to_item and view.item_elapsed_time can jump. A press while paused is counted (view.pointer_down_time takes the paused time), and view.time - view.pointer_down_time stays 0 until play. The sequence cannot be moved from the shader or the page: there is no seek, pause or jump to a phrase.

Names: `sequence`, `phrase`, `hold`, `transition`, `loop`, `phrases`

### Settings (settings, above the canvas) (`settings`)

em per height: the type's size, one em as a fraction of the canvas's height (with an aspect, the letterboxed canvas's): 0.5 sets the font's em at half the height, and larger is bigger type. So view.px_per_em is em per height × view.resolution.y unless overflow shrinks it. overflow: what a phrase wider than the canvas does: clipped, or shrunk to fit its width. pointer: whether the shader is handed the pointer (view.pointer, view.pointer_down); off, view.pointer stays at the canvas's centre. aspect: the canvas's shape as w:h, letterboxed in the frame; empty fills it. reach: how far each glyph's distance field is exact past its outline, in em, 0.1875 (empty) to 1. Past the reach field() goes on with no flat edge, close to exact, at every engine level (field(p, k), field_from, field_to), so contour rings, a ground gradient or a glow reach the canvas's edge at the default reach. Every glyph is baked again when reach changes. Each glyph's box grows by the reach on every side, so its memory grows with about the square: at 0.5 about 2.5x, at 1 about 5-7x (about 10x for a hairline font, baked twice as fine). At 1 the lab holds about 120-145 different characters (a hairline font's about 45); past that a character is left out, which the status says. Baking and the frame's GPU time barely change. The default fits most pieces: fills, outlines, bevels, short glows and crossings. Raise it for an exact distance far from the type (contour rings, a ground gradient that follows the letters, a cast shadow, a melt across a wide gap), and only as far as the effect reaches; a soft glow or haze is cheaper and softer blurred from a texture. In a piece's file: "reach": 0.5. Each setting is saved with the piece and exported with it.

Names: `settings`, `em`, `overflow`, `pointer`, `aspect`, `reach`

### What a piece costs (beside settings) (`cost`)

Beside settings: GPU 3.20 ms · 60 fps. The first is the GPU's time per frame, the mean over the last second, timed by the GPU itself around each pass; hover it for each pass's share. The second is the frames the canvas drew in that second. The lab draws as the element does with no max-fps ("Your own page"): every frame of a 60 Hz display and every second of a 120 or 144 Hz one, so it reads 60 on a 60 or 120 Hz display and 72 on a 144 Hz one; a reading under that means a frame takes longer than the display waits. A light piece reads higher than its work, since the GPU lowers its clock when it has little to do, so compare two versions by a change of several ms, not a fraction of one. A browser that gives no GPU timestamps shows "frame" instead: the time from handing a frame to the GPU to its being done, which includes the trip there and back. What the lab allows: new code is first drawn alone on the GPU, a few frames at sizes up to the canvas's own, and when a frame of it on the canvas would take over 200 ms (about 5 fps) it is held back while the last version keeps drawing; on the canvas, over 100 ms a frame (under 10 fps), the status says it runs slowly, and nothing stops it. Both thresholds were set on an Apple M5. For scale, on that Mac at 800×400: the lab's default shader about 0.2 ms; three pieces written for the lab, each a full-canvas shade(p) with noise, waves or a CRT grid, 2–5 ms; at 60 Hz a frame has 16.7 ms.

Names: `cost`, `gpu`, `ms`, `fps`, `slow`, `performance`, `timestamp`

### inspect: a storage buffer's values (`inspect`)

Under the timeline, "inspect" opens a table of a storage buffer's elements as they stand on the GPU: choose the buffer, the first element and how many (at most 1024, fewer for a wide struct: 64 KiB a read). A struct's members are the columns, a vector's components joined by commas. It reads twice a second while "live" is ticked, paused or playing, and on "read". Each read is a copy taken after the frames already drawn and handed back a frame or two later; the canvas never waits on it. For a stateful piece: see its state as numbers rather than painting it into the frame. Storage only: a uniform you declare holds what the pipeline says.

Names: `inspect`, `storage`, `read back`, `debug`, `state`

### host.js: the embedding page's part (`host-pane`)

JavaScript given piece (write, writeTexture, layout, onFrame) and stage, run in a sandboxed frame laid over the stage: stage is that frame's body. It cannot reach the lab's page, what driftype.com keeps in your browser (your pieces, your gallery keys), or the canvas itself, and it fetches as an origin of its own. It can draw over the canvas, write into the piece, and use the processor and the network. Writes are checked as it makes them and land a frame later. The pointer over the frame's empty parts goes on to the piece. A script that stops answering for 2s is stopped. Only the lab runs it: an exported page, "export piece" and the gallery's pages never do (a gallery piece opened in the lab waits for "run host"). So a piece must look right with its host: true resources at their declared values: give it a member that says the host is there (declared 0, written 1) and draw a fallback without it. piece.write(name, data, byteOffset = 0): bytes, an ArrayBuffer or a typed array (new Float32Array([...])), not an object, into a host: true storage or uniform at byteOffset; both multiples of 4; the rest keep what they had; lands before the next frame, the last write winning. piece.writeTexture(name, source): every texel of a host: true texture, from ImageData, an ImageBitmap, a canvas, an image or RGBA bytes, at its declared size. piece.layout(name): where the bytes go, { kind, bytes, members: { m: { offset, type } } } (a storage also { length, stride, type }, a texture { width, height }), null for a resource that is not host: true; write a member at layout(name).members.m.offset. A write that cannot be done throws, saying why, and changes nothing. onFrame's rect is a DOMRect (x, y, width, height, CSS px), the canvas on the page. The script can listen on window in its frame for what the shader never gets (wheel, dblclick, keys: see the pointer entry). To move a script onto a page: piece is the <graffito-piece> element (await el.ready first), stage is document.body. Place elements with position: fixed, from rect, in every onFrame (a page scrolls and reflows, which the lab's frame never does), and test that a wheel or key is over rect before preventDefault, or it stops the whole page scrolling.

Names: `host`, `piece`, `stage`, `write`, `writeTexture`, `layout`, `onFrame`

```
// pipeline: const clock = uniform({ live: f32(0), angle: f32(0) }, { host: true });
const at = piece.layout("clock").members;            // { live: { offset: 0, type: "f32" }, angle: { offset: 4, ... } }
piece.onFrame(({ time, rect }) => {                   // rect: the canvas on the page, a DOMRect
  piece.write("clock", new Float32Array([1]), at.live.offset);            // "the host is here"
  piece.write("clock", new Float32Array([time * 0.5]), at.angle.offset);  // bytes, at a byte offset
});
// WGSL: let angle = select(view.time * 0.5, clock.angle, clock.live > 0.5);   // right without a host too
```

### piece.onFrame: the time and the sequence (`on-frame`)

piece.onFrame(({ time, rect, item, from_item, to_item, transition, loop }) => ...) runs before each frame the host script is sent: time in seconds, rect the canvas on the page, and where the sequence is. item is the phrase it is on (an index into the phrases; during a cross, the one it leaves until the next arrives); from_item and to_item the phrases being left and entered, equal while holding; transition 0..1 across a cross, 0 while holding; loop how many times a looping sequence has wrapped. It also has the shader's view members of the same names, this frame's: time_slice, frame_count, item_elapsed_time, item_hold_time, item_transition_time, loop_count, reduced_motion and pointer_type (see view). On a page, <graffito-piece> fires events when these change, not every frame: graffito-item (detail.item: a phrase arrives), graffito-cross (detail.from_item, detail.to_item: a cross begins) and graffito-loop (detail.loop: the sequence wraps, before phrase 0's graffito-item), each with detail.time. Each is fired on the first frame drawn past its moment (a frame late at most), and only for what that frame sees: a phrase held for less than a frame (a hold of 0) gets no graffito-item, and a cut (a transition of 0) no graffito-cross, only the next phrase's graffito-item. After a restart, or a frame that stalled (it steps at most 0.1 s), only where it lands is said, once. For a sound on a phrase, listen for graffito-item. Nothing comes back from the shader. An element taken off the page and put back, or given a new src, drops the onFrame callbacks given before: give them again once it plays (a new el.ready).

Names: `onFrame`, `item`, `from_item`, `to_item`, `loop`, `graffito-item`, `graffito-cross`, `graffito-loop`, `sound`, `event`

## The page around a piece

### Your own page: the graffito-piece element (`embed`)

"export piece" writes a zip for your own site. Its folder holds the piece (a .json file named for it), the element that plays it (graffito-piece.js) and its engine (piece.wasm), to keep side by side, an index.html that plays it and lists what its page may write, and settings-panel.js when the piece has settings. Beside the folder is the piece as a .lab.json, for the lab's "open a file…". Serve the folder from any web server: a page opened from disk cannot fetch the piece. On your page, load graffito-piece.js as a module script and put the element where the piece goes, its src the piece's file, as below. What the element holds shows when the piece cannot play. Put that text in an element, as below: bare text is not hidden while the piece plays, and shows through a see-through ground. The element is the piece: await el.ready (it rejects, with the reason, when the piece cannot play: no WebGPU, a GPU reset, a piece made for another engine), then el.write(name, data, byteOffset), el.writeTexture(name, source), el.layout(name) and el.onFrame(cb) work as host.js's piece does; before ready they throw. They reach only the pipeline's host: true resources, which hold their declared values until the page writes them. The lab's host pane rehearses this. Page layout: a point the page writes is in CSS px from the viewport's top left, what getBoundingClientRect gives. The shader turns it into em with page_point(point), and a CSS length with page_length(length). view.canvas_rect (the canvas on the page) and view.px_per_css are measured every frame; onFrame's rect is that same rect, a DOMRect. Write from onFrame, which runs before every frame, so a shape follows its element through scrolling and reflow. Events on the element: graffito-ready; graffito-error (detail.reason); and as the sequence moves, graffito-item, graffito-cross and graffito-loop (piece.onFrame: the time and the sequence). Taken off the page and put back, the element starts afresh with a new el.ready, and the onFrame callbacks given before are dropped: give them again. Frames: the element draws on every k-th frame the display shows, the largest k that keeps about max-fps a second or more (60 when max-fps is absent), so from max-fps up to about twice it. Under 60, a 60, 75 or 90 Hz display draws every frame and a 120 or 144 Hz one every second (60 or 72 a second). max-fps="30" draws 30 a second at 60 Hz and every frame at 50 Hz; max-fps="0" draws every frame the display shows. A change to it takes at once. The piece's time runs as before: a frame drawn after a skipped one takes the time of both (view.time_slice). Below, a button's rect fed into the piece: the type melts into the button where it lies over the canvas.

Names: `embed`, `graffito-piece`, `export piece`, `zip`, `your page`, `website`, `ready`, `write`, `writeTexture`, `layout`, `onFrame`, `page_point`, `page_length`, `canvas_rect`, `px_per_css`, `getBoundingClientRect`, `graffito-ready`, `graffito-error`, `graffito-item`, `graffito-cross`, `graffito-loop`, `button`, `max-fps`, `frame rate`

```
// pipeline.js: a uniform the page writes, read by the render pass
const ui = uniform({ live: f32(0), button: vec4f(0, 0, 0, 0) }, { host: true });
return pipeline({
  resources: { ui },
  passes: [render("draw", { reads: [ui], vertex: "graffito_vs", fragment: "graffito_fs", draw: { vertices: 3 } })],
});

// shade.wgsl
// The button's rect as a box in em, positive inside, as field() is.
fn button_box(p: vec2f) -> f32 {
    let lo = page_point(ui.button.xy);                   // its top left
    let hi = page_point(ui.button.xy + ui.button.zw);    // its bottom right (in em, y is up)
    let q = abs(p - (lo + hi) * 0.5) - abs(hi - lo) * 0.5;
    return -(length(max(q, vec2f(0.0))) + min(max(q.x, q.y), 0.0));
}

fn shade(p: vec2f) -> vec4f {
    var d = field(p, 0.03);
    if (ui.live > 0.5) { d = smooth_max(d, button_box(p), 0.2); }   // the button melts into the type
    let aa = 0.5 / view.px_per_em;
    let ink = smoothstep(-aa, aa, d);
    return vec4f(mix(vec3f(0.96, 0.95, 0.92), vec3f(0.1, 0.1, 0.15), ink), 1.0);
}

<!-- your page, beside graffito-piece.js, piece.wasm and the piece -->
<script type="module" src="graffito-piece.js"></script>
<graffito-piece src="my-piece.json"><span>Shown when the piece cannot play.</span></graffito-piece>
<button id="go">Go</button>
<script type="module">
const el = document.querySelector("graffito-piece");
const button = document.getElementById("go");
await el.ready;                                         // rejects, with the reason, if it cannot play
const at = el.layout("ui").members;                     // { live: { offset: 0, type: "f32" }, button: { offset: 16, ... } }
el.write("ui", new Float32Array([1]), at.live.offset);  // the page is here
el.onFrame(() => {                                      // before every frame, so it follows scrolls and reflows
  const r = button.getBoundingClientRect();             // CSS px from the viewport's top left
  el.write("ui", new Float32Array([r.x, r.y, r.width, r.height]), at.button.offset);
});
</script>
```

### page_boxes: the page's own elements in the field (`page-boxes`)

A pipeline that declares a resource named page_boxes, a host: true storage of a struct with exactly the members rect: vec4f, radius: f32, kind: f32, hover: f32, press: f32 (1 to 64 of them), is written by graffito-piece every frame with no script of the page's: one box for each element on the page marked data-field. rect is the element's x, y, width, height in CSS px (page_box(p, b.rect, b.radius) turns one into a distance), radius its corners; kind is what data-field says: "" or shape 0 (a button: part of the field), clear 1 (text the piece should keep calm under, so it can be read), panel 2 (a section the field docks to), anchor 3 (where the page wants the type: move the field there); hover and press go from 0 to 1, eased, while the pointer is over the element and while it is pressed. The boxes come in the page's order, and the first of zero width ends them. In the lab nothing writes them: the piece must still look right with none. With <graffito-piece fullwindow> the piece is the page's background, behind everything the page draws, and the first box is the window itself (kind 4): the canvas is fixed over the window and reaches past it above and below; the boxes follow the page as it scrolls, a frame behind while it moves. Add fit="cover" (or fit="contain") and a piece with an aspect keeps it there: the canvas is the smallest box of its shape over the window (or the largest inside it), centred, the rest cut off (or the page around it), with no reach past the window. field-scope="main" on the element (any CSS selector) follows only the marked elements that match it or sit inside an element that does; field-scope="" follows none; without it, the whole document. On the site the header sits 12 px from the window's top, left and right (10 px at the sides on a phone): an ornament outside a box fits there or gives way.

Names: `page_boxes`, `PageBox`, `data-field`, `fullwindow`, `background`, `anchor`, `clear`, `panel`, `window`, `hover`, `press`, `field-scope`

```
// pipeline.js
const PageBox = struct({ rect: vec4f, radius: f32, kind: f32, hover: f32, press: f32 });
const page_boxes = storage(PageBox, { length: 32, host: true });
return pipeline({
  types: { PageBox },
  resources: { page_boxes },
  passes: [render("draw", { reads: [page_boxes], vertex: "graffito_vs", fragment: "graffito_fs", draw: { vertices: 3 } })],
});

// shade.wgsl: the type, and every shape the page marked, melted together
fn shade(p: vec2f) -> vec4f {
    var d = field(p, 0.03);
    for (var i = 0u; i < arrayLength(&page_boxes); i++) {
        let b = page_boxes[i];
        if (b.rect.z <= 0.0) { break; }                  // the end
        if (b.kind == 0.0) {
            d = smooth_max(d, page_box(p, b.rect, b.radius), page_length(8.0 + 40.0 * b.hover));
        }
    }
    let aa = 0.5 / view.px_per_em;
    return vec4f(mix(vec3f(0.96, 0.95, 0.92), vec3f(0.1, 0.1, 0.15), smoothstep(-aa, aa, d)), 1.0);
}

<!-- your page -->
<graffito-piece src="my-piece.json" fullwindow></graffito-piece>
<a href="/shop" data-field>shop</a>
<p data-field="clear">Text the piece keeps calm under.</p>
```

### page: the page around the piece (page_join) (`page-join`)

page (engine level 13) is the capability a code unit uses for a piece played among a page's panels, as the site's styles are. The piece's host hands it the page's boxes each frame, at most 64: <graffito-piece> its [data-field] elements (those field-scope follows, the window's own box first with fullwindow, the anchor even off the canvas); the lab and an exported page hand none, and with none the piece plays as any other. graffito_page holds them, an array<GraffitoPageBox, 64>, GraffitoPageBox { rect: vec4f, radius: f32, kind: f32, hover: f32, press: f32 } as page_boxes lays them out (rect x, y, width, height in CSS px from the viewport's top left; kind 0 shape, 1 clear, 2 panel, 3 anchor, 4 window; hover and press 0..1, eased), the first of no width ending them. The engine reads them twice. The type is laid into the first anchor box as into a canvas of that box's size (the piece's em per height taken of the box's height, fit_width within 85% of its width, centred on it; without an anchor, the canvas's), following it every frame, and view.pointer and the light grid with it: shade's p needs no moving, and page_point() of a box's rect is where that box is. And in a unit that uses glyphs and page, field() and its family (field_from, field_to, the field_cross and field_slope functions) join the panels and shapes to the letters over k em as the letters join each other (smooth_max; max at k 0), each swelling 6 CSS px as its hover goes to 1 and shrinking 2 as its press does; a clear cuts the letters alone, before the join, no deeper than -0.1875 em, so text inside a joined panel is the panel's. Anchors and the window are the piece's to read. page_join(p, d, k) is that join on a distance of the unit's own, page_join_slope(p, d, k) on a field_slope-style vec3f. The engine makes graffito_page only when a unit uses page, one more storage buffer in a pass whose unit does. The page's shapes (page_shapes_join) are not such a piece's: <graffito-piece> ignores page-shapes for it.

Names: `page_join`, `page_join_slope`, `graffito_page`, `GraffitoPageBox`, `anchor`

```
// code unit "draw", uses ["glyphs", "page"]: the letters, the page's panels and shapes joined
fn shade(p: vec2f) -> vec4f {
    let d = field(p, 0.04);
    let aa = 0.7 / view.px_per_em;
    return vec4f(mix(vec3f(0.96, 0.95, 0.92), vec3f(0.1, 0.1, 0.15), smoothstep(-aa, aa, d)), 1.0);
}
// a unit that uses page alone joins them to a distance of its own:
// let d = page_join(p, 0.3 - length(p - view.pointer), 0.1);

<!-- the page -->
<graffito-piece src="my-piece.json" fullwindow field-scope="main"></graffito-piece>
<main>
  <div class="hero" data-field="anchor"></div>
  <section data-field="panel"><p>Text inside a panel is the panel's.</p></section>
</main>
```

### the page's shapes (page_shapes_join) (`page-shapes`)

Shapes a page hands the engine (<graffito-piece page-shapes>: its [data-field] elements, the title page's panels and the shapes drawn there), joined to the text by field_from, field_to, field() and the field_cross functions, so whatever a piece does to its type it does to them, with no code of its own. view.page_shape_count is 0 unless a page sets some (the lab, the gallery and an export set none), and then every field function is as it was. Each shape is two of view.page_shapes: its rect (x, y, width, height in CSS px, as page_box takes it), then its radius, kind, hover and press. Kinds 0 (a shape) and 2 (a panel) join with smooth_max over view.page_shape_blend CSS px, swelling 6 px as hover goes to 1; kind 1 (clear) cuts after every join, no deeper than the text's own floor. page_shapes_join(p, d) is that join on a distance of your own, and page_shapes_join_slope(p, d) on a field_slope-style vec3f (the distance and its slope; engine level 4); both give d back as it came while there are none. A piece that declares page_boxes reads the page itself and is handed none, and so is one some code unit of which uses page: the engine joins the page for it (page_join). <graffito-piece field-scope="main"> hands only the marked elements that match the selector or sit inside an element that does (field-scope="" none); a page that marks elements and sets neither is warned on the console, once for each such element. graffito_field and graffito_placed_distance are the glyphs alone.

Names: `page_shapes`, `page_shapes_join`, `page_shapes_join_slope`, `page_shape_count`, `page_shape_blend`, `page-shapes`, `field-scope`

```
let text_only = graffito_field(p, 0.0, 0u, graffito_placed.count);   // no page shapes
let with_page = field(p, 0.0);                                      // the page's shapes joined
```

## Whole pieces to start from

Each is one of the lab's examples as a complete piece: copy it, change the
phrases and the WGSL. All of the lab's examples, to open in a tab of their
own, are listed after these.

### Shading the field (example `fill`)

shade(p) is asked for one color per pixel. field(p, 0.0) says how far p is from the outline, positive inside a letter: everything else is built on that number.

```json
{
  "format": "driftype-lab/6",
  "id": "Shading the field",
  "about": "shade(p) is asked for one color per pixel. field(p, 0.0) says how far p is from the outline, positive inside a letter: everything else is built on that number.",
  "sequence": [
    {
      "text": "CALM",
      "hold": 2,
      "transition": 1,
      "font": 0
    }
  ],
  "loop": false,
  "type": {
    "em_per_height": 0.45,
    "overflow": "fit_width"
  },
  "inputs": {
    "pointer": false
  },
  "fonts": [
    "Anton"
  ],
  "pipeline": {
    "version": 1,
    "resources": {},
    "passes": [
      {
        "name": "draw",
        "kind": "render",
        "vertex": "graffito_vs",
        "fragment": "graffito_fs",
        "draw": {
          "vertices": 3
        },
        "code": "draw"
      }
    ]
  },
  "pipeline_js": "// One render pass over the canvas. graffito_vs and graffito_fs are the\n// engine's: graffito_fs calls shade(p) for every pixel.\nreturn pipeline({\n  passes: [\n    render(\"draw\", { vertex: \"graffito_vs\", fragment: \"graffito_fs\", draw: { vertices: 3 } }),\n  ],\n});\n",
  "wgsl": null,
  "code": {
    "draw": {
      "uses": [
        "glyphs"
      ],
      "wgsl": "// p is a point in em: the baseline is y = 0, and one em is the font's size.\n// field(p, 0.0) is the phrase's signed distance: positive inside a letter,\n// negative outside, zero on the outline.\nfn shade(p: vec2f) -> vec4f {\n    let d = field(p, 0.0);\n\n    // Half a pixel, in em. Going from paper to ink across it, rather than at\n    // d = 0 exactly, gives the edge its anti-aliasing.\n    let aa = 0.5 / view.px_per_em;\n    let inside = smoothstep(-aa, aa, d);\n\n    // A color that changes along the phrase, from p.x alone.\n    let paper = vec3f(0.95, 0.93, 0.88);\n    let ink = mix(vec3f(0.85, 0.2, 0.3), vec3f(0.2, 0.3, 0.85), 0.5 + 0.5 * sin(p.x * 1.5));\n    return vec4f(mix(paper, ink, inside), 1.0);\n}\n"
    }
  }
}
```

### Following the pointer (example `pointer`)

view.pointer is where the pointer is over the canvas, in em like p, and view.pointer_down is 1 while a button is held. The letters swell towards it; press to reach further. A piece reads it only with the pointer setting on, which this example turns on.

```json
{
  "format": "driftype-lab/6",
  "id": "Following the pointer",
  "about": "view.pointer is where the pointer is over the canvas, in em like p, and view.pointer_down is 1 while a button is held. The letters swell towards it; press to reach further. A piece reads it only with the pointer setting on, which this example turns on.",
  "sequence": [
    {
      "text": "TOUCH",
      "hold": 2,
      "transition": 1,
      "font": 0
    }
  ],
  "loop": false,
  "type": {
    "em_per_height": 0.45,
    "overflow": "fit_width"
  },
  "inputs": {
    "pointer": true
  },
  "fonts": [
    "Anton"
  ],
  "pipeline": {
    "version": 1,
    "resources": {},
    "passes": [
      {
        "name": "draw",
        "kind": "render",
        "vertex": "graffito_vs",
        "fragment": "graffito_fs",
        "draw": {
          "vertices": 3
        },
        "code": "draw"
      }
    ]
  },
  "pipeline_js": "// One pass: the pointer is in the WGSL, through view.\nreturn pipeline({\n  passes: [\n    render(\"draw\", { vertex: \"graffito_vs\", fragment: \"graffito_fs\", draw: { vertices: 3 } }),\n  ],\n});\n",
  "wgsl": null,
  "code": {
    "draw": {
      "uses": [
        "glyphs"
      ],
      "wgsl": "fn shade(p: vec2f) -> vec4f {\n    // view.pointer is in em, in p's space, so p - view.pointer is how far this\n    // pixel is from it. Until the pointer moves over the canvas it rests at\n    // the centre.\n    let r = length(p - view.pointer);\n\n    // Pressed, the swell reaches further.\n    let reach = select(0.35, 0.7, view.pointer_down != 0u);\n    let swell = 0.08 * exp(-(r * r) / (reach * reach));\n\n    // Adding to the distance moves the outline outwards: the letters grow.\n    let d = field(p, 0.03) + swell;\n    let aa = 0.5 / view.px_per_em;\n    let inside = smoothstep(-aa, aa, d);\n\n    // A small ring where the pointer is, to see what the engine was told.\n    let ring = 1.0 - smoothstep(aa, 2.0 * aa, abs(r - 0.05));\n\n    let paper = vec3f(0.96, 0.95, 0.92);\n    let ink = mix(vec3f(0.1, 0.1, 0.15), vec3f(0.9, 0.3, 0.1), swell / 0.08);\n    return vec4f(mix(mix(paper, ink, inside), vec3f(0.1, 0.4, 0.9), ring), 1.0);\n}\n"
    }
  }
}
```

### State that lasts: trails (example `trails`)

A storage buffer keeps what a pass wrote into the next frame, so a piece can remember. A compute pass fades a grid of cells and lights the ones under the swaying phrase; the render pass draws the grid.

```json
{
  "format": "driftype-lab/6",
  "id": "State that lasts: trails",
  "about": "A storage buffer keeps what a pass wrote into the next frame, so a piece can remember. A compute pass fades a grid of cells and lights the ones under the swaying phrase; the render pass draws the grid.",
  "sequence": [
    {
      "text": "DRIFT",
      "hold": 2,
      "transition": 1,
      "font": 0
    }
  ],
  "loop": false,
  "type": {
    "em_per_height": 0.45,
    "overflow": "fit_width"
  },
  "inputs": {
    "pointer": false
  },
  "fonts": [
    "Anton"
  ],
  "pipeline": {
    "version": 1,
    "constants": [
      "GRID_W: u32 = 640",
      "GRID_H: u32 = 320"
    ],
    "resources": {
      "trail": {
        "kind": "storage",
        "element": "f32",
        "length": 204800
      }
    },
    "passes": [
      {
        "name": "advance",
        "kind": "compute",
        "writes": [
          "trail"
        ],
        "workgroup_size": 64,
        "dispatch": {
          "over": "trail"
        },
        "entry": "advance",
        "code": "advance"
      },
      {
        "name": "draw",
        "kind": "render",
        "reads": [
          "trail"
        ],
        "vertex": "graffito_vs",
        "fragment": "graffito_fs",
        "draw": {
          "vertices": 3
        },
        "code": "draw"
      }
    ]
  },
  "pipeline_js": "// A grid of cells, one f32 each, on the GPU. Nothing clears a storage\n// buffer between frames: what \"advance\" writes is there the next frame, and\n// that is how a piece keeps state. The constants reach both passes' WGSL.\nconst W = 640, H = 320;\nconst trail = storage(f32, W * H);\nreturn pipeline({\n  constants: { GRID_W: u32(W), GRID_H: u32(H) },\n  resources: { trail },\n  passes: [\n    compute(\"advance\", { writes: [trail], over: trail, workgroupSize: 64, entry: \"advance\" }),\n    render(\"draw\", { reads: [trail], vertex: \"graffito_vs\", fragment: \"graffito_fs\", draw: { vertices: 3 } }),\n  ],\n});\n",
  "wgsl": null,
  "code": {
    "advance": {
      "uses": [
        "glyphs"
      ],
      "wgsl": "// The grid covers the canvas. A cell's centre as a point in em, the way\n// graffito_fs maps a pixel.\nfn cell_point(i: u32) -> vec2f {\n    let cell = vec2f(f32(i % GRID_W), f32(i / GRID_W)) + 0.5;\n    let pixel = cell / vec2f(f32(GRID_W), f32(GRID_H)) * view.resolution;\n    return view.origin + vec2f(pixel.x, -pixel.y) / view.px_per_em;\n}\n\n// One invocation per cell, every frame: fade what was there, then light the\n// cell if the phrase covers it now. The fade is by time, not by frame:\n// 0.98 a sixtieth of a second, raised to the frame's time_slice, so the\n// trails are as long at 120 Hz as at 60, and hold still while paused\n// (time_slice is 0 then).\n@compute @workgroup_size(WORKGROUP_SIZE)\nfn advance(@builtin(global_invocation_id) gid: vec3u) {\n    let i = gid.x;\n    if (i >= arrayLength(&trail)) { return; }\n    let sway = vec2f(0.2 * sin(view.time * 1.3), 0.08 * sin(view.time * 2.1));\n    let now = select(0.0, 1.0, field(cell_point(i) - sway, 0.0) > 0.0);\n    trail[i] = max(trail[i] * pow(0.98, 60.0 * view.time_slice), now);\n}\n"
    },
    "draw": {
      "uses": [],
      "wgsl": "// The cell under p: graffito_fs's mapping, run backwards.\nfn shade(p: vec2f) -> vec4f {\n    let pixel = (p - view.origin) * view.px_per_em * vec2f(1.0, -1.0);\n    let grid = vec2f(f32(GRID_W), f32(GRID_H));\n    let cell = vec2u(clamp(pixel / view.resolution * grid, vec2f(0.0), grid - 1.0));\n    let heat = trail[cell.y * GRID_W + cell.x];\n\n    let paper = vec3f(0.04, 0.03, 0.06);\n    let color = paper + heat * mix(vec3f(0.5, 0.1, 0.6), vec3f(1.0, 0.75, 0.35), heat * heat);\n    return vec4f(color, 1.0);\n}\n"
    }
  }
}
```

### Light on a fixed clock: sparks (example `sparks`)

The engine keeps light for you (light_grid) and a fixed clock (step: {}). Sparks lift off the letters' upper edges; two compute passes marked step run once per step, 120 a second however fast the screen draws, so a spark lands in the same place at 30, 60 or 144 Hz. A spark never draws itself: it lays the path it flew into the light grid, and only the engine's fade takes light away. The draw reads the grid. Press to throw a ring of sparks.

```json
{
  "format": "driftype-lab/6",
  "id": "Light on a fixed clock: sparks",
  "about": "The engine keeps light for you (light_grid) and a fixed clock (step: {}). Sparks lift off the letters' upper edges; two compute passes marked step run once per step, 120 a second however fast the screen draws, so a spark lands in the same place at 30, 60 or 144 Hz. A spark never draws itself: it lays the path it flew into the light grid, and only the engine's fade takes light away. The draw reads the grid. Press to throw a ring of sparks.",
  "sequence": [
    {
      "text": "SPARK",
      "hold": 2,
      "transition": 1,
      "font": 0
    }
  ],
  "loop": false,
  "type": {
    "em_per_height": 0.45,
    "overflow": "fit_width"
  },
  "inputs": {
    "pointer": true
  },
  "fonts": [
    "Anton"
  ],
  "pipeline": {
    "version": 1,
    "types": {
      "Spark": [
        "pos: vec2f",
        "vel: vec2f",
        "age: f32",
        "life: f32"
      ],
      "Clock": [
        "press: f32",
        "next: u32"
      ]
    },
    "constants": [
      "SPARKS: u32 = 4096",
      "PER_STEP: u32 = 3",
      "BURST: u32 = 96"
    ],
    "resources": {
      "sparks": {
        "kind": "storage",
        "element": "Spark",
        "length": 4096
      },
      "clock": {
        "kind": "storage",
        "element": "Clock",
        "length": 1
      }
    },
    "passes": [
      {
        "name": "spawn",
        "kind": "compute",
        "step": {},
        "writes": [
          "clock",
          "sparks"
        ],
        "workgroup_size": 1,
        "dispatch": {
          "size": [
            1,
            1
          ]
        },
        "entry": "spawn",
        "code": "spawn"
      },
      {
        "name": "fly",
        "kind": "compute",
        "step": {},
        "writes": [
          "sparks"
        ],
        "workgroup_size": 64,
        "dispatch": {
          "over": "sparks"
        },
        "entry": "fly",
        "code": "fly"
      },
      {
        "name": "draw",
        "kind": "render",
        "vertex": "graffito_vs",
        "fragment": "graffito_fs",
        "draw": {
          "vertices": 3
        },
        "code": "draw"
      }
    ],
    "light_grid": {
      "fade": 0.8
    }
  },
  "pipeline_js": "// The sparks live in a storage buffer, a pool the GPU keeps between frames.\n// light_grid asks the engine for its light grid: light the compute passes\n// lay, that only the engine's fade lowers (fade: its time constant, s).\n// step: {} puts a compute pass on the engine's fixed clock.\nconst SPARKS = 4096;\nconst Spark = struct({ pos: vec2f, vel: vec2f, age: f32, life: f32 });\nconst Clock = struct({ press: f32, next: u32 });\nconst sparks = storage(Spark, SPARKS);\nconst clock = storage(Clock, 1);\nreturn pipeline({\n  types: { Spark, Clock },\n  constants: { SPARKS: u32(SPARKS), PER_STEP: u32(3), BURST: u32(96) },\n  resources: { sparks, clock },\n  light_grid: { fade: 0.8 },\n  passes: [\n    compute(\"spawn\", { writes: [clock, sparks], size: [1, 1], workgroupSize: 1, entry: \"spawn\", step: {} }),\n    compute(\"fly\", { writes: [sparks], over: sparks, workgroupSize: 64, entry: \"fly\", step: {} }),\n    render(\"draw\", { vertex: \"graffito_vs\", fragment: \"graffito_fs\", draw: { vertices: 3 } }),\n  ],\n});\n",
  "wgsl": null,
  "code": {
    "spawn": {
      "uses": [
        "glyphs",
        "steps"
      ],
      "wgsl": "// Once a step, one invocation: a few new sparks into the pool, each taking\n// the oldest one's place (one cut short just stops; the light it laid stays).\n// graffito_restart() is true on a restart (the first frame, a new build, the\n// restart button): empty the pool then, as the engine clears its grid. The\n// seeds come from the step count, never view.time, so every frame rate\n// spawns the same sparks.\n@compute @workgroup_size(WORKGROUP_SIZE)\nfn spawn() {\n    if (graffito_restart()) {\n        clock[0] = Clock(-1.0, 0u);\n        for (var i = 0u; i < SPARKS; i++) { sparks[i].life = 0.0; }\n        return;\n    }\n    var c = clock[0];\n    let corner = view.origin;   // the canvas's top left, in em\n    let size = view.resolution / view.px_per_em;\n    for (var j = 0u; j < PER_STEP; j++) {\n        // A random point on the canvas; in the ink, the outline is s.x away\n        // against the slope (field_slope's yz points inward). Kept where the\n        // edge faces up, so the sparks lift off the letters' tops.\n        for (var t = 0u; t < 16u; t++) {\n            let h = ((graffito_steps() * PER_STEP + j) * 16u + t) * 3u;\n            let q = corner + vec2f(graffito_rand(h), -graffito_rand(h + 1u)) * size;\n            let s = field_slope(q, 0.0);\n            let out = -s.yz / max(length(s.yz), 1e-3);\n            if (s.x > 0.0 && out.y > 0.5) {\n                let edge = q + out * (s.x + 0.005);\n                sparks[c.next % SPARKS] = Spark(edge, 0.15 * out, 0.0, mix(1.0, 2.2, graffito_rand(h + 2u)));\n                c.next++;\n                break;\n            }\n        }\n    }\n    // A new press (its time changed) throws a ring from where it landed.\n    if (view.pointer_down_time >= 0.0 && view.pointer_down_time != c.press) {\n        c.press = view.pointer_down_time;\n        for (var j = 0u; j < BURST; j++) {\n            let h = (c.next + j) * 3u + 1u;\n            let a = 6.2831853 * (f32(j) + graffito_rand(h)) / f32(BURST);\n            let v = mix(0.5, 1.3, graffito_rand(h + 1u)) * vec2f(cos(a), sin(a));\n            sparks[(c.next + j) % SPARKS] = Spark(view.pointer_down_pos, v, 0.0, mix(0.7, 1.3, graffito_rand(h + 2u)));\n        }\n        c.next += BURST;\n    }\n    clock[0] = c;\n}\n"
    },
    "fly": {
      "uses": [
        "steps",
        "light_grid_add"
      ],
      "wgsl": "// Once a step, one invocation a spark: lift, a sideways sway and drag move\n// it by view.step_dt, the step's length; then the path it flew this step goes\n// into the light grid, warm, dimmer with age. A spark only ever adds light.\n@compute @workgroup_size(WORKGROUP_SIZE)\nfn fly(@builtin(global_invocation_id) id: vec3u) {\n    if (id.x >= SPARKS || graffito_restart()) { return; }\n    var s = sparks[id.x];\n    if (s.age >= s.life) { return; }\n    let sway = sin(s.pos.y * 9.0 + f32(id.x) * 1.7 + graffito_step_time() * 2.0);\n    s.vel += (vec2f(0.4 * sway, 0.7) - 1.5 * s.vel) * view.step_dt;\n    let was = s.pos;\n    s.pos += s.vel * view.step_dt;\n    s.age += view.step_dt;\n    let warmth = 1.0 - s.age / s.life;\n    graffito_light_line(was, s.pos, vec3f(1.0, 0.5, 0.18) * warmth * warmth);\n    sparks[id.x] = s;\n}\n"
    },
    "draw": {
      "uses": [
        "glyphs",
        "light_grid"
      ],
      "wgsl": "// 1 - e^-x: light that rises towards white and never past it.\nfn rising_light(x: vec3f) -> vec3f {\n    return 1.0 - exp(-max(x, vec3f(0.0)));\n}\n\n// The draw reads only the grid (graffito_light, smooth), no loop over the\n// sparks. The ground is the light itself; a thin band inside the letters'\n// edge takes the light just past it, so a spark lifting off lights the edge\n// it left.\nfn shade(p: vec2f) -> vec4f {\n    let s = field_slope(p, 0.0);   // the distance and, in yz, its slope\n    let out = -s.yz / max(length(s.yz), 1e-3);   // away from the letters\n    let near = graffito_light(p + out * (max(s.x, 0.0) + 0.02));\n    let rim = 1.0 - smoothstep(0.0, 0.04, s.x);\n    let ground = vec3f(0.03, 0.03, 0.06) + rising_light(graffito_light(p) * 3.0);\n    let face = vec3f(0.12, 0.1, 0.1) + rising_light(near * rim * 3.0);\n    let ink = clamp(s.x * view.px_per_em + 0.5, 0.0, 1.0);\n    return vec4f(mix(ground, face, ink), 1.0);\n}\n"
    }
  }
}
```

### The page draws in: host writes (example `host`)

A resource marked host: true can be written by the page the piece is embedded in. Here the host pane plays that page: it puts a ring over the canvas you can drag, and every frame writes where it is into discs. The shader melts that disc into the letters.

```json
{
  "format": "driftype-lab/6",
  "id": "The page draws in: host writes",
  "about": "A resource marked host: true can be written by the page the piece is embedded in. Here the host pane plays that page: it puts a ring over the canvas you can drag, and every frame writes where it is into discs. The shader melts that disc into the letters.",
  "sequence": [
    {
      "text": "MELT",
      "hold": 2,
      "transition": 1,
      "font": 0
    }
  ],
  "loop": false,
  "type": {
    "em_per_height": 0.45,
    "overflow": "fit_width"
  },
  "inputs": {
    "pointer": false
  },
  "fonts": [
    "Anton"
  ],
  "pipeline": {
    "version": 1,
    "types": {
      "Disc": [
        "center: vec2f",
        "radius: f32",
        "pad: f32"
      ]
    },
    "resources": {
      "discs": {
        "kind": "storage",
        "element": "Disc",
        "length": 1,
        "host": true
      }
    },
    "passes": [
      {
        "name": "draw",
        "kind": "render",
        "reads": [
          "discs"
        ],
        "vertex": "graffito_vs",
        "fragment": "graffito_fs",
        "draw": {
          "vertices": 3
        },
        "code": "draw"
      }
    ]
  },
  "pipeline_js": "// One disc the page places. host: true lets the page write discs while the\n// piece runs; until it does, it holds its declared value, all zeros.\nconst Disc = struct({ center: vec2f, radius: f32, pad: f32 });\nconst discs = storage(Disc, { length: 1, host: true });\nreturn pipeline({\n  types: { Disc },\n  resources: { discs },\n  passes: [\n    render(\"draw\", { reads: [discs], vertex: \"graffito_vs\", fragment: \"graffito_fs\", draw: { vertices: 3 } }),\n  ],\n});\n",
  "wgsl": null,
  "code": {
    "draw": {
      "uses": [
        "glyphs"
      ],
      "wgsl": "// discs[0] is a circle on the page: centre and radius in CSS px, as\n// getBoundingClientRect measures them. page_point and page_length turn them\n// into em, where p is.\nfn shade(p: vec2f) -> vec4f {\n    let disc = discs[0];\n    // Positive inside, as field is.\n    let circle = page_length(disc.radius) - distance(p, page_point(disc.center));\n    // The union of the two, melted together over 0.15 em.\n    let d = smooth_max(field(p, 0.03), circle, 0.15);\n\n    let aa = 0.5 / view.px_per_em;\n    let inside = smoothstep(-aa, aa, d);\n    let paper = vec3f(0.96, 0.95, 0.92);\n    let ink = vec3f(0.1, 0.1, 0.15);\n    return vec4f(mix(paper, ink, inside), 1.0);\n}\n"
    }
  },
  "host_js": "// A ring to drag over the canvas: plain DOM, as any page has. stage is the\n// body of a sandboxed frame over the canvas, made anew each time this runs.\nconst ring = document.createElement(\"div\");\nring.style.cssText = \"position: absolute; left: 40%; top: 30%; width: 80px; height: 80px;\"\n  + \" border-radius: 50%; border: 2px dashed #d33; cursor: grab; touch-action: none\";\nstage.append(ring);\n\nlet grab = null;\nring.addEventListener(\"pointerdown\", (e) => {\n  grab = { x: e.clientX - ring.offsetLeft, y: e.clientY - ring.offsetTop };\n  ring.setPointerCapture(e.pointerId);\n});\nring.addEventListener(\"pointermove\", (e) => {\n  if (!grab) return;\n  ring.style.left = `${e.clientX - grab.x}px`;\n  ring.style.top = `${e.clientY - grab.y}px`;\n});\nring.addEventListener(\"pointerup\", () => { grab = null; });\n\n// Every frame, where the ring is on the page into discs[0]: centre x, centre\n// y, radius, pad, four f32s, as the pipeline's Disc lays them out.\npiece.onFrame(() => {\n  const r = ring.getBoundingClientRect();\n  piece.write(\"discs\", new Float32Array([r.x + r.width / 2, r.y + r.height / 2, r.width / 2, 0]));\n});\n"
}
```

## Every example in the lab

- **Shading the field** (`example-fill`), https://driftype.com/lab?example=fill: shade(p) is asked for one color per pixel. field(p, 0.0) says how far p is from the outline, positive inside a letter: everything else is built on that number.
- **Moving with view.time** (`example-motion`), https://driftype.com/lab?example=motion: view.time is seconds since the piece started. Move p before asking for the field and the letters move with it; change k and they fuse.
- **Outlines and glow** (`example-outline`), https://driftype.com/lab?example=outline: The distance is a number everywhere, not only on the letters: a band around zero is an outline, and a falloff outside is a glow, all in one pass.
- **Melting into the edge** (`example-frame`), https://driftype.com/lab?example=frame: view_frame(p, inset, radius) is the canvas's own edge as a distance, positive inside the view. Turned inside out it is a wall, and smooth_max melts the letters into it as it would two letters: here the wall breathes in until the type runs into it.
- **Following the pointer** (`example-pointer`), https://driftype.com/lab?example=pointer: view.pointer is where the pointer is over the canvas, in em like p, and view.pointer_down is 1 while a button is held. The letters swell towards it; press to reach further. A piece reads it only with the pointer setting on, which this example turns on.
- **Chaining render passes** (`example-chain`), https://driftype.com/lab?example=chain: A pass can draw into a texture instead of the canvas, and a later pass can sample it: here a glow made of 16 taps around each pixel. Each pass has a tab of its own in the WGSL pane.
- **State that lasts: trails** (`example-trails`), https://driftype.com/lab?example=trails: A storage buffer keeps what a pass wrote into the next frame, so a piece can remember. A compute pass fades a grid of cells and lights the ones under the swaying phrase; the render pass draws the grid.
- **Light on a fixed clock: sparks** (`example-sparks`), https://driftype.com/lab?example=sparks: The engine keeps light for you (light_grid) and a fixed clock (step: {}). Sparks lift off the letters' upper edges; two compute passes marked step run once per step, 120 a second however fast the screen draws, so a spark lands in the same place at 30, 60 or 144 Hz. A spark never draws itself: it lays the path it flew into the light grid, and only the engine's fade takes light away. The draw reads the grid. Press to throw a ring of sparks.
- **The page draws in: host writes** (`example-host`), https://driftype.com/lab?example=host: A resource marked host: true can be written by the page the piece is embedded in. Here the host pane plays that page: it puts a ring over the canvas you can drag, and every frame writes where it is into discs. The shader melts that disc into the letters.
- **Blobs you can drag** (`example-blobs`), https://driftype.com/lab?example=blobs: Shapes are distances too: a ball, a box, a ring, each positive inside like field, and smooth_max melts any of them together. A compute pass keeps the balls in a storage buffer, so a ball you drag with the pointer stays where you let it go.
- **Specks of light** (`example-glow`), https://driftype.com/lab?example=glow: A word made of points. Each speck sits on a jittered grid and asks field() whether the point it drifts around is inside a letter; specks on an edge wink in and out. The pointer is a hand in the water: specks near it are pushed aside and flare. On a change of phrase each speck switches on its own clock, so the word dissolves and reforms west to east.
- **Ink on wet paper** (`example-ink`), https://driftype.com/lab?example=ink: The outline, roughened with noise: field() warped and thresholded so the edge feathers and granulates like watercolor, darker where pigment pools at the rim. A change of phrase washes the old word out while the new one blooms from drops. The pointer is a wet brush; press to drop a blot.
