Skip to main content

Popfold guide

Alpha. Anything here can change in any commit. Nothing is kept backwards compatible before 1.0.0.

Popfold turns a long web page into a small 3D world that opens as you scroll. Each section of the page is one beat of a story: a box opens, a room slides out, furniture springs in, the camera moves on. Visitors can click pieces to read the story behind them. The same page also works with no 3D at all, for old browsers, search engines and AI agents.

This guide explains how Popfold works and where everything lives. To build a new site step by step, read create-a-site.md. To make 3D models, read models.md.

Paths in these docs are relative to the Popfold folder (in a site, that is its popfold/ submodule).

Words we use​

WordMeaning
SiteOne web page built on Popfold: its copy, its homes, its story and its assets.
HomeOne 3D scene a site can show. Described by a HomeRecipe. A site can have several and switch between them.
ShellThe kind of container a home is. There are three: the compact, the diorama and the tower.
FoldHow a compact opens: compact (lid lifts, drawers slide out) or book (side rooms turn like pages).
Room / zoneA part of a home that opens on its own beat. A compact has three rooms. A diorama has three zones. A tower has one zone per floor.
Piece / propOne object in a room. Built in code, or loaded from a .glb file.
KeyWhat layouts and stories call a piece: <room>/<id> when the piece has an id (left/reading-lamp), otherwise <room>/<piece>, numbered for repeats (center/chair#2).
Stage / stopOne <section class="stage"> of the page and its keyframe. The scroll position is a number: 0 is the first stage, 2.5 is halfway between the third and fourth.
KeyframeWhat the home and camera look like at one stage.
StoryThe text card that opens when a visitor clicks a piece.
LayoutA JSON file of changes to where pieces sit, made by eye in the studio.
StudioPopfold Studio, the workbench page each site has at /studio.html.
StillA picture of one stage, used by the page without 3D.
Simple pageThe page without 3D: the same copy, plus stills and written-out stories.

What is in the box​

src/ the engine: startScene(), the three shells, keyframes, layouts, stories, built-in pieces
src/studio/ Popfold Studio (mountStudio)
src/vite-plugin.ts the two Vite plugins: layoutSaver() and popfoldFallback()
src/fallback.ts the browser side of the page without 3D
bin/popfold.mjs the popfold command: init, build, stills, check, describe, shot, optimize, update
skills/popfold-site/ a skill for AI agents: the order of work for making or changing a site
assets/compact.glb the compact's shell model
templates/compact/ a complete small site to copy: an office in a box
templates/tower/ another: a studio in a four-floor building
tools/blender/ Blender scripts that build or convert models
tools/forge/ the AI model pipeline (ComfyUI + Blender)
docs/ this documentation

Popfold is used as TypeScript source by Vite sites. A site depends on it ("popfold": "workspace:*") and imports from popfold, popfold/studio, popfold/vite and popfold/fallback.

Try the template, from the workspace root:

pnpm install
pnpm --filter popfold-template-compact dev # http://127.0.0.1:5190 (studio: /studio.html)
pnpm --filter popfold-template-compact build:static # stills + dist/

How a site is put together​

A site is a normal Vite project with two pages. templates/compact and templates/tower are complete ones.

FileJob
index.htmlAll the copy. Each <section class="stage" id="…"> is one stage. Also holds <canvas id="scene">.
src/main.tsWorks out the scroll position, decides whether to start 3D, calls startScene().
src/home.jsonThe home as data: its look (colours and surfaces), the story (beats: one per stage, in the sections' order, each with its camera), and every piece, where it stands and the story behind it.
src/home.tsThe code that data needs: how each kind of piece is built. homeFromFile(json, { kinds }) makes the home and its story from the file.
src/style.cssThe page's look. The canvas is fixed behind the page.
studio.html, src/studio.tsPopfold Studio for this site. One call to mountStudio().
vite.config.tsTwo plugins: layoutSaver({ home }) and popfoldFallback({...}).
public/models/The site's .glb files.
public/layouts/<home>.jsonOnly for a home made in code: where the studio moved its pieces. A home made from its file keeps that in the file, under places.
public/stills/<home>-<n>.webpOne still per stage, captured from the studio.

The engine never reads the page. The page tells the engine one thing, many times a second: which stage are we at? (getStage()). The engine blends the beats on either side and draws the result.

The answer is only as good as the page's measurements. The sections change height after the first measurement (the written-out stories are hidden when 3D starts, web fonts arrive late), so scrollStage() (from popfold/fallback) measures them again whenever the page changes height. A site's main.ts passes its result as getStage.

The story: sections and beats​

The story is a list of beats, one per .stage section. The templates keep it in the home file:

"beats": [
{ "id": "top", "name": "Closed", "camera": [0, 4.4, 11.5], "lookAt": [0, 0.7, 0], "set": { "hero": 1, "side": 1 } },
{ "id": "approach", "name": "Centre room", "camera": [0, 4.6, 11], "lookAt": [0, 1.7, 0], "set": { "c": 1, "glow": 0.8, "side": -1 } }
]

A beat is the id of its section, a short name (the studio's stop buttons and popfold check use it), where the camera is and what it looks at, and what the home does there (set; anything left out is 0). beatsOf(home) turns the file's beats into what startScene() and mountStudio() take. In code the same beat is beat(sectionId, name, values, cameraPosition, lookAt, zones?), with every value given. The values are:

FieldMeaning
cCentre room. 0 closed, 0.45 lid open (or walls up), 1 furniture in.
L, RLeft and right rooms. 0 inside, 0.4 slid out, 0.6 wall up, 1 furniture in.
glowHow bright the home's lamp is.
badgesThe numbered step badges over the three rooms (0 hidden, 1 shown).
heroThe idle float and wobble of the closed shell (1 on the first stage, 0 once it opens).
sideWhere the home sits on wide screens: -1 left, 0 centre, 1 right. The text card goes on the other side.
av, ax, az, waveThe guide figure: shown or hidden, where it stands, whether it waves.
zonesExtra named values, one per tower floor: { lab: 1, security: 0.3 }. 0 closed, 0.3 slid out and lit, 1 furniture in.

Between two stages the engine holds still for the first and last fifth, and eases through the middle. So each section "rests" while it is centred on the screen.

The rule that matters: the beats and the .stage sections must be in the same order, one beat per section. Add, remove and reorder them together. popfold check compares their ids and names the one that is missing or out of place.

The three shells​

A shell is a home's body. Three ship with Popfold, and a site can add its own (see "A shell of your own" below). The engine only asks a shell to build a home and, each frame, to move its parts to where the story is.

Compact (and the book fold)​

A glossy clamshell, 4 units wide. The lid opens to become the back wall of the centre room. Two drawers slide out sideways, each with a wall that tips up. With fold: 'book' the side rooms are pages that turn open instead. The case itself is part of the home's look: look.shell is 'round' (soft and pillowy, the default), 'crisp' (the same modelled shell with nearly square edges), 'code' (built from simple shapes, with look.corner from 0 to 1 setting how round it is) or { url } for a shell of your own, built with tools/blender/build_compact.py. The lid carries a heart only if the home asks for one (emblem: { heart: true }).

You describe it with a look (colours and surface textures) and a list of pieces. The templates keep both in a JSON file, src/home.json, and make the home from it with homeFromFile(json, { kinds }). That checks the file first (readHome()) and names every mistake: a misspelt field, a room that does not exist, two pieces with one id, a pattern that is not one. In the file a surface is a colour or a pattern, { "pattern": "checker", "colors": ["#fff", "#eee"], "count": 8 }; in code it is a function that returns a texture, () => tex.checker('#fff', '#eee', 8), which a site can still write for a surface no pattern covers. In TypeScript the same list of pieces looks like this:

pieces: [
{ id: 'sofa', room: 'center', kind: 'sofa', at: [0, -1.3] }, // centre room floor: [x, z]
{ id: 'reading-lamp', room: 'left', kind: 'lamp', size: 1.2, at: [1.5, -1.3] }, // a model file from `props`
{ id: 'print', room: 'right', wall: true, kind: 'print', at: [1.4, 1.5], out: 0.17 }, // right wall: [x, height]
],
kinds: {
sofa: () => P.sofa(),
print: () => P.pictureFrame(0.6, 0.6, art, '#fff'),
},
  • id is the piece's own name within its room. Its key, which stories and saved layouts use, is <room>/<id>, or <room>-wall/<id> on a wall. It does not change when you add, remove or reorder other pieces.
  • kind says what to build: a function in kinds, or the name of a model file in props (then size is its longest side). A kind gets the piece's entry, so one kind can serve several pieces: plant: (s) => plant(Number(s.opts?.height ?? 1)).
  • room is center, left or right. wall: true hangs the piece on that room's wall; for the centre room that is the open lid.
  • story is the card behind the piece: { title, text, tags }. It puts a dot on the piece in 3D and a paragraph under the room's section on the page without 3D.
  • Also: turn (radians), lift (above the floor), out (from the wall), delay (0 to 0.4 into the room's pop-in; by default pieces spring in in the order listed), and lamp: true on the one lamp whose glow the story controls (its kind returns { group, bulb }, as P.floorLamp() does).
  • An unknown kind stops the home from loading, with a message that lists the kinds it has.

A recipe may also have a furnish(ctx) function, which runs after the list and places pieces in code. Use it for what a list cannot say; give those pieces an id with piece() (see "Layouts" below).

furnish(ctx) {
const { root, left, right, center, y0, fy, gen, place, pop } = ctx;
root.add(pop(center, place(P.sofa(), 0, y0, -1.3), 0.06)); // centre room floor
left.drawer.add(pop(left.props, place(gen('lamp', 1.2) ?? P.floorLamp(), 1.5, fy, -1.3), 0.1)); // left room floor
right.wall.add(pop(right.props, place(P.pictureFrame(0.6, 0.6, art, '#fff'), 1.4, 1.5, 0.17), 0.2)); // right wall
}
  • place(obj, x, y, z, turn) puts a piece somewhere. pop(list, obj, delay) makes it spring in with its room.
  • gen(name, size) returns a loaded .glb scaled so its longest side is size, or null if the file failed to load. Always have a fallback after ??.
  • Rooms are 4 units wide and walls are 2.2 tall. Floor pieces sit at y0 (centre) or fy (side rooms). Wall pieces go on left.wall / right.wall at z ≈ 0.14. The open lid is the centre room's back wall: add to lid with rotation.x = Math.PI / 2, y = -0.04, and z = height.
  • The rooms are keyed center, left and right. Name them yourself with rooms: { center: 'living', left: 'closet', right: 'dream' } in the recipe; keys become living/sofa.
  • Example: templates/compact/src/home.ts.

Diorama​

One modelled room, made in Blender, exported as a single .glb. Closed, its walls lie flat like an unfolded box. As the story opens the walls swing up, then three zones fill in on their own beats (c, L and R).

diorama: {
url: 'models/room.glb',
zones: { center: 'screen', left: 'lounge', right: 'desk' },
art: { art_tv: () => myCanvasTexture }, // paint screens and posters by material name
lamp: 'pendants', // the piece whose light the story's glow controls
}

A diorama can be kept in a home file too. The file holds what is data, and the code passes the art:

{
"id": "studio-room", "name": "Studio room", "blurb": "…",
"diorama": { "url": "models/room.glb", "scale": 0.5, "zones": { "center": "screen", "left": "lounge", "right": "desk" }, "lamp": "pendants" },
"beats": [ … ],
"pieces": [],
"stories": { "screen-wall/tv": { "title": "The big picture", "text": "…", "tags": ["Strategy"], "dot": "front" } }
}
export const { recipe, beats } = homeFromFile(json, { diorama: { art: { art_tv: tvSlide }, cover } });

A diorama's pieces come from its model, so pieces stays empty and their stories are kept by key under stories. Where the studio moves them goes under places (it writes that itself).

The .glb must follow a naming contract (floor, wall_back, piece_* with a zone). tools/blender/room_to_glb.py produces it from a .blend and a JSON description of the room. Details in models.md. Keys are <zone>/<piece> and <zone>-wall/<piece>.

Tower​

A cutaway building of stacked floors, for a long vertical story such as a resume. Each floor is a zone. As you scroll, the camera rides down, the floor slides forward, lights up and fills with pieces. An elevator follows, and an optional glowing pipeline runs down the side with a branch into every floor.

tower: {
floors: [{ id: 'lab', label: 'AI LAB', color: '#B8FF5C' }, { id: 'shop', label: 'SHOP', color: '#FF4FD8' }], // top floor first
spine: { color: '#3EE6FF' }, elevator: true,
},
pieces: [
{ id: 'desk', room: 'lab', kind: 'desk', at: [-1, -0.6] }, // on the floor: [x, z]
{ id: 'chart', room: 'lab', wall: true, kind: 'chart', at: [1.8, 1.2] }, // on the back wall: [x, height]
],
kinds: { desk: (spec, ctx) => desk('color' in ctx ? ctx.color : '#fff'), chart: () => chart() },
  • The pieces are the recipe's pieces list, as for a compact; a piece's room is its floor's id. A floor is 6 wide and 4 deep by default: x from -3 to 3, z from -2 (the back wall) to 2 (the open front). The floor's neon sign takes the top left of the back wall.
  • A kind is given the floor it is building for as its second argument: ctx.color is the floor's neon colour, so one kind can look at home on every floor.
  • A floor may also have build(ctx), which runs after its listed pieces, for what a list cannot say: ctx.flow(points) adds a glowing pipe, ctx.port(point) moves where the spine's branch enters, and ctx.pop(ctx.place(obj, x, 0, z), 'name') places a piece in code. For a tower kept in a home file, give each floor's build by its id: homeFromFile(json, { kinds, tower: { spine, build: { lab: (ctx) => ctx.flow(...) } } }).
  • Beats for a tower set one zone value per floor: "zones": { "lab": 1 } in the home file. 0 is closed, 0.3 slid out and lit, 1 furnished.
  • Keys are <floor id>/<id>, and <floor id>-wall/<id> for pieces on the back wall. A click on a floor calls onZone(id).
  • A tower reads best at night: the site calls scene.setLighting('evening'), and its studio page passes mood: 'evening' to mountStudio() so the studio and the stills match.
  • Example: templates/tower, a complete small site.

A shell of your own​

A shell is an object with a name, a test for which recipes it builds, a build() and a description of its rooms. Register it before startScene(); a recipe picks it by claiming (claims) or by name (shell: 'gallery').

import * as THREE from 'three';
import { registerShell, type PopItem, type Shell } from 'popfold';

const gallery: Shell = {
name: 'gallery',
claims: (recipe) => recipe.shell === 'gallery',
build: (recipe, env) => {
const root = new THREE.Group(); // build it: env.assets has the home's models by name
const hall: PopItem[] = []; // pieces that spring in
return {
root, badges: [], spinners: [], mixers: [], pickables: [root], editables: [],
// each frame: move your parts from the story's fields, say how open the home is and how lit its lamp
update: (cur, f) => { f.pop(hall, cur.c); return { open: cur.c, lit: cur.c }; },
};
},
zones: () => [{ field: 'c', room: 'hall', label: 'Hall' }], // the studio's sliders, and which rooms open first
rooms: () => ['hall'], // where the studio can add a listed piece
};
registerShell(gallery);

What a shell can say besides (shell.ts): extras (more sliders, such as glow), cams (the studio's camera presets), folds (offers the compact's fold styles) and lazy (its listed pieces' models may arrive after the first view). A house may have a lamp the story's glow lights, badges, zones a click reports, late pieces and a reset() for repeatable captures. The built-in shells are in shells.ts, and a good place to start.

Pieces​

Three ways to get a piece, from quickest to most work:

  1. Built-in pieces: P.sofa(), P.floorLamp(), P.rug(), P.bed(), P.shelf(), P.pictureFrame() and about ten more (src/props.ts). Colours are in C, canvas textures in tex (tex.checker, tex.stripes, tex.dots, tex.waves, tex.terrazzo…).
  2. Your own code-built pieces: boxes and cylinders with rbox(width, height, depth, radius, material) and toy(colour, options) materials, as a function in the recipe's kinds. See templates/compact/src/home.ts.
  3. .glb models: list the name in the recipe's props, put the file in propDir, and call gen(name, size). Every prop file follows one convention (front faces +Z, origin at the centre of its base, longest side = 1). A name with a folder (shared/clock) loads from sharedDir, for props several homes use. See models.md.

Stories​

A listed piece carries its story:

{ id: 'sofa', room: 'center', kind: 'sofa', at: [0, -1.3],
story: { title: 'The sofa', text: 'Why it is here…', tags: ['Sourcing'], meta: '2024', links: [{ label: 'See more', href: 'https://…' }] } },

A piece placed in code by furnish(), or in a diorama or a tower, gets its story from the recipe's stories, by key: stories: { 'center/sofa': { title: … } }. Pass the same record to popfoldFallback({ stories }).

On the page without 3D a room's stories are written in the order its pieces are listed. Moving stories from a separate stories record onto their pieces can therefore change their order on the page; reorder the pieces to reorder the stories.

A piece with a story gets a pulsing dot. Clicking the piece or the dot opens the card. A story's links may point outside (https://…, mailto:…; they open in a new tab) or within the site (docs/guide, #contact; same tab). dot: 'front' or 'below' moves the dot for wall or hanging pieces. On the simple page the same stories are written into the HTML. Keep stories in a file with no 3D code, so vite.config.ts can import it.

Setting a beat's camera in the studio​

Scrub the story to a beat, switch the camera to Free orbit and frame the shot. The panel shows the camera's position and the point it looks at. Use for "" writes them into that beat in src/home.json and goes back to the story camera, so you see the story as it now plays. Copy for a beat copies the two arrays instead, for a site that keeps its beats in code.

Setting what a beat does in the studio​

Scrub the story to a beat and tick Manual in the Fold group. The sliders (a compact's rooms, lamp and badges; a diorama's zones; a tower's floors; and for every home, which side of a wide screen it sits on and its float while closed) now move the home directly. When it looks right, Use for "" writes the sliders' values into that beat in src/home.json and switches Manual off, so the story plays them.

Beats themselves are added and removed in the file, together with their sections in index.html: a beat without a section, or a section without a beat, is what popfold check reports first.

Moving pieces in the studio​

Open the studio, tick Pick in view, click a piece, and drag it, turn it or resize it. Save layout then writes the change where the piece is defined:

  • A listed piece (one from the home file) is written back into src/home.json: its at, and turn, lift, out or scale if those changed. Only that piece's line changes, so the diff reads as what you did. This needs the site to say where its home file is: layoutSaver({ home: 'src/home.json' }) in vite.config.ts (a list of paths for a site with several homes). Ticking Hidden on a listed piece is saved there too, as "hidden": true: the piece stays in the file, parked, and the studio can bring it back.

  • A piece the file does not list (a diorama's model part, a piece placed in code) goes under places in the home file, by key, and is applied on top of where the model or the code puts it. The studio's story editor writes such a piece's story under stories, by key:

    "places": { "right/sculpture": { "p": [0.3, 0.55, 0.5], "r": [0, -0.35, 0], "s": 1.2, "hide": true } }

    A home made in code has no file to write to, and its changes go to public/layouts/<home id>.json instead.

Adding and removing pieces in the studio​

With a home file, the studio can change what is in the home, not only where it stands:

  • Add a piece (under the props list): choose a kind from the home's kinds and model files, the room or floor, whether it goes on the wall, and an id. It is written into home.json in the middle of its room; then select it, move it into place and save.
  • Remove… (on a selected listed piece) takes it out of home.json, after asking. To keep a piece but not show it, tick Hidden instead.
  • Kind (on a selected listed piece) puts another kind in its place: the same id, place, size and story, a different thing. It is written into the piece's entry as its kind.

Writing a piece's story in the studio​

Select a piece and open Story under its fields: a title, the text, tags separated by commas, and where the dot sits. Save story writes it into the piece's entry in home.json (a diorama's model part: under stories, by its key); No story takes it away. The same story is the card a visitor opens in 3D and a paragraph on the page without 3D, so one edit changes both.

Changing the look in the studio​

The Look group (for a home kept in a file) has a colour for each part of a compact's case, each floor and wall as a plain colour or a pattern with its colours, and the lid's title and subtitle. A tower has each floor's sign and colour. Every change is written into home.json when the colour picker closes.

After any of these edits, the studio builds the home again in place from the file the save wrote: the view, the story stop, the selection and any unsaved moves stay. (The save tells Vite not to reload the studio for it; a site page open in another tab shows the change on its next reload. A home made in code still reloads the page.)

Until you save, every change to where a piece stands, how it is turned, its size and whether it is hidden can be taken back: Ctrl+Z undoes, Ctrl+Shift+Z redoes, and the two arrows beside Save layout do the same. With nothing unsaved left to undo, the same keys step back through the saves of the home file (every edit above, and an agent's through popfold mcp), for as long as the dev server runs. Older history is git's.

Every edit that writes the home file is one of a short command list (place, add, remove, story, camera, beat, look, places): the studio sends them, and so can an agent (popfold mcp, in agent-tools.md) or a script.

Saving only works on the local dev server. Unsaved changes are kept as a draft in the browser and offered back after a reload.

One thing to know: keys for repeated pieces are numbered in the order the code adds them (#2, #3). If you add a second lamp before an existing one, the later ones shift, and their stories and layout entries move with the numbers. To stop that, give the piece an id of its own:

import { piece } from 'popfold';
root.add(pop(center, place(piece(P.floorLamp(), 'reading-lamp'), 1.5, y0, -1.3), 0.1)); // key: center/reading-lamp

Do this for every piece with a story and wherever a room has two of a kind. popfold check warns when a story or a layout entry hangs on a numbered piece, and fails when two pieces in a room share an id. In a diorama's model, a custom property id on the piece's node does the same.

Look, guide and clicks​

Nothing in Popfold carries a brand: the light, the story card, the dots and the badges are the site's to set. startScene() options a site usually sets:

OptionWhat it does
lightingOverride parts of the day and evening presets (sun, sky and ground colours and strengths) and the shadow colour. scene.setLighting('evening') switches mood. Pass the same object to mountStudio() so stills match the site.
storyDotThe colour of the dots on pieces that have a story.
baseWhere the site's files are as seen from this page. Leave it out for a page at the site's root; a page in a sub-folder (/tour/index.html) of a site built with base: './' passes '../'.
avatarThe guide figure: false for none, {} for the built-in one, { url } for your own rigged model.
onPick, onZone, onStoryWhat a click on a room, a tower floor or a story piece does.
lazyModelsShow the home once the models of its first rooms are in, and bring the rest in as they arrive (see "Loading models in stages").
warmUpBuilds every beat's materials in the background once the home is on show (see "A smooth first scroll"). On by default; false skips it; 'wait' holds startScene() until it is done.
onSceneCalled once with the scene before it warms up (and, with warmUp: 'wait', before startScene() resolves). Add the site's own lights and scene objects here so the warm-up builds for them. May return a promise.
onHomeCalled with a home's id when it goes on show: when the scene starts, and after every switch.
debug, debugRowsThe debug panel (see below). debug: false takes it away; debugRows adds rows of the site's own.
isOverUiThe canvas sits behind the page, so the engine must know which elements are page content. By default everything is, except <body>, <main> and the empty part of a .stage section.

The story card is plain HTML, styled by CSS variables on :root, all optional: --pf-card-bg, --pf-card-ink, --pf-card-accent, --pf-card-tag, --pf-card-focus, --pf-card-font, --pf-card-display. A compact's three step badges take their colours from look.badges and look.badgeRing, and emblem: { heart: false } removes the heart from its lid. mountStudio({ theme }) restyles the studio's panel.

Popfold Studio​

Every site has a studio at /studio.html. It runs the same engine as the site, but you drive it from a panel:

  • pick a home, scrub the story, jump to a stop, or play it;
  • open the folds by hand, switch the fold style;
  • use the story camera, fixed camera presets or a free orbit;
  • switch the guide figure, sparkles, idle float, story dots, day or evening light and the backdrop;
  • pick, move, turn, resize or hide pieces, and save the layout;
  • save a PNG of the view, copy a link to the view, and Capture stills for the simple page.

The address bar holds the view (?home=office&stage=4&cam=left&light=evening), so a link reopens it.

The page without 3D​

The HTML that ships is the simple page. 3D is an upgrade that starts only if the browser can do it.

  • At build time, popfoldFallback() writes each story under its section, puts a still beside each stage, and adds structured data, og:image, llms.txt, robots.txt and sitemap.xml.
  • In the browser, shouldStart3D() checks for WebGL, the visitor's saved choice, Save-Data and very low memory. markReady() switches the page to 3D once the scene is running. A Simple view / 3D view button lets the visitor choose.
  • ?view=simple or ?view=3d forces a mode.

More than one story page​

A site can have several story pages, each with its own home, stories and stills: a landing page and a tour, say. Put the second page in a folder (tour/index.html, with its own tour/studio.html), add both files to the Vite build inputs, and list the pages:

popfoldFallback({
siteName: 'My Studio', siteUrl: 'https://example.com/',
pages: [
{ html: 'index.html', homeFile: 'src/home.json', sections: { center: 'approach' } },
{ html: 'tour/index.html', homeFile: 'tour/src/home.json' }, // or, for a home kept in code: stories: TOUR_STORIES, stillsHome: 'tower'
],
})

A page in a folder passes base: '../' to startScene() and mountStudio(), so it finds the site's models and layouts. Stills for every page live in public/stills/ at the site's root, popfold stills captures each page's home from that page's studio, and llms.txt and the sitemap cover all the pages. The engine is built once.

Build and deploy​

pnpm build:static # in a site's folder

This typechecks and runs popfold build: it starts the site's dev server, opens the studio in a headless Chrome or Edge, captures a fresh still of every stage, and then runs vite build. It takes about 20 seconds with a GPU. popfold build --keep skips the capture. popfold stills only captures.

Captures are repeatable: the same scene gives the same picture every time. Each new still is compared with the one it replaces, and one that looks the same is put back untouched, so after a capture git shows exactly the stills your change altered. popfold stills --check changes nothing and fails if any still differs.

The output is a static dist/ folder with relative paths. Upload it to any static host.

A deploy replaces the build's files, so a page that was open (or cached) during a deploy asks for files that are gone. Each story page carries a few lines that reload it once when one of the site's own files fails to load; if the files are still missing, the page without 3D stays, and it does not reload again for 30 seconds. Serve the HTML pages with Cache-Control: max-age=0, must-revalidate (Cloudflare's static assets do) so a reload gets the new page.

A smooth first scroll​

A browser builds a material the first time it draws it, and that takes long enough to see: without care, the story stalls for a moment the first time each room opens. Popfold does two things about it, and a site can undo both by accident.

  • Warm-up. Once the home is on show, the engine sets up every other beat in turn and asks the browser to build what that beat shows, in the background. It then draws the beat once, with the true view drawn over it before the browser shows anything, because some shaders (the shadow pass's) are only built by a real draw. Only what the beat shows is built: a piece that stays hidden costs nothing. It does not delay the home's first appearance. startScene({ warmUp: false }) skips it; scene.warmed is a promise that settles when it is done. A model that arrives late (lazyModels) is warmed as it lands, and a home is warmed before setHome() swaps it in. The debug panel's warm-up row says how long the last one took.
  • warmUp: 'wait' does the same work but startScene() resolves only when it is finished. A site that shows a loader until then never stalls, even for a visitor who scrolls at once; the price is the loader staying a fraction of a second longer (0.3 to 0.8 s on the templates).
  • Add the site's own lights in onScene. The warm-up builds for the lights in the scene when it runs. A light the site adds after startScene() has resolved changes the count, and every material is built again on the first scroll (on the compact template, one extra light added afterwards cost a 362 ms frame; the same light added in onScene cost none). startScene({ onScene: (s) => { s.scene.add(myLight); } }). Without 'wait', code right after await startScene() still runs before the warm-up starts, but onScene is the sure place.
  • A steady number of lights. three.js builds every material on screen again whenever the number of lights in the scene changes, and a light counts only while everything above it is visible. Pieces are hidden until their room opens, so a light placed inside a piece changes the count the moment the piece appears, and the whole scene stalls. Keep a light in the scene (or on the home's root) for as long as the home is shown, at zero brightness when it is not needed, and move it to its piece each frame. The compact's own lamp light works this way.

Measured on the compact template, first pass through the story: the slowest frame went from 1,222 ms to 14 ms.

Loading models in stages​

A home with many model files does not have to wait for all of them. With startScene({ lazyModels: true }) the home appears as soon as the models of its first rooms have arrived: the rooms the story opens at its first two beats, which for a compact is usually the centre room and for a tower its top floor. The other models are asked for at once too, and each brings its pieces into the home when it lands, with their shadows, their saved places and their story dots. A piece that lands in a room already open springs in, as the others did.

  • A model that needs more than its file gives it does not need a code kind (which would load up front): say it in models, below.
  • It applies to a compact or a tower whose pieces are all in the home file (pieces). There the engine knows which room needs which model. A home that also places pieces in code (furnish(), or a floor's build()) and a diorama wait for every model, as before.
  • Use it on the site's page. Leave it off for the studio, which the stills are captured from: a picture must be complete, so mountStudio() never loads in stages.
  • A visitor who scrolls to a side room before its models arrive sees the room open without them, and then sees them spring in. On a slow connection that is the trade: an early home, and furniture that may arrive late.
  • The debug panel's models row shows how many have been fetched so far.

What a site says about a model: models​

A listed piece whose kind is a model file is built from the file as it is. For the rest, the recipe (or homeFromFile()'s second argument) has models, by the model's name:

models: {
'mushroom-lamp': { glow: 0.45 }, // let its own texture glow
'plume-lamp': { ready: (piece) => { piece.add(bulb()); } }, // add to it once it is built
'pendant-lamp': { loop: false, ready: (piece, { clip }) => swingOnEntry(piece, clip) }, // drive its animation yourself
'floor-lamp': { ready: (piece) => ({ group: piece, bulb: addBulb(piece) }) }, // the piece marked "lamp": return its bulb
}
  • glow (compact): 0 to 1.
  • loop: false (compact) leaves the model's animation alone; by default its first clip plays back and forth.
  • ready(piece, { clip, spec, ctx }) runs once the piece is built and in its room, whether its model came with the home or arrived later. clip is the model's first animation, if it has one.
  • For a tower: tint, clip and fit, as ctx.gen() takes them.
  • Do not add a light to the piece in ready: see "A smooth first scroll".
  • ready runs once for each time the piece is built, and a home is built once: switching to another home and back shows the same home again without building it. So whatever ready registers elsewhere (a list of moving pieces, say) must outlive the home leaving the scene and coming back. startScene({ onHome }) says which home is on show.
  • clip is the model's own animation, shared by every piece built from that model. Clone it before changing it.

A name in models is still a model, so it still loads in stages. A name in kinds is built in code, and a model fetched by that code loads up front.

The debug panel​

Press the small Debug button beside Simple view, add ?debug to a page's address, or press Alt+Shift+D, and a small panel opens in the corner. It says what build you are looking at and how the page is running:

  • Build: the site's commit (and whether it had uncommitted changes), when it was committed and built, and the versions of the site, of Popfold and of three.js. These come from popfoldFallback().
  • Page: the home, where the story is and the beat's name, the light, the window, the models fetched and their size, how long the home took to appear, and script memory where the browser tells.
  • Drawing: frames a second drawn of those the browser offered (the scene rests when nothing moves), the canvas, draw calls, triangles, geometries, textures, shaders and the graphics card.

Studio ↗ opens the site's studio in a new tab on the same home, story stop and light, to look closer or fix what you see (saving works on the local dev server only). It links to studio.html beside the page and shows only when that page exists; startScene({ debugStudio: 'tools/studio.html' }) points it elsewhere, and debugStudio: false leaves it out. Copy puts all of it on the clipboard with the page's address, for a bug report. On the page without 3D the panel still opens, with the build rows and a note that 3D is off.

Its code is fetched only when the panel is first opened; a page that never opens it carries a few lines for the shortcut. It is on by default, in production too.

A site decides how much of this it shows:

  • viewToggle({ debug: false }) leaves the Debug button out. The panel still opens from the address and the keyboard, for whoever knows to ask.
  • startScene({ debug: false }) and markFallback({ debug: false }) take the panel away altogether, and the button with it.
  • A site with a button of its own calls toggleDebug() from popfold; the document gets a pf-debug event, with detail true or false, whenever the panel opens or closes. A site adds rows of its own with debugRows: () => [['lazy models', 'on']].

What is rough today​

Popfold was grown from one site and is being turned into something anyone can pick up. Homes made in code (two sites still) have less studio help than homes kept in a file, and only the pure parts have unit tests. Known faults and the plan are kept with the project's TODO.md.