# Walleye: design and contracts

Walleye is a small, dependency-free toolkit for stereo pairs: a viewer, a
setup tool, a guide to making stereo images, and a library of examples. Its
source is the repository github.com/wkusner/walleye (Woden, 2026-12-02: "its
own repo"); wkusner.github.io serves a generated copy at `/walleye/`
(`tools/sync_to_site.py`). Pages use root-relative `/walleye/` URLs, so the
same files work in the site and in a local checkout served from its parent.

This file is the contract every part of the toolkit is built against. Change
it first, then the code.

## What went wrong in the atlas viewer, and the rule that answers it

| problem (from Woden, 2026-12-02, and a read of `assets/atlas/viewer.js`) | rule in Walleye |
|---|---|
| No visual prompts: nothing tells a newcomer what to do with the two views. | **Prompt in place.** A short coach line sits under the stage until the first drag; fusion dots sit above each pane; the setup tool is one click away. |
| No orientation cues: after a few drags you cannot tell which way is up. | **Keep up up.** Turntable rotation (yaw about the vertical axis, pitch clamped to ±85°), never a free trackball. An axis triad and a floor ring in every pane; a live caption names the view ("front, tilted 20° down"). |
| The images jump: the canvas changes size when stereo is switched (520 square to 900 by 450), so the page reflows. | **The stage never moves.** The stage has a fixed aspect ratio reserved by CSS before any script runs. Switching mono, parallel, cross-eyed, anaglyph or wiggle redraws inside the same box. The object is framed once from its bounding sphere and stays centred. |
| Hard to navigate: no way back, no named views, no zoom. | **Always a way home.** A Home button and the `0` key return to the starting view (animated, or instant under reduced motion). Named views (front, top, side). Zoom with wheel, pinch, `+` and `-`, clamped. |
| Stereo state is kept by rewriting the URL hash, which can scroll the page. | **No jumps on state change.** State lives in the query string, written with `history.replaceState`; nothing that changes state scrolls the page. |

From the Generative Lab accessibility work (commit 1cbb136): closing a panel
returns focus to the control that opened it; panels scroll into view with
`block: 'nearest'` and smooth only without reduced motion; a skip link; a
visible focus ring; text in `rem`; `prefers-reduced-motion` and
`prefers-contrast` honoured. Walleye adds: arriving at a deep link
(`#example-id`) centres the target (`scroll-margin` plus
`scrollIntoView({block: 'center'})`), and coming back from the viewer to the
gallery returns focus to the card that was opened, centred.

## Folder layout

```
walleye/
  index.html            landing page                       (pages agent)
  viewer/index.html     the viewer                         (viewer agent)
  setup/index.html      the setup tool                     (viewer agent)
  how-to/index.html     how to make and view stereo images (pages agent)
  examples/index.html   the gallery                        (examples agent)
  examples/manifest.json  list of examples                 (examples agent)
  examples/scenes/*.json  one scene per example            (examples agent; atlas-*.json from the converter)
  examples/pairs/       image pairs (side-by-side JPEG/PNG), if any
  lib/walleye.js        the library                        (viewer agent)
  lib/walleye.css       shared style for every page        (viewer agent)
  tools/                command-line helpers (Python 3, standard library only)
  tests/                smoke.js (Playwright), fixtures/, screenshots/  (viewer agent)
  docs/                 design.md (this), scene-format.md, api.md, contributing.md
  README.md             what it is, how to use it, how to embed it
```

Each agent writes only in its own files.

## Look

Calm and neutral, because texture and noise behind a stereo pair fight
fusion. Tokens on `:root`, light and dark (`prefers-color-scheme`, plus a
`data-theme` override stored under `walleye-theme`), a plain system serif
for prose and system sans for controls. The stage background is flat. One
accent colour. Contrast at least 4.5:1 for text and 3:1 for controls. Links
in the header to the Atlas (`/atlas/`) and the Wending House (`/palace/`).

## Viewing modes

| mode | id | layout | notes |
|---|---|---|---|
| mono | `mono` | one view centred in the stage | default for first visit |
| parallel (wall-eyed) | `parallel` | left eye image on the left | centres of the two panes at most `separationMm` apart (setup sets it; default 60 mm at 96 px per inch, 3 mm under a 63 mm eye separation) |
| cross-eyed | `cross` | left eye image on the right | pane width free (half the stage), or at most `crossMaxMm` if the setup page set it |
| anaglyph | `anaglyph` | one view, red left / cyan right | for people who cannot free-view; needs glasses |
| wiggle | `wiggle` | one view alternating left and right at about 6 Hz | gives depth without binocular vision; off under reduced motion (falls back to a manual left/right toggle) |

`S` swaps parallel and cross-eyed. The stage keeps its size in every mode:
the stage is always two panes wide; mono, anaglyph and wiggle draw one view
centred in it with the same scale as a stereo pane.

The box never changes; the picture inside it may. Pane width in parallel
mode is `min(stage width / 2, separationMm * pxPerMm)`, so on a wide screen
the parallel panes are narrower than half the stage and the object is drawn
smaller than in mono or cross-eyed. This is required for fusion, and is the
one place where the drawing scale changes with the mode (viewer agent,
2026-12-02). A faint frame and a fusion dot mark each stereo pane.

## Geometry and camera

- Right-handed, y up. A scene is framed by its bounding sphere: centre `c`,
  radius `r`. The camera looks at `c` from distance `d = r * scene.distance`
  (default 3.2), perspective with focal length chosen so the sphere fills
  about 80% of a pane.
- Turntable: `yaw` about y, `pitch` about the camera's x, pitch clamped to
  ±85°. Start view: `scene.view = {yaw, pitch, zoom}` (default yaw 30°,
  pitch 20°, zoom 1).
- Stereo: two **parallel (off-axis)** cameras offset along the camera's x by
  ± `b/2`, each image shifted sideways so `c` has zero disparity. Not toe-in:
  toe-in adds vertical parallax at the corners. Default baseline
  `b = d * 0.06` (about 3.4°, as in the atlas viewer); `settings.baseline`
  and `scene.stereo.baseline` scale it. Comfort caps: crossed disparity at
  most 8% of a pane width; in parallel mode uncrossed disparity at most
  `(eyeMm - separationMm) * pxPerMm` (at least 2 px), so the eyes never
  diverge. Zoom is magnification, so the caps also flatten depth when
  zoomed in rather than making the pair unfusable.
- Drawing: canvas 2D, painter's algorithm, depth-cued line width and
  opacity, flat-shaded faces with one light. Must stay smooth for 5,000
  segments and 3,000 faces on a laptop.

## Scene format (version 1)

A scene is JSON. Every field is optional except `version` and one of
`points`, `lines`, `mesh`, `surface`, `pair`, `atlas` (a `seed` scene may
have none and shows a short note instead).

```json
{
  "version": 1,
  "id": "critical-catenoid",
  "title": "The critical catenoid",
  "alt": "A waist-shaped surface meeting the unit sphere at right angles along two circles.",
  "caption": "One or two sentences shown under the stage.",
  "credit": "Who made it; data source; licence.",
  "view": { "yaw": 30, "pitch": 20, "zoom": 1 },
  "distance": 3.2,
  "stereo": { "baseline": 1.0 },
  "guides": { "sphere": true, "axes": true, "floor": true },

  "points": [[x, y, z], ...],
  "pointStyle": { "radius": 4, "color": "ink", "labels": false },
  "lines": [ { "pts": [[x,y,z], ...], "color": "accent", "width": 1.5, "closed": false } ],
  "mesh": { "vertices": [[x,y,z], ...], "faces": [[i,j,k], ...], "color": "surface", "alpha": 1, "wire": false },
  "surface": { "type": "param", "u": [u0, u1, nu], "v": [v0, v1, nv], "expr": "named generator, see below" },
  "pair": { "src": "pairs/name.jpg", "layout": "lr" | "rl", "width": 2400, "height": 900 },

  "atlas": { ... }   // a scene in the atlas viewer's format; converted on load
}
```

- Colours are token names (`ink`, `accent`, `up`, `low`, `surface`, `muted`,
  and `plain`, `faint` for the atlas's plain caps and zero-weight arcs) or
  CSS colours. Tokens follow the theme (`--wy-scene-<name>` in walleye.css).
- `surface.type: "param"` with a named generator from
  `Walleye.generators` (catenoid, helicoid, enneper, torus, clifford-torus,
  klein-bottle, trefoil, hopf-fibres, sphere, ...), with `params`. No `eval`.
- `pair` shows a photograph or drawing pair instead of a 3D scene: the
  viewer cuts it into two panes, aligns, and applies the same modes (wiggle
  and anaglyph included). Rotation is off; zoom and pan work. `src` is
  relative to the scene file, so a gallery scene writes
  `"../pairs/name.jpg"`; `"pairs/name.jpg"` from `examples/scenes/` also
  works (fallback). Optional `left`/`right` (two files), `shift`, `dy`.
- `atlas` accepts the atlas viewer's scene object unchanged (points, caps,
  pointCaps, arcs, arcWeights, rattlers, surface catenoid/grid, sphere,
  extent), so every atlas entity can open in Walleye.
- `seed: true` marks a scene that is a placeholder for later work (for
  example 4D); the gallery shows it with a "seed" badge.

## Library API (lib/walleye.js)

```js
Walleye.mount(element, sceneOrUrl, options) -> viewer
  options: { mode, controls: true, caption: true, coach: true, height }
viewer.setMode('mono'|'parallel'|'cross'|'anaglyph'|'wiggle')
viewer.home()            // animated return to the start view
viewer.setView({yaw, pitch, zoom})
viewer.load(sceneOrUrl)  // swap scene in place; stage does not resize
viewer.destroy()
Walleye.settings          // {mode, separationMm, pxPerMm, baseline, eyeMm, crossMaxMm} from localStorage 'walleye-settings'
Walleye.generators        // named surface and curve generators
```

Additions (names above unchanged): `viewer.ready`, `getView()`,
`getMode()`, `refresh()`, `animateTo()`, `namedView()`; options `keys`,
`modes`, `views`, `setupHref`, `settings`, `view`, `onload`, `onchange`,
`onerror`; events `walleye:load`, `walleye:change`, `walleye:error`;
`Walleye.saveSettings`, `resetSettings`, `theme`, `viewers`, `mountAll`.
Full reference in api.md.

Auto-mount: any element with `data-walleye` and either a child
`<script type="application/json">` or `data-src="url"`.

## Viewer page

Since 2026-12-03 the gallery opens examples in `view.html`, the one viewer; the page below is kept as the library's demo, for embedding.

`/walleye/viewer/?scene=examples/scenes/<id>.json&mode=parallel`. Shows the
title, stage, toolbar (mode, Home, named views, Spin, guides), caption,
credit, a "Set up your eyes" link, and Back to the gallery (returns focus to
the card that opened it). Keyboard: arrows turn, `+`/`-` zoom, `0` home,
`S` swap, `M` cycle mode, space spin, `?` shows the key list (also `1`-`3`
named views, `G` guides, `W` other eye in still wiggle, `Esc`). A live region
announces view changes at most once a second. The wheel zooms only when the
stage has focus or Ctrl is held (trackpad pinch); otherwise it scrolls the
page and the coach line says how to zoom, so the page never traps scrolling.

## Setup page

Four steps, one per screen section, each with a check the reader confirms:
1. Size: hold a bank card (85.60 mm by 53.98 mm, ISO/IEC 7810 ID-1) to the
   screen and drag until the outline matches: gives px per mm.
2. Eyes: choose parallel, cross-eyed, anaglyph or wiggle (a one-line
   description of each); enter or accept 63 mm as eye separation
   (`eyeMm`). `separationMm` starts 3 mm under it (60 mm by default).
3. Practise: fusion dots and a simple 3D test (a cube in front of a
   plane); the reader confirms they see three dots and the cube in front.
   Controls to shrink or grow the pair until it fuses comfortably
   (`separationMm` in parallel, `crossMaxMm` in cross-eyed).
4. Save: writes `walleye-settings`; links to the gallery.
Accessibility: anaglyph and wiggle are offered as first-class alternatives
for readers without stereo vision or who find free-viewing uncomfortable.

## Example library

Categories: historical, educational, mathematics, science, new, seeds.
Each example has a manifest entry:
`{id, title, category, scene, blurb, credit, tags, level: "intro"|"intermediate"|"advanced", seed?}`.
Historical examples are reconstructions drawn from the published figure,
with the source cited, or public-domain images with their catalogue record.
No image is added without a clear licence.

## Non-goals for version 1

WebGL, VR headsets, autostereograms (single-image random-dot) beyond a
static example, user uploads to a server.

## Changes to this contract

- 2026-12-02, viewer agent: stereo is off-axis (parallel cameras with image
  shift), with the two comfort caps above. Settings gain `eyeMm` (63, the
  reader's pupils) and `crossMaxMm` (0, no limit); `separationMm` (60) is the
  limit on parallel pane centres, kept below `eyeMm` so far points never ask
  the eyes to diverge. Parallel panes shrink on wide screens (the box does
  not). Wheel zoom needs focus or Ctrl. Pair paths are relative to the scene
  file. Tokens `plain` and `faint` added. The scene format and the API names
  above are unchanged; everything new is an addition.
