Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

Add forge studio, club diagnostics, and studio updates

nirholas0d317ff85ee1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 662f3a174..17ae34dd6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Credits** (`/credits`) — Top up with SOL or $THREE and spend credits on 3D generation, agents, and compute. Hold $THREE for up to 30% off every spend.
- **Docs · Walk Avatar** (`/docs/walk`) — Developer and user documentation for the three.ws walking-avatar system: the /walk page, iframe embeds, the JavaScript SDK, the postMessage event contract, companion mode, analytics, and the Chrome extension.
- **Feed** (`/feed`) — Recent activity from the people and agents you follow on three.ws.
+- **Studio — Object + Avatar from text** (`/forge-studio`) — One canvas for both text-to-3D pipelines: forge a textured object (GLB) in the Object tab, or describe a character and get a rigged avatar in the Avatar tab.
- **Walk** (`/walk`) — Your 3D avatar walks anywhere on the web. Live demos across six environments, a Chrome extension, one-tag embeds, and a global distance leaderboard.
- **Walk Leaderboard** (`/walk-leaderboard`) — Global leaderboard for the walking avatar — distance walked, sites visited, and time, ranked daily, weekly, and all-time.
- **"Fresh from the Forge" thumbnails now show your models** — The community strip on the Forge page shows the newest models people make. Half the tiles were rendering as blank dark squares: for models generated without a reference image, the page builds a thumbnail by snapshotting the 3D model itself — but it was doing that on a one-pixel-wide canvas, so the snapshot came out as a solid block. The snapshot now renders at full thumbnail resolution, and a snapshot that comes back empty cleanly falls back to a labeled prompt card instead of an empty tile. Every card in the strip now shows real artwork. (`/forge`) `[fix]`
@@ -20,6 +21,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Affiliate dashboard now shows who you referred** — The referrals dashboard lists each person you referred with their signup date, the revenue they generated, and the commission you earned — not just totals. (`/dashboard/referrals`) `[improvement]`
- **Agent payments now produce a signed receipt of exactly what was bought** — Autonomous agent-to-agent payments already run under a signed Intent Mandate (your standing authorization with budget and per-call caps). They now also issue a Cart Mandate for each transaction — a tamper-evident, signed record of the exact endpoint paid, the amount, currency, network, and line items, bound to the authorizing mandate. It comes back with every paid call and can be checked by anyone via a new verification endpoint, so a paid service has cryptographic proof of what its caller agreed to. This completes our alignment with Google's Agent Payments Protocol (AP2), layered cleanly on top of x402 settlement. `[feature, sdk]`
- **Agent Studio: fixed an invisible overlay that blocked the Brain tab** — The Brain tab of Agent Studio could become unclickable — a full-screen dialog layer that's meant to stay hidden until you open Templates or the behavior view was rendering invisibly on top of the whole studio, swallowing every click. It now stays properly hidden until you actually open it, so the Brain tab is usable again. (`/agent-studio`) `[fix]`
+- **Agent Studio: save your Brain and flow straight into Memory** — Building your agent's reasoning graph in the Brain tab now has a clear finish line. A new Save button writes the graph to the server on demand (or press ⌘/Ctrl+S), the header's save indicator finally lights up for Brain edits the way it does for the name and tagline, and a Done button saves and carries you on to the Memory tab so designing a mind flows naturally into the next step instead of dead-ending on the canvas. Pressing Escape now also closes the Templates and behavior dialogs so they can never trap you. (`/agent-studio`) `[improvement]`
- **Arm your agent gets its own setup page** — Configuring your 3D agent to trade Oracle conviction now has a dedicated page at /oracle/arm — a clean, focused setup laid out the way trading bots do it: a live status bar with a big arm switch, a stats strip, and step-by-step cards for entry rules, position sizing and caps, alerts, and simulate-vs-live mode. The Oracle tab now shows your agent's configuration at a glance and links straight to the full editor. (`/oracle/arm`) `[feature, improvement]`
- **Authorize $THREE once, then pay with no wallet popups** — The $THREE page now lets you set a spending allowance: approve a cap once, and paid actions across the platform — forge, skills, names, cosmetics — debit it automatically without asking you to sign every time. It's non-custodial and built on Solana's native, audited Subscriptions & Allowances program: your tokens stay in your own wallet until a charge pulls them, never more than the cap you set. You can see what your remaining cap covers, get a heads-up when it runs low, top it up, or revoke it in one click anytime. Prefer to sign each payment? Just leave it off. (`/three-token`) `[feature]`
- **Authorize $THREE once, then pay with no wallet popups** — The $THREE page now lets you set a spending allowance: approve a cap once, and paid actions across the platform — forge, skills, names, cosmetics — debit it automatically without asking you to sign every time. It's non-custodial and built on Solana's native, audited Subscriptions & Allowances program: your tokens stay in your own wallet until a charge pulls them, never more than the cap you set, and you can let it expire or revoke it anytime. Set a cap, top it up, or leave it off and keep signing each payment — your choice. (`/three-token`) `[feature]`
@@ -67,6 +69,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Payment hardening and a steadier holder leaderboard** — Two behind-the-scenes reliability and safety fixes. Agent payment invoices now verify that the wallet paying is actually linked to your account before an invoice is created, closing a gap that let bogus payment requests be generated against any agent. And the $THREE holder leaderboard, its share card, and the token stats panel no longer each kick off a full on-chain holder scan during a traffic spike — one scan now serves everyone and refreshes the shared snapshot, so the leaderboard stays fast and responsive under load. Nothing to do on your end. (`/leaderboard`) `[security, fix, infra]`
- **Pick your guide for the product tour — and walk her around yourself** — The 3D guide who walks you through the product tour now starts as Ava, our photoreal full-body character — and you can swap her for anyone in the cast. Open the tour menu and use the new Guide picker to choose any avatar (your own custom ones included); the tour switches on the spot and remembers your pick. In free roam you can now steer the guide with WASD or the arrow keys (hold Shift to run) and walk her across the whole page, just like steering your character on the Walk pages — clicking and dragging still work too. She also obeys gravity now: she drops in and plants her feet on the ground instead of hovering. `[feature, improvement]`
- **Platform-wide hardening: payment integrity, security, and scale** — A broad reliability pass across the parts of three.ws that move real money and serve heavy traffic. On the money side: bundle purchases and agent payments are now verified on-chain before anything unlocks, each payment is credited exactly once, withdrawals can't be processed twice, and recurring subscriptions can't be double-billed. On the security side: a set of input-handling and link-safety fixes across pages, stronger protection for custodial keys at rest, and tighter checks on outbound agent payments so funds only ever move in the expected asset. On the scale side: the busiest directory, profile, and feed pages now ride a short cache and run far fewer database queries, so they stay fast as the community grows. Most of this is invisible by design — it's the plumbing that keeps the platform correct and quick under load. `[security, improvement, infra]`
+- **Pole Club: every dancer stands on her stage** — Fixed a dancer who sank through her platform instead of standing on it. Avatars exported at centimetre scale (common for Mixamo-rigged characters) had their idle motion collapse, dropping them a metre into the floor. The animation engine now scales each dancer's footing to her own rig, so any avatar you pick stands cleanly at her pole. (`/club`) `[fix]`
- **Pole Club: tipping now works with the built-in three.ws wallet** — Tipping a dancer in the Pole Club opens an on-chain payment for $0.001 USDC. On Solana Mobile (Seeker), the payment window only recognized browser extensions like Phantom, so anyone using the three.ws wallet saw a checkout that couldn't be completed — the window opened but the pay button was greyed out. The checkout now recognizes the three.ws wallet (and Backpack and Solflare) the same way the rest of the site does, and names whichever wallet you're using throughout the flow, so tips go through. (`/club`) `[fix]`
- **Profiles you can edit — and follow** — Your three.ws profile at three.ws/u/<your-username> is now a real social home. Edit it in place: add a bio, a profile picture and banner image, your location, and a website link — all from an Edit button on your own profile. You can now follow other creators and agents, and they can follow you; every profile shows live follower and following counts you can tap to browse the lists, with one-tap follow buttons throughout. And there's a new Feed at three.ws/feed that gathers the latest avatars, agents, and coin launches from everyone you follow, newest first. Find your profile and Feed links from your account page. (`/feed`) `[feature]`
- **Provably-fair vanity grinder now listed in the x402 bazaar** — The provably-fair Solana vanity grinder — which returns a signed, independently-verifiable receipt proving the key was ground fresh and never kept — is now published in the x402 discovery catalog, so paying agents and bazaar crawlers can find and call it directly. (`/vanity/verify`) `[feature, sdk]`
diff --git a/data/changelog.json b/data/changelog.json
index a4bf24821..eb2d2bfb4 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,20 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-21",
+ "title": "Pole Club: every dancer stands on her stage",
+ "summary": "Fixed a dancer who sank through her platform instead of standing on it. Avatars exported at centimetre scale (common for Mixamo-rigged characters) had their idle motion collapse, dropping them a metre into the floor. The animation engine now scales each dancer's footing to her own rig, so any avatar you pick stands cleanly at her pole.",
+ "tags": ["fix"],
+ "link": "/club"
+ },
+ {
+ "date": "2026-06-21",
+ "title": "Agent Studio: save your Brain and flow straight into Memory",
+ "summary": "Building your agent's reasoning graph in the Brain tab now has a clear finish line. A new Save button writes the graph to the server on demand (or press ⌘/Ctrl+S), the header's save indicator finally lights up for Brain edits the way it does for the name and tagline, and a Done button saves and carries you on to the Memory tab so designing a mind flows naturally into the next step instead of dead-ending on the canvas. Pressing Escape now also closes the Templates and behavior dialogs so they can never trap you.",
+ "tags": ["improvement"],
+ "link": "/agent-studio"
+ },
{
"date": "2026-06-21",
"title": "Guided Tour: no longer stops dead on full-screen pages",
diff --git a/data/pages.json b/data/pages.json
index 2ecf97122..781984b27 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -223,6 +223,14 @@
"changefreq": "weekly",
"added": "2026-06-04"
},
+ {
+ "path": "/forge-studio",
+ "title": "Studio — Object + Avatar from text",
+ "description": "One canvas for both text-to-3D pipelines: forge a textured object (GLB) in the Object tab, or describe a character and get a rigged avatar in the Avatar tab.",
+ "priority": 0.8,
+ "changefreq": "weekly",
+ "added": "2026-06-21"
+ },
{
"path": "/scene",
"title": "Scene Studio",
diff --git a/pages/club.html b/pages/club.html
index c0dbcf5ef..68ce78bb3 100644
--- a/pages/club.html
+++ b/pages/club.html
@@ -2182,49 +2182,89 @@
</div>
</div>
- <!-- Entrance failsafe — the walk-in overlays (#club-loader, opaque and
- full-screen; #club-door-canvas, full-screen) are torn down ONLY by
- src/club-entrance.js. If that module fails to load, throws, or a venue/
- avatar asset hangs, the loader never reaches `is-done` and swallows
- every click on the stage — the visitor is trapped on a frozen alley.
- This is a classic (non-module) script on purpose: a module failure
- can't take it down. It watches real load progress and, only if the
- walk-in stalls with no progress, clears the overlays and surfaces the
- cover card — exactly the module's own degrade path (club:enter-door). -->
+ <!-- Entrance failsafe — the real click-trap is #club-door-canvas: a
+ full-screen, z-index-9400, pointer-events:auto canvas that owns input
+ ONLY while it's the visible walk-in. src/club-entrance.js removes it on
+ arrival (or on error). If that module hangs — a venue/avatar asset that
+ never resolves mid-walk, a stuck venue swap, a dispose that never runs —
+ the canvas is left behind and silently swallows every click on the stage
+ AND the side panel. The visitor sees the club but can't interact.
+
+ The earlier version of this watchdog keyed off the loader's `is-done`
+ class as "the module took over, stop watching." But `is-done` is set the
+ moment the alley finishes loading — long before the canvas is torn down —
+ so any hang after that point trapped clicks forever while the watchdog
+ sat idle. This rewrite watches the canvas itself and the two states that
+ prove it's trapping clicks. Classic (non-module) script on purpose: a
+ module failure can't take it down. -->
<script>
(function () {
- var loader = document.getElementById('club-loader');
- if (!loader) return;
- var STALL_MS = 15000; // no load progress for this long ⇒ walk-in is dead
+ var STALL_MS = 15000; // alley never finished loading this long ⇒ scene is dead
+ var FADED_MS = 1200; // canvas held transparent this long, never removed ⇒ trapped
+ var POLL_MS = 500;
var lastWidth = -1;
var lastProgressAt = Date.now();
+ var fadedSince = 0;
- // is-done means src/club-entrance.js rendered the alley and now owns the
- // overlays (the canvas legitimately persists for the walk and is removed
- // on arrival). Once that happens the watchdog has nothing left to guard.
- function tookOver() { return loader.classList.contains('is-done'); }
+ function doorCanvas() { return document.getElementById('club-door-canvas'); }
+ function barWidth() {
+ var bar = document.getElementById('club-loader-bar');
+ return bar ? (parseFloat(bar.style.width) || 0) : 0;
+ }
+ // Drop the dead overlay and hand the visitor onward. Dispatching
+ // club:enter-door surfaces the cover card if they haven't paid, and is a
+ // harmless no-op once they're admitted (the door card is already gone) —
+ // so a single reveal() is correct whether the hang happened before the
+ // cover charge or during the final fade onto the stage.
function reveal() {
try {
- var canvas = document.getElementById('club-door-canvas');
+ var canvas = doorCanvas();
if (canvas) canvas.remove();
- loader.classList.add('is-done');
- setTimeout(function () { try { loader.remove(); } catch (e) {} }, 800);
- // Mirror the module's degrade: a failed walk-in still lets the
- // visitor pay the cover and reach the stage.
+ var loader = document.getElementById('club-loader');
+ if (loader) {
+ loader.classList.add('is-done');
+ setTimeout(function () { try { loader.remove(); } catch (e) {} }, 800);
+ }
window.dispatchEvent(new CustomEvent('club:enter-door'));
} catch (e) {}
}
function tick() {
- if (tookOver()) return; // healthy — module is in control, stop watching
- var bar = document.getElementById('club-loader-bar');
- var w = bar ? (parseFloat(bar.style.width) || 0) : 0;
- if (w > lastWidth) { lastWidth = w; lastProgressAt = Date.now(); }
- if (Date.now() - lastProgressAt >= STALL_MS) { reveal(); return; }
- setTimeout(tick, 1000);
+ var canvas = doorCanvas();
+ if (!canvas) return; // module handed off cleanly — nothing left to guard
+
+ var op = parseFloat(getComputedStyle(canvas).opacity);
+ if (isNaN(op)) op = 1;
+
+ // Faded-but-present ⇒ the module faded the canvas out to reveal the
+ // live stage behind it (a final arrival, or a venue swap that's
+ // holding the fade for a download that never resolves) but never
+ // removed it. A canvas this transparent should already be gone.
+ // Require the state to persist so a normal ~0.6s fade transition is
+ // never mistaken for a hang.
+ if (op <= 0.02) {
+ if (!fadedSince) fadedSince = Date.now();
+ if (Date.now() - fadedSince >= FADED_MS) { reveal(); return; }
+ } else {
+ fadedSince = 0;
+ }
+
+ // Still opaque and the loader never reached 100% ⇒ the alley/avatar is
+ // still downloading. Track real byte progress; if it flatlines, the
+ // scene is dead. Once the bar hits 100 the load succeeded — an opaque
+ // canvas is then a legitimate walk-in we must NOT disturb (the visitor
+ // may simply be standing still), so the stall watch stops there and
+ // only the faded-trap check above can still fire.
+ var w = barWidth();
+ if (w < 100) {
+ if (w > lastWidth) { lastWidth = w; lastProgressAt = Date.now(); }
+ if (Date.now() - lastProgressAt >= STALL_MS) { reveal(); return; }
+ }
+
+ setTimeout(tick, POLL_MS);
}
- setTimeout(tick, 1000);
+ setTimeout(tick, POLL_MS);
})();
</script>
diff --git a/pages/forge-studio.html b/pages/forge-studio.html
new file mode 100644
index 000000000..4a11fe7ca
--- /dev/null
+++ b/pages/forge-studio.html
@@ -0,0 +1,3818 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Studio · Object + Avatar from text · three.ws</title>
+ <meta
+ name="description"
+ content="One place to turn text into 3D: forge a textured object (GLB) or describe a character and get a rigged avatar. Two pipelines, one canvas."
+ />
+ <meta property="og:title" content="Studio — Object + Avatar from text · three.ws" />
+ <meta
+ property="og:description"
+ content="Forge a textured object from a prompt, or describe a character and get a rigged avatar — in one place."
+ />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/forge-studio" />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=build&amp;t=Studio+%E2%80%94+Object+%2B+Avatar&amp;d=Forge+a+textured+object+from+a+prompt%2C+or+describe+a+character+and+get+a+rigged+avatar+%E2%80%94+in+one+place.&amp;p=%2Fforge-studio" />
+ <meta property="og:image:width" content="1200" />
+ <meta property="og:image:height" content="630" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="twitter:title" content="Studio · Object + Avatar from text · three.ws" />
+ <meta
+ name="twitter:description"
+ content="One place to turn text into 3D: forge a textured object (GLB) or describe a character and get a rigged avatar."
+ />
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=build&amp;t=Studio+%E2%80%94+Object+%2B+Avatar&amp;d=Forge+a+textured+object+from+a+prompt%2C+or+describe+a+character+and+get+a+rigged+avatar+%E2%80%94+in+one+place.&amp;p=%2Fforge-studio" />
+ <meta name="theme-color" content="#080814" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
+ <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/site.webmanifest" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="preconnect" href="https://ajax.googleapis.com" />
+ <script
+ type="module"
+ src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"
+ integrity="sha384-sr9b4Ux0WhAUGclJ0ym0FSY2zSOMmNSn0bP/SA0e6bNCrpn/5W3QL8mm+LdlQMKw"
+ crossorigin="anonymous"
+ ></script>
+ <style>
+ /* No per-surface accent override — forge uses the global monochrome tokens. */
+
+ .forge-main {
+ max-width: none;
+ margin: 0;
+ padding: var(--space-md) clamp(var(--space-md), 4vw, var(--space-2xl)) var(--space-2xl);
+ }
+ .forge-head {
+ /* Reset the global site-nav `header` rule from style.css —
+ this is an in-page hero, not the top bar. */
+ display: flex;
+ align-items: baseline;
+ gap: var(--space-md);
+ height: auto;
+ padding: 0 0 var(--space-md);
+ background: none;
+ backdrop-filter: none;
+ -webkit-backdrop-filter: none;
+ border-bottom: 1px solid var(--stroke);
+ overflow: visible;
+ white-space: normal;
+ line-height: var(--leading-normal);
+ z-index: auto;
+ -webkit-app-region: no-drag;
+ margin-bottom: var(--space-lg);
+ }
+
+ /* ── Workspace: composer rail + stage side by side on desktop ────── */
+ .forge-workspace {
+ display: grid;
+ /* Default (mobile / <1080px): one full-width column that may shrink
+ below its content's min-content width, so the rail and stage stack
+ vertically without forcing horizontal scroll. The 1080px query
+ below restores the two-column desktop layout. */
+ grid-template-columns: minmax(0, 1fr);
+ gap: var(--space-lg);
+ align-items: start;
+ }
+ @media (min-width: 1080px) {
+ .forge-workspace {
+ grid-template-columns: minmax(380px, 440px) minmax(0, 1fr);
+ gap: var(--space-xl);
+ }
+ .forge-rail {
+ position: sticky;
+ top: 84px;
+ }
+ }
+ /* Stage column — the viewer/result, your creations, and the showcase.
+ min-width:0 lets the 3D canvas shrink to its grid cell instead of
+ forcing the rail narrow; the sections stack with even spacing. */
+ .forge-stage {
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-lg);
+ }
+ /* forge-eyebrow removed — header is now inline h1 + tagline */
+ .forge-head h1 {
+ font-family: var(--font-display);
+ font-size: var(--text-xl);
+ line-height: 1;
+ margin: 0;
+ color: var(--ink);
+ flex: none;
+ }
+ .forge-head p {
+ color: var(--ink-dim);
+ font-size: var(--text-sm);
+ margin: 0;
+ line-height: var(--leading-normal);
+ }
+
+ /* Composer ---------------------------------------------------- */
+ .composer {
+ background: var(--surface-glass);
+ border: 1px solid var(--stroke-strong);
+ border-radius: var(--radius-lg);
+ padding: var(--space-md);
+ box-shadow: 0 24px 60px -30px rgba(0, 0, 0, 0.8);
+ }
+ .composer textarea {
+ width: 100%;
+ min-height: 120px;
+ resize: vertical;
+ background: transparent;
+ border: none;
+ outline: none;
+ color: var(--ink);
+ font-family: var(--font-body);
+ font-size: var(--text-lg);
+ line-height: var(--leading-normal);
+ }
+ .composer textarea::placeholder {
+ color: var(--ink-dim);
+ }
+ .composer-row {
+ display: flex;
+ align-items: center;
+ gap: var(--space-sm);
+ margin-top: var(--space-sm);
+ padding-top: var(--space-sm);
+ border-top: 1px solid var(--stroke);
+ flex-wrap: wrap;
+ }
+ .aspect {
+ display: inline-flex;
+ gap: 2px;
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md);
+ padding: 2px;
+ }
+ .aspect button {
+ background: transparent;
+ border: none;
+ color: var(--ink-dim);
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ padding: 0.32rem 0.55rem;
+ border-radius: var(--radius-sm);
+ cursor: pointer;
+ transition:
+ background 0.15s,
+ color 0.15s;
+ }
+ .aspect button:hover {
+ color: var(--ink);
+ }
+ .aspect button[aria-pressed='true'] {
+ background: var(--surface-3);
+ color: var(--ink);
+ }
+ /* Live backend health on the engine buttons: a throttled upstream gets
+ an amber dot, a down/unconfigured one is disabled with the reason in
+ its tooltip. Dots ride ::after so the label spacing stays put. */
+ .aspect button[data-health='degraded']::after {
+ content: '';
+ display: inline-block;
+ width: 0.4em;
+ height: 0.4em;
+ margin-left: 0.35em;
+ border-radius: 50%;
+ background: var(--warning, #e0a93e);
+ vertical-align: 0.08em;
+ }
+ .aspect button:disabled {
+ opacity: 0.45;
+ cursor: not-allowed;
+ }
+ /* Key glyph marks BYOK engines (Meshy/Tripo/Rodin/Stability/Replicate)
+ so users see which lanes run on their own API key vs the free/included
+ ones. Sits inside the button after the label; the health dot stays on
+ ::after, so the two never collide. */
+ .aspect button .eng-key {
+ width: 0.82em;
+ height: 0.82em;
+ margin-left: 0.42em;
+ vertical-align: -0.13em;
+ opacity: 0.5;
+ transition: opacity 0.15s;
+ }
+ .aspect button:hover .eng-key,
+ .aspect button[aria-pressed='true'] .eng-key {
+ opacity: 0.95;
+ }
+ /* "FREE" pill on zero-cost engines (catalog free:true). A quiet green
+ accent so the free lanes read at a glance without shouting over the
+ selected-state styling. Sits after the label, before the health dot. */
+ .aspect button .eng-free {
+ margin-left: 0.45em;
+ padding: 0.05em 0.4em;
+ border-radius: 999px;
+ font-size: 0.62em;
+ font-weight: 700;
+ letter-spacing: 0.04em;
+ line-height: 1.5;
+ vertical-align: 0.08em;
+ /* Dark theme is the default — a bright mint reads on the dark button. */
+ color: #4ade80;
+ background: rgba(34, 197, 94, 0.14);
+ border: 1px solid rgba(74, 222, 128, 0.38);
+ }
+ html[data-theme='light'] .aspect button .eng-free {
+ color: #0a7d33;
+ background: rgba(34, 197, 94, 0.16);
+ border-color: rgba(34, 197, 94, 0.32);
+ }
+ .aspect button:disabled .eng-free {
+ opacity: 0.5;
+ }
+ /* Static legend decoding the engine-button affordances (FREE pill, key
+ glyph, health dots) so the picker is self-explanatory at a glance. */
+ .engine-legend {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-xs) var(--space-md);
+ margin: var(--space-2xs) 0 0;
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ }
+ .engine-legend .el-item {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.4em;
+ white-space: nowrap;
+ }
+ .engine-legend .el-free {
+ padding: 0.05em 0.4em;
+ border-radius: 999px;
+ font-size: 0.85em;
+ font-weight: 700;
+ letter-spacing: 0.04em;
+ color: #4ade80;
+ background: rgba(34, 197, 94, 0.14);
+ border: 1px solid rgba(74, 222, 128, 0.38);
+ }
+ html[data-theme='light'] .engine-legend .el-free {
+ color: #0a7d33;
+ background: rgba(34, 197, 94, 0.16);
+ border-color: rgba(34, 197, 94, 0.32);
+ }
+ .engine-legend .el-key {
+ width: 0.92em;
+ height: 0.92em;
+ opacity: 0.6;
+ }
+ .engine-legend .el-dot {
+ width: 0.5em;
+ height: 0.5em;
+ border-radius: 50%;
+ }
+ .engine-legend .el-dot-busy {
+ background: var(--warning, #e0a93e);
+ }
+ .engine-legend .el-dot-down {
+ background: var(--danger, #e05a5a);
+ opacity: 0.7;
+ }
+ .aspect button:focus-visible,
+ .chip:focus-visible,
+ .btn:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ .btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.5rem;
+ font-family: var(--font-display);
+ font-weight: 600;
+ font-size: var(--text-base);
+ color: #0b0b0b;
+ background: var(--accent);
+ border: 1px solid var(--accent);
+ border-radius: var(--radius-md);
+ padding: 0.6rem 1.2rem;
+ cursor: pointer;
+ transition:
+ transform 0.12s ease,
+ opacity 0.15s,
+ box-shadow 0.15s;
+ }
+ .btn:hover {
+ box-shadow: 0 0 0 4px var(--accent-soft);
+ }
+ .btn:active {
+ transform: translateY(1px);
+ }
+ .btn[disabled] {
+ opacity: 0.45;
+ cursor: not-allowed;
+ }
+ .btn-ghost {
+ background: transparent;
+ color: var(--ink);
+ border: 1px solid var(--stroke-strong);
+ }
+ .btn-ghost:hover {
+ background: var(--surface-2);
+ box-shadow: none;
+ }
+ /* Primary action — full-width, monochrome fill. */
+ #generate {
+ width: 100%;
+ justify-content: center;
+ font-size: var(--text-lg);
+ padding: 0.75rem 1.2rem;
+ background: var(--btn-primary-bg);
+ border-color: transparent;
+ color: var(--btn-primary-fg);
+ }
+ #generate:hover {
+ box-shadow:
+ 0 0 0 4px var(--accent-soft),
+ 0 8px 28px -8px rgba(255, 255, 255, 0.15);
+ }
+ /* Gated (High needs $THREE): readable "locked perk" state, not a faded
+ dead button — the lock panel above explains, this stays legible. */
+ #generate.is-gated,
+ #generate.is-gated:hover {
+ opacity: 1;
+ cursor: not-allowed;
+ background: var(--surface-2);
+ color: var(--muted);
+ border: 1px solid rgba(245, 196, 81, 0.4);
+ box-shadow: none;
+ }
+ .gen-kbd {
+ font-family: var(--font-mono);
+ font-size: 0.72em;
+ line-height: 1;
+ padding: 0.2em 0.4em;
+ border-radius: var(--radius-sm);
+ background: rgba(0, 0, 0, 0.16);
+ border: 1px solid rgba(0, 0, 0, 0.22);
+ color: inherit;
+ opacity: 0.85;
+ }
+ @media (max-width: 560px) {
+ .gen-kbd {
+ display: none;
+ }
+ }
+
+ /* Prompt tools — surprise · coach · counter -------------------- */
+ .prompt-tools {
+ display: flex;
+ align-items: center;
+ gap: var(--space-sm);
+ margin-top: var(--space-xs);
+ flex-wrap: wrap;
+ }
+ .ptool {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.4rem;
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ border-radius: 999px;
+ color: var(--ink-dim);
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ letter-spacing: 0.02em;
+ padding: 0.32rem 0.72rem;
+ cursor: pointer;
+ transition:
+ color 0.15s,
+ border-color 0.15s,
+ background 0.15s;
+ }
+ .ptool:hover {
+ color: var(--ink);
+ border-color: var(--stroke-strong);
+ background: var(--surface-2);
+ }
+ .ptool:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ .ptool svg {
+ width: 14px;
+ height: 14px;
+ }
+ .ptool.is-rolling svg {
+ animation: dice-roll 0.5s cubic-bezier(0.3, 0.7, 0.3, 1);
+ }
+ @keyframes dice-roll {
+ from {
+ transform: rotate(0);
+ }
+ to {
+ transform: rotate(360deg);
+ }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .ptool.is-rolling svg {
+ animation: none;
+ }
+ }
+ .prompt-coach {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.45rem;
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ line-height: 1.4;
+ min-height: 1.2em;
+ flex: 1 1 12rem;
+ min-width: 0;
+ }
+ .prompt-coach::before {
+ content: '';
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--ink-dim);
+ flex: none;
+ transition:
+ background 0.2s,
+ box-shadow 0.2s;
+ }
+ .prompt-coach[data-grade='strong'] {
+ color: var(--success);
+ }
+ .prompt-coach[data-grade='strong']::before {
+ background: var(--success);
+ box-shadow: 0 0 8px var(--success);
+ }
+ .prompt-coach[data-grade='warn'] {
+ color: var(--warning, #e0a93e);
+ }
+ .prompt-coach[data-grade='warn']::before {
+ background: var(--warning, #e0a93e);
+ }
+ .prompt-coach[data-grade='tip']::before {
+ background: var(--accent);
+ }
+ .prompt-count {
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ flex: none;
+ font-variant-numeric: tabular-nums;
+ margin-left: auto;
+ }
+ .prompt-count[data-near='true'] {
+ color: var(--warning, #e0a93e);
+ }
+ .chips-more {
+ background: transparent;
+ border: 1px dashed var(--stroke-strong);
+ border-radius: 999px;
+ color: var(--ink-dim);
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ letter-spacing: 0.04em;
+ padding: 0.4rem 0.85rem;
+ cursor: pointer;
+ transition:
+ color 0.15s,
+ border-color 0.15s,
+ transform 0.4s ease;
+ }
+ .chips-more:hover {
+ color: var(--ink);
+ border-color: var(--accent);
+ }
+ .chips-more:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ .chips-more.is-rolling {
+ transform: rotate(180deg);
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .chips-more.is-rolling {
+ transform: none;
+ }
+ }
+ .chip.is-swapping {
+ opacity: 0;
+ }
+
+ /* Quality tier + engine + BYOK --------------------------------- */
+ .forge-quality {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-sm);
+ margin-top: var(--space-sm);
+ padding-top: var(--space-sm);
+ border-top: 1px solid var(--stroke);
+ }
+ .fq-row {
+ display: flex;
+ align-items: center;
+ gap: var(--space-sm);
+ flex-wrap: wrap;
+ }
+ .fq-label {
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ color: var(--ink-dim);
+ min-width: 4.2rem;
+ }
+ /* forge.js hides the #aspect control itself when the mode makes it
+ irrelevant — collapse the labeled row with it, no orphan label. */
+ /* High is a $THREE holder perk — a small lock pill on the button makes
+ the premium nature legible before the user selects it (a quality
+ signal, not a nag). Gold while locked, green once the viewer holds
+ $THREE. forge.js (applyHighAffordances) flips data-state from the
+ live /api/three/access read. */
+ #tier button[data-tier='high'] {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.4rem;
+ }
+ .tier-lock {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.22rem;
+ font-family: var(--font-mono);
+ font-size: 0.68em;
+ line-height: 1;
+ padding: 0.18em 0.42em;
+ border-radius: 999px;
+ color: #f0d488;
+ background: rgba(245, 196, 81, 0.12);
+ border: 1px solid rgba(245, 196, 81, 0.32);
+ transition:
+ color 0.15s,
+ background 0.15s,
+ border-color 0.15s;
+ }
+ .tier-lock-ico {
+ width: 0.92em;
+ height: 0.92em;
+ }
+ .tier-lock[data-state='unlocked'] {
+ color: #6ee7a8;
+ background: rgba(110, 231, 168, 0.13);
+ border-color: rgba(110, 231, 168, 0.34);
+ }
+ #tier button[data-tier='high']:hover .tier-lock,
+ #tier button[data-tier='high']:focus-visible .tier-lock {
+ border-color: rgba(245, 196, 81, 0.55);
+ }
+ #tier button[data-tier='high']:hover .tier-lock[data-state='unlocked'],
+ #tier button[data-tier='high']:focus-visible .tier-lock[data-state='unlocked'] {
+ border-color: rgba(110, 231, 168, 0.55);
+ }
+ #tier button[data-tier='high'][aria-pressed='true'] .tier-lock {
+ background: rgba(245, 196, 81, 0.2);
+ }
+ #tier button[data-tier='high'][aria-pressed='true'] .tier-lock[data-state='unlocked'] {
+ background: rgba(110, 231, 168, 0.2);
+ }
+ /* Inline holder note under the Quality row — links to /three. forge.js
+ hides it while High is selected (the full in-place lock panel takes
+ over) and swaps the copy once the viewer is a holder. */
+ .fq-holder-note {
+ display: flex;
+ align-items: center;
+ gap: 0.4rem;
+ margin: 0.1rem 0 0;
+ font-size: var(--text-xs);
+ line-height: 1.5;
+ color: var(--ink-dim);
+ }
+ .fq-holder-note a {
+ color: var(--accent);
+ text-decoration: none;
+ font-weight: 500;
+ white-space: nowrap;
+ transition: opacity 0.15s;
+ }
+ .fq-holder-note a:hover {
+ text-decoration: underline;
+ opacity: 0.85;
+ }
+ .fq-holder-note a:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ border-radius: 2px;
+ }
+ .fq-holder-note .fq-holder-ico {
+ color: #f5c451;
+ font-size: 0.9em;
+ }
+ .fq-holder-note[data-state='unlocked'] .fq-holder-ico {
+ color: #6ee7a8;
+ }
+ /* Quiet holder free-quota line under Generate + the Forge-local wallet
+ connect chip (Part A). Token-only, matches the holder-note treatment. */
+ .fq-perk-row {
+ display: flex;
+ align-items: center;
+ gap: 0.6rem;
+ flex-wrap: wrap;
+ margin: 0.6rem 0 0;
+ }
+ .fq-perk-line {
+ margin: 0;
+ font-size: var(--text-xs);
+ line-height: 1.5;
+ color: var(--ink-dim);
+ display: inline-flex;
+ align-items: center;
+ gap: 0.35rem;
+ }
+ .fq-perk-line[data-state='perk'] {
+ color: var(--ink);
+ }
+ .fq-perk-line .fq-perk-ico {
+ color: #6ee7a8;
+ }
+ .fq-perk-line strong {
+ color: #6ee7a8;
+ font-weight: 700;
+ }
+ .fq-perk-line a {
+ color: var(--accent);
+ text-decoration: none;
+ font-weight: 500;
+ }
+ .fq-perk-line a:hover {
+ text-decoration: underline;
+ }
+ .fq-perk-line a:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ border-radius: 2px;
+ }
+ .fq-connect-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.35rem;
+ font-size: var(--text-xs);
+ font-weight: 600;
+ color: var(--ink);
+ background: var(--surface-2);
+ border: 1px solid var(--surface-3);
+ border-radius: var(--radius-pill);
+ padding: 5px 12px;
+ cursor: pointer;
+ transition: border-color 0.15s, transform 0.15s, background 0.15s;
+ }
+ .fq-connect-btn:hover {
+ border-color: var(--accent);
+ transform: translateY(-1px);
+ }
+ .fq-connect-btn:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ .fq-connect-btn.is-connected {
+ color: #6ee7a8;
+ border-color: rgba(110, 231, 168, 0.4);
+ }
+ .fq-connect-btn .fq-connect-ico {
+ font-size: 0.95em;
+ opacity: 0.8;
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .tier-lock {
+ transition: none;
+ }
+ .fq-connect-btn {
+ transition: none;
+ }
+ }
+ .fq-row:has(> .aspect.is-hidden) {
+ display: none;
+ }
+ /* The key field appears only for bring-your-own-key engines, so it
+ reads as a deliberate, self-contained zone — an inset panel with an
+ accent edge that eases in when the engine is selected. */
+ .byok-row {
+ display: flex;
+ align-items: center;
+ gap: var(--space-sm);
+ flex-wrap: wrap;
+ position: relative;
+ padding: 0.7rem 0.8rem 0.7rem 1rem;
+ background: var(--surface-2);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md);
+ }
+ .byok-row::before {
+ content: '';
+ position: absolute;
+ left: 0;
+ top: 0.6rem;
+ bottom: 0.6rem;
+ width: 2px;
+ border-radius: 0 2px 2px 0;
+ background: var(--accent);
+ opacity: 0.7;
+ }
+ .byok-row:not(.is-hidden) {
+ animation: byok-reveal 0.22s ease both;
+ }
+ @keyframes byok-reveal {
+ from {
+ opacity: 0;
+ transform: translateY(-3px);
+ }
+ to {
+ opacity: 1;
+ transform: none;
+ }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .byok-row:not(.is-hidden) {
+ animation: none;
+ }
+ }
+ .byok-row .fq-label {
+ min-width: 0;
+ color: var(--ink);
+ }
+ .byok-input {
+ flex: 1 1 16rem;
+ min-width: 0;
+ background: var(--bg);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md);
+ color: var(--ink);
+ font-family: var(--font-mono);
+ font-size: var(--text-sm);
+ padding: 0.5rem 0.7rem;
+ outline: none;
+ transition:
+ border-color 0.15s,
+ box-shadow 0.15s,
+ background 0.15s;
+ }
+ .byok-input:hover {
+ border-color: var(--stroke-strong);
+ }
+ .byok-input:focus-visible {
+ border-color: var(--accent);
+ box-shadow: 0 0 0 3px var(--accent-soft);
+ }
+ .byok-input[aria-invalid='true'] {
+ border-color: var(--danger);
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--danger) 22%, transparent);
+ }
+ .byok-hint {
+ flex-basis: 100%;
+ font-size: var(--text-xs);
+ line-height: 1.5;
+ color: var(--ink-dim);
+ }
+ .byok-hint a {
+ color: var(--accent);
+ text-decoration: none;
+ font-weight: 500;
+ white-space: nowrap;
+ transition: opacity 0.15s;
+ }
+ .byok-hint a:hover {
+ text-decoration: underline;
+ opacity: 0.85;
+ }
+ .fq-estimate {
+ margin: 0;
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ min-height: 1.1em;
+ }
+ .fq-estimate strong {
+ color: var(--ink);
+ font-weight: 600;
+ }
+ .fq-estimate .est-free {
+ color: var(--success);
+ font-weight: 700;
+ }
+ .fq-estimate .est-cost {
+ color: var(--ink);
+ font-weight: 700;
+ }
+
+ /* Mode switch — now lives inside .composer as the first element */
+ .mode-switch-wrap {
+ display: flex;
+ margin: calc(-1 * var(--space-md)) calc(-1 * var(--space-md)) var(--space-sm);
+ border-bottom: 1px solid var(--stroke);
+ }
+ .mode-switch {
+ display: flex;
+ width: 100%;
+ gap: 0;
+ background: transparent;
+ border: none;
+ border-radius: 0;
+ padding: 0;
+ }
+ .mode-switch button {
+ flex: 1;
+ background: transparent;
+ border: none;
+ border-bottom: 2px solid transparent;
+ color: var(--ink-dim);
+ font-family: var(--font-display);
+ font-size: var(--text-sm);
+ font-weight: 600;
+ padding: 0.65rem 0.6rem;
+ border-radius: 0;
+ cursor: pointer;
+ transition:
+ color 0.15s,
+ border-color 0.15s;
+ margin-bottom: -1px;
+ }
+ .mode-switch button:hover {
+ color: var(--ink);
+ }
+ .mode-switch button[aria-selected='true'] {
+ background: transparent;
+ color: var(--ink);
+ border-bottom-color: var(--accent);
+ }
+ .mode-switch button:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+
+ /* View slots — image / multi-view mode ------------------------- */
+ .image-pane {
+ display: flex;
+ flex-direction: column;
+ }
+ .views-grid {
+ display: grid;
+ grid-template-columns: repeat(4, 1fr);
+ gap: var(--space-sm);
+ }
+ @media (max-width: 620px) {
+ .views-grid {
+ grid-template-columns: repeat(2, 1fr);
+ }
+ }
+ /* Sketch mode reuses the view-slot kit with a single, wider slot.
+ Declared after both .views-grid rules so it wins at every width. */
+ .sketch-grid {
+ grid-template-columns: minmax(140px, 240px);
+ }
+ .view-slot {
+ position: relative;
+ aspect-ratio: 1 / 1;
+ border: 1px dashed var(--stroke-strong);
+ border-radius: var(--radius-md);
+ background: var(--surface-1);
+ overflow: hidden;
+ display: grid;
+ place-items: center;
+ cursor: pointer;
+ transition:
+ border-color 0.15s,
+ background 0.15s,
+ transform 0.12s;
+ }
+ .view-slot:hover {
+ border-color: var(--accent);
+ }
+ .view-slot:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ .view-slot.drop-target {
+ border-color: var(--accent);
+ border-style: solid;
+ background: var(--accent-soft);
+ transform: scale(1.02);
+ }
+ .view-slot[data-state='uploaded'] {
+ border-style: solid;
+ cursor: grab;
+ }
+ .view-slot[data-state='uploaded']:active {
+ cursor: grabbing;
+ }
+ .view-slot[data-state='error'] {
+ border-color: var(--danger);
+ border-style: solid;
+ }
+ .view-slot.dragging {
+ opacity: 0.4;
+ }
+ /* Inner regions toggled by the slot's data-state. */
+ .vs-empty,
+ .vs-uploading,
+ .vs-error {
+ display: none;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 0.35rem;
+ color: var(--ink-dim);
+ font-size: var(--text-xs);
+ padding: 0.5rem;
+ text-align: center;
+ }
+ .vs-thumb,
+ .vs-remove,
+ .vs-badge {
+ display: none;
+ }
+ .view-slot[data-state='empty'] .vs-empty {
+ display: flex;
+ }
+ .view-slot[data-state='uploading'] .vs-uploading {
+ display: flex;
+ }
+ .view-slot[data-state='uploaded'] .vs-thumb {
+ display: block;
+ }
+ .view-slot[data-state='uploaded'] .vs-remove {
+ display: grid;
+ }
+ .view-slot[data-state='uploaded'] .vs-badge {
+ display: block;
+ }
+ .view-slot[data-state='error'] .vs-error {
+ display: flex;
+ }
+ .vs-icon {
+ font-size: 1.5rem;
+ line-height: 1;
+ color: var(--ink-dim);
+ }
+ .vs-label {
+ font-family: var(--font-mono);
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ }
+ .vs-thumb {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ pointer-events: none;
+ }
+ .vs-remove {
+ position: absolute;
+ top: 5px;
+ right: 5px;
+ width: 22px;
+ height: 22px;
+ place-items: center;
+ border: none;
+ border-radius: 50%;
+ background: rgba(0, 0, 0, 0.6);
+ color: #fff;
+ font-size: 1rem;
+ line-height: 1;
+ cursor: pointer;
+ backdrop-filter: blur(4px);
+ transition: background 0.15s;
+ }
+ .vs-remove:hover {
+ background: var(--danger);
+ }
+ .vs-badge {
+ position: absolute;
+ bottom: 5px;
+ left: 5px;
+ font-family: var(--font-mono);
+ font-size: 0.6rem;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ padding: 1px 6px;
+ border-radius: 999px;
+ background: rgba(0, 0, 0, 0.6);
+ color: var(--ink);
+ backdrop-filter: blur(4px);
+ }
+ .vs-uploading .shimmer {
+ position: absolute;
+ inset: 0;
+ background: linear-gradient(
+ 100deg,
+ transparent 20%,
+ rgba(255, 255, 255, 0.06) 50%,
+ transparent 80%
+ );
+ background-size: 200% 100%;
+ animation: shimmer 1.4s linear infinite;
+ }
+ .vs-retry {
+ background: transparent;
+ border: 1px solid var(--stroke-strong);
+ color: var(--ink);
+ border-radius: var(--radius-sm);
+ font-size: var(--text-xs);
+ padding: 0.2rem 0.5rem;
+ cursor: pointer;
+ }
+ .vs-retry:hover {
+ border-color: var(--accent);
+ }
+ .views-hint {
+ color: var(--ink-dim);
+ font-size: var(--text-xs);
+ margin: var(--space-sm) 0 0;
+ text-align: center;
+ }
+
+ /* Live multi-view counter — turns four anonymous empty boxes into a
+ legible "0 of 4" progress with pips, and teaches that more views ⇒
+ sharper mesh. Updated by src/forge.js as slots fill. */
+ .views-counter {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 0.55rem;
+ margin-top: var(--space-sm);
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ }
+ .views-pips {
+ display: inline-flex;
+ gap: 4px;
+ }
+ .views-pips i {
+ width: 9px;
+ height: 9px;
+ border-radius: 50%;
+ border: 1px solid var(--stroke-strong);
+ background: transparent;
+ transition:
+ background 0.2s ease,
+ border-color 0.2s ease,
+ transform 0.2s ease;
+ }
+ .views-pips i[data-filled='true'] {
+ background: var(--accent);
+ border-color: var(--accent);
+ transform: scale(1.08);
+ }
+ .views-counter .vc-text strong {
+ color: var(--ink);
+ font-weight: 600;
+ }
+ .views-counter .vc-quality {
+ color: var(--accent);
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .views-pips i {
+ transition: none;
+ }
+ }
+
+ /* Required-input cue for the sketch prompt — sketch mode can't generate
+ without a description, so it earns a visible "Required" tag that turns
+ to a danger tint when the user tries to submit empty. */
+ .req-tag {
+ display: inline-block;
+ margin-left: 0.4rem;
+ font-family: var(--font-mono);
+ font-size: 0.62rem;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ color: var(--ink-dim);
+ border: 1px solid var(--stroke);
+ border-radius: 999px;
+ padding: 1px 6px;
+ vertical-align: 0.1em;
+ transition:
+ color 0.15s,
+ border-color 0.15s,
+ background 0.15s;
+ }
+ .image-prompt[aria-invalid='true'] {
+ border-color: var(--danger);
+ }
+ .image-prompt[aria-invalid='true'] + .views-hint .req-tag,
+ .req-tag[data-missing='true'] {
+ color: var(--danger);
+ border-color: var(--danger);
+ background: color-mix(in srgb, var(--danger) 14%, transparent);
+ }
+ .image-prompt {
+ width: 100%;
+ min-height: 52px;
+ resize: vertical;
+ margin-top: var(--space-sm);
+ background: transparent;
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md);
+ outline: none;
+ color: var(--ink);
+ font-family: var(--font-body);
+ font-size: var(--text-base);
+ line-height: var(--leading-normal);
+ padding: 0.55rem 0.7rem;
+ }
+ .image-prompt:focus {
+ border-color: var(--stroke-strong);
+ }
+ .image-prompt::placeholder {
+ color: var(--ink-dim);
+ }
+ .views-badge {
+ font-family: var(--font-mono);
+ font-size: 0.62rem;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: var(--ink-dim);
+ border: 1px solid var(--stroke);
+ border-radius: 999px;
+ padding: 1px 7px;
+ margin-left: 0.5rem;
+ }
+
+ /* Example chips ------------------------------------------------ */
+ .chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-xs);
+ margin-top: var(--space-sm);
+ }
+ .chip {
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ border-radius: 999px;
+ color: var(--ink-dim);
+ font-size: var(--text-sm);
+ padding: 0.4rem 0.85rem;
+ cursor: pointer;
+ transition:
+ color 0.15s,
+ border-color 0.15s,
+ background 0.15s,
+ opacity 0.18s ease;
+ }
+ .chip:hover {
+ color: var(--ink);
+ border-color: var(--accent);
+ background: var(--accent-soft);
+ }
+
+ /* Workspace / states ------------------------------------------ */
+ .stage {
+ min-height: min(calc(100svh - 200px), 700px);
+ display: flex;
+ flex-direction: column;
+ }
+ .stage > .panel,
+ .stage > .forge-empty {
+ flex: 1;
+ }
+
+ /* Idle — a live model, not a void. The newest community forge (or a
+ labeled first-party sample) stands here so the first thing a visitor
+ sees is the product's output. Markup in #state-empty; data wiring in
+ the inline idle-teaser module at the end of the page. */
+ .idle-viewer-wrap {
+ position: relative;
+ }
+ .idle-viewer-wrap model-viewer {
+ width: 100%;
+ height: min(52vh, 480px);
+ background: radial-gradient(120% 120% at 50% 0%, #1a1612 0%, #0b0a09 70%);
+ --poster-color: transparent;
+ }
+ html[data-theme='light'] .idle-viewer-wrap model-viewer {
+ background: radial-gradient(120% 120% at 50% 0%, #f3eee9 0%, #e7e2dc 70%);
+ }
+ .idle-tag {
+ position: absolute;
+ top: 10px;
+ left: 12px;
+ font-family: var(--font-mono);
+ font-size: 0.65rem;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ color: var(--ink-dim);
+ background: rgba(0, 0, 0, 0.45);
+ border: 1px solid var(--stroke);
+ border-radius: 999px;
+ padding: 2px 9px;
+ backdrop-filter: blur(4px);
+ }
+ .idle-bar {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-sm);
+ padding: var(--space-sm) var(--space-md);
+ border-top: 1px solid var(--stroke);
+ flex-wrap: wrap;
+ }
+ .idle-caption {
+ display: flex;
+ flex-direction: column;
+ gap: 0.15rem;
+ min-width: 0;
+ flex: 1 1 16rem;
+ }
+ .idle-kicker {
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: var(--accent);
+ }
+ .idle-prompt {
+ color: var(--ink);
+ font-size: var(--text-sm);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .idle-hint {
+ flex-basis: 100%;
+ margin: 0;
+ color: var(--ink-dim);
+ font-size: var(--text-xs);
+ line-height: var(--leading-normal);
+ }
+ .panel {
+ background: var(--surface-glass);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-lg);
+ overflow: hidden;
+ }
+ .is-hidden {
+ display: none !important;
+ }
+
+ /* Generating state */
+ .gen {
+ display: grid;
+ grid-template-columns: 1fr 1.1fr;
+ gap: var(--space-md);
+ padding: var(--space-md);
+ }
+ @media (max-width: 720px) {
+ .gen {
+ grid-template-columns: 1fr;
+ }
+ .composer-row {
+ justify-content: stretch;
+ }
+ .composer-row .btn {
+ width: 100%;
+ justify-content: center;
+ }
+ }
+ .gen-preview {
+ position: relative;
+ aspect-ratio: 1 / 1;
+ border-radius: var(--radius-md);
+ border: 1px solid var(--stroke);
+ background: var(--surface-1);
+ overflow: hidden;
+ display: grid;
+ place-items: center;
+ }
+ .gen-preview img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ animation: paint-in 0.9s cubic-bezier(0.2, 0.7, 0.2, 1) both;
+ }
+ @keyframes paint-in {
+ from {
+ opacity: 0;
+ filter: blur(16px) saturate(0.7);
+ transform: scale(1.05);
+ }
+ to {
+ opacity: 1;
+ filter: blur(0) saturate(1);
+ transform: none;
+ }
+ }
+ /* Reconstruction scanline — sweeps the reference image while the mesh
+ step is live, so the wait reads as work, not silence. */
+ .gen-preview.is-reconstructing::after {
+ content: '';
+ position: absolute;
+ inset: 0;
+ background: linear-gradient(
+ 180deg,
+ transparent 0%,
+ color-mix(in srgb, var(--accent) 30%, transparent) 50%,
+ transparent 100%
+ );
+ background-size: 100% 34%;
+ background-repeat: no-repeat;
+ animation: forge-scan 2.6s ease-in-out infinite;
+ mix-blend-mode: screen;
+ pointer-events: none;
+ }
+ @keyframes forge-scan {
+ from {
+ background-position: 0 -40%;
+ }
+ to {
+ background-position: 0 140%;
+ }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .gen-preview img {
+ animation: none;
+ }
+ .gen-preview.is-reconstructing::after {
+ display: none;
+ }
+ }
+ .gen-preview .shimmer {
+ position: absolute;
+ inset: 0;
+ background: linear-gradient(
+ 100deg,
+ transparent 20%,
+ rgba(255, 255, 255, 0.06) 50%,
+ transparent 80%
+ );
+ background-size: 200% 100%;
+ animation: shimmer 1.4s linear infinite;
+ }
+ @keyframes shimmer {
+ to {
+ background-position: -200% 0;
+ }
+ }
+ .gen-steps {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ gap: var(--space-sm);
+ }
+ .step {
+ display: flex;
+ align-items: center;
+ gap: 0.7rem;
+ color: var(--ink-dim);
+ font-size: var(--text-sm);
+ }
+ .step .dot {
+ width: 14px;
+ height: 14px;
+ border-radius: 50%;
+ border: 2px solid var(--stroke-strong);
+ flex: none;
+ }
+ .step[data-state='active'] {
+ color: var(--ink);
+ }
+ .step[data-state='active'] .dot {
+ border-color: var(--accent);
+ border-top-color: transparent;
+ animation: spin 0.8s linear infinite;
+ }
+ .step[data-state='done'] {
+ color: var(--ink);
+ }
+ .step[data-state='done'] .dot {
+ background: var(--success);
+ border-color: var(--success);
+ }
+ @keyframes spin {
+ to {
+ transform: rotate(360deg);
+ }
+ }
+ .gen-meta {
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ margin-top: var(--space-xs);
+ }
+ .gen-meta strong {
+ color: var(--ink);
+ font-weight: 600;
+ }
+
+ /* Honest elapsed-vs-typical meter. The fill maps real elapsed time
+ against the engine's real catalog ETA on an asymptotic curve that
+ never reaches 100% on its own — only a real finished GLB snaps it to
+ full. Past the typical time it holds near the cap and recolours to
+ amber ("longer than usual"), so the bar is informative, never faked. */
+ .gen-progress {
+ position: relative;
+ height: 5px;
+ margin-top: var(--space-sm);
+ border-radius: 999px;
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ overflow: hidden;
+ }
+ .gen-progress-fill {
+ position: absolute;
+ inset: 0;
+ width: 0%;
+ border-radius: inherit;
+ background: linear-gradient(
+ 90deg,
+ color-mix(in srgb, var(--accent) 70%, transparent),
+ var(--accent)
+ );
+ transition: width 0.9s cubic-bezier(0.33, 1, 0.68, 1), background 0.4s ease;
+ }
+ /* Moving sheen reads as live work without implying a known finish. */
+ .gen-progress-fill::after {
+ content: '';
+ position: absolute;
+ inset: 0;
+ background: linear-gradient(
+ 100deg,
+ transparent 30%,
+ rgba(255, 255, 255, 0.28) 50%,
+ transparent 70%
+ );
+ background-size: 220% 100%;
+ animation: gen-sheen 1.6s linear infinite;
+ }
+ .gen-progress[data-over='true'] .gen-progress-fill {
+ background: linear-gradient(
+ 90deg,
+ color-mix(in srgb, var(--warning, #e0a93e) 70%, transparent),
+ var(--warning, #e0a93e)
+ );
+ }
+ .gen-progress[data-done='true'] .gen-progress-fill {
+ background: linear-gradient(
+ 90deg,
+ color-mix(in srgb, var(--success) 70%, transparent),
+ var(--success)
+ );
+ }
+ .gen-progress[data-done='true'] .gen-progress-fill::after,
+ .gen-progress[data-indeterminate='true'] .gen-progress-fill::after {
+ animation-play-state: running;
+ }
+ /* No catalog ETA (unknown duration) — a slim travelling band instead of
+ a measured fill, so we never imply a finish time we don't have. */
+ .gen-progress[data-indeterminate='true'] .gen-progress-fill {
+ width: 38% !important;
+ animation: gen-indeterminate 1.5s ease-in-out infinite;
+ }
+ @keyframes gen-sheen {
+ to {
+ background-position: -220% 0;
+ }
+ }
+ @keyframes gen-indeterminate {
+ 0% {
+ transform: translateX(-120%);
+ }
+ 100% {
+ transform: translateX(330%);
+ }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .gen-progress-fill::after {
+ animation: none;
+ }
+ .gen-progress[data-indeterminate='true'] .gen-progress-fill {
+ animation: none;
+ width: 100% !important;
+ opacity: 0.5;
+ }
+ .gen-progress-fill {
+ transition: none;
+ }
+ }
+
+ /* Result state */
+ .viewer-shell {
+ position: relative;
+ }
+ .viewer-shell .viewer-load-error {
+ display: none;
+ position: absolute;
+ inset: 0;
+ z-index: 4;
+ align-items: center;
+ justify-content: center;
+ flex-direction: column;
+ gap: var(--space-sm);
+ text-align: center;
+ background: radial-gradient(120% 120% at 50% 0%, #1a1612 0%, #0b0a09 70%);
+ padding: var(--space-xl);
+ }
+ html[data-theme='light'] .viewer-shell .viewer-load-error {
+ background: radial-gradient(120% 120% at 50% 0%, #f3eee9 0%, #e7e2dc 70%);
+ }
+ .viewer-shell.has-load-error .viewer-load-error {
+ display: flex;
+ }
+ .viewer-shell.has-load-error model-viewer {
+ opacity: 0;
+ pointer-events: none;
+ }
+ /* Load skeleton — covers the dark void between a result being revealed and
+ the GLB actually painting. Shown while .is-loading is set, removed on the
+ model-viewer 'load' event (or on load error, which has its own panel). */
+ .viewer-shell .viewer-skeleton {
+ display: none;
+ position: absolute;
+ inset: 0;
+ z-index: 3;
+ align-items: center;
+ justify-content: center;
+ overflow: hidden;
+ background: radial-gradient(120% 120% at 50% 0%, #1a1612 0%, #0b0a09 70%);
+ }
+ html[data-theme='light'] .viewer-shell .viewer-skeleton {
+ background: radial-gradient(120% 120% at 50% 0%, #f3eee9 0%, #e7e2dc 70%);
+ }
+ .viewer-shell.is-loading .viewer-skeleton {
+ display: flex;
+ }
+ .viewer-shell.is-loading.has-load-error .viewer-skeleton {
+ display: none;
+ }
+ .viewer-skeleton-sheen {
+ position: absolute;
+ inset: 0;
+ background: linear-gradient(
+ 105deg,
+ transparent 30%,
+ color-mix(in srgb, var(--accent) 12%, transparent) 50%,
+ transparent 70%
+ );
+ transform: translateX(-100%);
+ animation: viewer-skeleton-sweep 1.6s ease-in-out infinite;
+ }
+ .viewer-skeleton-label {
+ position: relative;
+ z-index: 1;
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ letter-spacing: 0.04em;
+ }
+ @keyframes viewer-skeleton-sweep {
+ to {
+ transform: translateX(100%);
+ }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .viewer-skeleton-sheen {
+ animation: none;
+ }
+ }
+ .viewer-load-error-icon {
+ font-size: 2rem;
+ opacity: 0.5;
+ }
+ .viewer-load-error p {
+ color: var(--ink-dim);
+ font-size: var(--text-sm);
+ max-width: 28ch;
+ margin: 0;
+ line-height: var(--leading-normal);
+ }
+ .result model-viewer {
+ width: 100%;
+ height: min(62vh, 600px);
+ background: radial-gradient(120% 120% at 50% 0%, #1a1612 0%, #0b0a09 70%);
+ --poster-color: transparent;
+ transition: opacity 0.45s ease;
+ }
+ html[data-theme='light'] .result model-viewer {
+ background: radial-gradient(120% 120% at 50% 0%, #f3eee9 0%, #e7e2dc 70%);
+ }
+ /* Materialize reveal — the WebGL overlay src/forge-reveal.js plays the
+ dissolve in, then crossfades away to the standing viewer beneath. */
+ .forge-reveal-overlay {
+ position: absolute;
+ inset: 0;
+ z-index: 2;
+ pointer-events: none;
+ transition: opacity 0.42s ease;
+ }
+ .forge-reveal-overlay canvas {
+ display: block;
+ width: 100%;
+ height: 100%;
+ }
+ .forge-reveal-overlay.is-fading {
+ opacity: 0;
+ }
+
+ /* Cinema mode — distraction-free fullscreen turntable (F / Esc).
+ Built for screen recording: chrome hides until the pointer rests
+ on the bottom bar. */
+ body.forge-cinema {
+ overflow: hidden;
+ }
+ .result.is-cinema {
+ position: fixed;
+ inset: 0;
+ z-index: 90;
+ border: none;
+ border-radius: 0;
+ display: flex;
+ flex-direction: column;
+ background: radial-gradient(120% 90% at 50% 10%, #181a1f 0%, #0a0b0d 60%, #060708 100%);
+ }
+ .result.is-cinema > :not(.viewer-shell):not(.result-bar) {
+ display: none;
+ }
+ .result.is-cinema .viewer-shell {
+ flex: 1;
+ min-height: 0;
+ display: flex;
+ }
+ .result.is-cinema model-viewer {
+ flex: 1;
+ height: 100%;
+ background: transparent;
+ }
+ .result.is-cinema .result-bar {
+ position: absolute;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ border-top: none;
+ background: linear-gradient(transparent, rgba(0, 0, 0, 0.6));
+ opacity: 0;
+ transition: opacity 0.3s ease;
+ }
+ .result.is-cinema .result-bar:hover,
+ .result.is-cinema .result-bar:focus-within {
+ opacity: 1;
+ }
+ .result.is-cinema::after {
+ content: 'F or Esc to exit · drag to orbit';
+ position: absolute;
+ top: 14px;
+ right: 16px;
+ font-family: var(--font-mono);
+ font-size: 12px;
+ color: rgba(255, 255, 255, 0.55);
+ pointer-events: none;
+ animation: cinema-hint 4.5s ease forwards;
+ }
+ @keyframes cinema-hint {
+ 0%,
+ 70% {
+ opacity: 1;
+ }
+ 100% {
+ opacity: 0;
+ }
+ }
+ .result-bar {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-sm);
+ padding: var(--space-sm) var(--space-md);
+ border-top: 1px solid var(--stroke);
+ flex-wrap: wrap;
+ }
+ .result-bar .label {
+ font-size: var(--text-sm);
+ color: var(--ink-dim);
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ /* Auto-save confirmation chip — shown briefly after generation completes */
+ @keyframes saved-pop {
+ 0% { opacity: 0; transform: translateY(3px); }
+ 20% { opacity: 1; transform: translateY(0); }
+ 80% { opacity: 1; }
+ 100% { opacity: 0; }
+ }
+ .saved-chip {
+ font-size: 0.7rem;
+ color: var(--accent);
+ background: var(--accent-soft);
+ border: 1px solid color-mix(in srgb, var(--accent) 40%, transparent);
+ border-radius: 999px;
+ padding: 1px 8px;
+ flex: none;
+ white-space: nowrap;
+ animation: saved-pop 3s ease forwards;
+ }
+ .saved-chip.is-hidden { display: none; }
+ .result-bar .actions {
+ display: flex;
+ gap: var(--space-xs);
+ flex: none;
+ align-items: center;
+ flex-wrap: wrap;
+ justify-content: flex-end;
+ }
+
+ /* Refine — re-run the same prompt/views one quality tier higher. An
+ accent-tinted "level up" affordance: clearly more inviting than the
+ ghost buttons, but it yields visual primacy to the solid "Make
+ another" CTA beside it. Hidden by JS once the result is already High. */
+ .btn-refine {
+ color: var(--accent);
+ background: var(--accent-soft);
+ border: 1px solid color-mix(in srgb, var(--accent) 55%, transparent);
+ }
+ .btn-refine:hover {
+ background: color-mix(in srgb, var(--accent) 18%, transparent);
+ box-shadow: 0 0 0 3px var(--accent-soft);
+ }
+ .btn-refine .refine-arrow {
+ transition: transform 0.18s ease;
+ }
+ .btn-refine:hover .refine-arrow {
+ transform: translateY(-2px);
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .btn-refine .refine-arrow {
+ transition: none;
+ }
+ }
+
+ /* On phones the action row is the most cramped surface — let it wrap
+ into a tidy grid where the two primary CTAs (Refine + Make another)
+ span full width and lead, with the secondary tools below them. */
+ @media (max-width: 560px) {
+ .result-bar {
+ flex-direction: column;
+ align-items: stretch;
+ }
+ .result-bar .actions {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: var(--space-xs);
+ justify-content: stretch;
+ }
+ .result-bar .actions > .btn {
+ width: 100%;
+ justify-content: center;
+ }
+ /* Primary CTAs first and full-bleed; the verdict pair spans too. */
+ .result-bar .actions #again,
+ .result-bar .actions #refine {
+ grid-column: 1 / -1;
+ order: -2;
+ }
+ .result-bar .actions #refine {
+ order: -3;
+ }
+ .result-bar .actions .verdict {
+ grid-column: 1 / -1;
+ order: -1;
+ justify-content: center;
+ }
+ }
+
+ /* Download stamping — dim the link while the GLB is being fetched + stamped */
+ #download[data-stamping] {
+ opacity: 0.5;
+ pointer-events: none;
+ cursor: wait;
+ }
+ #download[data-stamping]::after {
+ content: '…';
+ }
+
+ /* Category picker — appears below the result bar after generation */
+ .cat-picker {
+ display: flex;
+ align-items: center;
+ gap: var(--space-xs);
+ padding: var(--space-xs) var(--space-md);
+ border-top: 1px solid var(--stroke);
+ flex-wrap: wrap;
+ }
+ .cat-picker-label {
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ font-family: var(--font-mono);
+ letter-spacing: 0.06em;
+ white-space: nowrap;
+ flex: none;
+ }
+ .forge-cat-btn {
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ border-radius: 999px;
+ color: var(--ink-dim);
+ font-size: var(--text-xs);
+ font-family: var(--font-mono);
+ padding: 0.25rem 0.7rem;
+ cursor: pointer;
+ transition: background 0.15s, color 0.15s, border-color 0.15s;
+ }
+ .forge-cat-btn:hover {
+ color: var(--ink);
+ border-color: var(--stroke-strong);
+ }
+ .forge-cat-btn:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ .forge-cat-btn.active {
+ background: var(--surface-3);
+ border-color: var(--stroke-strong);
+ color: var(--ink);
+ }
+ /* Two-class grouping inside the picker: "Agents" (can get a brain) vs
+ "Items" (objects). Subtle labels + a divider keep it scannable. */
+ .cat-group-label {
+ font-size: var(--text-xs);
+ font-family: var(--font-mono);
+ color: var(--ink);
+ letter-spacing: 0.04em;
+ opacity: 0.75;
+ white-space: nowrap;
+ flex: none;
+ }
+ .cat-group-sep {
+ width: 1px;
+ align-self: stretch;
+ min-height: 18px;
+ background: var(--stroke);
+ margin: 0 0.25rem;
+ flex: none;
+ }
+ .cat-picker-help {
+ flex-basis: 100%;
+ margin: 0.35rem 0 0;
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ line-height: 1.45;
+ }
+
+ /* Keep / discard verdict (the flywheel signal) */
+ .verdict {
+ display: inline-flex;
+ gap: 2px;
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md);
+ padding: 2px;
+ }
+ .verdict button {
+ background: transparent;
+ border: none;
+ color: var(--ink-dim);
+ font-size: var(--text-sm);
+ padding: 0.34rem 0.6rem;
+ border-radius: var(--radius-sm);
+ cursor: pointer;
+ transition:
+ background 0.15s,
+ color 0.15s;
+ }
+ .verdict button:hover {
+ color: var(--ink);
+ }
+ .verdict button:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ .verdict button[aria-pressed='true'][data-outcome='accepted'] {
+ background: color-mix(in srgb, var(--success) 22%, transparent);
+ color: var(--success);
+ }
+ .verdict button[aria-pressed='true'][data-outcome='rejected'] {
+ background: color-mix(in srgb, var(--danger) 20%, transparent);
+ color: var(--danger);
+ }
+
+ /* Optimize / retopology panel --------------------------------- */
+ .optimize {
+ border-top: 1px solid var(--stroke);
+ }
+ .optimize-toggle {
+ width: 100%;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-sm);
+ background: transparent;
+ border: none;
+ color: var(--ink);
+ font-family: var(--font-display);
+ font-weight: 600;
+ font-size: var(--text-sm);
+ padding: var(--space-sm) var(--space-md);
+ cursor: pointer;
+ }
+ .optimize-toggle:hover {
+ background: var(--surface-2);
+ }
+ .optimize-toggle:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: -2px;
+ }
+ .optimize-toggle .chev {
+ transition: transform 0.18s ease;
+ color: var(--ink-dim);
+ }
+ .optimize[data-open='true'] .optimize-toggle .chev {
+ transform: rotate(180deg);
+ }
+ .optimize-body {
+ display: none;
+ flex-direction: column;
+ gap: var(--space-md);
+ padding: 0 var(--space-md) var(--space-md);
+ }
+ .optimize[data-open='true'] .optimize-body {
+ display: flex;
+ }
+ .opt-field {
+ display: flex;
+ flex-direction: column;
+ gap: 0.4rem;
+ }
+ .opt-field > span {
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ font-family: var(--font-mono);
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ }
+ .seg {
+ display: inline-flex;
+ flex-wrap: wrap;
+ gap: 2px;
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md);
+ padding: 2px;
+ }
+ .seg button {
+ flex: 1 1 auto;
+ background: transparent;
+ border: none;
+ color: var(--ink-dim);
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ padding: 0.4rem 0.7rem;
+ border-radius: var(--radius-sm);
+ cursor: pointer;
+ transition:
+ background 0.15s,
+ color 0.15s;
+ }
+ .seg button:hover {
+ color: var(--ink);
+ }
+ .seg button[aria-pressed='true'] {
+ background: var(--surface-3);
+ color: var(--ink);
+ }
+ .seg button:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ .opt-mode-hint {
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ line-height: 1.4;
+ min-height: 1.4em;
+ }
+ .opt-row {
+ display: flex;
+ gap: var(--space-md);
+ flex-wrap: wrap;
+ }
+ .opt-row .opt-field {
+ flex: 1 1 140px;
+ }
+ .opt-select {
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md);
+ color: var(--ink);
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ padding: 0.45rem 0.6rem;
+ }
+ .opt-select:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 1px;
+ }
+ .opt-actions {
+ display: flex;
+ align-items: center;
+ gap: var(--space-md);
+ flex-wrap: wrap;
+ }
+ .opt-status {
+ font-size: var(--text-xs);
+ font-family: var(--font-mono);
+ color: var(--ink-dim);
+ }
+ .opt-status[data-kind='error'] {
+ color: var(--danger);
+ }
+ .opt-status[data-kind='done'] {
+ color: var(--success);
+ }
+ .opt-stats {
+ display: flex;
+ gap: var(--space-md);
+ flex-wrap: wrap;
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ }
+ .opt-stats strong {
+ color: var(--ink);
+ font-weight: 600;
+ }
+
+ /* Stylize — one-click geometric filters ----------------------- */
+ .stylize {
+ border-top: 1px solid var(--stroke);
+ padding: var(--space-md);
+ }
+ .stylize-head h3 {
+ font-family: var(--font-display);
+ font-size: var(--text-base);
+ margin: 0 0 0.15rem;
+ }
+ .stylize-sub {
+ color: var(--ink-dim);
+ font-size: var(--text-sm);
+ line-height: var(--leading-normal);
+ margin: 0 0 var(--space-md);
+ max-width: 60ch;
+ }
+ .stylize-gallery {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
+ gap: var(--space-sm);
+ }
+ .stylize-card {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 0.35rem;
+ text-align: left;
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md);
+ padding: var(--space-sm);
+ cursor: pointer;
+ color: var(--ink);
+ font: inherit;
+ transition:
+ border-color 0.15s,
+ transform 0.12s,
+ box-shadow 0.15s,
+ background 0.15s;
+ }
+ .stylize-card:hover {
+ border-color: var(--stroke-strong);
+ transform: translateY(-2px);
+ box-shadow: 0 16px 36px -26px rgba(0, 0, 0, 0.9);
+ }
+ .stylize-card:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ .stylize-card:active {
+ transform: translateY(0);
+ }
+ .stylize-card[aria-pressed='true'] {
+ border-color: var(--accent);
+ background: var(--accent-soft);
+ }
+ .stylize-card[disabled] {
+ opacity: 0.5;
+ cursor: not-allowed;
+ transform: none;
+ box-shadow: none;
+ }
+ .stylize-thumb {
+ width: 100%;
+ aspect-ratio: 16 / 10;
+ display: grid;
+ place-items: center;
+ border-radius: var(--radius-sm);
+ background: radial-gradient(120% 120% at 50% 0%, #161616 0%, #0c0c0c 75%);
+ color: var(--ink-dim);
+ transition:
+ color 0.15s,
+ transform 0.2s ease;
+ }
+ .stylize-thumb svg {
+ width: 58%;
+ height: 58%;
+ }
+ .stylize-card:hover .stylize-thumb,
+ .stylize-card[aria-pressed='true'] .stylize-thumb {
+ color: var(--accent);
+ }
+ .stylize-card:hover .stylize-thumb svg {
+ transform: scale(1.08) rotate(-4deg);
+ }
+ .stylize-name {
+ font-family: var(--font-display);
+ font-weight: 600;
+ font-size: var(--text-sm);
+ }
+ .stylize-blurb {
+ color: var(--ink-dim);
+ font-size: var(--text-xs);
+ line-height: var(--leading-snug);
+ }
+ .stylize-controls {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-md);
+ margin-top: var(--space-md);
+ flex-wrap: wrap;
+ }
+ .stylize-slider {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-sm);
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ }
+ .stylize-slider input[type='range'] {
+ accent-color: var(--accent);
+ width: 160px;
+ cursor: pointer;
+ }
+ .stylize-slider input[type='range']:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 3px;
+ }
+ .stylize-slider output {
+ color: var(--ink);
+ min-width: 2.5ch;
+ text-align: right;
+ }
+ .stylize-actions {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-xs);
+ flex-wrap: wrap;
+ }
+ .stylize-status {
+ margin-top: var(--space-sm);
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ min-height: 1.2em;
+ }
+ .stylize-status[data-kind='busy'] {
+ color: var(--accent);
+ }
+ .stylize-status[data-kind='error'] {
+ color: var(--danger);
+ }
+ .stylize-status[data-kind='done'] {
+ color: var(--success);
+ }
+ .stylize[data-busy='true'] .stylize-thumb svg {
+ animation: spin 1.1s linear infinite;
+ }
+
+ /* Your creations gallery -------------------------------------- */
+ .creations {
+ margin-top: var(--space-2xl);
+ }
+ .creations-head {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: var(--space-sm);
+ margin-bottom: var(--space-md);
+ }
+ .creations-head h2 {
+ font-family: var(--font-display);
+ font-size: var(--text-lg);
+ margin: 0;
+ }
+ .creations-head .count {
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ }
+ .creations-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
+ gap: 12px;
+ }
+ /* Showcase uses larger cards — the section spans full width */
+ #showcase .creations-grid {
+ grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
+ gap: 14px;
+ }
+ .creation {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ text-align: left;
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ border-radius: 12px;
+ overflow: hidden;
+ cursor: pointer;
+ padding: 0;
+ color: inherit;
+ font: inherit;
+ transition:
+ border-color 0.15s,
+ transform 0.15s,
+ box-shadow 0.15s;
+ }
+ .creation:hover {
+ border-color: var(--stroke-strong);
+ transform: translateY(-2px);
+ box-shadow: 0 12px 32px -16px rgba(0, 0, 0, 0.7);
+ }
+ .creation:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ .creation .thumb {
+ aspect-ratio: 1 / 1;
+ width: 100%;
+ object-fit: cover;
+ background: var(--surface-2);
+ display: block;
+ }
+ .creation .thumb.placeholder {
+ display: grid;
+ place-items: center;
+ color: var(--ink-dim);
+ font-size: 1.6rem;
+ }
+ .creation .thumb.gradient-ph {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ position: relative;
+ overflow: hidden;
+ padding: 1rem;
+ }
+ .creation .thumb .gradient-ph-text {
+ font-size: 12px;
+ line-height: 1.45;
+ color: rgba(255,255,255,0.5);
+ display: -webkit-box;
+ -webkit-line-clamp: 4;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+ text-align: center;
+ letter-spacing: 0.01em;
+ }
+ .creation .meta {
+ padding: 0.55rem 0.7rem;
+ font-size: 12.5px;
+ color: var(--ink-dim);
+ line-height: 1.4;
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+ }
+ .creation .badge {
+ position: absolute;
+ top: 6px;
+ right: 6px;
+ font-size: 0.65rem;
+ font-family: var(--font-mono);
+ padding: 1px 6px;
+ border-radius: 999px;
+ background: rgba(0, 0, 0, 0.55);
+ backdrop-filter: blur(4px);
+ }
+ .creation .badge[data-outcome='accepted'] {
+ color: var(--success);
+ }
+ .creation .badge[data-outcome='rejected'] {
+ color: var(--danger);
+ }
+
+ /* Fresh from the Forge — community showcase ------------------- */
+ /* Taller thumb area for showcase cards */
+ #showcase .creation .thumb {
+ aspect-ratio: unset;
+ min-height: 200px;
+ height: 200px;
+ }
+ /* Showcase cards get slightly larger meta text + 3-line clamp */
+ #showcase .creation .meta {
+ font-size: 0.8rem;
+ -webkit-line-clamp: 3;
+ padding: 0.6rem 0.75rem;
+ }
+ .showcase-head-right {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-xs);
+ }
+ .showcase-refresh {
+ display: inline-grid;
+ place-items: center;
+ width: 26px;
+ height: 26px;
+ background: transparent;
+ border: 1px solid var(--stroke);
+ border-radius: 50%;
+ color: var(--ink-dim);
+ cursor: pointer;
+ transition:
+ color 0.15s,
+ border-color 0.15s,
+ transform 0.3s ease;
+ }
+ .showcase-refresh:hover {
+ color: var(--ink);
+ border-color: var(--stroke-strong);
+ transform: rotate(90deg);
+ }
+ .showcase-refresh:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ .showcase-sub {
+ margin: calc(-1 * var(--space-sm)) 0 var(--space-md);
+ color: var(--ink-dim);
+ font-size: var(--text-sm);
+ }
+ .showcase-sub strong {
+ color: var(--ink);
+ }
+ .showcase-view-all {
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ text-decoration: none;
+ letter-spacing: 0.03em;
+ transition: color 0.15s;
+ }
+ .showcase-view-all:hover { color: var(--ink); }
+ /* Card footer: time-ago on the left, Remix on the right. */
+ .showcase-foot {
+ display: flex;
+ flex-direction: row;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-sm);
+ padding: 0.4rem 0.75rem 0.6rem;
+ margin-top: auto;
+ border-top: 1px solid var(--stroke);
+ }
+ .showcase-when {
+ font-family: var(--font-mono);
+ font-size: 0.7rem;
+ color: var(--ink-dim);
+ opacity: 0.75;
+ flex-shrink: 0;
+ }
+ .showcase-remix {
+ font-family: var(--font-mono);
+ white-space: nowrap;
+ flex-shrink: 0;
+ font-size: 11px;
+ letter-spacing: 0.04em;
+ padding: 3px 10px;
+ border-radius: 999px;
+ border: 1px solid var(--stroke);
+ background: transparent;
+ color: var(--ink-dim);
+ cursor: pointer;
+ transition:
+ color 0.15s,
+ border-color 0.15s,
+ background 0.15s;
+ }
+ .showcase-card:hover .showcase-remix,
+ .showcase-remix:hover {
+ color: var(--ink);
+ border-color: var(--accent);
+ }
+ .showcase-remix:hover {
+ background: var(--accent-soft);
+ }
+ .showcase-remix:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ /* Hover-to-spin: the card's real model, laid over the square thumb,
+ faded in only after its GLB finishes loading. */
+ .showcase-preview {
+ position: absolute;
+ top: 0;
+ left: 0;
+ right: 0;
+ aspect-ratio: 1 / 1;
+ width: 100%;
+ background: var(--surface-2);
+ opacity: 0;
+ pointer-events: none;
+ transition: opacity 0.25s ease;
+ }
+ .showcase-card.is-previewing .showcase-preview {
+ opacity: 1;
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .showcase-refresh,
+ .showcase-remix,
+ .showcase-preview {
+ transition: none;
+ }
+ .showcase-refresh:hover {
+ transform: none;
+ }
+ }
+
+ /* Remix flash: border pulse + glow on the prompt box when a prompt loads */
+ @keyframes prompt-remix-flash {
+ 0% {
+ box-shadow: 0 0 0 0 color-mix(in srgb, var(--accent) 60%, transparent);
+ border-color: var(--accent);
+ background: color-mix(in srgb, var(--accent) 6%, transparent);
+ }
+ 30% {
+ box-shadow: 0 0 0 5px color-mix(in srgb, var(--accent) 18%, transparent);
+ border-color: var(--accent);
+ }
+ 100% {
+ box-shadow: 0 0 0 0 transparent;
+ border-color: var(--stroke);
+ background: var(--surface-2, transparent);
+ }
+ }
+ #prompt.remix-flash {
+ animation: prompt-remix-flash 0.9s cubic-bezier(0.22, 1, 0.36, 1) forwards;
+ }
+
+ /* Remix toast — slides in from above, then fades out */
+ @keyframes toast-enter {
+ from { opacity: 0; transform: translateX(-50%) translateY(-10px); }
+ to { opacity: 1; transform: translateX(-50%) translateY(0); }
+ }
+ .remix-toast {
+ position: fixed;
+ top: 5.5rem;
+ left: 50%;
+ transform: translateX(-50%) translateY(0);
+ background: color-mix(in srgb, var(--surface-3, #1a1a1a) 92%, transparent);
+ backdrop-filter: blur(12px);
+ -webkit-backdrop-filter: blur(12px);
+ border: 1px solid color-mix(in srgb, var(--accent) 55%, transparent);
+ color: var(--ink);
+ font-size: 0.78rem;
+ font-weight: 500;
+ letter-spacing: 0.01em;
+ padding: 0.45rem 1.1rem 0.45rem 0.9rem;
+ border-radius: 999px;
+ pointer-events: none;
+ white-space: nowrap;
+ z-index: 1000;
+ opacity: 1;
+ display: flex;
+ align-items: center;
+ gap: 0.45rem;
+ box-shadow: 0 4px 24px rgba(0, 0, 0, 0.4);
+ animation: toast-enter 0.3s cubic-bezier(0.22, 1, 0.36, 1) forwards;
+ transition: opacity 0.35s ease, transform 0.35s ease;
+ }
+ .remix-toast .toast-dot {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--accent);
+ flex: none;
+ }
+ .remix-toast.fade-out {
+ opacity: 0;
+ transform: translateX(-50%) translateY(-8px);
+ }
+
+ /* Forge empty state — open canvas, not a boxed notice */
+ .forge-empty {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ min-height: 420px;
+ gap: var(--space-md);
+ border: 1px dashed var(--stroke);
+ border-radius: var(--radius-lg);
+ background: var(--surface-1);
+ }
+ .forge-empty-art {
+ width: 140px;
+ color: var(--ink-dim);
+ opacity: 0.6;
+ animation: forge-cube-float 6s ease-in-out infinite;
+ }
+ @keyframes forge-cube-float {
+ 0%, 100% { transform: translateY(0); }
+ 50% { transform: translateY(-8px); }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .forge-empty-art { animation: none; }
+ }
+ .forge-empty-label {
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: var(--ink-dim);
+ margin: 0;
+ }
+
+ /* Error + unconfigured notices */
+ .notice {
+ padding: var(--space-2xl) var(--space-lg);
+ text-align: center;
+ color: var(--ink-dim);
+ }
+ .notice h3 {
+ color: var(--ink);
+ font-family: var(--font-display);
+ margin: 0 0 var(--space-xs);
+ }
+ .notice p {
+ max-width: 48ch;
+ margin: 0 auto;
+ line-height: var(--leading-normal);
+ }
+ .notice .glyph {
+ font-size: 2.4rem;
+ opacity: 0.5;
+ display: block;
+ margin-bottom: var(--space-sm);
+ }
+ .notice.error h3 {
+ color: var(--danger);
+ }
+ .notice .actions {
+ margin-top: var(--space-md);
+ display: inline-flex;
+ gap: var(--space-xs);
+ }
+ .hint-foot {
+ text-align: center;
+ color: var(--ink-dim);
+ font-size: var(--text-xs);
+ margin-top: var(--space-lg);
+ line-height: var(--leading-normal);
+ }
+ .hint-foot a {
+ color: var(--ink);
+ }
+
+ /* ── Mobile polish (≤720px) ─────────────────────────────────────
+ The rail and stage already stack via .forge-workspace's default
+ single column; these rules keep the dense composer controls from
+ overflowing the viewport and meet phone touch/zoom ergonomics. */
+ @media (max-width: 720px) {
+ /* Hero: stack the title above the tagline instead of a cramped
+ baseline-aligned flex row that overflows narrow screens. */
+ .forge-head {
+ flex-direction: column;
+ align-items: flex-start;
+ gap: var(--space-xs);
+ }
+ .forge-head h1 {
+ font-size: var(--text-lg);
+ }
+ /* Engine / quality / tier / aspect button groups carry up to seven
+ chips — let them wrap instead of forcing horizontal scroll. */
+ .aspect {
+ flex-wrap: wrap;
+ }
+ /* iOS zooms the page when a focused field is under 16px. Bump the
+ few sub-16px controls in the rail to the reading baseline. */
+ .byok-input {
+ font-size: var(--text-base);
+ }
+ /* Comfortable tap targets for the small chip-style controls. */
+ .aspect button,
+ .seg button {
+ min-height: 44px;
+ }
+ .ptool,
+ .chip,
+ .chips-more,
+ .forge-cat-btn,
+ .verdict button {
+ min-height: 44px;
+ }
+ .opt-select {
+ font-size: var(--text-sm);
+ min-height: 44px;
+ }
+ }
+
+ /* Fullscreen cinema bar must clear the home-indicator / notch. */
+ .result.is-cinema .result-bar {
+ padding-bottom: calc(var(--space-sm) + env(safe-area-inset-bottom, 0px));
+ padding-left: max(var(--space-md), env(safe-area-inset-left, 0px));
+ padding-right: max(var(--space-md), env(safe-area-inset-right, 0px));
+ }
+
+ /* ========================================================================
+ Studio merge — page-level Object / Avatar mode switch + the avatar
+ (prompt → rigged avatar) pane. All avatar rules are scoped under
+ #studio-avatar so they can never leak into the Forge (Object) pane.
+ ======================================================================== */
+ .studio-tabs {
+ display: inline-flex;
+ gap: 4px;
+ padding: 4px;
+ border-radius: 999px;
+ border: 1px solid var(--border, #1a1a1a);
+ background: var(--surface-1, #0a0a0a);
+ margin-top: var(--space-md);
+ }
+ .studio-tabs button {
+ appearance: none;
+ border: 0;
+ background: transparent;
+ color: var(--text-muted, #888);
+ font: inherit;
+ font-weight: 600;
+ font-size: 14px;
+ padding: 8px 18px;
+ border-radius: 999px;
+ cursor: pointer;
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ transition: color 0.15s, background 0.15s, transform 0.12s;
+ }
+ .studio-tabs button:hover { color: var(--text, #e8e8e8); }
+ .studio-tabs button:active { transform: translateY(1px); }
+ .studio-tabs button[aria-selected='true'] {
+ color: var(--accent-ink, #000);
+ background: var(--accent, #fff);
+ }
+ .studio-tabs button:focus-visible {
+ outline: 2px solid var(--accent, #fff);
+ outline-offset: 2px;
+ }
+ .studio-tabs button .dot {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: currentColor;
+ opacity: 0.55;
+ }
+ .studio-pane[hidden] { display: none; }
+
+ /* ── Avatar pane (scoped copy of /create/prompt) ───────────────────── */
+ #studio-avatar {
+ --bg: #000000;
+ --panel: #0a0a0a;
+ --panel-elev: #111111;
+ --border: #1a1a1a;
+ --border-strong: #2a2a2a;
+ --text: #e8e8e8;
+ --muted: #888888;
+ --accent: #ffffff;
+ --accent-ink: #000000;
+ --danger: #f87171;
+ --danger-dim: #4a1a1a;
+ max-width: 760px;
+ margin: 0 auto;
+ padding: 8px 20px 40px;
+ display: flex;
+ flex-direction: column;
+ }
+ @keyframes studioFade {
+ from { opacity: 0; transform: translateY(6px); }
+ to { opacity: 1; transform: none; }
+ }
+ @keyframes studioSpin { to { transform: rotate(360deg); } }
+ #studio-avatar .step { display: none; flex-direction: column; }
+ #studio-avatar .step.active { display: flex; animation: studioFade 0.35s ease; }
+ #studio-avatar h1 {
+ font-size: clamp(26px, 5vw, 36px);
+ line-height: 1.1;
+ margin: 12px 0 8px;
+ letter-spacing: -0.02em;
+ color: var(--text);
+ }
+ #studio-avatar .sub { color: var(--muted); margin: 0 0 24px; max-width: 56ch; }
+ #studio-avatar .composer {
+ border: 1px solid transparent;
+ border-radius: 16px;
+ background:
+ linear-gradient(var(--panel), var(--panel)) padding-box,
+ linear-gradient(120deg, var(--border-strong), var(--border-strong)) border-box;
+ padding: 6px 6px 14px;
+ transition: box-shadow 0.2s;
+ }
+ #studio-avatar .composer:focus-within {
+ background:
+ linear-gradient(var(--panel), var(--panel)) padding-box,
+ linear-gradient(
+ 120deg,
+ rgba(255, 180, 84, 0.65),
+ rgba(255, 106, 213, 0.65) 38%,
+ rgba(139, 92, 246, 0.65) 64%,
+ rgba(79, 195, 255, 0.65)
+ )
+ border-box;
+ box-shadow: 0 0 24px rgba(139, 92, 246, 0.1);
+ }
+ #studio-avatar #cp-prompt {
+ width: 100%;
+ min-height: 120px;
+ resize: vertical;
+ border: 0;
+ background: transparent;
+ color: var(--text);
+ font: inherit;
+ line-height: 1.5;
+ padding: 14px 14px 6px;
+ outline: none;
+ }
+ #studio-avatar #cp-prompt::placeholder { color: #555; }
+ #studio-avatar .composer-foot {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 0 10px;
+ }
+ #studio-avatar .counter { color: #555; font-size: 12px; font-variant-numeric: tabular-nums; }
+ #studio-avatar .counter.warn { color: var(--danger); }
+ #studio-avatar .examples { display: flex; flex-wrap: wrap; gap: 8px; margin: 16px 0 4px; }
+ #studio-avatar .example {
+ border: 1px solid var(--border-strong);
+ background: var(--panel);
+ color: var(--muted);
+ border-radius: 999px;
+ padding: 7px 13px;
+ font-size: 13px;
+ cursor: pointer;
+ transition: border-color 0.15s, color 0.15s, background 0.15s, transform 0.12s;
+ }
+ #studio-avatar .example:hover { border-color: #444; color: var(--text); background: var(--panel-elev); }
+ #studio-avatar .example:active { transform: translateY(1px); }
+ #studio-avatar .example:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+ #studio-avatar .actions { display: flex; align-items: center; gap: 14px; margin-top: 22px; }
+ #studio-avatar .btn-primary {
+ display: inline-flex;
+ align-items: center;
+ gap: 9px;
+ background: var(--accent);
+ color: var(--accent-ink);
+ border: 0;
+ border-radius: 12px;
+ padding: 13px 22px;
+ font-size: 15px;
+ font-weight: 600;
+ cursor: pointer;
+ transition: opacity 0.15s, transform 0.12s;
+ }
+ #studio-avatar .btn-primary:hover { opacity: 0.9; }
+ #studio-avatar .btn-primary:active { transform: translateY(1px); }
+ #studio-avatar .btn-primary:disabled { opacity: 0.4; cursor: not-allowed; }
+ #studio-avatar .btn-primary:focus-visible { outline: 2px solid #fff; outline-offset: 3px; }
+ #studio-avatar .hint { color: #666; font-size: 12.5px; }
+ #studio-avatar .hint .chip-auth { color: var(--muted); }
+ #studio-avatar .note {
+ margin-top: 28px;
+ color: #666;
+ font-size: 12.5px;
+ border-top: 1px solid var(--border);
+ padding-top: 16px;
+ max-width: 60ch;
+ }
+ #studio-avatar .note a {
+ color: #aaa;
+ text-decoration: underline;
+ text-underline-offset: 2px;
+ transition: color 0.15s;
+ }
+ #studio-avatar .note a:hover { color: var(--text); }
+ #studio-avatar .note a:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 2px; }
+ #studio-avatar .build-wrap { align-items: center; text-align: center; padding-top: 24px; }
+ #studio-avatar .orb {
+ width: 132px;
+ height: 132px;
+ border-radius: 50%;
+ margin: 8px auto 26px;
+ background: radial-gradient(circle at 32% 30%, #2a2a2a, #0c0c0c 70%);
+ border: 1px solid var(--border-strong);
+ position: relative;
+ overflow: hidden;
+ }
+ #studio-avatar .orb::after {
+ content: '';
+ position: absolute;
+ inset: -40%;
+ background: conic-gradient(from 0deg, transparent 0 70%, rgba(255, 255, 255, 0.14) 85%, transparent 100%);
+ animation: studioSpin 1.5s linear infinite;
+ }
+ #studio-avatar .orb::before {
+ content: '';
+ position: absolute;
+ inset: 0;
+ border-radius: 50%;
+ box-shadow: inset 0 0 30px rgba(255, 255, 255, 0.05);
+ z-index: 1;
+ }
+ #studio-avatar .build-prompt {
+ color: var(--text);
+ font-size: 16px;
+ max-width: 46ch;
+ margin: 0 auto 6px;
+ font-style: italic;
+ }
+ #studio-avatar .build-status { color: var(--muted); font-size: 14px; margin-top: 12px; min-height: 20px; }
+ #studio-avatar .progress-track {
+ width: min(420px, 90%);
+ height: 4px;
+ border-radius: 4px;
+ background: var(--border-strong);
+ margin: 22px auto 0;
+ overflow: hidden;
+ }
+ #studio-avatar .progress-fill {
+ height: 100%;
+ width: 8%;
+ border-radius: 4px;
+ background: var(--accent);
+ transition: width 0.8s cubic-bezier(0.4, 0, 0.2, 1);
+ }
+ #studio-avatar .elapsed { color: #555; font-size: 12px; margin-top: 14px; font-variant-numeric: tabular-nums; }
+ #studio-avatar .done-wrap { align-items: center; text-align: center; padding-top: 8px; }
+ #studio-avatar .done-viewer {
+ width: 100%;
+ max-width: 460px;
+ aspect-ratio: 4/5;
+ margin: 18px auto 0;
+ border: 1px solid var(--border-strong);
+ border-radius: 16px;
+ background: var(--panel);
+ overflow: hidden;
+ }
+ #studio-avatar .done-viewer model-viewer { width: 100%; height: 100%; --poster-color: transparent; }
+ #studio-avatar .done-tags { display: flex; gap: 8px; justify-content: center; margin: 16px 0 0; flex-wrap: wrap; }
+ #studio-avatar .tag {
+ font-size: 12px;
+ color: var(--muted);
+ border: 1px solid var(--border-strong);
+ border-radius: 999px;
+ padding: 5px 11px;
+ }
+ #studio-avatar .tag.ok { color: #6ee7a8; border-color: #1f3a2a; }
+ #studio-avatar .done-actions { display: flex; gap: 12px; justify-content: center; margin-top: 24px; flex-wrap: wrap; }
+ #studio-avatar .btn-ghost {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ background: var(--panel);
+ color: var(--text);
+ border: 1px solid var(--border-strong);
+ border-radius: 12px;
+ padding: 12px 20px;
+ font-size: 15px;
+ font-weight: 500;
+ cursor: pointer;
+ transition: border-color 0.15s, background 0.15s, transform 0.12s;
+ text-decoration: none;
+ }
+ #studio-avatar .btn-ghost:hover { border-color: #444; background: var(--panel-elev); }
+ #studio-avatar .btn-ghost:active { transform: translateY(1px); }
+ #studio-avatar .btn-ghost:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+ #studio-avatar .error-box {
+ display: none;
+ margin-top: 18px;
+ border: 1px solid var(--danger-dim);
+ background: rgba(248, 113, 113, 0.06);
+ border-radius: 12px;
+ padding: 14px 16px;
+ color: #f3b4b4;
+ font-size: 14px;
+ }
+ #studio-avatar .error-box.show { display: block; animation: studioFade 0.25s ease; }
+ #studio-avatar .error-box strong { color: var(--danger); }
+ @media (max-width: 520px) {
+ #studio-avatar .actions { flex-direction: column; align-items: stretch; }
+ #studio-avatar .btn-primary { justify-content: center; }
+ #studio-avatar .hint { text-align: center; }
+ }
+ </style>
+
+ <link rel="canonical" href="https://three.ws/forge-studio">
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Studio — Object + Avatar from text","description":"One place to turn text into 3D: forge a textured object (GLB) or describe a character and get a rigged avatar. Two pipelines, one canvas.","url":"https://three.ws/forge-studio","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
+
+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">
+ <meta property="og:locale" content="en_US">
+ <meta property="og:image:alt" content="Forge — Text to 3D — three.ws">
+ <script type="module" src="/model-viewer-meshopt.js"></script>
+</head>
+ <body class="forge-page">
+ <div id="nav-container"></div>
+
+ <main class="forge-main">
+ <header class="forge-head">
+ <h1>Studio</h1>
+ <p>Text → 3D, two ways. Forge a textured object, or describe a character and get a rigged avatar.</p>
+ <div class="studio-tabs" role="tablist" aria-label="Studio mode">
+ <button
+ type="button"
+ role="tab"
+ id="studio-tab-object"
+ data-studio-mode="object"
+ aria-selected="true"
+ aria-controls="studio-object"
+ >
+ <span class="dot" aria-hidden="true"></span>Object
+ </button>
+ <button
+ type="button"
+ role="tab"
+ id="studio-tab-avatar"
+ data-studio-mode="avatar"
+ aria-selected="false"
+ aria-controls="studio-avatar"
+ >
+ <span class="dot" aria-hidden="true"></span>Avatar
+ </button>
+ </div>
+ </header>
+
+ <section id="studio-object" class="studio-pane" role="tabpanel" aria-labelledby="studio-tab-object">
+ <div class="forge-workspace">
+ <div class="forge-rail">
+ <form class="composer" id="composer" autocomplete="off">
+ <div class="mode-switch-wrap">
+ <div
+ class="mode-switch"
+ role="tablist"
+ aria-label="Generation mode"
+ id="mode-switch"
+ >
+ <button type="button" role="tab" data-mode="text" aria-selected="true">
+ Describe it
+ </button>
+ <button type="button" role="tab" data-mode="image" aria-selected="false">
+ From photos
+ </button>
+ <!-- Hidden until the catalog reports a live sketch engine (TripoSG
+ self-host) — no dead tab on deployments without the worker. -->
+ <button type="button" role="tab" data-mode="sketch" aria-selected="false" hidden>
+ From a sketch
+ </button>
+ </div>
+ </div>
+ <!-- Text → 3D -->
+ <div id="text-pane">
+ <label for="prompt" class="is-hidden">Describe the object to generate</label>
+ <textarea
+ id="prompt"
+ name="prompt"
+ maxlength="1000"
+ placeholder="a worn leather armchair, studio lighting, plain background"
+ aria-describedby="prompt-coach"
+ ></textarea>
+ <div class="prompt-tools" id="prompt-tools">
+ <button type="button" class="ptool" id="surprise" aria-label="Fill the box with a random vivid prompt">
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <rect x="3" y="3" width="18" height="18" rx="3" />
+ <circle cx="8.5" cy="8.5" r="1.4" fill="currentColor" stroke="none" />
+ <circle cx="15.5" cy="15.5" r="1.4" fill="currentColor" stroke="none" />
+ <circle cx="15.5" cy="8.5" r="1.4" fill="currentColor" stroke="none" />
+ <circle cx="8.5" cy="15.5" r="1.4" fill="currentColor" stroke="none" />
+ </svg>
+ Surprise me
+ </button>
+ <span class="prompt-coach" id="prompt-coach" data-grade="tip" aria-live="polite"></span>
+ <span class="prompt-count" id="prompt-count">0 / 1000</span>
+ </div>
+ </div>
+
+ <!-- Image / multi-view → 3D -->
+ <div id="image-pane" class="image-pane is-hidden">
+ <div
+ class="views-grid"
+ id="views-grid"
+ aria-label="Reference views — add up to four photos of the same object"
+ ></div>
+ <div class="views-counter" id="views-counter" aria-live="polite">
+ <span class="views-pips" id="views-pips" aria-hidden="true"></span>
+ <span class="vc-text" id="views-counter-text"
+ ><strong>0</strong> of 4 views</span
+ >
+ </div>
+ <input
+ type="file"
+ id="view-file-input"
+ accept="image/png,image/jpeg,image/webp"
+ multiple
+ hidden
+ />
+ <label for="image-prompt" class="is-hidden"
+ >Optional guidance for reconstruction</label
+ >
+ <textarea
+ id="image-prompt"
+ class="image-prompt"
+ maxlength="1000"
+ placeholder="Optional guidance — e.g. “matte plastic, neutral pose, no background”"
+ ></textarea>
+ <p class="views-hint">
+ Add 1–4 views of the <strong>same</strong> object (front · back · left ·
+ right). Drag to drop, click to browse, paste from the clipboard
+ (<kbd class="gen-kbd">⌘V</kbd> / <kbd class="gen-kbd">Ctrl+V</kbd>), drag a thumbnail to reorder.
+ PNG/JPG/WebP, up to 8&nbsp;MB each.
+ </p>
+ </div>
+
+ <!-- Sketch → 3D (TripoSG-scribble) -->
+ <div id="sketch-pane" class="image-pane is-hidden">
+ <div
+ class="views-grid sketch-grid"
+ id="sketch-grid"
+ aria-label="Your sketch — add one drawing"
+ ></div>
+ <input
+ type="file"
+ id="sketch-file-input"
+ accept="image/png,image/jpeg,image/webp"
+ hidden
+ />
+ <label for="sketch-prompt" class="is-hidden"
+ >What does the sketch depict? (required)</label
+ >
+ <textarea
+ id="sketch-prompt"
+ class="image-prompt"
+ maxlength="1000"
+ aria-required="true"
+ placeholder="What is it? — e.g. “a cartoon rocket with two tail fins”"
+ ></textarea>
+ <p class="views-hint">
+ Drop one drawing — dark strokes on a light background work best — and say
+ what it depicts<span class="req-tag" id="sketch-req-tag">Required</span>.
+ PNG/JPG/WebP, up to 8&nbsp;MB. The result is untextured geometry: use
+ <strong>Stylize</strong> or <strong>Retexture</strong> on it after.
+ </p>
+ </div>
+
+ <!-- Quality tier + generation engine + BYOK key -->
+ <div class="forge-quality" id="forge-quality">
+ <div class="fq-row">
+ <span class="fq-label" id="tier-label">Quality</span>
+ <div class="aspect" role="group" aria-labelledby="tier-label" id="tier">
+ <button type="button" data-tier="draft" aria-pressed="false">
+ Draft
+ </button>
+ <button type="button" data-tier="standard" aria-pressed="true">
+ Standard
+ </button>
+ <button
+ type="button"
+ data-tier="high"
+ data-access="locked"
+ aria-pressed="false"
+ aria-label="High quality — $THREE holder feature"
+ >
+ <span class="tier-name">High</span>
+ <span class="tier-lock" data-state="locked" title="High quality is a $THREE holder feature">
+ <svg class="tier-lock-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="5" y="11" width="14" height="9" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg>
+ <span class="tier-lock-txt">$THREE</span>
+ </span>
+ </button>
+ </div>
+ </div>
+ <p class="fq-holder-note" id="fq-holder-note" data-state="locked">
+ <span class="fq-holder-ico" aria-hidden="true">◆</span> High quality is a
+ <a href="/three-token">$THREE holder</a> feature — hold to unlock, or pay per generation.
+ </p>
+ <div class="fq-row">
+ <span class="fq-label" id="engine-label">Engine</span>
+ <div
+ class="aspect"
+ role="group"
+ aria-labelledby="engine-label"
+ id="engine"
+ ></div>
+ </div>
+ <p class="engine-legend" id="engine-legend">
+ <span class="el-item"><span class="el-free">FREE</span> no API key</span>
+ <span class="el-item"
+ ><svg class="el-key" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="15" r="4"/><path d="M10.85 12.15 19 4"/><path d="m18 5 2 2"/><path d="m15 8 2 2"/></svg>
+ your own key</span
+ >
+ <span class="el-item"><span class="el-dot el-dot-busy"></span> busy</span>
+ <span class="el-item"><span class="el-dot el-dot-down"></span> unavailable</span>
+ </p>
+ <div class="byok-row is-hidden" id="byok-row">
+ <label class="fq-label" for="provider-key" id="byok-label">API key</label>
+ <input
+ class="byok-input"
+ id="provider-key"
+ type="password"
+ autocomplete="off"
+ autocapitalize="off"
+ spellcheck="false"
+ placeholder="Your provider API key (kept in this browser)"
+ aria-describedby="byok-hint"
+ />
+ <span class="byok-hint" id="byok-hint"></span>
+ </div>
+ <p class="fq-estimate" id="estimate" aria-live="polite"></p>
+ </div>
+
+ <div class="composer-row">
+ <div
+ class="aspect"
+ role="group"
+ aria-label="Reference image aspect ratio"
+ id="aspect"
+ >
+ <button type="button" data-aspect="1:1" aria-pressed="true">1:1</button>
+ <button type="button" data-aspect="4:3" aria-pressed="false">4:3</button>
+ <button type="button" data-aspect="3:4" aria-pressed="false">3:4</button>
+ <button type="button" data-aspect="16:9" aria-pressed="false">16:9</button>
+ </div>
+ </div>
+ <button class="btn" id="generate" type="submit">
+ <span id="generate-label">Generate</span>
+ <kbd class="gen-kbd" aria-hidden="true">⌘↵</kbd>
+ </button>
+
+ <!-- Quiet holder line under Generate: an active free-quota perk for $THREE
+ holders, or a non-blocking upsell + a reachable wallet connect so a
+ holder who hasn't connected can reveal their perk. Filled by forge.js
+ (updatePerkLine) from the wallet-aware access matrix. -->
+ <div class="fq-perk-row" id="forge-perk-row" hidden>
+ <p class="fq-perk-line" id="forge-perk-line" aria-live="polite"></p>
+ <button type="button" class="fq-connect-btn" id="connect-wallet-btn" hidden>
+ <span class="fq-connect-ico" aria-hidden="true">◎</span>
+ <span data-wallet-label>Connect wallet</span>
+ </button>
+ </div>
+
+ </form>
+
+ <div class="chips" id="examples" aria-label="Example prompts">
+ <button class="chip" type="button">a low-poly red fox, sitting</button>
+ <button class="chip" type="button">a sci-fi combat helmet, brushed metal</button>
+ <button class="chip" type="button">a potted monstera plant</button>
+ <button class="chip" type="button">a vintage film camera</button>
+ <button class="chip" type="button">a glazed ceramic teapot</button>
+ <button class="chips-more" type="button" id="chips-more" aria-label="Swap in a fresh set of example prompts">↻ More ideas</button>
+ </div>
+ </div>
+ <!-- ── Stage column: viewer, your creations, community showcase ── -->
+ <div class="forge-stage">
+
+ <section class="stage" id="stage" aria-live="polite">
+ <!-- Empty / idle -->
+ <div class="forge-empty" id="state-empty">
+ <div class="forge-empty-art" aria-hidden="true">
+ <svg viewBox="0 0 240 200" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <!-- isometric cube wireframe -->
+ <g stroke="currentColor" stroke-linecap="round" stroke-linejoin="round">
+ <!-- top face -->
+ <polygon points="120,24 190,64 120,104 50,64" stroke-width="1.5" opacity="0.5"/>
+ <!-- left face -->
+ <polygon points="50,64 120,104 120,168 50,128" stroke-width="1.5" opacity="0.3"/>
+ <!-- right face -->
+ <polygon points="190,64 120,104 120,168 190,128" stroke-width="1.5" opacity="0.3"/>
+ <!-- internal cross lines on top face -->
+ <line x1="120" y1="24" x2="120" y2="104" stroke-width="0.75" opacity="0.2"/>
+ <line x1="50" y1="64" x2="190" y2="64" stroke-width="0.75" opacity="0.2"/>
+ <!-- vertex dots -->
+ <circle cx="120" cy="24" r="2.5" fill="currentColor" opacity="0.5"/>
+ <circle cx="190" cy="64" r="2.5" fill="currentColor" opacity="0.4"/>
+ <circle cx="50" cy="64" r="2.5" fill="currentColor" opacity="0.4"/>
+ <circle cx="120" cy="104" r="2.5" fill="currentColor" opacity="0.6"/>
+ <circle cx="190" cy="128" r="2.5" fill="currentColor" opacity="0.3"/>
+ <circle cx="50" cy="128" r="2.5" fill="currentColor" opacity="0.3"/>
+ <circle cx="120" cy="168" r="2.5" fill="currentColor" opacity="0.4"/>
+ </g>
+ </svg>
+ </div>
+ <p class="forge-empty-label">Enter a prompt to generate</p>
+ </div>
+
+ <!-- Generating -->
+ <div class="panel gen is-hidden" id="state-generating">
+ <div class="gen-preview" id="gen-preview">
+ <div class="shimmer" aria-hidden="true"></div>
+ </div>
+ <div class="gen-steps">
+ <div class="step" id="step-image" data-state="active">
+ <span class="dot" aria-hidden="true"></span>
+ <span>Painting reference image</span>
+ </div>
+ <div class="step" id="step-mesh" data-state="pending">
+ <span class="dot" aria-hidden="true"></span>
+ <span>Reconstructing textured mesh</span>
+ </div>
+ <div class="step" id="step-finish" data-state="pending">
+ <span class="dot" aria-hidden="true"></span>
+ <span>Finalizing GLB</span>
+ </div>
+ <div
+ class="gen-progress"
+ id="gen-progress"
+ role="progressbar"
+ aria-label="Generation progress"
+ aria-valuemin="0"
+ aria-valuemax="100"
+ aria-valuenow="0"
+ >
+ <div class="gen-progress-fill" id="gen-progress-fill"></div>
+ </div>
+ <div class="gen-meta" id="gen-meta">Elapsed 0s</div>
+ <div style="margin-top: var(--space-sm)">
+ <button class="btn btn-ghost" type="button" id="cancel">Cancel</button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Result -->
+ <div class="panel result is-hidden" id="state-result">
+ <div class="viewer-shell" id="viewer-shell">
+ <model-viewer
+ id="viewer"
+ camera-controls
+ auto-rotate
+ auto-rotate-delay="0"
+ rotation-per-second="18deg"
+ shadow-intensity="1.0"
+ shadow-softness="0.9"
+ exposure="1.5"
+ tone-mapping="aces"
+ ar
+ ar-modes="webxr scene-viewer quick-look"
+ interaction-prompt="none"
+ crossorigin="anonymous"
+ alt="Generated 3D model"
+ ></model-viewer>
+ <div class="viewer-skeleton" id="viewer-skeleton" aria-hidden="true">
+ <span class="viewer-skeleton-sheen"></span>
+ <span class="viewer-skeleton-label">Loading model…</span>
+ </div>
+ <div class="viewer-load-error" id="viewer-load-error" role="alert" aria-live="polite">
+ <span class="viewer-load-error-icon" aria-hidden="true">⚠</span>
+ <p>Model failed to load — often a brief network hiccup on the file. Retry, or use the download button below to save it directly.</p>
+ <button type="button" class="btn ghost" id="viewer-retry">Retry loading</button>
+ </div>
+ </div>
+ <div class="result-bar">
+ <span class="label" id="result-label"></span>
+ <span class="saved-chip is-hidden" id="result-saved" aria-label="Auto-saved to gallery">Saved ✓</span>
+ <span
+ class="views-badge is-hidden"
+ id="result-views"
+ title="Reference views fused"
+ ></span>
+ <div class="actions">
+ <button
+ class="btn btn-ghost"
+ type="button"
+ id="cinema"
+ aria-pressed="false"
+ title="Cinema mode — fullscreen turntable for recording (F)"
+ >
+ <svg
+ width="15"
+ height="15"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ aria-hidden="true"
+ >
+ <path d="M8 3H5a2 2 0 0 0-2 2v3" />
+ <path d="M16 3h3a2 2 0 0 1 2 2v3" />
+ <path d="M8 21H5a2 2 0 0 1-2-2v-3" />
+ <path d="M16 21h3a2 2 0 0 0 2-2v-3" />
+ </svg>
+ Cinema
+ </button>
+ <div
+ class="verdict"
+ id="verdict"
+ role="group"
+ aria-label="Rate this model"
+ >
+ <button
+ type="button"
+ data-outcome="accepted"
+ aria-pressed="false"
+ title="Keep — good result"
+ >
+ 👍 Keep
+ </button>
+ <button
+ type="button"
+ data-outcome="rejected"
+ aria-pressed="false"
+ title="Discard — bad result"
+ >
+ 👎 Discard
+ </button>
+ </div>
+ <button
+ class="btn btn-ghost"
+ type="button"
+ id="forge-share-btn"
+ aria-label="Share this creation"
+ >
+ <svg
+ width="15"
+ height="15"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ aria-hidden="true"
+ >
+ <circle cx="18" cy="5" r="3" />
+ <circle cx="6" cy="12" r="3" />
+ <circle cx="18" cy="19" r="3" />
+ <line x1="8.59" y1="13.51" x2="15.42" y2="17.49" />
+ <line x1="15.41" y1="6.51" x2="8.59" y2="10.49" />
+ </svg>
+ Share
+ </button>
+ <a
+ class="btn btn-ghost"
+ id="forge-segment-btn"
+ title="Split this model into selectable parts"
+ >Split into parts</a
+ >
+ <button
+ class="btn btn-ghost"
+ type="button"
+ id="forge-gameready-btn"
+ aria-expanded="false"
+ title="Retopologize to a poly budget and export an engine-ready GLB + FBX"
+ >
+ <svg
+ width="15"
+ height="15"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ aria-hidden="true"
+ >
+ <polygon points="12 2 2 7 12 12 22 7 12 2" />
+ <polyline points="2 17 12 22 22 17" />
+ <polyline points="2 12 12 17 22 12" />
+ </svg>
+ Game-Ready
+ </button>
+ <button
+ class="btn btn-ghost"
+ type="button"
+ id="forge-embed-btn"
+ title="Embed this model on any website"
+ >
+ <svg
+ width="15"
+ height="15"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ aria-hidden="true"
+ >
+ <polyline points="16 18 22 12 16 6" />
+ <polyline points="8 6 2 12 8 18" />
+ </svg>
+ Embed
+ </button>
+ <button
+ class="btn btn-ghost"
+ type="button"
+ id="forge-ar-btn"
+ title="View this model in AR — place it in your room"
+ >
+ <svg
+ width="15"
+ height="15"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ aria-hidden="true"
+ >
+ <path d="M12 2 3 7v10l9 5 9-5V7l-9-5Z" />
+ <path d="m3 7 9 5 9-5" />
+ <path d="M12 12v10" />
+ </svg>
+ View in AR
+ </button>
+ <button
+ class="btn btn-refine is-hidden"
+ type="button"
+ id="refine"
+ title="Re-run this exact prompt at a higher quality tier"
+ >
+ <svg
+ class="refine-arrow"
+ width="15"
+ height="15"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ aria-hidden="true"
+ >
+ <line x1="12" y1="19" x2="12" y2="5" />
+ <polyline points="5 12 12 5 19 12" />
+ </svg>
+ <span id="refine-label">Refine</span>
+ </button>
+ <a class="btn btn-ghost" id="open-in-composer" href="/compose" title="Open this model in Scene Composer to attach it to an avatar or place it in a scene">Compose</a>
+ <a class="btn btn-ghost" id="download" download>Download GLB</a>
+ <button class="btn" type="button" id="again">Make another</button>
+ </div>
+ </div>
+
+ <!-- Category picker — label your model so the gallery and explore feed
+ can surface it under the right filter. Wired in forge.js via the
+ forge-category-picker id; hidden by default, becomes visible when
+ the user is signed in or when a creation_id is available. -->
+ <div class="cat-picker" id="forge-category-picker" hidden>
+ <span class="cat-picker-label">Tag as:</span>
+ <span class="cat-group-label" title="Can be given a brain and become an agent">Agents</span>
+ <button class="forge-cat-btn" type="button" data-cat="avatar">Avatar</button>
+ <button class="forge-cat-btn" type="button" data-cat="creature">Creature</button>
+ <span class="cat-group-sep" aria-hidden="true"></span>
+ <span class="cat-group-label" title="3D objects — props, not personalities">Items</span>
+ <button class="forge-cat-btn" type="button" data-cat="item">Item</button>
+ <button class="forge-cat-btn" type="button" data-cat="accessory">Accessory</button>
+ <button class="forge-cat-btn" type="button" data-cat="scene">Scene</button>
+ <button class="forge-cat-btn" type="button" data-cat="vehicle">Vehicle</button>
+ <p class="cat-picker-help">Only avatars &amp; creatures can be given a brain and become agents — everything else saves as a 3D item.</p>
+ </div>
+
+ <!-- Optimize topology panel (triangle / quad / low-poly remesh) is
+ injected into this result panel by /src/forge-optimize.js. -->
+
+ <!-- Stylize — one-click geometric filters on the current model -->
+ <div class="stylize" id="stylize-panel" data-busy="false" hidden>
+ <div class="stylize-head">
+ <h3>Stylize</h3>
+ <p class="stylize-sub">
+ One-click geometric filters. Restyle this model as voxels, bricks,
+ an open lattice, or low-poly — source color is carried over where
+ the style allows.
+ </p>
+ </div>
+ <div
+ class="stylize-gallery"
+ id="stylize-gallery"
+ role="group"
+ aria-label="Stylization filters"
+ ></div>
+ <div class="stylize-controls is-hidden" id="stylize-controls">
+ <div class="stylize-slider">
+ <label id="stylize-res-label" for="stylize-res">Resolution</label>
+ <input type="range" id="stylize-res" min="8" max="96" value="32" />
+ <output id="stylize-res-val" for="stylize-res">32</output>
+ </div>
+ <div class="stylize-actions">
+ <button class="btn btn-ghost" type="button" id="stylize-apply">
+ Re-apply
+ </button>
+ <a class="btn btn-ghost" id="stylize-download" download hidden
+ >Download stylized GLB</a
+ >
+ <button
+ class="btn btn-ghost"
+ type="button"
+ id="stylize-revert"
+ hidden
+ >
+ Revert to original
+ </button>
+ </div>
+ </div>
+ <div
+ class="stylize-status"
+ id="stylize-status"
+ role="status"
+ aria-live="polite"
+ ></div>
+ </div>
+ </div>
+
+ <!-- Error -->
+ <div class="panel notice error is-hidden" id="state-error">
+ <span class="glyph" aria-hidden="true">⚠</span>
+ <h3>Generation failed</h3>
+ <p id="error-message">
+ Something went wrong. Try a simpler, single-subject prompt.
+ </p>
+ <div class="actions">
+ <button class="btn" type="button" id="retry">Try again</button>
+ <button class="btn btn-ghost is-hidden" type="button" id="refine-locally">Refine current model instead</button>
+ <button class="btn btn-ghost is-hidden" type="button" id="generate-anyway">Generate anyway</button>
+ </div>
+ </div>
+
+ <!-- Unconfigured -->
+ <div class="panel notice is-hidden" id="state-unconfigured">
+ <span class="glyph" aria-hidden="true">◌</span>
+ <h3>Generator not configured</h3>
+ <p>
+ No 3D engine is reachable on this deployment. Set any one of
+ <code>NVIDIA_API_KEY</code> or <code>HF_TOKEN</code> for the free lanes, or
+ <code>REPLICATE_API_TOKEN</code> for the flux → TRELLIS pipeline — Forge picks
+ up whichever is configured with no further changes.
+ </p>
+ </div>
+ </section>
+
+ <!-- Your creations — durable, reusable models tied to this browser -->
+ <section class="creations is-hidden" id="creations" aria-label="Your forged models">
+ <div class="creations-head">
+ <h2>Your creations</h2>
+ <span class="count" id="creations-count"></span>
+ </div>
+ <div class="creations-grid" id="creations-grid"></div>
+ </section>
+
+ <!-- Fresh from the Forge — newest community models (src/forge-showcase.js).
+ Hidden until the public feed returns real rows, so deployments without
+ a durable store never show a hollow strip. -->
+ <section
+ class="creations showcase is-hidden"
+ id="showcase"
+ aria-label="Fresh from the Forge — recent community models"
+ >
+ <div class="creations-head">
+ <h2>Fresh from the Forge</h2>
+ <div class="showcase-head-right">
+ <a href="/gallery#forge-section" class="showcase-view-all">View all →</a>
+ <span class="count" id="showcase-count"></span>
+ <button
+ type="button"
+ class="showcase-refresh"
+ id="showcase-refresh"
+ title="Refresh the community feed"
+ aria-label="Refresh the community feed"
+ >
+ <svg
+ width="13"
+ height="13"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ aria-hidden="true"
+ >
+ <path d="M21 12a9 9 0 1 1-2.64-6.36" />
+ <path d="M21 3v6h-6" />
+ </svg>
+ </button>
+ </div>
+ </div>
+ <p class="showcase-sub">
+ What other people just forged. Open one in the viewer, or
+ <strong>Remix</strong> its prompt and make it yours.
+ </p>
+ <div class="creations-grid" id="showcase-grid"></div>
+ </section>
+
+ <p class="hint-foot">
+ Multi-engine pipeline — Free uses NVIDIA-hosted generation; Fast, Meshy, Tripo, Rodin, Stability, and Replicate require an API key. Best results: one clearly described subject with a material and lighting cue. Photo mode accepts up to 4 views for multi-view reconstruction. The same pipeline is available to agents over MCP at <a href="/docs">/api/mcp-3d</a>.
+ </p>
+ </div><!-- /.forge-stage -->
+ </div><!-- /.forge-workspace -->
+ </section><!-- /#studio-object -->
+
+ <section id="studio-avatar" class="studio-pane" role="tabpanel" aria-labelledby="studio-tab-avatar" hidden>
+ <!-- Step 1: compose -->
+ <section class="step active" data-step="compose" aria-label="Describe your avatar">
+ <h1>Describe it. Get a rigged 3D avatar.</h1>
+ <p class="sub">
+ Type what you want — a character, a creature, a style. We render a clean
+ reference, reconstruct it into 3D, and add a skeleton so it can move.
+ </p>
+
+ <div class="composer">
+ <textarea
+ id="cp-prompt"
+ maxlength="600"
+ placeholder="A cyberpunk street samurai in a worn red coat, neon trim, calm expression…"
+ aria-label="Describe the avatar you want to generate"
+ ></textarea>
+ <div class="composer-foot">
+ <span class="hint" id="cp-cost-hint">Single subject, full body works best.</span>
+ <span class="counter" id="cp-counter">0 / 600</span>
+ </div>
+ </div>
+
+ <div class="examples" role="group" aria-label="Example prompts">
+ <button class="example" type="button">
+ A friendly robot mascot, rounded white shell, glowing blue eyes
+ </button>
+ <button class="example" type="button">
+ A medieval knight in battered steel plate, weathered cape
+ </button>
+ <button class="example" type="button">
+ A fox-eared ranger in green leather, bow on the back
+ </button>
+ <button class="example" type="button">
+ An astronaut in a sleek matte-black suit, gold visor
+ </button>
+ </div>
+
+ <div class="actions">
+ <button class="btn-primary" id="cp-generate-btn" type="button" disabled>
+ <svg
+ width="17"
+ height="17"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ aria-hidden="true"
+ >
+ <path d="M12 3l1.9 5.3L19 10l-5.1 1.7L12 17l-1.9-5.3L5 10l5.1-1.7z" />
+ </svg>
+ Generate avatar
+ </button>
+ <span class="hint"
+ ><span class="chip-auth">Sign-in required</span> · ~1 min · rigged GLB</span
+ >
+ </div>
+
+ <div class="error-box" id="cp-compose-error" role="alert"></div>
+
+ <p class="note">
+ Avatars come out best with a single, clearly described subject. Abstract scenes
+ or multiple characters reconstruct poorly. You can refine the face, outfit, and
+ animations in the editor afterward. Making an object, prop, or scene piece
+ instead of a character? Switch to the <strong>Object</strong> tab above.
+ </p>
+ </section>
+
+ <!-- Step 2: building -->
+ <section
+ class="step build-wrap"
+ data-step="building"
+ aria-label="Building your avatar"
+ aria-live="polite"
+ >
+ <div class="orb" aria-hidden="true"></div>
+ <p class="build-prompt" id="cp-build-prompt"></p>
+ <div class="progress-track" aria-hidden="true">
+ <div class="progress-fill" id="cp-progress-fill"></div>
+ </div>
+ <p class="build-status" id="cp-build-status">Rendering a reference image…</p>
+ <p class="elapsed" id="cp-elapsed">0:00</p>
+ <div class="error-box" id="cp-build-error" role="alert"></div>
+ </section>
+
+ <!-- Step 3: done -->
+ <section class="step done-wrap" data-step="done" aria-label="Your avatar is ready">
+ <h1>Your avatar is ready</h1>
+ <p class="sub" style="margin-bottom: 0">
+ Open it in the editor to animate, dress, and export.
+ </p>
+ <div class="done-viewer">
+ <model-viewer
+ id="cp-done-model"
+ auto-rotate
+ rotation-per-second="14deg"
+ interaction-prompt="none"
+ camera-controls
+ shadow-intensity="0.7"
+ shadow-softness="0.8"
+ environment-image="neutral"
+ exposure="0.95"
+ camera-orbit="0deg 80deg auto"
+ loading="eager"
+ alt="Your newly generated 3D avatar"
+ ></model-viewer>
+ </div>
+ <div class="done-tags" id="cp-done-tags"></div>
+ <div class="done-actions">
+ <a class="btn-primary" id="cp-open-editor" href="#">
+ Open in editor
+ <svg
+ width="14"
+ height="14"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2.2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ aria-hidden="true"
+ >
+ <line x1="5" y1="12" x2="19" y2="12" />
+ <polyline points="12 5 19 12 12 19" />
+ </svg>
+ </a>
+ <button class="btn-ghost" id="cp-make-another" type="button">Make another</button>
+ </div>
+ </section>
+ </section><!-- /#studio-avatar -->
+ </main>
+
+ <script src="/nav.js" defer></script>
+ <script type="module" src="/src/forge-studio/forge.js"></script>
+ <script type="module" src="/src/forge-studio/forge-prompt-studio.js"></script>
+ <script type="module" src="/src/forge-studio/forge-enhance.js"></script>
+ <script type="module" src="/src/forge-studio/forge-refine.js"></script>
+ <script type="module" src="/src/forge-studio/forge-stylize.js"></script>
+ <script type="module" src="/src/forge-studio/forge-optimize.js"></script>
+ <script type="module" src="/src/forge-studio/forge-gameready.js"></script>
+ <script type="module" src="/src/forge-studio/forge-export.js"></script>
+ <script type="module" src="/src/forge-studio/forge-embed-panel.js"></script>
+ <script type="module" src="/src/forge-studio/forge-ar.js"></script>
+ <script type="module" src="/src/forge-studio/forge-showcase.js"></script>
+ <script type="module" src="/src/forge-studio/forge-dropzone.js"></script>
+ <script type="module">
+ // Page-level Object / Avatar mode switch. Object (Forge) renders eagerly;
+ // the Avatar pane (prompt → rigged avatar) lazy-inits its controller the
+ // first time it's shown so it never competes with Forge on load.
+ import { initCreatePrompt, focusPrompt } from '/src/forge-studio/create-prompt.js';
+
+ const tabs = Array.from(document.querySelectorAll('.studio-tabs [data-studio-mode]'));
+ const panes = {
+ object: document.getElementById('studio-object'),
+ avatar: document.getElementById('studio-avatar'),
+ };
+
+ function setMode(mode, { focus = false } = {}) {
+ if (!panes[mode]) return;
+ for (const t of tabs) {
+ const on = t.dataset.studioMode === mode;
+ t.setAttribute('aria-selected', on ? 'true' : 'false');
+ }
+ panes.object.hidden = mode !== 'object';
+ panes.avatar.hidden = mode !== 'avatar';
+ if (mode === 'avatar') {
+ initCreatePrompt();
+ if (focus) focusPrompt();
+ }
+ const url = new URL(window.location.href);
+ if (mode === 'object') url.searchParams.delete('mode');
+ else url.searchParams.set('mode', mode);
+ history.replaceState(null, '', url);
+ }
+
+ for (const t of tabs) {
+ t.addEventListener('click', () => setMode(t.dataset.studioMode, { focus: true }));
+ }
+
+ // Deep-link: /forge-studio?mode=avatar opens straight into the avatar pane.
+ const initial = new URLSearchParams(window.location.search).get('mode');
+ if (initial === 'avatar') setMode('avatar');
+ </script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ </body>
+</html>
diff --git a/public/brain-studio.css b/public/brain-studio.css
index 680902279..edcb247c7 100644
--- a/public/brain-studio.css
+++ b/public/brain-studio.css
@@ -34,6 +34,7 @@
.studio__btn-primary { background: var(--accent); color: var(--bg-0); border-color: var(--accent); }
.studio__btn-primary:hover { filter: brightness(1.08); }
.studio__btn:disabled { opacity: .5; cursor: not-allowed; }
+.studio__btn.is-saved { border-color: var(--node-market); color: var(--node-market); }
.brainstudio__editor { display: flex; flex-direction: column; height: 100%; min-height: 0; }
diff --git a/public/changelog.json b/public/changelog.json
index 7d163e866..0776124e1 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-21T17:08:23.568Z",
+ "generated_at": "2026-06-21T17:29:42.338Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -46,6 +46,16 @@
"launch"
]
},
+ {
+ "date": "2026-06-21",
+ "type": "launch",
+ "title": "Studio — Object + Avatar from text",
+ "summary": "One canvas for both text-to-3D pipelines: forge a textured object (GLB) in the Object tab, or describe a character and get a rigged avatar in the Avatar tab.",
+ "link": "/forge-studio",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-06-21",
"type": "launch",
@@ -148,6 +158,16 @@
"fix"
]
},
+ {
+ "date": "2026-06-21",
+ "type": "update",
+ "title": "Agent Studio: save your Brain and flow straight into Memory",
+ "summary": "Building your agent's reasoning graph in the Brain tab now has a clear finish line. A new Save button writes the graph to the server on demand (or press ⌘/Ctrl+S), the header's save indicator finally lights up for Brain edits the way it does for the name and tagline, and a Done button saves and carries you on to the Memory tab so designing a mind flows naturally into the next step instead of dead-ending on the canvas. Pressing Escape now also closes the Templates and behavior dialogs so they can never trap you.",
+ "link": "/agent-studio",
+ "tags": [
+ "improvement"
+ ]
+ },
{
"date": "2026-06-21",
"type": "update",
@@ -645,6 +665,16 @@
"infra"
]
},
+ {
+ "date": "2026-06-21",
+ "type": "update",
+ "title": "Pole Club: every dancer stands on her stage",
+ "summary": "Fixed a dancer who sank through her platform instead of standing on it. Avatars exported at centimetre scale (common for Mixamo-rigged characters) had their idle motion collapse, dropping them a metre into the floor. The animation engine now scales each dancer's footing to her own rig, so any avatar you pick stands cleanly at her pole.",
+ "link": "/club",
+ "tags": [
+ "fix"
+ ]
+ },
{
"date": "2026-06-21",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 3c986648e..8c0e30e70 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -38,6 +38,14 @@
<category>launch</category>
<description>Recent activity from the people and agents you follow on three.ws.</description>
</item>
+ <item>
+ <title>Studio — Object + Avatar from text</title>
+ <link>https://three.ws/forge-studio</link>
+ <guid isPermaLink="false">2026-06-21:Studio — Object + Avatar from text</guid>
+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>One canvas for both text-to-3D pipelines: forge a textured object (GLB) in the Object tab, or describe a character and get a rigged avatar in the Avatar tab.</description>
+ </item>
<item>
<title>Walk</title>
<link>https://three.ws/walk</link>
@@ -118,6 +126,14 @@
<category>fix</category>
<description>The Brain tab of Agent Studio could become unclickable — a full-screen dialog layer that's meant to stay hidden until you open Templates or the behavior view was rendering invisibly on top of the whole studio, swallowing every click. It now stays properly hidden until you actually open it, so the Brain tab is usable again.</description>
</item>
+ <item>
+ <title>Agent Studio: save your Brain and flow straight into Memory</title>
+ <link>https://three.ws/agent-studio</link>
+ <guid isPermaLink="false">2026-06-21:Agent Studio: save your Brain and flow straight into Memory</guid>
+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>Building your agent's reasoning graph in the Brain tab now has a clear finish line. A new Save button writes the graph to the server on demand (or press ⌘/Ctrl+S), the header's save indicator finally lights up for Brain edits the way it does for the name and tagline, and a Done button saves and carries you on to the Memory tab so designing a mind flows naturally into the next step instead of dead-ending on the canvas. Pressing Escape now also closes the Templates and behavior dialogs so they can never trap you.</description>
+ </item>
<item>
<title>Arm your agent gets its own setup page</title>
<link>https://three.ws/oracle/arm</link>
@@ -494,6 +510,14 @@
<category>security</category>
<description>A broad reliability pass across the parts of three.ws that move real money and serve heavy traffic. On the money side: bundle purchases and agent payments are now verified on-chain before anything unlocks, each payment is credited exactly once, withdrawals can't be processed twice, and recurring subscriptions can't be double-billed. On the security side: a set of input-handling and link-safety fixes across pages, stronger protection for custodial keys at rest, and tighter checks on outbound agent payments so funds only ever move in the expected asset. On the scale side: the busiest directory, profile, and feed pages now ride a short cache and run far fewer database queries, so they stay fast as the community grows. Most of this is invisible by design — it's the plumbing that keeps the platform correct and quick under load.</description>
</item>
+ <item>
+ <title>Pole Club: every dancer stands on her stage</title>
+ <link>https://three.ws/club</link>
+ <guid isPermaLink="false">2026-06-21:Pole Club: every dancer stands on her stage</guid>
+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Fixed a dancer who sank through her platform instead of standing on it. Avatars exported at centimetre scale (common for Mixamo-rigged characters) had their idle motion collapse, dropping them a metre into the floor. The animation engine now scales each dancer's footing to her own rig, so any avatar you pick stands cleanly at her pole.</description>
+ </item>
<item>
<title>Pole Club: tipping now works with the built-in three.ws wallet</title>
<link>https://three.ws/club</link>
diff --git a/public/features.json b/public/features.json
index f503d4a88..88c8bf954 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-21T17:08:23.534Z",
+ "generated_at": "2026-06-21T17:29:42.288Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -272,6 +272,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/forge-studio",
+ "title": "Studio — Object + Avatar from text",
+ "description": "One canvas for both text-to-3D pipelines: forge a textured object (GLB) in the Object tab, or describe a character and get a rigged avatar in the Avatar tab.",
+ "added": "2026-06-21",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/scene",
"title": "Scene Studio",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index ead2eef64..8b16cb5db 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -170,6 +170,12 @@ URL: https://three.ws/forge
Type a prompt — or drop in photos or a sketch — and get a downloadable textured 3D model (GLB). Pick from multiple generation engines with live health status.
+### Studio — Object + Avatar from text
+
+URL: https://three.ws/forge-studio
+
+One canvas for both text-to-3D pipelines: forge a textured object (GLB) in the Object tab, or describe a character and get a rigged avatar in the Avatar tab.
+
### Scene Studio
URL: https://three.ws/scene
diff --git a/public/llms.txt b/public/llms.txt
index f6b145181..2c45fb854 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -39,6 +39,7 @@ Create and customize an agent.
- [Viewer](https://three.ws/app): Drag-and-drop glTF/GLB viewer for inspecting 3D models in the browser.
- [Describe it to 3D](https://three.ws/create/prompt): Type a description. About a minute later: a rigged 3D avatar you can animate and download.
- [Forge — Text to 3D](https://three.ws/forge): Type a prompt — or drop in photos or a sketch — and get a downloadable textured 3D model (GLB). Pick from multiple generation engines with live health status.
+- [Studio — Object + Avatar from text](https://three.ws/forge-studio): One canvas for both text-to-3D pipelines: forge a textured object (GLB) in the Object tab, or describe a character and get a rigged avatar in the Avatar tab.
- [Scene Studio](https://three.ws/scene): Full 3D scene editor in the browser — import GLB models, arrange them with transform gizmos, edit materials and lights, and export complete scenes.
- [Scene Composer](https://three.ws/compose): Real-time 3D scene composer: forge items from text, attach them to your avatar's skeleton bones, arrange and scale freely, then export your creation or save it as an outfit.
- [Animation Studio](https://three.ws/pose): Pose any three.ws avatar or the built-in mannequin with FK/IK, keyframe a timeline, and preview the motion live. Export an animated GLB or clip JSON, save animations to your account, play them back across the platform, and sell them for USDC.
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 6f45c79d5..1afa2bf8d 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -65,7 +65,7 @@
<main class="sm-wrap">
<div class="sm-hero">
<h1>Sitemap</h1>
- <p>All 187 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 188 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
<div class="sm-formats">
<a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a>
<a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>
@@ -77,7 +77,7 @@
</div>
<div class="sm-filter">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
- <input id="sm-filter-input" type="search" placeholder="Filter 187 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 188 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
<kbd aria-hidden="true">/</kbd>
</div>
<p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>
@@ -230,7 +230,7 @@
<section class="sm-section" id="build">
<header>
- <h2>Build<span class="sm-count" data-count>31</span></h2>
+ <h2>Build<span class="sm-count" data-count>32</span></h2>
<p class="sm-section-desc">Create and customize an agent.</p>
</header>
<ul class="sm-list">
@@ -283,6 +283,13 @@
<span class="sm-desc">Type a prompt — or drop in photos or a sketch — and get a downloadable textured 3D model (GLB). Pick from multiple generation engines with live health status.</span>
</a>
</li>
+ <li>
+ <a href="/forge-studio">
+ <span class="sm-title">Studio — Object + Avatar from text</span>
+ <span class="sm-path">/forge-studio</span>
+ <span class="sm-desc">One canvas for both text-to-3D pipelines: forge a textured object (GLB) in the Object tab, or describe a character and get a rigged avatar in the Avatar tab.</span>
+ </a>
+ </li>
<li>
<a href="/scene">
<span class="sm-title">Scene Studio</span>
diff --git a/scripts/club-diag.mjs b/scripts/club-diag.mjs
new file mode 100644
index 000000000..e22952c89
--- /dev/null
+++ b/scripts/club-diag.mjs
@@ -0,0 +1,99 @@
+import { chromium } from 'playwright';
+
+const URL = process.env.CLUB_URL || 'http://localhost:3001/club';
+const SETTLE = Number(process.env.SETTLE || 12000);
+
+const browser = await chromium.launch({
+ args: ['--no-sandbox', '--disable-dev-shm-usage', '--ignore-gpu-blocklist', '--enable-unsafe-swiftshader', '--use-gl=angle', '--use-angle=swiftshader'],
+});
+const ctx = await browser.newContext({ viewport: { width: 1600, height: 1000 } });
+await ctx.addInitScript(() => {
+ const future = new Date(Date.now() + 12 * 3600 * 1000).toISOString();
+ localStorage.setItem('club:pass:v1', JSON.stringify({ passId: 'dev', tier: 'regular', visits: 1, expiresAt: future, wallet: 'devwallet', issuedAt: new Date().toISOString() }));
+});
+const page = await ctx.newPage();
+const logs = [];
+page.on('console', (m) => logs.push(`[${m.type()}] ${m.text()}`));
+await page.goto(URL, { waitUntil: 'domcontentloaded', timeout: 45000 });
+await page.waitForTimeout(SETTLE);
+
+const diag = await page.evaluate(() => {
+ const THREE = window.__THREE || null;
+ const stations = window.__clubStations || [];
+ function applyMat(m, x, y, z) {
+ const e = m.elements;
+ return {
+ x: e[0] * x + e[4] * y + e[8] * z + e[12],
+ y: e[1] * x + e[5] * y + e[9] * z + e[13],
+ z: e[2] * x + e[6] * y + e[10] * z + e[14],
+ };
+ }
+ function boxOf(obj) {
+ try {
+ obj.updateMatrixWorld(true);
+ const min = { x: Infinity, y: Infinity, z: Infinity };
+ const max = { x: -Infinity, y: -Infinity, z: -Infinity };
+ let skinned = 0, meshes = 0;
+ obj.traverse((n) => {
+ if (n.isSkinnedMesh) skinned++;
+ if (n.isMesh) meshes++;
+ if (n.isMesh && n.geometry) {
+ let bb;
+ if (n.isSkinnedMesh && typeof n.computeBoundingBox === 'function') {
+ n.skeleton?.update?.();
+ n.computeBoundingBox();
+ bb = n.boundingBox;
+ } else {
+ n.geometry.computeBoundingBox?.();
+ bb = n.geometry.boundingBox;
+ }
+ if (!bb) return;
+ for (const xi of [bb.min.x, bb.max.x]) for (const yi of [bb.min.y, bb.max.y]) for (const zi of [bb.min.z, bb.max.z]) {
+ const w = applyMat(n.matrixWorld, xi, yi, zi);
+ min.x = Math.min(min.x, w.x); min.y = Math.min(min.y, w.y); min.z = Math.min(min.z, w.z);
+ max.x = Math.max(max.x, w.x); max.y = Math.max(max.y, w.y); max.z = Math.max(max.z, w.z);
+ }
+ }
+ });
+ const r = (v) => +v.toFixed(2);
+ return {
+ meshes, skinned,
+ worldMin: { x: r(min.x), y: r(min.y), z: r(min.z) },
+ worldMax: { x: r(max.x), y: r(max.y), z: r(max.z) },
+ worldH: r(max.y - min.y), worldW: r(max.x - min.x),
+ };
+ } catch (e) { return { err: String(e) }; }
+ }
+ return stations.map((s) => {
+ const rig = s.rig;
+ const child = rig && rig.children && rig.children[0];
+ const info = {
+ idx: s.idx, id: s.id,
+ walkPhase: s.walkPhase,
+ rigPos: rig ? { x: +rig.position.x.toFixed(2), y: +rig.position.y.toFixed(2), z: +rig.position.z.toFixed(2) } : null,
+ rigChildren: rig ? rig.children.length : -1,
+ skinnedSet: !!s.skinned,
+ child: child ? boxOf(child) : null,
+ childScale: child ? { x: +child.scale.x.toFixed(3), y: +child.scale.y.toFixed(3), z: +child.scale.z.toFixed(3) } : null,
+ childPosY: child ? +child.position.y.toFixed(3) : null,
+ childVisible: child ? child.visible : null,
+ hasAnim: !!s.anim,
+ currentName: s.anim?.currentName ?? null,
+ actions: s.anim ? [...s.anim.actions.keys()] : null,
+ supportsCanonical: s.anim?.supportsCanonicalClips?.() ?? null,
+ };
+ // Force bind pose: stop the mixer, reset the skeleton to bind, re-measure.
+ try {
+ s.anim?.mixer?.stopAllAction();
+ if (child) {
+ child.traverse((n) => { if (n.isSkinnedMesh) { n.skeleton.pose(); n.skeleton.update(); } });
+ info.bindBox = boxOf(child);
+ }
+ } catch (e) { info.bindErr = String(e); }
+ return info;
+ });
+});
+console.log(JSON.stringify(diag, null, 2));
+console.log('--- relevant logs ---');
+console.log(logs.filter((l) => /club|retarget|avatar|fallen|error|warn/i.test(l)).slice(0, 30).join('\n'));
+await browser.close();
diff --git a/scripts/club-probe.mjs b/scripts/club-probe.mjs
deleted file mode 100644
index 5f6a974cb..000000000
--- a/scripts/club-probe.mjs
+++ /dev/null
@@ -1,50 +0,0 @@
-import { chromium } from 'playwright';
-
-const browser = await chromium.launch();
-const page = await browser.newPage({ viewport: { width: 1400, height: 900 } });
-const errors = [];
-page.on('console', m => { if (m.type() === 'error') errors.push('CONSOLE: ' + m.text()); });
-page.on('pageerror', e => errors.push('PAGEERROR: ' + e.message));
-
-await page.goto('http://localhost:3000/club', { waitUntil: 'load' });
-await page.waitForTimeout(8000);
-
-// Probe several screen points for the topmost element
-const points = [
- { name: 'top-bar Audio btn', x: 1130, y: 32 },
- { name: 'right panel Tip btn area', x: 1150, y: 560 },
- { name: 'right panel Change Avatar', x: 1150, y: 460 },
- { name: 'stage center', x: 500, y: 450 },
- { name: 'top center reactions', x: 600, y: 80 },
-];
-
-const info = await page.evaluate((pts) => {
- function desc(el) {
- if (!el) return 'null';
- const cs = getComputedStyle(el);
- return `${el.tagName.toLowerCase()}#${el.id || ''}.${(el.className && el.className.baseVal !== undefined ? el.className.baseVal : el.className) || ''} [z=${cs.zIndex} pe=${cs.pointerEvents} pos=${cs.position} op=${cs.opacity} disp=${cs.display}]`;
- }
- // List all fixed/absolute full-viewport elements that might overlay
- const overlays = [];
- document.querySelectorAll('*').forEach(el => {
- const cs = getComputedStyle(el);
- if ((cs.position === 'fixed' || cs.position === 'absolute')) {
- const r = el.getBoundingClientRect();
- if (r.width >= window.innerWidth * 0.8 && r.height >= window.innerHeight * 0.6 && cs.pointerEvents !== 'none' && cs.display !== 'none' && cs.visibility !== 'hidden') {
- overlays.push(`${desc(el)} rect=${Math.round(r.width)}x${Math.round(r.height)}@${Math.round(r.left)},${Math.round(r.top)}`);
- }
- }
- });
- const hits = pts.map(p => ({ name: p.name, top: desc(document.elementFromPoint(p.x, p.y)) }));
- return { overlays, hits, loaderExists: !!document.getElementById('club-loader'), loaderDone: document.getElementById('club-loader')?.classList.contains('is-done'), doorCanvas: !!document.getElementById('club-door-canvas') };
-}, points);
-
-console.log('=== Big pointer-capturing overlays ===');
-info.overlays.forEach(o => console.log(' ' + o));
-console.log('=== elementFromPoint hits ===');
-info.hits.forEach(h => console.log(` ${h.name}: ${h.top}`));
-console.log('loaderExists', info.loaderExists, 'loaderDone', info.loaderDone, 'doorCanvas', info.doorCanvas);
-console.log('=== JS errors ===');
-errors.slice(0, 20).forEach(e => console.log(' ' + e));
-
-await browser.close();
diff --git a/scripts/club-shot.mjs b/scripts/club-shot.mjs
new file mode 100644
index 000000000..8205ebeb9
--- /dev/null
+++ b/scripts/club-shot.mjs
@@ -0,0 +1,46 @@
+import { chromium } from 'playwright';
+
+const URL = process.env.CLUB_URL || 'http://localhost:3001/club';
+const OUT = process.env.OUT || '/tmp/club.png';
+const SETTLE = Number(process.env.SETTLE || 9000);
+
+const browser = await chromium.launch({
+ args: [
+ '--no-sandbox',
+ '--disable-dev-shm-usage',
+ '--ignore-gpu-blocklist',
+ '--enable-unsafe-swiftshader',
+ '--use-gl=angle',
+ '--use-angle=swiftshader',
+ ],
+});
+const ctx = await browser.newContext({ viewport: { width: 1600, height: 1000 }, deviceScaleFactor: 1 });
+await ctx.addInitScript(() => {
+ const future = new Date(Date.now() + 12 * 3600 * 1000).toISOString();
+ localStorage.setItem('club:pass:v1', JSON.stringify({
+ passId: 'dev', tier: 'regular', visits: 1,
+ expiresAt: future, wallet: 'devwallet', issuedAt: new Date().toISOString(),
+ }));
+});
+const page = await ctx.newPage();
+const errors = [];
+page.on('console', (m) => { if (m.type() === 'error' || m.type() === 'warning') errors.push(`[${m.type()}] ${m.text()}`); });
+page.on('pageerror', (e) => errors.push(`[pageerror] ${e.message}`));
+await page.goto(URL, { waitUntil: 'domcontentloaded', timeout: 45000 });
+await page.waitForTimeout(SETTLE);
+const state = await page.evaluate(() => (window.__clubStations || []).map((s) => ({
+ idx: s.idx, id: s.id,
+ curr: s.anim?.currentName ?? null,
+ clips: s.anim ? [...(s.anim.clips?.keys?.() || [])] : null,
+ actions: s.anim ? [...s.anim.actions.keys()] : null,
+ fallen: s.anim?._fallen ? [...s.anim._fallen] : null,
+ failed: s.anim?._failed ? [...s.anim._failed] : null,
+ idleWeight: (() => { const a = s.anim?.actions?.get('idle'); return a ? +a.getEffectiveWeight().toFixed(2) : null; })(),
+ mixerTime: s.anim?.mixer?.time ?? null,
+})));
+console.log('STATE', JSON.stringify(state));
+await page.screenshot({ path: OUT, timeout: 90000, animations: 'disabled' });
+console.log('saved', OUT);
+console.log('--- console errors/warnings ---');
+console.log(errors.slice(0, 40).join('\n'));
+await browser.close();
diff --git a/src/animation-manager.js b/src/animation-manager.js
index 56f6564ff..47c5ac347 100644
--- a/src/animation-manager.js
+++ b/src/animation-manager.js
@@ -12,6 +12,8 @@ import { canonicalizeBoneName } from './glb-canonicalize.js';
import {
canonicalNodeMapFromObject,
canonicalRestMapFromObject,
+ clipHipBaselineY,
+ hipRestLocalHeight,
hipsParentWorldQuat,
retargetClip,
} from './animation-retarget.js';
@@ -191,6 +193,12 @@ export class AnimationManager {
// World rotation of the Hips' parent (within the model), so root motion is
// re-expressed in the rig's own frame and travels the right way on any rig.
this._hipsParentWorldQuat = hipsParentWorldQuat(model);
+ // Rest height of the Hips in the parent's local units (metres for a
+ // metre-native rig, ~100 for a centimetre-scale Mixamo armature). Hip
+ // tracks set the Hips' *local* position, so _retarget scales each clip by
+ // this ÷ the clip's authored baseline — without it a 0.01-scaled rig's
+ // hips collapse to the floor (metre-valued track × 0.01 parent ≈ 1cm).
+ this._hipTargetLocalY = hipRestLocalHeight(model);
this._canonicalClipsSupported = _modelSupportsCanonicalClips(model);
for (const [name, clip] of this.clips) {
@@ -212,9 +220,20 @@ export class AnimationManager {
*/
_retarget(clip) {
if (!this._canonicalToNode || this._canonicalToNode.size === 0) return null;
+ // Scale the clip's hip translation into the rig's local frame. For a
+ // metre-native rig this is ≈1 (no-op); for a centimetre-scale armature it
+ // is ~100, which is what keeps the dancer standing on the stage instead of
+ // sinking a metre through it. Clamped so a degenerate baseline can't fling
+ // the root away.
+ let hipScale = 1;
+ const baseline = clipHipBaselineY(clip);
+ if (this._hipTargetLocalY > 0.05 && baseline > 0.05) {
+ hipScale = Math.min(200, Math.max(0.2, this._hipTargetLocalY / baseline));
+ }
const { clip: out } = retargetClip(clip, this._canonicalToNode, {
targetRest: this._canonicalRest,
hipsParentWorldQuat: this._hipsParentWorldQuat,
+ hipScale,
});
return out;
}
diff --git a/src/animation-retarget.js b/src/animation-retarget.js
index 904a3aadc..da398e92c 100644
--- a/src/animation-retarget.js
+++ b/src/animation-retarget.js
@@ -358,9 +358,48 @@ export function hipRestHeight(rig) {
return _v.y;
}
+const _hipScalePos = new Vector3();
+const _hipScaleQuat = new Quaternion();
+const _hipScaleScale = new Vector3();
+
+/**
+ * Rest height of an Object3D rig's Hips expressed in the *hips-parent's local
+ * units*, i.e. world height divided by the parent's accumulated world scale.
+ * Hip-position tracks are authored in metres and set the Hips bone's *local*
+ * position, so the scale factor that lands them at the right place is this local
+ * height ÷ the clip's authored baseline — not the world height. The two agree
+ * for a metre-native rig (parent scale ≈ 1) but diverge hard for a centimetre
+ * rig (e.g. a Mixamo armature exported at `scale 0.01`, whose Hips local sits
+ * near −100): matching world heights there would collapse the hip track to ~1cm
+ * of motion and sink the avatar a metre into the floor. Returns 0 when the hips
+ * or a usable parent scale can't be determined (caller then skips hip scaling).
+ *
+ * @param {import('three').Object3D} root
+ * @returns {number}
+ */
+export function hipRestLocalHeight(root) {
+ let hips = null;
+ root.traverse((n) => {
+ if (!hips && n.isBone && n.name && canonicalizeBoneName(n.name) === 'Hips') hips = n;
+ });
+ if (!hips) {
+ root.traverse((n) => {
+ if (!hips && n.name && canonicalizeBoneName(n.name) === 'Hips') hips = n;
+ });
+ }
+ if (!hips || !hips.parent) return 0;
+ hips.updateWorldMatrix(true, false);
+ hips.getWorldPosition(_hipScalePos);
+ const worldY = _hipScalePos.y;
+ hips.parent.matrixWorld.decompose(_hipScalePos, _hipScaleQuat, _hipScaleScale);
+ const parentScale = (_hipScaleScale.x + _hipScaleScale.y + _hipScaleScale.z) / 3;
+ if (!(parentScale > 1e-6) || !Number.isFinite(worldY)) return 0;
+ return worldY / parentScale;
+}
+
// First Y value of a `Hips.position` track — the height the clip's root motion
// was authored around. The retarget scales other-height rigs by target/source.
-function clipHipBaselineY(clip) {
+export function clipHipBaselineY(clip) {
const track = clip.tracks.find(
(t) =>
t.name.endsWith('.position') && canonicalizeBoneName(t.name.split('.')[0]) === 'Hips',
diff --git a/src/club.js b/src/club.js
index 41ae6bf34..ee1654c52 100644
--- a/src/club.js
+++ b/src/club.js
@@ -475,6 +475,12 @@ const DANCER_META = [
// differently-authored gallery avatars reads as one lineup.
const DANCER_HEIGHT_M = 1.75;
+// An idle pose that renders shorter than this (metres) has collapsed — the rig's
+// skeleton didn't drive the clip, so the dancer is flattened invisibly on the
+// disc and re-grounding can't rescue her; she falls back to a known-good rig.
+// Set well below DANCER_HEIGHT_M so a genuinely short (but standing) pose passes.
+const MIN_IDLE_STANDING_M = 1.2;
+
/**
* Scale a freshly-cloned avatar root to `targetHeight` and ground its feet at
* local y=0, measuring with the skinning-aware (`precise`) bounding box so a
@@ -723,6 +729,33 @@ class PoleStation {
return root;
}
+ /**
+ * Plant the live (idle) pose's feet on the stage and report her standing
+ * height. fitRigToHeight grounds the *bind* pose, but a retargeted idle can
+ * carry its own vertical offset — some rigs idle a full metre below the bind
+ * feet line, sinking the dancer through the disc. Measuring the posed skinned
+ * bounds (precise) and dropping the avatar root by the floor gap re-plants her
+ * on the stage. Returns the rendered height (m) so the caller can detect a
+ * collapsed retarget that grounding alone can't rescue.
+ * @returns {number}
+ */
+ _groundAndMeasureIdle() {
+ const root = this.skinned;
+ if (!root || !this.anim) return 0;
+ // play() only queues the action; advance the mixer one frame so the idle
+ // pose is realized on the skeleton before we measure it.
+ this.anim.update(0.1);
+ root.updateMatrixWorld(true);
+ root.traverse((n) => { if (n.isSkinnedMesh) n.skeleton?.update?.(); });
+ const box = new Box3().setFromObject(root, true);
+ if (!Number.isFinite(box.min.y) || !Number.isFinite(box.max.y)) return 0;
+ // The rig holder sits at world y=0; drop the avatar root so her lowest
+ // vertex (her feet) lands on that plane — the rig's yaw-only transform
+ // leaves the vertical axis untouched, so the world offset applies directly.
+ root.position.y -= box.min.y;
+ return box.max.y - box.min.y;
+ }
+
/**
* Bind the pre-fetched locomotion clips (idle + walk) into this dancer's
* mixer so the first `play('idle')` resolves from memory — no network fetch,
@@ -768,14 +801,20 @@ class PoleStation {
this.skinned = root;
this.anim.setAnimationDefs(animationDefs);
this._injectLocomotion();
- // Await idle so we can detect if the fallen-pose guard rejects the
- // retarget — in which case swap to the fallback rig rather than leave
- // the dancer frozen in her bind pose. With the locomotion clips injected
- // above, idle binds synchronously — the dancer's first rendered frame is
- // her resting stance, never a T-pose.
+ // Await idle so we can detect a retarget that doesn't leave her standing —
+ // rejected outright (fallen-pose guard) or collapsed to a flat pose (the
+ // skeleton didn't drive the clip) — and swap to the fallback rig rather
+ // than leave a dancer sunk through the disc or flattened invisibly on it.
+ // On whichever rig does stand, re-ground her idle pose so her feet sit on
+ // the stage: fitRigToHeight grounds the bind pose, but a retargeted idle
+ // can impose its own vertical offset (some rigs idle a metre low). With the
+ // locomotion clips injected above, idle binds synchronously — the dancer's
+ // first rendered frame is her resting stance, never a T-pose.
this.anim.play('idle').then((ok) => {
- if (ok || !fallback || fallback === template) return;
- log.warn(`[club] dancer ${this.id} idle retarget rejected — falling back to default avatar`);
+ const standing = ok ? this._groundAndMeasureIdle() : 0;
+ if (standing >= MIN_IDLE_STANDING_M) return;
+ if (!fallback || fallback === template) return;
+ log.warn(`[club] dancer ${this.id} idle not standing (${standing.toFixed(2)}m) — falling back to default avatar`);
this.anim.detach();
this.rig.remove(root);
const fbRoot = this._buildAvatarRoot(fallback);
@@ -784,7 +823,7 @@ class PoleStation {
this.skinned = fbRoot;
this.anim.setAnimationDefs(animationDefs);
this._injectLocomotion();
- this.anim.play('idle').catch(() => {});
+ this.anim.play('idle').then((ok2) => { if (ok2) this._groundAndMeasureIdle(); }).catch(() => {});
}).catch(() => {});
// Pre-load the walk clip so the first tip's walk starts immediately
// without a network round-trip mid-performance.
diff --git a/src/forge-studio/create-prompt.js b/src/forge-studio/create-prompt.js
new file mode 100644
index 000000000..f802fc82c
--- /dev/null
+++ b/src/forge-studio/create-prompt.js
@@ -0,0 +1,353 @@
+/**
+ * Prompt → 3D avatar controller for the merged Studio page (/forge-studio).
+ *
+ * This is an isolated copy of src/create-prompt.js, restructured for the merged
+ * page so it can never interfere with the live /create/prompt page:
+ * - Every DOM id is namespaced `cp-*` (the live page keeps the bare ids).
+ * - All markup lives under `#studio-avatar`; class queries are scoped to it
+ * so they don't pick up Forge's `.step`/`.example`/`.composer` elements.
+ * - Nothing runs at import time. `initCreatePrompt()` is called once, the
+ * first time the user switches to the Avatar mode, by forge-studio.html.
+ *
+ * Flow (reuses the same backend as the selfie pipeline):
+ * prompt text
+ * -> POST /api/avatars/reconstruct { name, prompt, visibility }
+ * (server turns the prompt into a frontal reference image via Flux,
+ * then runs the identical reconstruct -> auto-rig pipeline)
+ * -> poll /api/avatars/regenerate-status?jobId=...
+ * -> on { status:'done', resultAvatarId } -> fetch the avatar, preview it,
+ * and offer "Open in editor" / "Make another"
+ */
+
+import { log } from '../shared/log.js';
+
+const SUBMIT_ENDPOINT = '/api/avatars/reconstruct';
+const STATUS_ENDPOINT = '/api/avatars/regenerate-status';
+const POLL_INTERVAL_MS = 3000;
+const POLL_TIMEOUT_MS = 8 * 60 * 1000;
+const RETURN_PATH = '/forge-studio';
+const ROOT_SEL = '#studio-avatar';
+
+const root = () => /** @type {HTMLElement} */ (document.querySelector(ROOT_SEL));
+const $ = (sel) => /** @type {HTMLElement} */ (root()?.querySelector(sel));
+
+let _inited = false;
+let _submitting = false;
+let _startedAt = 0;
+let _elapsedTimer = 0;
+
+// Resolved in initCreatePrompt() once the markup is in the DOM.
+let promptEl, counterEl, generateBtn, composeError, buildError, buildPrompt, buildStatus, progressFill, elapsedEl;
+
+function showStep(step) {
+ for (const el of root().querySelectorAll('.step')) {
+ el.classList.toggle('active', el.getAttribute('data-step') === step);
+ }
+}
+
+function setError(box, message) {
+ if (!box) return;
+ if (message) {
+ box.innerHTML = message;
+ box.classList.add('show');
+ } else {
+ box.textContent = '';
+ box.classList.remove('show');
+ }
+}
+
+// ── Compose ─────────────────────────────────────────────────────────────────
+
+function updateCounter() {
+ const n = promptEl.value.length;
+ counterEl.textContent = `${n} / 600`;
+ counterEl.classList.toggle('warn', n > 600);
+ generateBtn.disabled = promptEl.value.trim().length < 3 || _submitting;
+}
+
+// ── Submit + poll ────────────────────────────────────────────────────────────
+
+function nameFromPrompt(prompt) {
+ const words = prompt.replace(/\s+/g, ' ').trim().split(' ').slice(0, 6).join(' ');
+ return (words.length > 60 ? words.slice(0, 60) : words) || 'Prompt avatar';
+}
+
+async function start() {
+ if (_submitting) return;
+ const prompt = promptEl.value.trim();
+ if (prompt.length < 3) {
+ setError(composeError, 'Add a few words describing what you want.');
+ return;
+ }
+
+ _submitting = true;
+ generateBtn.disabled = true;
+ setError(composeError, '');
+
+ buildPrompt.textContent = `“${prompt}”`;
+ setError(buildError, '');
+ setProgress(8, 'Rendering a reference image…');
+ startElapsed();
+ showStep('building');
+
+ let jobId;
+ try {
+ const res = await fetch(SUBMIT_ENDPOINT, {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ name: nameFromPrompt(prompt), prompt, visibility: 'private' }),
+ });
+ if (res.status === 401) {
+ window.location.assign(`/login?next=${encodeURIComponent(RETURN_PATH)}`);
+ return;
+ }
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok || !data.jobId) {
+ throw new ApiError(mapSubmitError(res.status, data));
+ }
+ jobId = data.jobId;
+ } catch (err) {
+ failBuild(err);
+ return;
+ }
+
+ try {
+ const final = await pollUntilDone(jobId);
+ await renderDone(final.resultAvatarId);
+ } catch (err) {
+ failBuild(err);
+ }
+}
+
+class ApiError extends Error {}
+
+/** @param {string | null | undefined} raw */
+function friendlyJobError(raw) {
+ if (!raw) return 'Generation failed. Try a different prompt.';
+ const lower = raw.toLowerCase();
+ if (lower.includes('face') && (lower.includes('detect') || lower.includes('no face')))
+ return 'Couldn\'t find a face in the generated reference image. Try rewording your prompt to describe the person more clearly.';
+ if (lower.includes('nsfw'))
+ return 'Content safety blocked this image. Try a different prompt.';
+ if (lower.includes('unreachable') || lower.includes('502') || lower.includes('503'))
+ return 'The avatar engine is temporarily unavailable. Try again in a few minutes.';
+ if (lower.includes('timeout') || lower.includes('timed out'))
+ return 'The engine took too long. Try again in a moment.';
+ if (lower.includes('oom') || lower.includes('memory'))
+ return 'The engine ran out of resources. Try a simpler prompt.';
+ return 'Generation failed. Try a different prompt.';
+}
+
+function mapSubmitError(status, data) {
+ // The API error envelope is { error: <code string>, error_description: <message> }
+ // (see api/_lib/http.js error()). Read those fields directly.
+ const code = typeof data?.error === 'string' ? data.error : data?.code;
+ const description = data?.error_description;
+ if (code === 'txt2img_rate_limited' || status === 429) {
+ return 'The image engine is busy right now — wait a moment and try again.';
+ }
+ if (code === 'regen_unconfigured' || code === 'txt2img_unconfigured') {
+ return 'The avatar generator isn\'t configured on this deployment yet. Try the <a href="/create/selfie">selfie scanner</a> instead.';
+ }
+ if (code === 'txt2img_billing') return 'The image engine is temporarily unavailable (provider billing). Try again later.';
+ if (code === 'txt2img_unreachable') return 'Couldn\'t reach the image engine. Check your connection and try again.';
+ if (code === 'txt2img_error') return 'Couldn\'t render a reference image from that prompt. Try rewording it.';
+ if (code === 'regen_provider_error') return 'The avatar engine rejected this job. Try again in a moment.';
+ return description || `The avatar engine returned ${status}. Try again.`;
+}
+
+async function pollUntilDone(jobId) {
+ const deadline = Date.now() + POLL_TIMEOUT_MS;
+ while (Date.now() < deadline) {
+ await sleep(POLL_INTERVAL_MS);
+ let data;
+ try {
+ const res = await fetch(`${STATUS_ENDPOINT}?jobId=${encodeURIComponent(jobId)}`, {
+ credentials: 'include',
+ });
+ if (res.status === 401) {
+ window.location.assign(`/login?next=${encodeURIComponent(RETURN_PATH)}`);
+ throw new ApiError('redirecting');
+ }
+ data = await res.json().catch(() => ({}));
+ if (!res.ok) throw new ApiError(data?.error_description || `status ${res.status}`);
+ } catch (err) {
+ if (err instanceof ApiError) throw err;
+ // Transient network blip — keep polling until the deadline.
+ log.warn('[studio-prompt] poll blip', err);
+ continue;
+ }
+
+ advanceProgress(data.status);
+
+ if (data.status === 'done' && data.resultAvatarId) {
+ setProgress(100, 'Done.');
+ return data;
+ }
+ if (data.status === 'failed') {
+ throw new ApiError(friendlyJobError(data.error));
+ }
+ }
+ throw new ApiError('This is taking longer than expected. Your avatar may still finish — check your dashboard in a minute.');
+}
+
+// Map backend job states to human progress. The bar creeps within each phase so
+// it always feels alive, then jumps on real state transitions.
+const PHASE = {
+ queued: { pct: 18, label: 'Rendering a reference image…' },
+ running: { pct: 55, label: 'Reconstructing it into 3D…' },
+ rigging: { pct: 85, label: 'Adding a skeleton so it can move…' },
+};
+function advanceProgress(status) {
+ const phase = PHASE[status];
+ if (phase) setProgress(phase.pct, phase.label);
+}
+function setProgress(pct, label) {
+ progressFill.style.width = `${pct}%`;
+ if (label) buildStatus.textContent = label;
+}
+
+// ── Done ─────────────────────────────────────────────────────────────────────
+
+async function renderDone(avatarId) {
+ let avatar = null;
+ try {
+ const res = await fetch(`/api/avatars/${encodeURIComponent(avatarId)}`, { credentials: 'include' });
+ const data = await res.json().catch(() => ({}));
+ avatar = data?.avatar || data || null;
+ } catch (err) {
+ log.warn('[studio-prompt] could not fetch finished avatar', err);
+ }
+
+ const editorUrl = `/avatars/${encodeURIComponent(avatarId)}/edit`;
+ $('#cp-open-editor').setAttribute('href', editorUrl);
+ $('#cp-make-another').addEventListener('click', () => resetToCompose());
+
+ const modelUrl = avatar?.model_url || avatar?.modelUrl;
+ const viewer = /** @type {any} */ ($('#cp-done-model'));
+ if (modelUrl && viewer) viewer.setAttribute('src', modelUrl);
+
+ const rigged = avatar?.source_meta?.is_rigged ?? avatar?.tags?.includes?.('rigged');
+ const tagsEl = $('#cp-done-tags');
+ tagsEl.innerHTML = '';
+ const tag = (text, ok) => {
+ const s = document.createElement('span');
+ s.className = `tag${ok ? ' ok' : ''}`;
+ s.textContent = text;
+ tagsEl.appendChild(s);
+ };
+ if (rigged) tag('Animation-ready', true);
+ else tag('Static mesh — riggable in editor', false);
+ tag('Private to you', false);
+
+ stopElapsed();
+ // If the model can't render (no URL yet), go straight to the editor rather
+ // than showing an empty viewer box.
+ if (!modelUrl) {
+ window.location.assign(editorUrl);
+ return;
+ }
+ showStep('done');
+ // Let the site-wide discovery layer offer the natural next steps
+ // (Studio, agent wizard, Walk) with this avatar pre-loaded.
+ document.dispatchEvent(
+ new CustomEvent('tws:feature-done', {
+ detail: {
+ feature: 'prompt',
+ avatarId,
+ model: {
+ glbUrl: modelUrl,
+ label: avatar?.display_name || avatar?.name || 'Prompt avatar',
+ },
+ },
+ }),
+ );
+}
+
+function resetToCompose() {
+ _submitting = false;
+ stopElapsed();
+ setError(composeError, '');
+ updateCounter();
+ showStep('compose');
+ promptEl.focus();
+}
+
+// ── Failure ──────────────────────────────────────────────────────────────────
+
+function failBuild(err) {
+ if (err instanceof ApiError && err.message === 'redirecting') return;
+ stopElapsed();
+ _submitting = false;
+ log.error('[studio-prompt]', err);
+ const message =
+ err instanceof ApiError ? err.message : 'Something went wrong. Try again.';
+ setError(buildError, `${message} <button id="cp-build-retry" class="example" style="margin-left:8px">Back</button>`);
+ const retry = root().querySelector('#cp-build-retry');
+ if (retry) retry.addEventListener('click', resetToCompose);
+}
+
+// ── Elapsed clock ────────────────────────────────────────────────────────────
+
+function startElapsed() {
+ _startedAt = Date.now();
+ stopElapsed();
+ _elapsedTimer = window.setInterval(() => {
+ const s = Math.floor((Date.now() - _startedAt) / 1000);
+ elapsedEl.textContent = `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
+ }, 1000);
+}
+function stopElapsed() {
+ if (_elapsedTimer) { clearInterval(_elapsedTimer); _elapsedTimer = 0; }
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+// ── Init (called once, lazily, by the mode switch) ────────────────────────────
+
+export function initCreatePrompt() {
+ if (_inited) return;
+ const scope = root();
+ if (!scope) return;
+ _inited = true;
+
+ promptEl = /** @type {HTMLTextAreaElement} */ ($('#cp-prompt'));
+ counterEl = $('#cp-counter');
+ generateBtn = /** @type {HTMLButtonElement} */ ($('#cp-generate-btn'));
+ composeError = $('#cp-compose-error');
+ buildError = $('#cp-build-error');
+ buildPrompt = $('#cp-build-prompt');
+ buildStatus = $('#cp-build-status');
+ progressFill = $('#cp-progress-fill');
+ elapsedEl = $('#cp-elapsed');
+
+ promptEl.addEventListener('input', () => {
+ updateCounter();
+ if (composeError.classList.contains('show')) setError(composeError, '');
+ });
+
+ // Cmd/Ctrl+Enter submits.
+ promptEl.addEventListener('keydown', (e) => {
+ if ((e.metaKey || e.ctrlKey) && e.key === 'Enter' && !generateBtn.disabled) {
+ e.preventDefault();
+ start();
+ }
+ });
+
+ for (const chip of scope.querySelectorAll('.example')) {
+ chip.addEventListener('click', () => {
+ promptEl.value = chip.textContent.trim();
+ updateCounter();
+ promptEl.focus();
+ });
+ }
+
+ generateBtn.addEventListener('click', start);
+
+ updateCounter();
+}
+
+export function focusPrompt() {
+ if (promptEl) promptEl.focus();
+}
diff --git a/src/forge-studio/forge-ar.js b/src/forge-studio/forge-ar.js
new file mode 100644
index 000000000..ed3ea18a1
--- /dev/null
+++ b/src/forge-studio/forge-ar.js
@@ -0,0 +1,208 @@
+// Forge "See it in your space" — bridge desktop → phone AR.
+//
+// model-viewer can only enter AR on a phone/tablet, so a desktop visitor who
+// just forged something has no way to place it in their room. This panel
+// closes that gap:
+// • on a desktop, it shows a QR code to the AR-capable embed viewer
+// (/forge/embed) — scan it and the model opens on your phone, one tap from
+// AR (the embed page reveals a big "View in AR" launcher there).
+// • on a touch device, it launches AR straight from the page's own viewer.
+//
+// Self-contained: reads the live GLB URL off the result bar's Download link,
+// reuses the zero-dep QR encoder and the shared Modal — no coupling to
+// src/forge.js internals, no network calls, no new dependencies.
+
+import { Modal } from '../shared/modal.js';
+import { renderQRToSVG } from '../erc8004/qr.js';
+
+const ORIGIN = 'https://three.ws';
+const STYLE_ID = 'tws-forge-ar-styles';
+
+function esc(s) {
+ return String(s ?? '').replace(
+ /[&<>"']/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
+ );
+}
+
+function absoluteGlb(url) {
+ if (!url) return '';
+ try {
+ return new URL(url, ORIGIN).href;
+ } catch {
+ return url;
+ }
+}
+
+// Short URL for the QR (no title — keeps the code low-density and easy to scan).
+function arUrl(glbUrl) {
+ return `${ORIGIN}/forge/embed?src=${encodeURIComponent(glbUrl)}`;
+}
+
+// Richer URL for the tappable link (carries the prompt through as alt text).
+function arLink(glbUrl, title) {
+ const u = arUrl(glbUrl);
+ return title ? `${u}&title=${encodeURIComponent(title.slice(0, 120))}` : u;
+}
+
+function isTouch() {
+ return typeof window !== 'undefined' && window.matchMedia?.('(pointer: coarse)').matches;
+}
+
+function ensureStyles() {
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;
+ const el = document.createElement('style');
+ el.id = STYLE_ID;
+ el.textContent = CSS;
+ (document.head || document.documentElement).appendChild(el);
+}
+
+function qrMarkup(glbUrl) {
+ try {
+ const svg = renderQRToSVG(arUrl(glbUrl), {
+ scale: 6,
+ margin: 2,
+ dark: '#0b0b0b',
+ light: '#ffffff',
+ });
+ return `<div class="tws-ar-qr" aria-label="QR code linking to the AR viewer">${svg}</div>`;
+ } catch {
+ // Payload too large for the encoder — degrade to link-only, never a broken QR.
+ return '';
+ }
+}
+
+const cubeIcon = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 2 3 7v10l9 5 9-5V7l-9-5Z"/><path d="m3 7 9 5 9-5"/><path d="M12 12v10"/></svg>`;
+
+function bodyHtml({ glbUrl, title, touch }) {
+ const link = esc(arLink(glbUrl, title));
+ const nameHtml = title ? `<p class="tws-ar-name">${esc(title)}</p>` : '';
+ const qr = qrMarkup(glbUrl);
+
+ const linkBtn = `<a class="tws-ar-cta" href="${link}" target="_blank" rel="noopener">${cubeIcon}<span>Open AR viewer</span></a>`;
+
+ if (touch) {
+ // Touch device: launch AR right here from the page's own viewer.
+ const qrSecondary = qr
+ ? `<details class="tws-ar-more">
+ <summary>On a computer? Scan from your phone</summary>
+ ${qr}
+ </details>`
+ : '';
+ return `
+ <div class="tws-ar">
+ ${nameHtml}
+ <p class="tws-ar-hint">Place this model in your room — point your camera at a flat surface and drop it in.</p>
+ <button class="tws-ar-cta" type="button" data-ar-launch>${cubeIcon}<span>View in your space</span></button>
+ <a class="tws-ar-link" href="${link}" target="_blank" rel="noopener">Open in a new tab instead ↗</a>
+ ${qrSecondary}
+ </div>
+ `;
+ }
+
+ // Desktop: QR is the bridge to the phone.
+ return `
+ <div class="tws-ar">
+ ${nameHtml}
+ ${qr}
+ <p class="tws-ar-hint">Scan with your phone camera to view this model in AR and place it in your room.</p>
+ ${linkBtn}
+ </div>
+ `;
+}
+
+export function showARPanel({ glbUrl, title } = {}, triggerEl = null) {
+ ensureStyles();
+ const abs = absoluteGlb(glbUrl);
+ if (!abs) return null;
+ const touch = isTouch();
+
+ const modal = new Modal({
+ title: 'See it in your space',
+ body: bodyHtml({ glbUrl: abs, title: (title || '').trim(), touch }),
+ dismissible: true,
+ }).open(triggerEl);
+
+ const root = modal.bodyEl;
+ root.addEventListener('click', (e) => {
+ if (!e.target.closest('[data-ar-launch]')) return;
+ // Launch AR from the page's main viewer (already AR-enabled in result state).
+ const viewer = document.getElementById('viewer');
+ try {
+ viewer?.activateAR?.();
+ modal.close?.();
+ } catch {
+ /* fall back to the "open in new tab" link the user can still tap */
+ }
+ });
+
+ return modal;
+}
+
+// Wire the result-bar button. GLB URL is read from the Download link at click
+// time, so this never depends on Forge's internal state.
+function wire() {
+ const btn = document.getElementById('forge-ar-btn');
+ if (!btn || btn.dataset.arWired) return;
+ btn.dataset.arWired = '1';
+ btn.addEventListener('click', () => {
+ const glbUrl = document.getElementById('download')?.getAttribute('href') || '';
+ const title = document.getElementById('result-label')?.textContent || '';
+ if (!glbUrl) return;
+ showARPanel({ glbUrl, title }, btn);
+ });
+}
+
+if (typeof document !== 'undefined') {
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', wire, { once: true });
+ } else {
+ wire();
+ }
+}
+
+const CSS = `
+.tws-ar { display: flex; flex-direction: column; align-items: center; gap: 14px; padding: 4px 0 2px; text-align: center; }
+.tws-ar-name {
+ margin: 0; max-width: 32ch;
+ font: 600 14px/1.4 var(--font-body, system-ui, sans-serif);
+ color: var(--ink, #ececf4);
+}
+.tws-ar-qr {
+ width: 208px; height: 208px; padding: 12px;
+ background: #fff; border-radius: 16px;
+ box-shadow: 0 16px 40px -16px rgba(0,0,0,0.7);
+ display: grid; place-items: center;
+}
+.tws-ar-qr svg { width: 100%; height: 100%; display: block; border-radius: 4px; }
+.tws-ar-hint {
+ margin: 0; max-width: 34ch;
+ font-size: 13px; line-height: 1.5; color: var(--ink-dim, #9a9aa8);
+}
+.tws-ar-cta {
+ display: inline-flex; align-items: center; justify-content: center; gap: 9px;
+ width: 100%; box-sizing: border-box; cursor: pointer; text-decoration: none;
+ padding: 13px 18px; border: 0; border-radius: 12px;
+ font: 600 14.5px/1 var(--font-body, system-ui, sans-serif);
+ color: #07140e; background: var(--success, #6ee7b7);
+ box-shadow: 0 10px 28px -10px rgba(110,231,183,0.55);
+ transition: filter 0.14s ease, transform 0.1s ease;
+}
+.tws-ar-cta:hover { filter: brightness(1.06); }
+.tws-ar-cta:active { transform: translateY(1px); }
+.tws-ar-cta:focus-visible { outline: 2px solid var(--ink, #fff); outline-offset: 2px; }
+.tws-ar-cta svg { width: 18px; height: 18px; }
+.tws-ar-link {
+ font-size: 13px; color: var(--accent, #6ee7b7); text-decoration: none;
+}
+.tws-ar-link:hover { text-decoration: underline; }
+.tws-ar-more { width: 100%; margin-top: 2px; }
+.tws-ar-more summary {
+ cursor: pointer; list-style: none; font-size: 12.5px;
+ color: var(--ink-dim, #9a9aa8); padding: 6px 0;
+}
+.tws-ar-more summary::-webkit-details-marker { display: none; }
+.tws-ar-more summary:hover { color: var(--ink, #ececf4); }
+.tws-ar-more[open] summary { margin-bottom: 10px; }
+.tws-ar-more .tws-ar-qr { width: 168px; height: 168px; margin: 0 auto; }
+`;
diff --git a/src/forge-studio/forge-dropzone.js b/src/forge-studio/forge-dropzone.js
new file mode 100644
index 000000000..2a1a68037
--- /dev/null
+++ b/src/forge-studio/forge-dropzone.js
@@ -0,0 +1,226 @@
+// Forge dropzone — paste or drop reference photos anywhere on /forge.
+//
+// Two capture paths, both routed through the `forge:add-images` hook in
+// src/forge.js (which switches to the right input mode and distributes files
+// into free view slots, or the sketch slot in sketch mode):
+//
+// • Paste (⌘V / Ctrl+V) — an image on the clipboard becomes a reference
+// view from anywhere on the page. Text pastes into inputs are untouched.
+// • Drag a file over the page — outside photo mode a full-page overlay
+// invites the drop ("the slots aren't visible, so say where it goes");
+// inside photo mode the slots already light up individually, so the only
+// page-level job is catching drops that miss a slot instead of letting
+// the browser navigate away to the image.
+//
+// Self-contained: injects its own styles, owns its overlay + toast nodes,
+// talks to forge.js only via the CustomEvent contract.
+
+const STYLE_ID = 'forge-dropzone-styles';
+const IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp']);
+
+function injectStyles() {
+ if (document.getElementById(STYLE_ID)) return;
+ const style = document.createElement('style');
+ style.id = STYLE_ID;
+ style.textContent = `
+ .forge-drop-overlay {
+ position: fixed;
+ inset: 0;
+ z-index: 80;
+ display: grid;
+ place-items: center;
+ background: color-mix(in srgb, var(--bg, #0b0b10) 72%, transparent);
+ backdrop-filter: blur(3px);
+ -webkit-backdrop-filter: blur(3px);
+ opacity: 0;
+ pointer-events: none;
+ transition: opacity 0.15s ease;
+ }
+ .forge-drop-overlay[data-active='true'] {
+ opacity: 1;
+ pointer-events: auto;
+ }
+ .forge-drop-card {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 0.6rem;
+ padding: 2.2rem 2.8rem;
+ border: 2px dashed var(--accent, #7c9cff);
+ border-radius: var(--radius-lg, 16px);
+ background: var(--surface-1, rgba(255, 255, 255, 0.04));
+ text-align: center;
+ transform: scale(0.97);
+ transition: transform 0.15s ease;
+ }
+ .forge-drop-overlay[data-active='true'] .forge-drop-card {
+ transform: scale(1);
+ }
+ .forge-drop-card .glyph {
+ font-size: 2rem;
+ color: var(--accent, #7c9cff);
+ line-height: 1;
+ }
+ .forge-drop-card h3 {
+ margin: 0;
+ color: var(--ink, #fff);
+ font-family: var(--font-display, inherit);
+ font-size: var(--text-lg, 1.1rem);
+ }
+ .forge-drop-card p {
+ margin: 0;
+ color: var(--ink-dim, #aab);
+ font-size: var(--text-sm, 0.85rem);
+ max-width: 34ch;
+ }
+ .forge-toast {
+ position: fixed;
+ left: 50%;
+ bottom: 28px;
+ transform: translate(-50%, 8px);
+ z-index: 90;
+ background: var(--surface-3, #1d1d26);
+ border: 1px solid var(--stroke-strong, rgba(255, 255, 255, 0.16));
+ border-radius: 999px;
+ color: var(--ink, #fff);
+ font-size: var(--text-sm, 0.85rem);
+ padding: 0.55rem 1.1rem;
+ box-shadow: 0 12px 32px -12px rgba(0, 0, 0, 0.7);
+ opacity: 0;
+ pointer-events: none;
+ transition: opacity 0.18s ease, transform 0.18s ease;
+ }
+ .forge-toast[data-show='true'] {
+ opacity: 1;
+ transform: translate(-50%, 0);
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .forge-drop-overlay, .forge-drop-card, .forge-toast {
+ transition: none;
+ }
+ }
+ `;
+ document.head.appendChild(style);
+}
+
+// ── Toast ───────────────────────────────────────────────────────────────────
+
+let toastEl = null;
+let toastTimer = null;
+function toast(message) {
+ if (!toastEl) {
+ toastEl = document.createElement('div');
+ toastEl.className = 'forge-toast';
+ toastEl.setAttribute('role', 'status');
+ toastEl.setAttribute('aria-live', 'polite');
+ document.body.appendChild(toastEl);
+ }
+ toastEl.textContent = message;
+ toastEl.dataset.show = 'true';
+ clearTimeout(toastTimer);
+ toastTimer = setTimeout(() => {
+ toastEl.dataset.show = 'false';
+ }, 2600);
+}
+
+// ── Mode + file helpers ─────────────────────────────────────────────────────
+
+function currentMode() {
+ return (
+ document.querySelector('#mode-switch [aria-selected="true"]')?.dataset.mode || 'text'
+ );
+}
+
+function imageFilesOf(list) {
+ return Array.from(list || []).filter((f) => f && IMAGE_TYPES.has(f.type));
+}
+
+function addImages(files, source) {
+ if (!files.length) return;
+ const sketch = currentMode() === 'sketch';
+ document.dispatchEvent(new CustomEvent('forge:add-images', { detail: { files } }));
+ if (sketch) {
+ toast(`${source} added as your sketch`);
+ } else {
+ toast(
+ files.length === 1
+ ? `${source} added as a reference view`
+ : `${files.length} photos added as reference views`,
+ );
+ }
+}
+
+// ── Paste ───────────────────────────────────────────────────────────────────
+
+document.addEventListener('paste', (e) => {
+ const files = imageFilesOf(e.clipboardData?.files);
+ if (!files.length) return; // text paste — leave the browser alone
+ e.preventDefault();
+ addImages(files, 'Pasted image');
+});
+
+// ── Page-level drag & drop ──────────────────────────────────────────────────
+
+let overlay = null;
+function ensureOverlay() {
+ if (overlay) return overlay;
+ overlay = document.createElement('div');
+ overlay.className = 'forge-drop-overlay';
+ overlay.setAttribute('aria-hidden', 'true');
+ overlay.innerHTML = `
+ <div class="forge-drop-card">
+ <span class="glyph" aria-hidden="true">⇣</span>
+ <h3>Drop photos to forge in 3D</h3>
+ <p>1–4 views of one object. I'll switch to <strong>From photos</strong> and place them for you.</p>
+ </div>`;
+ document.body.appendChild(overlay);
+ return overlay;
+}
+
+function draggingFiles(e) {
+ return Array.from(e.dataTransfer?.types || []).includes('Files');
+}
+
+// dragenter/leave fire for every child node — a depth counter is the reliable
+// way to know when the pointer truly left the window.
+let dragDepth = 0;
+function setOverlay(active) {
+ ensureOverlay().dataset.active = String(active);
+}
+
+document.addEventListener('dragenter', (e) => {
+ if (!draggingFiles(e)) return;
+ dragDepth++;
+ // In photo mode the view slots are on screen and light up themselves; the
+ // overlay would cover them and steal their per-slot targeting.
+ if (currentMode() !== 'image') setOverlay(true);
+});
+
+document.addEventListener('dragleave', () => {
+ dragDepth = Math.max(0, dragDepth - 1);
+ if (dragDepth === 0) setOverlay(false);
+});
+
+document.addEventListener('dragover', (e) => {
+ if (!draggingFiles(e)) return;
+ // Without this the drop never fires and the browser navigates to the file.
+ e.preventDefault();
+});
+
+document.addEventListener('drop', (e) => {
+ dragDepth = 0;
+ setOverlay(false);
+ if (!draggingFiles(e)) return;
+ e.preventDefault();
+ // A drop directly on a view slot was already handled there (capture order:
+ // slot listener runs first and reads the same event) — don't double-add.
+ if (e.target instanceof Element && e.target.closest('.view-slot')) return;
+ const files = imageFilesOf(e.dataTransfer.files);
+ if (!files.length) {
+ toast('Only PNG, JPG, or WebP images can become reference views');
+ return;
+ }
+ addImages(files, 'Dropped photo');
+});
+
+injectStyles();
diff --git a/src/forge-studio/forge-embed-panel.js b/src/forge-studio/forge-embed-panel.js
new file mode 100644
index 000000000..1f4ecbc4d
--- /dev/null
+++ b/src/forge-studio/forge-embed-panel.js
@@ -0,0 +1,270 @@
+// Forge embed panel — turn a finished creation into a one-line embed for any
+// website. Self-contained: it reads the live GLB URL straight off the result
+// bar's Download link, so it never needs Forge's internal state and stays
+// decoupled from src/forge.js (which is edited often).
+//
+// Two embed flavours, both real:
+// • iframe — points at /forge/embed?src=<glb>, a zero-dependency three.ws
+// viewer page (orbit + AR + branding). Works on any site, no scripts,
+// no CORS to worry about (the iframe document is same-origin with the GLB
+// host the way Forge already loads it).
+// • web component — a <model-viewer> snippet for builders who want the model
+// inline in their own DOM with their own controls.
+
+import { Modal } from '../shared/modal.js';
+import {
+ EMBED_SIZES,
+ embedSize,
+ escEmbed as esc,
+ absoluteGlb,
+ embedPageUrl as embedPageUrlFor,
+ embedPreviewUrl,
+ buildIframeSnippet,
+ buildWebComponentSnippet,
+} from './forge-embed-snippets.js';
+
+const STYLE_ID = 'tws-forge-embed-styles';
+
+// Snippet shapes, size presets, and /forge/embed URLs all live in
+// ./forge-embed-snippets.js so the homepage mini Forge embed sheet stays
+// byte-identical. These thin wrappers just bind the module's pure builders to
+// this panel's `state`, keeping every call site below unchanged.
+const SIZES = EMBED_SIZES;
+
+let state = { sizeId: 'wide', tab: 'iframe', glbUrl: '', title: '' };
+
+function size() {
+ return embedSize(state.sizeId);
+}
+
+function embedPageUrl() {
+ return embedPageUrlFor(state.glbUrl, state.title);
+}
+
+function previewSrc() {
+ return embedPreviewUrl(state.glbUrl, state.title);
+}
+
+function iframeSnippet() {
+ return buildIframeSnippet(state.glbUrl, state.title, state.sizeId);
+}
+
+function webComponentSnippet() {
+ return buildWebComponentSnippet(state.glbUrl, state.title, state.sizeId);
+}
+
+function currentSnippet() {
+ return state.tab === 'iframe' ? iframeSnippet() : webComponentSnippet();
+}
+
+function ensureStyles() {
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;
+ const el = document.createElement('style');
+ el.id = STYLE_ID;
+ el.textContent = CSS;
+ (document.head || document.documentElement).appendChild(el);
+}
+
+function bodyHtml() {
+ const s = size();
+ const tabBtn = (id, label) =>
+ `<button type="button" class="tws-emb-tab" data-tab="${id}" aria-pressed="${state.tab === id}">${label}</button>`;
+ const sizeBtn = (sz) =>
+ `<button type="button" class="tws-emb-size" data-size="${sz.id}" aria-pressed="${state.sizeId === sz.id}">${sz.label}</button>`;
+
+ return `
+ <div class="tws-emb">
+ <div class="tws-emb-preview" style="aspect-ratio:${s.ratio}">
+ <iframe class="tws-emb-frame" src="${esc(previewSrc())}" title="Embed preview"
+ allow="xr-spatial-tracking; fullscreen" loading="lazy"></iframe>
+ </div>
+
+ <div class="tws-emb-controls">
+ <div class="tws-emb-seg" role="group" aria-label="Embed type">
+ ${tabBtn('iframe', 'iframe')}
+ ${tabBtn('component', 'Web component')}
+ </div>
+ <div class="tws-emb-seg" role="group" aria-label="Size">
+ ${SIZES.map(sizeBtn).join('')}
+ </div>
+ </div>
+
+ <label class="tws-emb-codelabel" for="tws-emb-code">Paste this where you want the model</label>
+ <textarea id="tws-emb-code" class="tws-emb-code" readonly spellcheck="false" rows="5">${esc(currentSnippet())}</textarea>
+
+ <button type="button" class="tws-emb-copy" data-emb-copy>
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
+ <span class="tws-emb-copy-label">Copy embed code</span>
+ </button>
+
+ <p class="tws-emb-foot">
+ Drops a live, orbitable model on any site — AR-ready on phones.
+ <a href="${esc(embedPageUrl())}" target="_blank" rel="noopener">Open the standalone viewer ↗</a>
+ </p>
+ </div>
+ `;
+}
+
+function rerender(modalBody) {
+ const codeEl = modalBody.querySelector('#tws-emb-code');
+ if (codeEl) codeEl.value = currentSnippet();
+ const preview = modalBody.querySelector('.tws-emb-preview');
+ if (preview) preview.style.aspectRatio = size().ratio;
+ for (const b of modalBody.querySelectorAll('.tws-emb-tab')) {
+ b.setAttribute('aria-pressed', String(b.dataset.tab === state.tab));
+ }
+ for (const b of modalBody.querySelectorAll('.tws-emb-size')) {
+ b.setAttribute('aria-pressed', String(b.dataset.size === state.sizeId));
+ }
+}
+
+async function copyText(text, btn) {
+ const label = btn.querySelector('.tws-emb-copy-label');
+ const original = label ? label.textContent : '';
+ try {
+ if (navigator.clipboard?.writeText) await navigator.clipboard.writeText(text);
+ else {
+ const ta = document.createElement('textarea');
+ ta.value = text;
+ ta.style.position = 'fixed';
+ ta.style.opacity = '0';
+ document.body.appendChild(ta);
+ ta.select();
+ document.execCommand('copy');
+ ta.remove();
+ }
+ btn.classList.add('is-copied');
+ if (label) label.textContent = 'Copied ✓';
+ } catch {
+ if (label) label.textContent = 'Press ⌘/Ctrl+C to copy';
+ }
+ setTimeout(() => {
+ btn.classList.remove('is-copied');
+ if (label) label.textContent = original;
+ }, 2400);
+}
+
+export function showEmbedPanel({ glbUrl, title } = {}, triggerEl = null) {
+ ensureStyles();
+ state = {
+ sizeId: 'wide',
+ tab: 'iframe',
+ glbUrl: absoluteGlb(glbUrl),
+ title: (title || '').trim(),
+ };
+
+ if (!state.glbUrl) return null;
+
+ const modal = new Modal({ title: 'Embed this model', body: bodyHtml(), dismissible: true }).open(triggerEl);
+ const root = modal.bodyEl;
+
+ root.addEventListener('click', (e) => {
+ const tab = e.target.closest('.tws-emb-tab');
+ if (tab) {
+ state.tab = tab.dataset.tab;
+ rerender(root);
+ return;
+ }
+ const sz = e.target.closest('.tws-emb-size');
+ if (sz) {
+ state.sizeId = sz.dataset.size;
+ rerender(root);
+ return;
+ }
+ const copy = e.target.closest('[data-emb-copy]');
+ if (copy) {
+ copyText(currentSnippet(), copy);
+ }
+ });
+
+ return modal;
+}
+
+// Wire the result-bar button. The button lives in forge.html; we read the GLB
+// URL from the Download link's href at click time (always set in result state)
+// and the prompt from the result label, so no coupling to forge.js internals.
+function wire() {
+ const btn = document.getElementById('forge-embed-btn');
+ if (!btn || btn.dataset.embedWired) return;
+ btn.dataset.embedWired = '1';
+ btn.addEventListener('click', () => {
+ const dl = document.getElementById('download');
+ const glbUrl = dl?.getAttribute('href') || '';
+ const label = document.getElementById('result-label')?.textContent || '';
+ if (!glbUrl) return;
+ showEmbedPanel({ glbUrl, title: label }, btn);
+ });
+}
+
+if (typeof document !== 'undefined') {
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', wire, { once: true });
+ } else {
+ wire();
+ }
+}
+
+const CSS = `
+.tws-emb { display: flex; flex-direction: column; gap: 12px; padding: 2px 0; }
+.tws-emb-preview {
+ width: 100%;
+ border-radius: 12px;
+ overflow: hidden;
+ border: 1px solid var(--stroke, rgba(255,255,255,0.1));
+ background: #0b0b0b;
+}
+.tws-emb-frame { display: block; width: 100%; height: 100%; border: 0; }
+.tws-emb-controls { display: flex; flex-wrap: wrap; gap: 8px; justify-content: space-between; }
+.tws-emb-seg {
+ display: inline-flex; gap: 2px; padding: 2px;
+ background: var(--surface-1, rgba(255,255,255,0.03));
+ border: 1px solid var(--stroke, rgba(255,255,255,0.1));
+ border-radius: 10px;
+}
+.tws-emb-tab, .tws-emb-size {
+ background: transparent; border: 0; cursor: pointer;
+ color: var(--ink-dim, #9a9aa8);
+ font: 600 12px/1 var(--font-mono, ui-monospace, monospace);
+ padding: 7px 11px; border-radius: 8px;
+ transition: background 0.14s, color 0.14s;
+}
+.tws-emb-tab:hover, .tws-emb-size:hover { color: var(--ink, #ececf4); }
+.tws-emb-tab[aria-pressed='true'], .tws-emb-size[aria-pressed='true'] {
+ background: var(--surface-3, rgba(255,255,255,0.1)); color: var(--ink, #fff);
+}
+.tws-emb-tab:focus-visible, .tws-emb-size:focus-visible, .tws-emb-copy:focus-visible {
+ outline: 2px solid var(--accent, #6ee7b7); outline-offset: 2px;
+}
+.tws-emb-codelabel {
+ font: 600 11px/1 var(--font-mono, ui-monospace, monospace);
+ text-transform: uppercase; letter-spacing: 0.06em;
+ color: var(--ink-dim, #9a9aa8); margin-top: 2px;
+}
+.tws-emb-code {
+ width: 100%; box-sizing: border-box; resize: vertical;
+ background: var(--surface-1, rgba(0,0,0,0.35));
+ border: 1px solid var(--stroke, rgba(255,255,255,0.1));
+ border-radius: 10px; padding: 11px 12px;
+ color: var(--ink, #e8e8e8);
+ font: 12.5px/1.55 var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);
+ white-space: pre; overflow-x: auto;
+}
+.tws-emb-code:focus-visible { outline: 2px solid var(--accent, #6ee7b7); outline-offset: 1px; }
+.tws-emb-copy {
+ display: inline-flex; align-items: center; justify-content: center; gap: 8px;
+ width: 100%; box-sizing: border-box; cursor: pointer;
+ padding: 12px 16px; border-radius: 10px;
+ border: 1px solid transparent;
+ background: var(--btn-primary-bg, rgba(255,255,255,0.92)); color: var(--btn-primary-fg, #0a0a0f);
+ font: 600 14px/1 var(--font-body, system-ui, sans-serif);
+ transition: background 0.14s, transform 0.1s;
+}
+.tws-emb-copy:hover { background: var(--btn-primary-bg-hover, rgba(255,255,255,0.85)); }
+.tws-emb-copy:active { transform: translateY(1px); }
+.tws-emb-copy.is-copied { background: var(--success, #6ee7b7); }
+.tws-emb-foot {
+ margin: 0; font-size: 12.5px; line-height: 1.5; color: var(--ink-dim, #9a9aa8);
+}
+.tws-emb-foot a { color: var(--accent, #6ee7b7); text-decoration: none; }
+.tws-emb-foot a:hover { text-decoration: underline; }
+`;
diff --git a/src/forge-studio/forge-embed-snippets.js b/src/forge-studio/forge-embed-snippets.js
new file mode 100644
index 000000000..30f1c215a
--- /dev/null
+++ b/src/forge-studio/forge-embed-snippets.js
@@ -0,0 +1,95 @@
+// Forge embed snippets — the single source of truth for the "embed this model"
+// code the platform hands out. Pure, framework-free builders shared by the full
+// Forge embed modal (src/forge-embed-panel.js) and the homepage mini Forge embed
+// sheet (src/home-forge.js), so the two surfaces never drift on snippet shape,
+// size presets, or the /forge/embed URLs.
+//
+// Two flavours, both real:
+// • iframe — points at /forge/embed?src=<glb>, the zero-dependency
+// three.ws viewer page (orbit + AR + branding). Drops onto
+// any site with no scripts on the host page.
+// • web component — a <model-viewer> snippet for builders who want the model
+// inline in their own DOM with their own controls.
+
+const ORIGIN = 'https://three.ws';
+const MODEL_VIEWER_CDN =
+ 'https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js';
+
+export const EMBED_SIZES = [
+ { id: 'wide', label: '16 : 9', w: 640, h: 360, ratio: '16 / 9' },
+ { id: 'square', label: 'Square', w: 480, h: 480, ratio: '1 / 1' },
+ { id: 'portrait', label: '4 : 5', w: 432, h: 540, ratio: '4 / 5' },
+];
+
+export function embedSize(sizeId) {
+ return EMBED_SIZES.find((s) => s.id === sizeId) || EMBED_SIZES[0];
+}
+
+export function escEmbed(s) {
+ return String(s ?? '').replace(
+ /[&<>"']/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
+ );
+}
+
+// Forge's download href is already a public hosted URL; resolve relatives
+// against the prod origin so a copied snippet works off-site.
+export function absoluteGlb(url) {
+ if (!url) return '';
+ try {
+ return new URL(url, ORIGIN).href;
+ } catch {
+ return url;
+ }
+}
+
+function embedQuery(glbUrl, title) {
+ const q = new URLSearchParams({ src: glbUrl });
+ if (title) q.set('title', String(title).slice(0, 120));
+ return q.toString();
+}
+
+// Pretty, absolute URL for the copyable snippet + "open standalone" link —
+// resolves via the /forge/embed rewrite in production.
+export function embedPageUrl(glbUrl, title) {
+ return `${ORIGIN}/forge/embed?${embedQuery(glbUrl, title)}`;
+}
+
+// Same viewer at the built file path on the *current* origin, so an in-panel
+// live preview renders in local dev and previews too (the clean /forge/embed
+// route is a production rewrite).
+export function embedPreviewUrl(glbUrl, title, origin) {
+ const o = origin || (typeof location !== 'undefined' ? location.origin : ORIGIN);
+ return `${o}/forge-embed.html?${embedQuery(glbUrl, title)}`;
+}
+
+export function buildIframeSnippet(glbUrl, title, sizeId) {
+ const s = embedSize(sizeId);
+ const src = embedPageUrl(glbUrl, title);
+ return (
+ `<iframe src="${escEmbed(src)}"\n` +
+ ` width="${s.w}" height="${s.h}"\n` +
+ ` style="border:0;border-radius:14px;max-width:100%"\n` +
+ ` allow="xr-spatial-tracking; fullscreen"\n` +
+ ` loading="lazy" title="${escEmbed(title || '3D model forged on three.ws')}">` +
+ `</iframe>`
+ );
+}
+
+export function buildWebComponentSnippet(glbUrl, title, sizeId) {
+ const s = embedSize(sizeId);
+ const alt = escEmbed(title || '3D model forged on three.ws');
+ return (
+ `<!-- once per page -->\n` +
+ `<script type="module"\n` +
+ ` src="${MODEL_VIEWER_CDN}"></scr` +
+ `ipt>\n\n` +
+ `<model-viewer\n` +
+ ` src="${escEmbed(glbUrl)}"\n` +
+ ` alt="${alt}"\n` +
+ ` camera-controls auto-rotate ar\n` +
+ ` shadow-intensity="1"\n` +
+ ` style="width:${s.w}px;height:${s.h}px;max-width:100%;background:#0b0b0b;border-radius:14px">` +
+ `\n</model-viewer>`
+ );
+}
diff --git a/src/forge-studio/forge-enhance.js b/src/forge-studio/forge-enhance.js
new file mode 100644
index 000000000..8c1dc030d
--- /dev/null
+++ b/src/forge-studio/forge-enhance.js
@@ -0,0 +1,259 @@
+// Forge prompt enhancer — the one AI-powered authoring aid in the text composer.
+//
+// "Surprise me" and the prompt coach (src/forge-prompt-studio.js) are curated,
+// client-side helpers. This is the opposite: it takes whatever the user actually
+// typed and rewrites it with a real model into a sharper, single-subject prompt
+// shaped for the FLUX → TRELLIS pipeline (material, lighting and background cues
+// the reconstructor reads cleanly). It runs on the site's free-first LLM chain
+// via POST /api/forge-enhance, so it costs the visitor nothing and needs no key.
+//
+// Self-contained on purpose: it injects its own button into the existing
+// #prompt-tools toolbar and owns its styles, so it composes with the rest of the
+// composer without the page wiring it explicitly — the same pattern as
+// forge-stylize.js and forge-optimize.js.
+
+const prompt = document.getElementById('prompt');
+const tools = document.getElementById('prompt-tools');
+const anchor = document.getElementById('surprise'); // insert right after "Surprise me"
+
+// No text composer on this render (page markup changed, or module loaded on the
+// wrong page) — degrade to nothing rather than throw.
+if (prompt && tools) {
+ injectStyles();
+
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'ptool ptool--ai';
+ btn.id = 'enhance';
+ btn.setAttribute('aria-label', 'Rewrite your prompt into a sharper, model-ready description');
+ btn.title = 'Rewrite your prompt into a sharper, model-ready description';
+ btn.innerHTML = `
+ <svg class="enhance-spark" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
+ <path d="M12 2.5l1.9 5 5 1.9-5 1.9-1.9 5-1.9-5-5-1.9 5-1.9 1.9-5zM19 14l.85 2.15L22 17l-2.15.85L19 20l-.85-2.15L16 17l2.15-.85L19 14zM5.5 14.5l.7 1.8 1.8.7-1.8.7-.7 1.8-.7-1.8-1.8-.7 1.8-.7.7-1.8z"/>
+ </svg>
+ <span class="enhance-label">Enhance</span>`;
+
+ const undo = document.createElement('button');
+ undo.type = 'button';
+ undo.className = 'ptool ptool--undo is-hidden';
+ undo.id = 'enhance-undo';
+ undo.textContent = 'Undo';
+ undo.title = 'Restore the prompt you wrote';
+
+ const note = document.createElement('p');
+ note.className = 'enhance-note is-hidden';
+ note.id = 'enhance-note';
+ note.setAttribute('role', 'status');
+ note.setAttribute('aria-live', 'polite');
+
+ // Order: Surprise me → Enhance → Undo, then the rest of the toolbar.
+ if (anchor && anchor.parentNode === tools) {
+ anchor.after(btn, undo);
+ } else {
+ tools.prepend(undo);
+ tools.prepend(btn);
+ }
+ tools.after(note);
+
+ let prevPrompt = null; // the user's words before the last enhance, for Undo
+ let busy = false;
+ let selfEdit = false; // true while WE write to the textarea, so the input
+ // listener below doesn't mistake our programmatic write for the user editing
+ let noteTimer = null;
+
+ function showNote(msg, kind = 'tip') {
+ note.textContent = msg;
+ note.dataset.kind = kind;
+ note.classList.remove('is-hidden');
+ clearTimeout(noteTimer);
+ // Keep errors up a touch longer than neutral tips; never permanent.
+ noteTimer = setTimeout(() => note.classList.add('is-hidden'), kind === 'error' ? 5200 : 3600);
+ }
+
+ function hideNote() {
+ clearTimeout(noteTimer);
+ note.classList.add('is-hidden');
+ }
+
+ // Write into the textarea and let the rest of the composer (coach + counter in
+ // forge-prompt-studio.js, the submit guard in forge.js) react as if the user
+ // typed it — one input event keeps every dependent feature in sync.
+ function setPrompt(value, { flash = false } = {}) {
+ selfEdit = true;
+ prompt.value = value;
+ prompt.dispatchEvent(new Event('input', { bubbles: true }));
+ selfEdit = false;
+ prompt.focus();
+ try {
+ prompt.setSelectionRange(value.length, value.length);
+ } catch {
+ /* setSelectionRange throws on some inputs — caret position is cosmetic */
+ }
+ if (flash) {
+ prompt.classList.remove('enhance-flash');
+ void prompt.offsetWidth; // restart the animation
+ prompt.classList.add('enhance-flash');
+ }
+ }
+
+ function setBusy(on) {
+ busy = on;
+ btn.disabled = on;
+ btn.classList.toggle('is-working', on);
+ btn.querySelector('.enhance-label').textContent = on ? 'Enhancing…' : 'Enhance';
+ prompt.classList.toggle('is-enhancing', on);
+ prompt.setAttribute('aria-busy', String(on));
+ }
+
+ async function enhance() {
+ if (busy) return;
+ const raw = prompt.value.trim();
+ if (raw.length < 3) {
+ prompt.focus();
+ showNote('Describe the object in a few words first, then enhance it.', 'tip');
+ return;
+ }
+
+ setBusy(true);
+ hideNote();
+ try {
+ const res = await fetch('/api/forge-enhance', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ prompt: raw }),
+ });
+
+ if (res.status === 429) {
+ const data = await res.json().catch(() => ({}));
+ const secs = Number(data.retry_after);
+ showNote(
+ Number.isFinite(secs) && secs > 0
+ ? `Easy — try enhancing again in ${secs}s.`
+ : 'Slow down a moment, then try again.',
+ 'error',
+ );
+ return;
+ }
+ if (res.status === 503) {
+ showNote('The enhancer is offline right now — your prompt is unchanged.', 'error');
+ return;
+ }
+ if (!res.ok) {
+ showNote("Couldn't enhance that one. Try again, or tweak the wording.", 'error');
+ return;
+ }
+
+ const data = await res.json();
+ const next = typeof data.prompt === 'string' ? data.prompt.trim() : '';
+ if (!next || next.toLowerCase() === raw.toLowerCase()) {
+ showNote('That prompt is already in good shape.', 'tip');
+ return;
+ }
+
+ prevPrompt = raw;
+ setPrompt(next, { flash: true });
+ undo.classList.remove('is-hidden');
+ showNote('Rewritten for sharper geometry. Edit freely, or Undo.', 'strong');
+ } catch {
+ showNote('Network hiccup — your prompt is unchanged. Try again.', 'error');
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ btn.addEventListener('click', enhance);
+
+ undo.addEventListener('click', () => {
+ if (prevPrompt == null) return;
+ setPrompt(prevPrompt);
+ prevPrompt = null;
+ undo.classList.add('is-hidden');
+ hideNote();
+ });
+
+ // Once the user edits the prompt by hand, the previous-words snapshot is stale
+ // — retire Undo so it can never restore something they didn't mean.
+ prompt.addEventListener('input', () => {
+ if (selfEdit) return;
+ if (prevPrompt != null) {
+ prevPrompt = null;
+ undo.classList.add('is-hidden');
+ }
+ });
+
+ // ⌘/Ctrl+E enhances without leaving the keyboard — pairs with the existing
+ // ⌘/Ctrl+Enter to generate.
+ prompt.addEventListener('keydown', (e) => {
+ if ((e.metaKey || e.ctrlKey) && (e.key === 'e' || e.key === 'E')) {
+ e.preventDefault();
+ enhance();
+ }
+ });
+}
+
+function injectStyles() {
+ if (document.getElementById('forge-enhance-styles')) return;
+ const style = document.createElement('style');
+ style.id = 'forge-enhance-styles';
+ style.textContent = `
+ .ptool--ai {
+ color: var(--accent);
+ border-color: color-mix(in srgb, var(--accent) 45%, var(--stroke));
+ background: color-mix(in srgb, var(--accent) 8%, transparent);
+ }
+ .ptool--ai:hover {
+ color: var(--accent);
+ border-color: var(--accent);
+ background: var(--accent-soft);
+ }
+ .ptool--ai .enhance-spark { width: 14px; height: 14px; }
+ .ptool--ai.is-working { cursor: progress; }
+ .ptool--ai.is-working .enhance-spark { animation: enhance-spin 0.9s linear infinite; transform-origin: 50% 50%; }
+ .ptool--undo { color: var(--ink-dim); }
+ .enhance-note {
+ margin: var(--space-xs) 0 0;
+ font-size: var(--text-xs);
+ line-height: 1.45;
+ color: var(--ink-dim);
+ display: flex;
+ align-items: center;
+ gap: 0.45rem;
+ }
+ .enhance-note::before {
+ content: '';
+ width: 6px; height: 6px; border-radius: 50%;
+ background: var(--accent); flex: none;
+ }
+ .enhance-note[data-kind='strong'] { color: var(--success); }
+ .enhance-note[data-kind='strong']::before { background: var(--success); box-shadow: 0 0 8px var(--success); }
+ .enhance-note[data-kind='error'] { color: var(--danger); }
+ .enhance-note[data-kind='error']::before { background: var(--danger); }
+ .enhance-note.is-hidden { display: none; }
+ #prompt.is-enhancing {
+ background-image: linear-gradient(
+ 100deg,
+ transparent 30%,
+ color-mix(in srgb, var(--accent) 14%, transparent) 50%,
+ transparent 70%
+ );
+ background-size: 220% 100%;
+ background-repeat: no-repeat;
+ animation: enhance-sheen 1.15s linear infinite;
+ border-radius: var(--radius-sm);
+ }
+ #prompt.enhance-flash { animation: enhance-flash 0.7s ease; }
+ @keyframes enhance-spin { to { transform: rotate(360deg); } }
+ @keyframes enhance-sheen { to { background-position: -220% 0; } }
+ @keyframes enhance-flash {
+ 0% { box-shadow: 0 0 0 0 var(--accent-soft); }
+ 40% { box-shadow: 0 0 0 4px var(--accent-soft); }
+ 100% { box-shadow: 0 0 0 0 transparent; }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .ptool--ai.is-working .enhance-spark,
+ #prompt.is-enhancing,
+ #prompt.enhance-flash { animation: none; }
+ }
+ `;
+ document.head.appendChild(style);
+}
diff --git a/src/forge-studio/forge-export.js b/src/forge-studio/forge-export.js
new file mode 100644
index 000000000..b6330fbb8
--- /dev/null
+++ b/src/forge-studio/forge-export.js
@@ -0,0 +1,307 @@
+// Multi-format export layered onto the forge result viewer.
+//
+// The download button always offers the source GLB instantly. This module adds
+// a format menu beside it that converts the live model in the browser with
+// three.js exporters — no worker, no queue, no upload:
+// • OBJ — universal geometry for DCC tools (geometry + UVs, no materials)
+// • STL — solid geometry for 3D printing (binary)
+// • PLY — vertex data for scanning/point-cloud tools (binary)
+// • USDZ — textured AR asset for iPhone / Vision Pro
+//
+// three.js and the exporters load lazily on first use; the parsed scene is
+// cached per model URL so switching formats doesn't re-download the GLB.
+// Like the stylize/optimize panels, this module injects its own markup and
+// styles and only needs the result panel's download anchor to exist.
+
+import { createLogger } from '../shared/log.js';
+
+const log = createLogger('forge-export');
+
+const download = document.getElementById('download');
+const resultPanel = document.getElementById('state-result');
+
+if (download && resultPanel) {
+ const FORMATS = [
+ {
+ id: 'glb',
+ label: 'GLB',
+ blurb: 'Source format — textures embedded. Works everywhere glTF does.',
+ ext: 'glb',
+ },
+ {
+ id: 'obj',
+ label: 'OBJ',
+ blurb: 'Universal geometry + UVs for Blender, Maya, C4D. Materials not included.',
+ ext: 'obj',
+ mime: 'text/plain',
+ },
+ {
+ id: 'stl',
+ label: 'STL',
+ blurb: 'Solid geometry for 3D printing and CAD. Binary, compact.',
+ ext: 'stl',
+ mime: 'model/stl',
+ },
+ {
+ id: 'ply',
+ label: 'PLY',
+ blurb: 'Vertex-level data for scanning and point-cloud tools. Binary.',
+ ext: 'ply',
+ mime: 'application/octet-stream',
+ },
+ {
+ id: 'usdz',
+ label: 'USDZ',
+ blurb: 'Textured AR asset — opens directly on iPhone and Vision Pro.',
+ ext: 'usdz',
+ mime: 'model/vnd.usdz+zip',
+ },
+ ];
+
+ // ---- markup ------------------------------------------------------------
+
+ const style = document.createElement('style');
+ style.textContent = `
+ .export-split { position: relative; display: inline-flex; align-items: stretch; }
+ .export-caret {
+ display: inline-flex; align-items: center; justify-content: center;
+ margin-left: 1px; padding: 0 0.55rem;
+ border: 1px solid var(--border, rgba(255,255,255,0.14));
+ border-radius: 0 8px 8px 0; background: var(--surface-2, rgba(255,255,255,0.05));
+ color: inherit; cursor: pointer;
+ transition: background 0.15s ease, border-color 0.15s ease;
+ }
+ .export-caret:hover, .export-caret:focus-visible { background: var(--surface-3, rgba(255,255,255,0.1)); }
+ .export-caret:focus-visible { outline: 2px solid var(--accent, #7c6cff); outline-offset: 2px; }
+ .export-caret svg { width: 12px; height: 12px; transition: transform 0.18s ease; }
+ .export-caret[aria-expanded="true"] svg { transform: rotate(180deg); }
+ .export-split > a { border-top-right-radius: 0 !important; border-bottom-right-radius: 0 !important; }
+ .export-menu {
+ position: absolute; right: 0; bottom: calc(100% + 8px); z-index: 40;
+ min-width: 290px; padding: 0.35rem;
+ border: 1px solid var(--border, rgba(255,255,255,0.14));
+ border-radius: 12px;
+ background: var(--surface-1, #16161d);
+ box-shadow: 0 16px 40px rgba(0,0,0,0.45);
+ opacity: 0; transform: translateY(6px); pointer-events: none;
+ transition: opacity 0.16s ease, transform 0.16s ease;
+ }
+ .export-menu.is-open { opacity: 1; transform: translateY(0); pointer-events: auto; }
+ .export-item {
+ display: flex; align-items: baseline; gap: 0.65rem; width: 100%;
+ padding: 0.55rem 0.7rem; border: 0; border-radius: 8px;
+ background: transparent; color: inherit; text-align: left; cursor: pointer;
+ transition: background 0.12s ease;
+ }
+ .export-item:hover, .export-item:focus-visible { background: var(--surface-3, rgba(255,255,255,0.08)); }
+ .export-item:focus-visible { outline: 2px solid var(--accent, #7c6cff); outline-offset: -2px; }
+ .export-item[aria-disabled="true"] { opacity: 0.55; cursor: progress; }
+ .export-item .fmt { font-weight: 600; font-size: 0.86rem; min-width: 3.2em; letter-spacing: 0.02em; }
+ .export-item .blurb { flex: 1; font-size: 0.78rem; opacity: 0.72; line-height: 1.35; }
+ .export-item .status { font-size: 0.74rem; min-width: 5.5em; text-align: right; opacity: 0.85; }
+ .export-item .status.is-error { color: var(--danger, #ff6b6b); }
+ .export-spinner {
+ display: inline-block; width: 0.85em; height: 0.85em; vertical-align: -0.1em;
+ border: 2px solid currentColor; border-right-color: transparent;
+ border-radius: 50%; animation: export-spin 0.7s linear infinite;
+ }
+ @keyframes export-spin { to { transform: rotate(360deg); } }
+ @media (prefers-reduced-motion: reduce) {
+ .export-menu { transition: none; }
+ .export-caret svg { transition: none; }
+ .export-spinner { animation-duration: 1.5s; }
+ }
+ `;
+ document.head.appendChild(style);
+
+ const split = document.createElement('div');
+ split.className = 'export-split';
+ download.parentNode.insertBefore(split, download);
+ split.appendChild(download);
+
+ const caret = document.createElement('button');
+ caret.type = 'button';
+ caret.className = 'export-caret';
+ caret.setAttribute('aria-haspopup', 'menu');
+ caret.setAttribute('aria-expanded', 'false');
+ caret.setAttribute('aria-label', 'More download formats');
+ caret.title = 'More formats: OBJ, STL, PLY, USDZ';
+ caret.innerHTML =
+ '<svg viewBox="0 0 12 12" fill="none" aria-hidden="true"><path d="M2 4.5 6 8.5 10 4.5" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>';
+ split.appendChild(caret);
+
+ const menu = document.createElement('div');
+ menu.className = 'export-menu';
+ menu.setAttribute('role', 'menu');
+ menu.setAttribute('aria-label', 'Download format');
+ split.appendChild(menu);
+
+ const itemStatus = new Map();
+ for (const f of FORMATS) {
+ const item = document.createElement('button');
+ item.type = 'button';
+ item.className = 'export-item';
+ item.setAttribute('role', 'menuitem');
+ item.dataset.format = f.id;
+ item.innerHTML = `
+ <span class="fmt">.${f.ext}</span>
+ <span class="blurb">${f.blurb}</span>
+ <span class="status" aria-live="polite"></span>
+ `;
+ item.addEventListener('click', () => onPick(f, item));
+ menu.appendChild(item);
+ itemStatus.set(f.id, item.querySelector('.status'));
+ }
+
+ // ---- menu behavior -------------------------------------------------------
+
+ function setOpen(open) {
+ menu.classList.toggle('is-open', open);
+ caret.setAttribute('aria-expanded', String(open));
+ if (open) menu.querySelector('.export-item')?.focus();
+ }
+ const isOpen = () => menu.classList.contains('is-open');
+
+ caret.addEventListener('click', () => setOpen(!isOpen()));
+ document.addEventListener('click', (e) => {
+ if (isOpen() && !split.contains(e.target)) setOpen(false);
+ });
+ split.addEventListener('keydown', (e) => {
+ if (!isOpen()) return;
+ const items = [...menu.querySelectorAll('.export-item')];
+ const idx = items.indexOf(document.activeElement);
+ if (e.key === 'Escape') {
+ setOpen(false);
+ caret.focus();
+ } else if (e.key === 'ArrowDown') {
+ e.preventDefault();
+ items[(idx + 1) % items.length]?.focus();
+ } else if (e.key === 'ArrowUp') {
+ e.preventDefault();
+ items[(idx - 1 + items.length) % items.length]?.focus();
+ }
+ });
+
+ // ---- conversion ----------------------------------------------------------
+
+ let three = null; // { THREE, GLTFLoader, exporters... } cached after first load
+ async function loadThree() {
+ if (three) return three;
+ const [THREE, gltf, draco, obj, stl, ply, usdz] = await Promise.all([
+ import('three'),
+ import('three/addons/loaders/GLTFLoader.js'),
+ import('three/addons/loaders/DRACOLoader.js'),
+ import('three/addons/exporters/OBJExporter.js'),
+ import('three/addons/exporters/STLExporter.js'),
+ import('three/addons/exporters/PLYExporter.js'),
+ import('three/addons/exporters/USDZExporter.js'),
+ ]);
+ three = {
+ THREE,
+ GLTFLoader: gltf.GLTFLoader,
+ DRACOLoader: draco.DRACOLoader,
+ OBJExporter: obj.OBJExporter,
+ STLExporter: stl.STLExporter,
+ PLYExporter: ply.PLYExporter,
+ USDZExporter: usdz.USDZExporter,
+ };
+ return three;
+ }
+
+ // Parsed-scene cache: one fetch+parse per model URL no matter how many
+ // formats the user exports.
+ let sceneCache = { url: null, scene: null };
+ async function loadScene(url) {
+ if (sceneCache.url === url && sceneCache.scene) return sceneCache.scene;
+ const t = await loadThree();
+ const loader = new t.GLTFLoader();
+ const dracoLoader = new t.DRACOLoader();
+ dracoLoader.setDecoderPath('/three/draco/gltf/');
+ loader.setDRACOLoader(dracoLoader);
+ const gltf = await loader.loadAsync(url);
+ sceneCache = { url, scene: gltf.scene };
+ return gltf.scene;
+ }
+
+ function baseName() {
+ const attr = download.getAttribute('download') || 'forge.glb';
+ return attr.replace(/\.glb$/i, '') || 'forge';
+ }
+
+ function saveBlob(data, mime, filename) {
+ const blob = data instanceof Blob ? data : new Blob([data], { type: mime });
+ const a = document.createElement('a');
+ a.href = URL.createObjectURL(blob);
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ setTimeout(() => URL.revokeObjectURL(a.href), 30_000);
+ }
+
+ async function convert(format, scene) {
+ const t = await loadThree();
+ switch (format.id) {
+ case 'obj':
+ return new t.OBJExporter().parse(scene);
+ case 'stl':
+ return new t.STLExporter().parse(scene, { binary: true });
+ case 'ply':
+ return await new Promise((resolve, reject) => {
+ try {
+ new t.PLYExporter().parse(scene, resolve, { binary: true });
+ } catch (err) {
+ reject(err);
+ }
+ });
+ case 'usdz':
+ return await new t.USDZExporter().parseAsync(scene);
+ default:
+ throw new Error(`unknown export format: ${format.id}`);
+ }
+ }
+
+ const busy = new Set();
+ async function onPick(format, item) {
+ if (format.id === 'glb') {
+ // The source GLB needs no conversion — hand off to the primary anchor.
+ setOpen(false);
+ download.click();
+ return;
+ }
+ if (busy.has(format.id)) return;
+ const url = download.getAttribute('href');
+ if (!url) return;
+ const status = itemStatus.get(format.id);
+ busy.add(format.id);
+ item.setAttribute('aria-disabled', 'true');
+ status.classList.remove('is-error');
+ status.innerHTML = '<span class="export-spinner" aria-hidden="true"></span> converting';
+ try {
+ const scene = await loadScene(url);
+ const data = await convert(format, scene);
+ saveBlob(data, format.mime, `${baseName()}.${format.ext}`);
+ status.textContent = 'saved ✓';
+ setTimeout(() => {
+ if (status.textContent === 'saved ✓') status.textContent = '';
+ }, 4000);
+ } catch (err) {
+ log.error(format.id, err);
+ status.textContent = 'failed — retry';
+ status.classList.add('is-error');
+ } finally {
+ busy.delete(format.id);
+ item.removeAttribute('aria-disabled');
+ }
+ }
+
+ // A new generation invalidates the parsed-scene cache (the href changes, but
+ // clearing eagerly also frees the old scene graph for GC).
+ document.addEventListener('forge:model-ready', () => {
+ sceneCache = { url: null, scene: null };
+ for (const status of itemStatus.values()) {
+ status.textContent = '';
+ status.classList.remove('is-error');
+ }
+ });
+}
diff --git a/src/forge-studio/forge-gameready.js b/src/forge-studio/forge-gameready.js
new file mode 100644
index 000000000..705176c1d
--- /dev/null
+++ b/src/forge-studio/forge-gameready.js
@@ -0,0 +1,722 @@
+// Game-Ready export — the one-click engine-ready output for the forge result
+// view. Layered onto the live model (forge.js dispatches `forge:model-ready`),
+// it drives the real /api/forge-gameready route to retopologize the current mesh
+// to a poly budget and deliver a textured GLB + an FBX for Unity/Unreal in one
+// job.
+//
+// • Quad — field-aligned QuadriFlow retopology: clean edge loops that deform
+// well for rigging & animation.
+// • Tri — silhouette-preserving low-poly with the source texture re-unwrapped
+// and re-baked onto the new mesh.
+//
+// The panel proves its value the way game devs screenshot it: the before→after
+// poly delta and a live wireframe of the retopologized mesh. Nothing fakes
+// progress — it polls the job; the wireframe is the real returned GLB.
+//
+// Charging: the export runs the remesh GPU worker (real cost), so it's a $THREE
+// holder perk with a one-time pay-per-export path — the same hold-or-pay model as
+// High-tier generation. A verified holder exports free; a non-holder is offered the
+// designed $THREE pay modal and the export retries with the settled proof. The
+// price is whatever the server gate quotes — never hardcoded here.
+
+import { payForConsumption } from './forge-pay.js';
+import { threeHeaders } from '../three-tier-pass.js';
+
+const resultPanel = document.getElementById('state-result');
+const viewer = document.getElementById('viewer');
+const viewerShell = document.getElementById('viewer-shell');
+const triggerBtn = document.getElementById('forge-gameready-btn');
+
+if (resultPanel && viewer && triggerBtn) {
+ const POLL_MS = 2500;
+ const MAX_MS = 8 * 60 * 1000; // quad/lowpoly bakes can take a couple of minutes
+
+ // Reuse the forge anonymous client id (set by forge.js) for rate-limit
+ // fairness; harmless if absent.
+ const CLIENT_HEADERS = (() => {
+ try {
+ const id = localStorage.getItem('forge:cid');
+ return id ? { 'x-forge-client': id } : {};
+ } catch {
+ return {};
+ }
+ })();
+
+ const PRESETS = [
+ [5_000, '5k', 'mobile'],
+ [15_000, '15k', 'standard'],
+ [50_000, '50k', 'hero'],
+ ];
+ const SLIDER_MIN = 1_000;
+ const SLIDER_MAX = 200_000;
+
+ const TOPO_HINTS = {
+ quad: 'Field-aligned QuadriFlow retopology — clean quad-dominant edge loops that deform well for rigging & animation.',
+ tri: 'Silhouette-preserving low-poly. UVs are re-unwrapped and the original texture re-baked onto the new mesh for real-time engines.',
+ };
+
+ // ── Styles ─────────────────────────────────────────────────────────────────
+ if (!document.getElementById('forge-gameready-styles')) {
+ const style = document.createElement('style');
+ style.id = 'forge-gameready-styles';
+ style.textContent = `
+ .gameready { border-top: 1px solid var(--stroke); display: none; flex-direction: column; gap: var(--space-md); padding: var(--space-md); }
+ .gameready[data-open='true'] { display: flex; }
+ .gr-head { display: flex; align-items: baseline; justify-content: space-between; gap: var(--space-sm); }
+ .gr-head h3 { font-family: var(--font-display); font-size: var(--text-md); font-weight: 700; margin: 0; }
+ .gr-sub { font-size: var(--text-xs); color: var(--ink-dim); line-height: 1.5; margin: 0; max-width: 60ch; }
+ .gr-field { display: flex; flex-direction: column; gap: 0.45rem; }
+ .gr-field > span.gr-label { font-size: var(--text-xs); color: var(--ink-dim); font-family: var(--font-mono); text-transform: uppercase; letter-spacing: 0.04em; }
+ .gr-seg { display: inline-flex; gap: 2px; background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-md); padding: 2px; }
+ .gr-seg button { flex: 1 1 auto; background: transparent; border: none; color: var(--ink-dim); font-family: var(--font-mono); font-size: var(--text-xs); padding: 0.45rem 0.9rem; border-radius: var(--radius-sm); cursor: pointer; transition: background 0.15s, color 0.15s; }
+ .gr-seg button:hover { color: var(--ink); }
+ .gr-seg button[aria-pressed='true'] { background: var(--surface-3); color: var(--ink); }
+ .gr-seg button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+ .gr-topo-hint { font-size: var(--text-xs); color: var(--ink-dim); line-height: 1.4; min-height: 1.4em; margin: 0; }
+ .gr-budget-row { display: flex; align-items: center; gap: var(--space-md); flex-wrap: wrap; }
+ .gr-budget-row input[type='range'] { flex: 1 1 200px; accent-color: var(--accent); cursor: pointer; min-width: 160px; }
+ .gr-budget-row input[type='range']:focus-visible { outline: 2px solid var(--accent); outline-offset: 4px; }
+ .gr-budget-val { font-family: var(--font-mono); font-size: var(--text-sm); color: var(--ink); font-weight: 600; min-width: 7ch; text-align: right; }
+ .gr-presets { display: inline-flex; gap: 2px; background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-md); padding: 2px; }
+ .gr-presets button { background: transparent; border: none; color: var(--ink-dim); font-family: var(--font-mono); font-size: var(--text-xs); padding: 0.35rem 0.6rem; border-radius: var(--radius-sm); cursor: pointer; transition: background 0.15s, color 0.15s; }
+ .gr-presets button:hover { color: var(--ink); }
+ .gr-presets button[aria-pressed='true'] { background: var(--surface-3); color: var(--ink); }
+ .gr-presets button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+ .gr-row { display: flex; gap: var(--space-md); flex-wrap: wrap; }
+ .gr-row .gr-field { flex: 1 1 150px; }
+ .gr-select { background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-md); color: var(--ink); font-family: var(--font-mono); font-size: var(--text-xs); padding: 0.45rem 0.6rem; }
+ .gr-select:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
+ .gr-formats { display: flex; gap: var(--space-md); flex-wrap: wrap; }
+ .gr-check { display: inline-flex; align-items: center; gap: 0.45rem; font-family: var(--font-mono); font-size: var(--text-xs); color: var(--ink); cursor: pointer; }
+ .gr-check input { accent-color: var(--accent); width: 1rem; height: 1rem; cursor: pointer; }
+ .gr-check input:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+ .gr-rig { font-size: var(--text-xs); color: var(--ink-dim); line-height: 1.4; margin: 0; padding-left: 1.45rem; }
+ .gr-rig.is-hidden { display: none; }
+ .gr-actions { display: flex; align-items: center; gap: var(--space-md); flex-wrap: wrap; }
+ .gr-status { font-size: var(--text-xs); font-family: var(--font-mono); color: var(--ink-dim); }
+ .gr-status[data-kind='error'] { color: var(--danger); }
+ .gr-status[data-kind='done'] { color: var(--success); }
+ .gr-pay-note { font-size: var(--text-xs); color: var(--ink-dim); line-height: 1.4; margin: 0; }
+ .gr-pay-note a { color: var(--accent); text-decoration: none; }
+ .gr-pay-note a:hover { text-decoration: underline; }
+ .gr-pay-note a:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 3px; }
+ .gr-skeleton { display: none; height: 4px; border-radius: 2px; overflow: hidden; background: var(--surface-1); position: relative; }
+ .gameready[data-busy='true'] .gr-skeleton { display: block; }
+ .gr-skeleton::after { content: ''; position: absolute; inset: 0; width: 40%; border-radius: 2px; background: linear-gradient(90deg, transparent, var(--accent), transparent); animation: gr-sweep 1.1s ease-in-out infinite; }
+ @keyframes gr-sweep { 0% { transform: translateX(-120%); } 100% { transform: translateX(320%); } }
+ .gr-delta { display: none; flex-wrap: wrap; align-items: center; gap: 0.5rem; font-family: var(--font-mono); font-size: var(--text-sm); }
+ .gr-delta.is-shown { display: flex; }
+ .gr-delta .gr-from { color: var(--ink-dim); }
+ .gr-delta .gr-arrow { color: var(--ink-dim); }
+ .gr-delta .gr-to { color: var(--ink); font-weight: 700; }
+ .gr-delta .gr-tag { font-size: var(--text-xs); color: var(--ink-dim); border: 1px solid var(--stroke); border-radius: var(--radius-sm); padding: 0.1rem 0.45rem; }
+ .gr-downloads { display: none; gap: var(--space-sm); flex-wrap: wrap; }
+ .gr-downloads.is-shown { display: flex; }
+ .gr-wire-toggle { margin-left: auto; }
+ .gr-wire-toggle[aria-pressed='true'] { background: var(--surface-3); color: var(--ink); }
+ .gr-wire-overlay { position: absolute; inset: 0; z-index: 4; display: none; background: var(--surface-0, #0b0b10); }
+ .gr-wire-overlay.is-shown { display: block; }
+ .gr-wire-overlay canvas { width: 100% !important; height: 100% !important; display: block; }
+ .gr-wire-badge { position: absolute; top: 10px; left: 10px; font-family: var(--font-mono); font-size: var(--text-xs); color: var(--ink-dim); background: color-mix(in srgb, var(--surface-1) 80%, transparent); border: 1px solid var(--stroke); border-radius: var(--radius-sm); padding: 0.2rem 0.5rem; pointer-events: none; }
+ `;
+ document.head.appendChild(style);
+ }
+
+ // ── DOM ──────────────────────────────────────────────────────────────────
+ const panel = document.createElement('section');
+ panel.className = 'gameready';
+ panel.dataset.open = 'false';
+ panel.dataset.busy = 'false';
+ panel.setAttribute('aria-label', 'Game-Ready export');
+ panel.innerHTML = `
+ <div class="gr-head">
+ <h3>Game-Ready export</h3>
+ </div>
+ <p class="gr-sub">Retopologize this model to a poly budget and export an engine-ready asset — a textured GLB plus an FBX for Unity &amp; Unreal — in one click.</p>
+ <div class="gr-field">
+ <span class="gr-label">Topology</span>
+ <div class="gr-seg gr-topo" role="group" aria-label="Topology">
+ <button type="button" data-topo="quad" aria-pressed="true">Quad retopo</button>
+ <button type="button" data-topo="tri" aria-pressed="false">Tri low-poly</button>
+ </div>
+ <p class="gr-topo-hint"></p>
+ </div>
+ <div class="gr-field">
+ <span class="gr-label">Poly budget — <span class="gr-budget-unit">target faces</span></span>
+ <div class="gr-budget-row">
+ <input class="gr-budget" type="range" min="${SLIDER_MIN}" max="${SLIDER_MAX}" step="1000" value="15000"
+ aria-label="Poly budget (target faces)" />
+ <span class="gr-budget-val" aria-live="polite">15k</span>
+ <div class="gr-presets" role="group" aria-label="Poly budget presets">
+ ${PRESETS.map(
+ ([v, short, tag]) =>
+ `<button type="button" data-budget="${v}" aria-pressed="false" title="${tag}">${short}</button>`,
+ ).join('')}
+ </div>
+ </div>
+ </div>
+ <div class="gr-row">
+ <label class="gr-field">
+ <span class="gr-label">Texture</span>
+ <select class="gr-select gr-texsize">
+ <option value="1024" selected>1024px</option>
+ <option value="2048">2048px</option>
+ </select>
+ </label>
+ <div class="gr-field">
+ <span class="gr-label">Formats</span>
+ <div class="gr-formats">
+ <label class="gr-check"><input type="checkbox" class="gr-fmt" value="glb" checked /> GLB (preview)</label>
+ <label class="gr-check"><input type="checkbox" class="gr-fmt" value="fbx" checked /> FBX</label>
+ </div>
+ </div>
+ </div>
+ <label class="gr-check gr-rig-toggle"><input type="checkbox" class="gr-rig-check" /> Preserve rig on FBX</label>
+ <p class="gr-rig is-hidden">Retopology rebuilds geometry, so a retopologized FBX is a clean re-riggable mesh. Tick this only if your source is skinned and you need the existing skeleton kept — the FBX is then exported at the original topology.</p>
+ <div class="gr-actions">
+ <button class="btn gr-run" type="button"><span class="gr-run-label">Export game-ready</span></button>
+ <button class="btn btn-ghost gr-wire-toggle" type="button" aria-pressed="false" hidden title="Show the retopologized wireframe">Wireframe</button>
+ <span class="gr-status" role="status" aria-live="polite"></span>
+ </div>
+ <p class="gr-pay-note">$THREE holders export free — others pay once per export in $THREE. <a href="/three-token">Hold $THREE →</a></p>
+ <div class="gr-skeleton" aria-hidden="true"></div>
+ <div class="gr-delta" aria-live="polite"></div>
+ <div class="gr-downloads"></div>
+ `;
+ resultPanel.appendChild(panel);
+
+ // Wireframe overlay lives inside the viewer shell, above the model-viewer.
+ const wireOverlay = document.createElement('div');
+ wireOverlay.className = 'gr-wire-overlay';
+ wireOverlay.innerHTML = `<span class="gr-wire-badge">Retopology wireframe</span>`;
+ (viewerShell || viewer.parentElement)?.appendChild(wireOverlay);
+
+ const topoGroup = panel.querySelector('.gr-topo');
+ const topoHint = panel.querySelector('.gr-topo-hint');
+ const budgetSlider = panel.querySelector('.gr-budget');
+ const budgetVal = panel.querySelector('.gr-budget-val');
+ const presetGroup = panel.querySelector('.gr-presets');
+ const texsizeSel = panel.querySelector('.gr-texsize');
+ const fmtChecks = [...panel.querySelectorAll('.gr-fmt')];
+ const rigToggle = panel.querySelector('.gr-rig-toggle');
+ const rigCheck = panel.querySelector('.gr-rig-check');
+ const rigHint = panel.querySelector('.gr-rig');
+ const runBtn = panel.querySelector('.gr-run');
+ const runLabel = panel.querySelector('.gr-run-label');
+ const wireBtn = panel.querySelector('.gr-wire-toggle');
+ const statusEl = panel.querySelector('.gr-status');
+ const deltaEl = panel.querySelector('.gr-delta');
+ const downloadsEl = panel.querySelector('.gr-downloads');
+
+ const state = {
+ glbUrl: null,
+ label: 'model',
+ topology: 'quad',
+ sourceFaces: null,
+ running: false,
+ pollAbort: false,
+ previewUrl: null, // retopologized GLB used by the wireframe preview
+ };
+
+ // ── Helpers ────────────────────────────────────────────────────────────────
+ function fmtCount(n) {
+ if (!Number.isFinite(n)) return '—';
+ if (n >= 10_000) return `${(n / 1000).toFixed(n >= 100_000 ? 0 : 1).replace(/\.0$/, '')}k`;
+ return n.toLocaleString();
+ }
+
+ function setStatus(text, kind) {
+ statusEl.textContent = text || '';
+ if (kind) statusEl.dataset.kind = kind;
+ else statusEl.removeAttribute('data-kind');
+ }
+
+ function setRunning(running) {
+ state.running = running;
+ runBtn.disabled = running;
+ panel.dataset.busy = String(running);
+ runLabel.textContent = running ? 'Exporting…' : 'Export game-ready';
+ }
+
+ function selectedFormats() {
+ return fmtChecks.filter((c) => c.checked).map((c) => c.value);
+ }
+
+ function syncRigVisibility() {
+ const fbx = fmtChecks.find((c) => c.value === 'fbx')?.checked;
+ rigToggle.style.display = fbx ? 'inline-flex' : 'none';
+ rigHint.classList.toggle('is-hidden', !(fbx && rigCheck.checked));
+ }
+
+ function snapPresets(value) {
+ for (const b of presetGroup.querySelectorAll('button')) {
+ b.setAttribute('aria-pressed', String(Number(b.dataset.budget) === value));
+ }
+ }
+
+ function setBudget(value, { snap = true } = {}) {
+ const v = Math.max(SLIDER_MIN, Math.min(SLIDER_MAX, Math.round(value / 1000) * 1000));
+ budgetSlider.value = String(v);
+ budgetVal.textContent = fmtCount(v);
+ if (snap) snapPresets(v);
+ }
+
+ // Default the budget to a fraction of the model's current size — a real
+ // reduction target, not a fixed number — snapped to the nearest preset.
+ function defaultBudgetFor(sourceFaces) {
+ if (!Number.isFinite(sourceFaces) || sourceFaces <= 0) return 15_000;
+ const target = Math.round(sourceFaces * 0.3);
+ let nearest = PRESETS[0][0];
+ let best = Infinity;
+ for (const [v] of PRESETS) {
+ const d = Math.abs(v - target);
+ if (d < best) {
+ best = d;
+ nearest = v;
+ }
+ }
+ // Never propose a budget above the source — that would add, not reduce.
+ return Math.min(nearest, Math.max(SLIDER_MIN, Math.round(sourceFaces)));
+ }
+
+ function applyTopology(topo) {
+ state.topology = topo;
+ for (const b of topoGroup.querySelectorAll('button')) {
+ b.setAttribute('aria-pressed', String(b.dataset.topo === topo));
+ }
+ topoHint.textContent = TOPO_HINTS[topo];
+ panel.querySelector('.gr-budget-unit').textContent = topo === 'quad' ? 'target quads' : 'target faces';
+ }
+
+ // Count triangles in a GLB without a full 3D parse: read the JSON chunk and
+ // sum each mesh primitive's index (or position) accessor count. Accurate for
+ // the TRIANGLES-mode meshes forge produces; returns null if it can't tell.
+ function countGlbTriangles(buffer) {
+ try {
+ const dv = new DataView(buffer);
+ if (dv.getUint32(0, true) !== 0x46546c67) return null; // 'glTF'
+ let offset = 12;
+ let json = null;
+ while (offset < dv.byteLength) {
+ const chunkLen = dv.getUint32(offset, true);
+ const chunkType = dv.getUint32(offset + 4, true);
+ if (chunkType === 0x4e4f534a) {
+ // 'JSON'
+ json = JSON.parse(new TextDecoder().decode(new Uint8Array(buffer, offset + 8, chunkLen)));
+ break;
+ }
+ offset += 8 + chunkLen;
+ }
+ if (!json?.meshes || !json?.accessors) return null;
+ let tris = 0;
+ for (const mesh of json.meshes) {
+ for (const prim of mesh.primitives || []) {
+ if (prim.mode !== undefined && prim.mode !== 4) continue; // not TRIANGLES
+ const accIdx = prim.indices !== undefined ? prim.indices : prim.attributes?.POSITION;
+ const count = json.accessors[accIdx]?.count;
+ if (Number.isFinite(count)) tris += Math.floor(count / 3);
+ }
+ }
+ return tris > 0 ? tris : null;
+ } catch {
+ return null;
+ }
+ }
+
+ async function loadSourceFaceCount(url) {
+ state.sourceFaces = null;
+ try {
+ const res = await fetch(url);
+ if (!res.ok) return;
+ const buf = await res.arrayBuffer();
+ const tris = countGlbTriangles(buf);
+ if (tris && state.glbUrl === url) {
+ state.sourceFaces = tris;
+ setBudget(defaultBudgetFor(tris));
+ }
+ } catch {
+ // Network/CORS hiccup — leave the sensible default budget in place.
+ }
+ }
+
+ function safeLabel() {
+ return state.label.replace(/[^a-z0-9]+/gi, '-').slice(0, 48).replace(/^-|-$/g, '') || 'forge';
+ }
+
+ function renderDownloads(outputs) {
+ downloadsEl.innerHTML = '';
+ const order = ['glb', 'fbx'];
+ const budget = Number(budgetSlider.value);
+ for (const fmt of order) {
+ const out = outputs[fmt];
+ if (!out?.url) continue;
+ const a = document.createElement('a');
+ a.className = 'btn';
+ a.href = out.url;
+ a.setAttribute('download', `${safeLabel()}-${state.topology}-${fmtCount(budget)}.${fmt}`);
+ a.textContent = `Download ${fmt.toUpperCase()}`;
+ a.rel = 'noopener';
+ downloadsEl.appendChild(a);
+ }
+ downloadsEl.classList.toggle('is-shown', downloadsEl.childElementCount > 0);
+ }
+
+ function renderDelta(data) {
+ const after = data.face_count;
+ const unit = state.topology === 'quad' ? (data.quad_ratio > 0 ? 'quads' : 'faces') : 'tris';
+ const parts = [];
+ if (Number.isFinite(state.sourceFaces)) {
+ parts.push(`<span class="gr-from">${state.sourceFaces.toLocaleString()} tris</span><span class="gr-arrow">→</span>`);
+ }
+ parts.push(`<span class="gr-to">${Number.isFinite(after) ? after.toLocaleString() : '—'} ${unit}</span>`);
+ if (Number.isFinite(state.sourceFaces) && Number.isFinite(after) && after > 0 && after < state.sourceFaces) {
+ const pct = Math.round((1 - after / state.sourceFaces) * 100);
+ parts.push(`<span class="gr-tag">−${pct}%</span>`);
+ }
+ if (Number.isFinite(data.quad_ratio) && data.quad_ratio > 0) {
+ parts.push(`<span class="gr-tag">${Math.round(data.quad_ratio * 100)}% quad-dominant</span>`);
+ }
+ if (data.textured === true) parts.push('<span class="gr-tag">texture re-baked ✓</span>');
+ deltaEl.innerHTML = parts.join(' ');
+ deltaEl.classList.add('is-shown');
+ }
+
+ // ── Network ──────────────────────────────────────────────────────────────
+ function sleep(ms) {
+ return new Promise((r) => setTimeout(r, ms));
+ }
+
+ async function startExport(formats, payment) {
+ // Carry the holder's $THREE tier pass so an eligible holder clears the gate
+ // (no payment); harmless / empty for everyone else. A non-holder attaches the
+ // settled pay-per-export proof instead.
+ const threeHdrs = await threeHeaders();
+ const res = await fetch('/api/forge-gameready', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', ...CLIENT_HEADERS, ...threeHdrs },
+ body: JSON.stringify({
+ mesh_url: state.glbUrl,
+ topology: state.topology,
+ poly_budget: Number(budgetSlider.value),
+ texture_size: Number(texsizeSel.value),
+ formats,
+ preserve_rig: rigCheck.checked && formats.includes('fbx'),
+ ...(payment?.paymentId && payment?.refId
+ ? { payment_id: payment.paymentId, ref_id: payment.refId }
+ : {}),
+ }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (res.status === 503 || data.error === 'unconfigured') {
+ throw new Error('Game-Ready export is not configured on this deployment yet.');
+ }
+ // $THREE hold-or-pay gate, or a pay-per-export proof that didn't verify — both
+ // recoverable by paying once. Tag it so run() can open the pay modal and retry.
+ if (
+ res.status === 402 &&
+ (data.error === 'three_hold_required' ||
+ data.error === 'payment_invalid' ||
+ data.error === 'payment_expired')
+ ) {
+ const e = new Error(data.message || 'Game-Ready export is a $THREE holder perk — or pay per export.');
+ e.kind = 'pay_required';
+ e.gate = data;
+ throw e;
+ }
+ // Proof already spent — clear it and re-offer Pay so a retry never replays it.
+ if (res.status === 409 && data.error === 'payment_already_used') {
+ const e = new Error(data.message || 'That payment was already used. Pay again to export.');
+ e.kind = 'pay_required';
+ e.gate = data;
+ throw e;
+ }
+ if (res.status === 429 || data.error === 'rate_limited') {
+ const secs = Number(data.retry_after) > 0 ? Math.ceil(Number(data.retry_after)) : 10;
+ throw new Error(`The exporter is busy. Try again in about ${secs}s.`);
+ }
+ if (!res.ok || !data.job_id) {
+ throw new Error(data.message || `The exporter returned ${res.status}.`);
+ }
+ return data.job_id;
+ }
+
+ // Start the export, transparently handling the $THREE hold-or-pay gate: a holder
+ // passes straight through; a non-holder is offered the one-time pay modal, then
+ // the export retries with the settled proof. Returns the job id, or null when the
+ // user dismissed the payment. The price comes from the server gate — never
+ // hardcoded — so it stays correct if the catalog price changes.
+ async function startWithGate(formats) {
+ try {
+ return await startExport(formats);
+ } catch (err) {
+ if (err.kind !== 'pay_required') throw err;
+ const usd = Number(err.gate?.pay_per_use?.usd) || 0;
+ if (!(usd > 0)) throw err; // hold-only with no pay path — surface the gate copy
+ setStatus('Waiting for payment…');
+ const paid = await payForConsumption({
+ usd,
+ unit: 'one Game-Ready export',
+ confirm: 'One engine-ready export (retopology + PBR re-bake), paid in $THREE.',
+ footnote: '$THREE is the only coin on three.ws. Draft &amp; Standard generation stay free.',
+ successText: 'Payment confirmed — starting your export…',
+ refPrefix: 'forge-gameready',
+ });
+ if (!paid?.ok) {
+ setStatus('Export cancelled — no $THREE was spent.');
+ return null;
+ }
+ return await startExport(formats, { paymentId: paid.paymentId, refId: paid.refId });
+ }
+ }
+
+ async function pollExport(jobId) {
+ const deadline = performance.now() + MAX_MS;
+ while (!state.pollAbort && performance.now() < deadline) {
+ await sleep(POLL_MS);
+ if (state.pollAbort) return null;
+ const res = await fetch(`/api/forge-gameready?job=${encodeURIComponent(jobId)}`, {
+ headers: CLIENT_HEADERS,
+ });
+ const data = await res.json().catch(() => ({}));
+ if (data.status === 'done' && data.outputs) return data;
+ if (data.status === 'failed') throw new Error(data.error || 'Game-Ready export failed.');
+ setStatus(data.status === 'running' ? 'Retopologizing & baking…' : 'Queued…');
+ }
+ if (state.pollAbort) return null;
+ throw new Error('Export timed out. Try a lower poly budget.');
+ }
+
+ function applyResult(data) {
+ const outputs = data.outputs || {};
+ // GLB renders inline — swap the live viewer so the new topology shows
+ // immediately and feeds the wireframe preview.
+ if (outputs.glb?.url) {
+ viewer.setAttribute('src', outputs.glb.url);
+ state.previewUrl = outputs.glb.url;
+ wireBtn.hidden = false;
+ resetWireframe();
+ } else {
+ // FBX-only export: no inline GLB to preview, so the wireframe stays off.
+ wireBtn.hidden = true;
+ hideWireframe();
+ }
+ renderDelta(data);
+ renderDownloads(outputs);
+ }
+
+ async function run() {
+ if (state.running || !state.glbUrl) return;
+ const formats = selectedFormats();
+ if (formats.length === 0) {
+ setStatus('Pick at least one format (GLB or FBX).', 'error');
+ return;
+ }
+ state.pollAbort = false;
+ setRunning(true);
+ setStatus('Starting…');
+ deltaEl.classList.remove('is-shown');
+ downloadsEl.classList.remove('is-shown');
+ try {
+ const jobId = await startWithGate(formats);
+ if (!jobId) return; // user dismissed the $THREE payment — already messaged
+ const done = await pollExport(jobId);
+ if (!done) return; // superseded by a newer model / cancelled
+ applyResult(done);
+ setStatus('Done — engine-ready asset is ready to download.', 'done');
+ } catch (err) {
+ setStatus(err.message || 'Export failed.', 'error');
+ } finally {
+ setRunning(false);
+ }
+ }
+
+ // ── Wireframe preview (lazy three.js overlay) ──────────────────────────────
+ const wire = {
+ ready: false,
+ loading: false,
+ THREE: null,
+ renderer: null,
+ scene: null,
+ camera: null,
+ controls: null,
+ group: null,
+ raf: 0,
+ ro: null,
+ loadedUrl: null,
+ };
+
+ function sizeWireRenderer() {
+ if (!wire.renderer) return;
+ const w = wireOverlay.clientWidth || 1;
+ const h = wireOverlay.clientHeight || 1;
+ wire.renderer.setSize(w, h, false);
+ wire.camera.aspect = w / h;
+ wire.camera.updateProjectionMatrix();
+ }
+
+ async function ensureWireEngine() {
+ if (wire.ready || wire.loading) return wire.ready;
+ wire.loading = true;
+ try {
+ const [THREE, { GLTFLoader }, { OrbitControls }] = await Promise.all([
+ import('three'),
+ import('three/addons/loaders/GLTFLoader.js'),
+ import('three/addons/controls/OrbitControls.js'),
+ ]);
+ wire.THREE = THREE;
+ wire.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
+ wire.renderer.setPixelRatio(Math.min(devicePixelRatio || 1, 2));
+ wireOverlay.appendChild(wire.renderer.domElement);
+ wire.scene = new THREE.Scene();
+ wire.camera = new THREE.PerspectiveCamera(45, 1, 0.01, 1000);
+ wire.camera.position.set(0, 0, 3);
+ wire.controls = new OrbitControls(wire.camera, wire.renderer.domElement);
+ wire.controls.enableDamping = true;
+ wire.controls.autoRotate = true;
+ wire.controls.autoRotateSpeed = 1.4;
+ wire.group = new THREE.Group();
+ wire.scene.add(wire.group);
+ wire._loader = new GLTFLoader();
+ sizeWireRenderer();
+ wire.ro = new ResizeObserver(sizeWireRenderer);
+ wire.ro.observe(wireOverlay);
+ const tick = () => {
+ wire.raf = requestAnimationFrame(tick);
+ wire.controls.update();
+ wire.renderer.render(wire.scene, wire.camera);
+ };
+ tick();
+ wire.ready = true;
+ } catch {
+ wire.ready = false;
+ } finally {
+ wire.loading = false;
+ }
+ return wire.ready;
+ }
+
+ function clearWireGroup() {
+ if (!wire.group) return;
+ for (const child of [...wire.group.children]) {
+ wire.group.remove(child);
+ child.traverse?.((n) => {
+ n.geometry?.dispose?.();
+ if (Array.isArray(n.material)) n.material.forEach((m) => m.dispose?.());
+ else n.material?.dispose?.();
+ });
+ }
+ }
+
+ function frameWireModel(root) {
+ const THREE = wire.THREE;
+ const box = new THREE.Box3().setFromObject(root);
+ const size = box.getSize(new THREE.Vector3());
+ const center = box.getCenter(new THREE.Vector3());
+ const maxDim = Math.max(size.x, size.y, size.z) || 1;
+ root.position.sub(center);
+ const dist = maxDim * 2.2;
+ wire.camera.position.set(dist * 0.6, dist * 0.3, dist);
+ wire.camera.near = maxDim / 100;
+ wire.camera.far = maxDim * 100;
+ wire.camera.updateProjectionMatrix();
+ wire.controls.target.set(0, 0, 0);
+ wire.controls.update();
+ }
+
+ async function loadWireModel(url) {
+ if (!(await ensureWireEngine())) return;
+ if (wire.loadedUrl === url && wire.group.children.length) return;
+ const THREE = wire.THREE;
+ wire._loader.load(
+ url,
+ (gltf) => {
+ clearWireGroup();
+ const accent = getComputedStyle(document.documentElement).getPropertyValue('--accent').trim() || '#7c9cff';
+ const wireMat = new THREE.MeshBasicMaterial({ color: new THREE.Color(accent), wireframe: true });
+ gltf.scene.traverse((node) => {
+ if (node.isMesh) node.material = wireMat;
+ });
+ wire.group.add(gltf.scene);
+ frameWireModel(gltf.scene);
+ wire.loadedUrl = url;
+ },
+ undefined,
+ () => {
+ /* load error — keep the overlay hidden, user still has the textured viewer */
+ hideWireframe();
+ },
+ );
+ }
+
+ function showWireframe() {
+ if (!state.previewUrl) return;
+ wireOverlay.classList.add('is-shown');
+ wireBtn.setAttribute('aria-pressed', 'true');
+ loadWireModel(state.previewUrl);
+ }
+ function hideWireframe() {
+ wireOverlay.classList.remove('is-shown');
+ wireBtn.setAttribute('aria-pressed', 'false');
+ }
+ function resetWireframe() {
+ // A new export invalidates the previously loaded wireframe model.
+ wire.loadedUrl = null;
+ if (wireOverlay.classList.contains('is-shown')) showWireframe();
+ }
+
+ // ── Wiring ─────────────────────────────────────────────────────────────────
+ function openPanel(open) {
+ panel.dataset.open = String(open);
+ triggerBtn.setAttribute('aria-expanded', String(open));
+ if (open) panel.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
+ else hideWireframe();
+ }
+
+ triggerBtn.addEventListener('click', () => {
+ openPanel(panel.dataset.open !== 'true');
+ });
+
+ topoGroup.addEventListener('click', (e) => {
+ const btn = e.target.closest('button[data-topo]');
+ if (btn) applyTopology(btn.dataset.topo);
+ });
+
+ budgetSlider.addEventListener('input', () => setBudget(Number(budgetSlider.value)));
+
+ presetGroup.addEventListener('click', (e) => {
+ const btn = e.target.closest('button[data-budget]');
+ if (btn) setBudget(Number(btn.dataset.budget));
+ });
+
+ for (const c of fmtChecks) c.addEventListener('change', syncRigVisibility);
+ rigCheck.addEventListener('change', syncRigVisibility);
+
+ runBtn.addEventListener('click', run);
+
+ wireBtn.addEventListener('click', () => {
+ if (wireOverlay.classList.contains('is-shown')) hideWireframe();
+ else showWireframe();
+ });
+
+ // Pick up the live model whenever one is forged or loaded from the gallery.
+ document.addEventListener('forge:model-ready', (e) => {
+ const url = e.detail?.glbUrl;
+ if (!url) return;
+ state.glbUrl = url;
+ state.label = e.detail?.label || 'model';
+ state.previewUrl = null;
+ state.pollAbort = true; // cancel any in-flight poll for the previous model
+ setStatus('');
+ deltaEl.classList.remove('is-shown');
+ downloadsEl.classList.remove('is-shown');
+ wireBtn.hidden = true;
+ hideWireframe();
+ openPanel(false);
+ loadSourceFaceCount(url);
+ });
+
+ // Initial render.
+ applyTopology('quad');
+ setBudget(15_000);
+ syncRigVisibility();
+}
diff --git a/src/forge-studio/forge-optimize.js b/src/forge-studio/forge-optimize.js
new file mode 100644
index 000000000..6d2e78083
--- /dev/null
+++ b/src/forge-studio/forge-optimize.js
@@ -0,0 +1,398 @@
+// Topology optimizer layered onto the forge result viewer.
+//
+// When a model becomes available (forge.js dispatches `forge:model-ready`),
+// this panel lets the user produce game/animation-ready output from the live
+// GLB via the real /api/forge-remesh route:
+// • triangle — quadric (QEM) decimation, fast polygon reduction
+// • quad — field-aligned quad-dominant retopology (QuadriFlow): clean
+// edge loops that deform well for rigging & animation
+// • lowpoly — silhouette-preserving low-poly with the original texture
+// re-unwrapped + re-baked onto the new mesh
+//
+// GLB output renders inline (swaps the live <model-viewer> src); every other
+// format is download-only. Nothing fakes progress — the panel polls the job.
+//
+// The panel injects its own markup + styles so it survives independently of the
+// forge.html template: it only needs the result panel, viewer, and download
+// button to be present.
+
+const resultPanel = document.getElementById('state-result');
+const viewer = document.getElementById('viewer');
+const download = document.getElementById('download');
+
+if (resultPanel && viewer) {
+ const OPT_POLL_MS = 2500;
+ const OPT_MAX_MS = 8 * 60 * 1000; // quad/lowpoly bakes can take a couple minutes
+
+ // Reuse the forge anonymous client id (set by forge.js) for rate-limit
+ // fairness; harmless if absent.
+ const CLIENT_HEADERS = (() => {
+ try {
+ const id = localStorage.getItem('forge:cid');
+ return id ? { 'x-forge-client': id } : {};
+ } catch {
+ return {};
+ }
+ })();
+
+ const MODE_HINTS = {
+ triangle:
+ 'Quadric (QEM) decimation. Fast, general-purpose polygon reduction — best for trimming size before download.',
+ quad:
+ 'Field-aligned quad-dominant retopology (QuadriFlow). Clean edge loops that deform well for rigging & animation. GLB triangulates for preview — pick OBJ for true quad faces.',
+ lowpoly:
+ 'Silhouette-preserving low-poly for real-time use. UVs are re-unwrapped and the original texture is re-baked onto the new mesh so it still renders correctly.',
+ };
+
+ const TARGETS = {
+ triangle: {
+ label: 'Target faces',
+ options: [
+ [5000, '5k'],
+ [10000, '10k'],
+ [20000, '20k'],
+ [50000, '50k'],
+ [100000, '100k'],
+ ],
+ default: 20000,
+ },
+ quad: {
+ label: 'Target quads',
+ options: [
+ [2500, '2.5k'],
+ [5000, '5k'],
+ [10000, '10k'],
+ [20000, '20k'],
+ [40000, '40k'],
+ ],
+ default: 10000,
+ },
+ lowpoly: {
+ label: 'Poly budget',
+ options: [
+ [1000, '1k — mobile'],
+ [5000, '5k — standard'],
+ [20000, '20k — hero'],
+ ],
+ default: 5000,
+ },
+ };
+
+ const FORMATS = [
+ ['glb', 'GLB (textured)'],
+ ['obj', 'OBJ (true quads)'],
+ ['fbx', 'FBX'],
+ ['stl', 'STL'],
+ ['ply', 'PLY'],
+ ['usdz', 'USDZ'],
+ ['3mf', '3MF'],
+ ];
+
+ // ── Styles ───────────────────────────────────────────────────────────────
+ if (!document.getElementById('forge-optimize-styles')) {
+ const style = document.createElement('style');
+ style.id = 'forge-optimize-styles';
+ style.textContent = `
+ .optimize { border-top: 1px solid var(--stroke); }
+ .optimize-toggle {
+ width: 100%; display: flex; align-items: center; justify-content: space-between;
+ gap: var(--space-sm); background: transparent; border: none; color: var(--ink);
+ font-family: var(--font-display); font-weight: 600; font-size: var(--text-sm);
+ padding: var(--space-sm) var(--space-md); cursor: pointer;
+ }
+ .optimize-toggle:hover { background: var(--surface-2); }
+ .optimize-toggle:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
+ .optimize-toggle .chev { transition: transform 0.18s ease; color: var(--ink-dim); }
+ .optimize[data-open='true'] .optimize-toggle .chev { transform: rotate(180deg); }
+ .optimize-body { display: none; flex-direction: column; gap: var(--space-md); padding: 0 var(--space-md) var(--space-md); }
+ .optimize[data-open='true'] .optimize-body { display: flex; }
+ .opt-field { display: flex; flex-direction: column; gap: 0.4rem; }
+ .opt-field > span {
+ font-size: var(--text-xs); color: var(--ink-dim); font-family: var(--font-mono);
+ text-transform: uppercase; letter-spacing: 0.04em;
+ }
+ .seg {
+ display: inline-flex; flex-wrap: wrap; gap: 2px; background: var(--surface-1);
+ border: 1px solid var(--stroke); border-radius: var(--radius-md); padding: 2px;
+ }
+ .seg button {
+ flex: 1 1 auto; background: transparent; border: none; color: var(--ink-dim);
+ font-family: var(--font-mono); font-size: var(--text-xs); padding: 0.4rem 0.7rem;
+ border-radius: var(--radius-sm); cursor: pointer; transition: background 0.15s, color 0.15s;
+ }
+ .seg button:hover { color: var(--ink); }
+ .seg button[aria-pressed='true'] { background: var(--surface-3); color: var(--ink); }
+ .seg button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+ .opt-mode-hint { font-size: var(--text-xs); color: var(--ink-dim); line-height: 1.4; min-height: 1.4em; margin: 0; }
+ .opt-row { display: flex; gap: var(--space-md); flex-wrap: wrap; }
+ .opt-row .opt-field { flex: 1 1 140px; }
+ .opt-select {
+ background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-md);
+ color: var(--ink); font-family: var(--font-mono); font-size: var(--text-xs); padding: 0.45rem 0.6rem;
+ }
+ .opt-select:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
+ .opt-actions { display: flex; align-items: center; gap: var(--space-md); flex-wrap: wrap; }
+ .opt-status { font-size: var(--text-xs); font-family: var(--font-mono); color: var(--ink-dim); }
+ .opt-status[data-kind='error'] { color: var(--danger); }
+ .opt-status[data-kind='done'] { color: var(--success); }
+ .opt-stats { display: flex; gap: var(--space-md); flex-wrap: wrap; font-family: var(--font-mono); font-size: var(--text-xs); color: var(--ink-dim); }
+ .opt-stats strong { color: var(--ink); font-weight: 600; }
+ .opt-stats.is-hidden { display: none; }
+ `;
+ document.head.appendChild(style);
+ }
+
+ // ── DOM ────────────────────────────────────────────────────────────────────
+ const panel = document.createElement('div');
+ panel.className = 'optimize';
+ panel.dataset.open = 'false';
+ panel.innerHTML = `
+ <button class="optimize-toggle" type="button" aria-expanded="false">
+ <span>Optimize topology — quad remesh &amp; game-ready low-poly</span>
+ <svg class="chev" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
+ stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <polyline points="6 9 12 15 18 9" />
+ </svg>
+ </button>
+ <div class="optimize-body">
+ <div class="opt-field">
+ <span>Mode</span>
+ <div class="seg opt-mode" role="group" aria-label="Remesh mode">
+ <button type="button" data-mode="triangle" aria-pressed="false">Triangle</button>
+ <button type="button" data-mode="quad" aria-pressed="true">Quad retopo</button>
+ <button type="button" data-mode="lowpoly" aria-pressed="false">Low-poly</button>
+ </div>
+ <p class="opt-mode-hint"></p>
+ </div>
+ <div class="opt-row">
+ <label class="opt-field">
+ <span class="opt-target-label">Target faces</span>
+ <select class="opt-select opt-target"></select>
+ </label>
+ <label class="opt-field">
+ <span>Format</span>
+ <select class="opt-select opt-format"></select>
+ </label>
+ <label class="opt-field opt-texsize-field">
+ <span>Texture</span>
+ <select class="opt-select opt-texsize">
+ <option value="512">512px</option>
+ <option value="1024" selected>1024px</option>
+ <option value="2048">2048px</option>
+ </select>
+ </label>
+ </div>
+ <div class="opt-actions">
+ <button class="btn opt-run" type="button"><span class="opt-run-label">Optimize</span></button>
+ <span class="opt-status" role="status" aria-live="polite"></span>
+ </div>
+ <div class="opt-stats is-hidden"></div>
+ </div>
+ `;
+ resultPanel.appendChild(panel);
+
+ const toggle = panel.querySelector('.optimize-toggle');
+ const modeGroup = panel.querySelector('.opt-mode');
+ const modeHint = panel.querySelector('.opt-mode-hint');
+ const targetSel = panel.querySelector('.opt-target');
+ const targetLabel = panel.querySelector('.opt-target-label');
+ const formatSel = panel.querySelector('.opt-format');
+ const texsizeField = panel.querySelector('.opt-texsize-field');
+ const texsizeSel = panel.querySelector('.opt-texsize');
+ const runBtn = panel.querySelector('.opt-run');
+ const runLabel = panel.querySelector('.opt-run-label');
+ const statusEl = panel.querySelector('.opt-status');
+ const stats = panel.querySelector('.opt-stats');
+
+ for (const [value, text] of FORMATS) {
+ const opt = document.createElement('option');
+ opt.value = value;
+ opt.textContent = text;
+ formatSel.appendChild(opt);
+ }
+
+ const state = {
+ glbUrl: null,
+ label: 'model',
+ mode: 'quad',
+ running: false,
+ pollAbort: false,
+ };
+
+ function setStatus(text, kind) {
+ statusEl.textContent = text || '';
+ if (kind) statusEl.dataset.kind = kind;
+ else statusEl.removeAttribute('data-kind');
+ }
+
+ function fillTargets(mode) {
+ const cfg = TARGETS[mode];
+ targetLabel.textContent = cfg.label;
+ targetSel.innerHTML = '';
+ for (const [value, text] of cfg.options) {
+ const opt = document.createElement('option');
+ opt.value = String(value);
+ opt.textContent = text;
+ if (value === cfg.default) opt.selected = true;
+ targetSel.appendChild(opt);
+ }
+ }
+
+ function applyMode(mode) {
+ state.mode = mode;
+ for (const b of modeGroup.querySelectorAll('button')) {
+ b.setAttribute('aria-pressed', String(b.dataset.mode === mode));
+ }
+ modeHint.textContent = MODE_HINTS[mode];
+ fillTargets(mode);
+ // Texture re-bake only applies to quad/lowpoly.
+ texsizeField.classList.toggle('is-hidden', mode === 'triangle');
+ }
+
+ function reset(glbUrl, label) {
+ state.glbUrl = glbUrl;
+ state.label = label || 'model';
+ state.pollAbort = true; // cancel any in-flight poll for the previous model
+ setStatus('');
+ stats.classList.add('is-hidden');
+ stats.innerHTML = '';
+ // The source model is always the forged GLB — restore the default label
+ // in case a prior optimization repointed the download button.
+ if (download) download.textContent = 'Download GLB';
+ panel.dataset.open = 'false';
+ toggle.setAttribute('aria-expanded', 'false');
+ }
+
+ function setRunning(running) {
+ state.running = running;
+ runBtn.disabled = running;
+ runLabel.textContent = running ? 'Optimizing…' : 'Optimize';
+ }
+
+ function sleep(ms) {
+ return new Promise((r) => setTimeout(r, ms));
+ }
+
+ async function startRemesh() {
+ const res = await fetch('/api/forge-remesh', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', ...CLIENT_HEADERS },
+ body: JSON.stringify({
+ mesh_url: state.glbUrl,
+ remesh_mode: state.mode,
+ target_faces: Number(targetSel.value),
+ output_format: formatSel.value,
+ texture_size: Number(texsizeSel.value),
+ }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (res.status === 503 || data.error === 'unconfigured') {
+ throw new Error('Mesh optimization is not configured on this deployment yet.');
+ }
+ if (res.status === 429 || data.error === 'rate_limited') {
+ const secs = Number(data.retry_after) > 0 ? Math.ceil(Number(data.retry_after)) : 10;
+ throw new Error(`Optimizer is busy. Try again in about ${secs}s.`);
+ }
+ if (!res.ok || !data.job_id) {
+ throw new Error(data.message || `Optimizer returned ${res.status}.`);
+ }
+ return data.job_id;
+ }
+
+ async function pollRemesh(jobId) {
+ const deadline = performance.now() + OPT_MAX_MS;
+ while (!state.pollAbort && performance.now() < deadline) {
+ await sleep(OPT_POLL_MS);
+ if (state.pollAbort) return null;
+ const res = await fetch(`/api/forge-remesh?job=${encodeURIComponent(jobId)}`, {
+ headers: CLIENT_HEADERS,
+ });
+ const data = await res.json().catch(() => ({}));
+ if (data.status === 'done' && data.result_url) return data;
+ if (data.status === 'failed') throw new Error(data.error || 'Optimization failed.');
+ setStatus(data.status === 'running' ? 'Optimizing topology…' : 'Queued…');
+ }
+ if (state.pollAbort) return null;
+ throw new Error('Optimization timed out.');
+ }
+
+ function showStats(data, format) {
+ const parts = [];
+ if (typeof data.face_count === 'number') {
+ parts.push(
+ `<span><strong>${data.face_count.toLocaleString()}</strong> ${
+ state.mode === 'quad' ? 'quads' : 'faces'
+ }</span>`,
+ );
+ }
+ if (typeof data.quad_ratio === 'number' && data.quad_ratio > 0) {
+ parts.push(
+ `<span><strong>${Math.round(data.quad_ratio * 100)}%</strong> quad-dominant</span>`,
+ );
+ }
+ if (data.textured === true) parts.push('<span>texture re-baked ✓</span>');
+ parts.push(`<span>${format.toUpperCase()}</span>`);
+ stats.innerHTML = parts.join('');
+ stats.classList.remove('is-hidden');
+ }
+
+ function applyResult(data) {
+ const format = formatSel.value;
+ const result = data.result_url;
+ // GLB renders inline — swap the live viewer so the user sees the new
+ // topology immediately. Other formats are download-only.
+ if (format === 'glb') {
+ viewer.setAttribute('src', result);
+ state.glbUrl = result; // chain further optimizations from the new mesh
+ }
+ const safe =
+ state.label.replace(/[^a-z0-9]+/gi, '-').slice(0, 48).replace(/^-|-$/g, '') || 'forge';
+ if (download) {
+ download.href = result;
+ download.setAttribute('download', `${safe}-${state.mode}.${format}`);
+ download.textContent = `Download ${format.toUpperCase()}`;
+ }
+ showStats(data, format);
+ }
+
+ async function run() {
+ if (state.running || !state.glbUrl) return;
+ state.pollAbort = false;
+ setRunning(true);
+ setStatus('Starting…');
+ stats.classList.add('is-hidden');
+ try {
+ const jobId = await startRemesh();
+ const done = await pollRemesh(jobId);
+ if (!done) return; // superseded by a newer model / cancelled
+ applyResult(done);
+ setStatus('Done — optimized mesh ready to download.', 'done');
+ } catch (err) {
+ setStatus(err.message || 'Optimization failed.', 'error');
+ } finally {
+ setRunning(false);
+ }
+ }
+
+ // ── Wiring ───────────────────────────────────────────────────────────────
+ toggle.addEventListener('click', () => {
+ const open = panel.dataset.open === 'true';
+ panel.dataset.open = String(!open);
+ toggle.setAttribute('aria-expanded', String(!open));
+ });
+
+ modeGroup.addEventListener('click', (e) => {
+ const btn = e.target.closest('button[data-mode]');
+ if (btn) applyMode(btn.dataset.mode);
+ });
+
+ runBtn.addEventListener('click', run);
+
+ // Pick up the live model whenever one is forged or loaded from the gallery.
+ document.addEventListener('forge:model-ready', (e) => {
+ const url = e.detail?.glbUrl;
+ if (url) reset(url, e.detail?.label);
+ });
+
+ applyMode('quad');
+}
diff --git a/src/forge-studio/forge-pay.js b/src/forge-studio/forge-pay.js
new file mode 100644
index 000000000..f17a6dbe9
--- /dev/null
+++ b/src/forge-studio/forge-pay.js
@@ -0,0 +1,342 @@
+// Pay-per-use for Forge High — the client flow that lets a non-holder pay $THREE
+// for one High generation instead of holding. Drives the server-authoritative
+// quote → sign → settle rail (src/token-pay.js → /api/token/quote|settle) behind
+// a designed status modal, then hands the settled { paymentId, refId } back so the
+// caller can retry the generation with the proof attached.
+//
+// One entry point:
+//
+// import { payForHighGeneration } from './forge-pay.js';
+// const r = await payForHighGeneration({ usd: 0.5 });
+// if (r.ok) run({ ...cfg, payment: { paymentId: r.paymentId, refId: r.refId } });
+//
+// Every state is designed: the confirm step, the live phases (pricing → approve →
+// confirming → verifying), and the recoverable errors — no wallet, sign-in needed,
+// payment cancelled, not enough $THREE (→ Get $THREE), and settlement failure
+// (Retry). The modal never throws; it resolves { ok:false } on cancel/error and
+// { ok:true, paymentId, refId } on a verified on-chain payment.
+
+import { payWithToken } from '../token-pay.js';
+
+const ECONOMY_URL = '/three-token';
+const SIGN_IN_URL = '/login';
+const WALLET_URL = 'https://phantom.app/';
+
+let _stylesInjected = false;
+
+function escapeHtml(s) {
+ return String(s ?? '').replace(
+ /[&<>"']/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
+ );
+}
+
+// A fresh client nonce per payment — recorded as token_payments.ref_id at quote
+// time and presented again (with the payment_id) when the action redeems it, so
+// possession of the payment_id alone can't unlock a dispatch. The prefix names the
+// action (e.g. `forge-high`, `forge-gameready`) for readable ledger/audit rows.
+function clientNonce(prefix = 'forge') {
+ const id =
+ (typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID()) ||
+ `${Date.now()}-${Math.random().toString(16).slice(2)}`;
+ return `${prefix}-${id}`;
+}
+
+function usdLabel(usd) {
+ return `$${(Number(usd) || 0).toFixed(2)}`;
+}
+
+// Map a payWithToken phase to holder-readable status copy.
+const PHASE_COPY = {
+ quoting: 'Pricing in $THREE…',
+ awaiting_signature: 'Approve the payment in your wallet…',
+ confirming: 'Confirming on Solana…',
+ settling: 'Verifying your payment…',
+};
+
+// Classify a thrown error into a designed, recoverable state. Returns
+// { title, detail, cta } where cta is { label, href } | { label, retry:true } | null.
+function classifyError(err) {
+ const code = err?.code || '';
+ const msg = String(err?.message || '');
+
+ if (code === 'no_wallet' || code === 'not_connected' || code === 'no_pubkey') {
+ return {
+ title: 'No Solana wallet',
+ detail: 'Connect a Solana wallet (Phantom) to pay in $THREE, then try again.',
+ cta: { label: 'Get Phantom', href: WALLET_URL, external: true },
+ };
+ }
+ if (code === 'unauthorized') {
+ return {
+ title: 'Sign in to pay',
+ detail: 'Sign in to three.ws first so we can issue your $THREE payment quote.',
+ cta: { label: 'Sign in', href: SIGN_IN_URL },
+ };
+ }
+ if (/reject|denied|cancel|declin|user.*reject/i.test(msg)) {
+ return {
+ title: 'Payment cancelled',
+ detail: 'You dismissed the wallet request — no $THREE was spent.',
+ cta: { label: 'Try again', retry: true },
+ };
+ }
+ if (
+ code === 'insufficient_funds' ||
+ /insufficient|0x1\b|not enough|debit|exceeds.*balance/i.test(msg)
+ ) {
+ return {
+ title: 'Not enough $THREE',
+ detail: "Your wallet doesn't hold enough $THREE for this generation.",
+ cta: { label: 'Get $THREE', href: ECONOMY_URL },
+ };
+ }
+ if (code === 'price_unavailable') {
+ return {
+ title: 'Price feed unavailable',
+ detail: 'We couldn’t price $THREE just now. Try again in a moment.',
+ cta: { label: 'Try again', retry: true },
+ };
+ }
+ if (code === 'already_settled') {
+ return {
+ title: 'Already paid',
+ detail: 'This payment already settled — retry your generation.',
+ cta: { label: 'Try again', retry: true },
+ };
+ }
+ // Settlement / verification or any other transient failure.
+ return {
+ title: 'Payment didn’t go through',
+ detail:
+ msg && msg.length < 160
+ ? msg
+ : 'Something interrupted the payment. Try again — no $THREE is spent unless it settles.',
+ cta: { label: 'Try again', retry: true },
+ };
+}
+
+/**
+ * Run the pay-per-use flow for one Forge consumption action (High generation,
+ * Game-Ready export, …). Drives the same server-authoritative quote → sign →
+ * settle rail behind the designed status modal, then hands back the settled
+ * { paymentId, refId } so the caller can retry the action with the proof attached.
+ * @param {object} params
+ * @param {number} params.usd price in USD (settled in $THREE)
+ * @param {string} [params.unit] short unit shown under the price ("one export")
+ * @param {string} [params.confirm] one-line confirm-step description
+ * @param {string} [params.footnote] trusted footnote markup under the actions
+ * @param {string} [params.successText] copy shown on a verified payment
+ * @param {string} [params.refPrefix] client-nonce prefix (action name)
+ * @returns {Promise<{ ok: true, paymentId: string, refId: string } | { ok: false, cancelled?: boolean }>}
+ */
+export function payForConsumption({
+ usd,
+ unit = 'one generation',
+ confirm = 'One generation, paid in $THREE.',
+ footnote = '$THREE is the only coin on three.ws.',
+ successText = 'Payment confirmed — continuing…',
+ refPrefix = 'forge',
+} = {}) {
+ injectStyles();
+ return new Promise((resolve) => {
+ const refId = clientNonce(refPrefix);
+ let settled = false;
+
+ const overlay = document.createElement('div');
+ overlay.className = 'fpay-overlay';
+ overlay.innerHTML = renderShell(usd, { unit, footnote });
+ document.body.appendChild(overlay);
+
+ const modal = overlay.querySelector('.fpay-modal');
+ const statusEl = overlay.querySelector('.fpay-status');
+ const actionsEl = overlay.querySelector('.fpay-actions');
+
+ const cleanup = () => {
+ if (overlay._onKey) document.removeEventListener('keydown', overlay._onKey);
+ overlay.classList.remove('fpay-in');
+ const remove = () => overlay.remove();
+ overlay.addEventListener('transitionend', remove, { once: true });
+ setTimeout(remove, 260);
+ };
+ const finish = (result) => {
+ if (overlay._done) return;
+ overlay._done = true;
+ cleanup();
+ resolve(result);
+ };
+ const close = () => finish({ ok: false, cancelled: true });
+
+ // ── State renderers ────────────────────────────────────────────────────
+ function showStatus(text, { busy = false } = {}) {
+ statusEl.className = 'fpay-status' + (busy ? ' fpay-status--busy' : '');
+ statusEl.innerHTML = busy
+ ? `<span class="fpay-spinner" aria-hidden="true"></span><span>${escapeHtml(text)}</span>`
+ : escapeHtml(text);
+ }
+
+ function showConfirm() {
+ showStatus(confirm);
+ actionsEl.innerHTML =
+ `<button type="button" class="fpay-btn fpay-btn--primary" data-fpay-pay>Pay ${usdLabel(usd)}</button>` +
+ `<button type="button" class="fpay-btn fpay-btn--ghost" data-fpay-cancel>Cancel</button>`;
+ actionsEl.querySelector('[data-fpay-pay]').addEventListener('click', startPayment);
+ actionsEl.querySelector('[data-fpay-cancel]').addEventListener('click', close);
+ actionsEl.querySelector('[data-fpay-pay]').focus();
+ }
+
+ function showError(err) {
+ const info = classifyError(err);
+ statusEl.className = 'fpay-status fpay-status--err';
+ statusEl.innerHTML =
+ `<strong class="fpay-err-title">${escapeHtml(info.title)}</strong>` +
+ `<span class="fpay-err-detail">${escapeHtml(info.detail)}</span>`;
+ const buttons = [];
+ if (info.cta?.href) {
+ const ext = info.cta.external ? ' target="_blank" rel="noopener"' : '';
+ buttons.push(
+ `<a class="fpay-btn fpay-btn--primary" href="${escapeHtml(info.cta.href)}"${ext}>${escapeHtml(info.cta.label)}</a>`,
+ );
+ }
+ if (info.cta?.retry) {
+ buttons.push(
+ `<button type="button" class="fpay-btn fpay-btn--primary" data-fpay-retry>${escapeHtml(info.cta.label)}</button>`,
+ );
+ }
+ buttons.push(
+ `<button type="button" class="fpay-btn fpay-btn--ghost" data-fpay-cancel>Close</button>`,
+ );
+ actionsEl.innerHTML = buttons.join('');
+ actionsEl.querySelector('[data-fpay-retry]')?.addEventListener('click', startPayment);
+ actionsEl.querySelector('[data-fpay-cancel]').addEventListener('click', close);
+ }
+
+ async function startPayment() {
+ actionsEl.innerHTML = '';
+ showStatus(PHASE_COPY.quoting, { busy: true });
+ try {
+ const result = await payWithToken({
+ purpose: 'consumption',
+ usd,
+ refType: 'forge',
+ refId,
+ onStatus: (phase) =>
+ showStatus(PHASE_COPY[phase] || 'Working…', { busy: true }),
+ });
+ if (!result?.ok || !result.payment_id) {
+ throw Object.assign(new Error('Payment could not be verified.'), {
+ code: 'verification_failed',
+ });
+ }
+ settled = true;
+ statusEl.className = 'fpay-status fpay-status--ok';
+ statusEl.innerHTML = `<span class="fpay-check" aria-hidden="true">✓</span> ${escapeHtml(successText)}`;
+ actionsEl.innerHTML = '';
+ setTimeout(() => finish({ ok: true, paymentId: result.payment_id, refId }), 850);
+ } catch (err) {
+ if (settled) return; // already resolved
+ showError(err);
+ }
+ }
+
+ // ── Mount ────────────────────────────────────────────────────────────────
+ overlay.addEventListener('click', (e) => {
+ if (e.target === overlay) close();
+ });
+ overlay.querySelector('[data-fpay-x]').addEventListener('click', close);
+ const onKey = (e) => {
+ if (e.key === 'Escape') close();
+ };
+ overlay._onKey = onKey;
+ document.addEventListener('keydown', onKey);
+ requestAnimationFrame(() => {
+ overlay.classList.add('fpay-in');
+ (modal || overlay).focus?.();
+ });
+ showConfirm();
+ });
+}
+
+/**
+ * Pay-per-use for one Forge High generation — the original entry point, preserved
+ * exactly. A thin wrapper over payForConsumption with the High copy/nonce.
+ * @param {{ usd: number }} params
+ * @returns {Promise<{ ok: true, paymentId: string, refId: string } | { ok: false, cancelled?: boolean }>}
+ */
+export function payForHighGeneration({ usd }) {
+ return payForConsumption({
+ usd,
+ unit: 'one High generation',
+ confirm: 'One High-quality generation (200k poly + PBR), paid in $THREE.',
+ footnote: '$THREE is the only coin on three.ws. Draft &amp; Standard generation stay free.',
+ successText: 'Payment confirmed — starting your generation…',
+ refPrefix: 'forge-high',
+ });
+}
+
+function renderShell(usd, { unit = 'one generation', footnote = '$THREE is the only coin on three.ws.' } = {}) {
+ return (
+ `<div class="fpay-modal" role="dialog" aria-modal="true" aria-labelledby="fpay-title">` +
+ `<button class="fpay-x" data-fpay-x type="button" aria-label="Close">✕</button>` +
+ `<div class="fpay-badge" aria-hidden="true">◆</div>` +
+ `<h2 class="fpay-title" id="fpay-title">Pay ${usdLabel(usd)} in $THREE</h2>` +
+ `<div class="fpay-price"><span class="fpay-price-amt">${usdLabel(usd)}</span><span class="fpay-price-unit">in $THREE · ${escapeHtml(unit)}</span></div>` +
+ `<div class="fpay-status" role="status" aria-live="polite"></div>` +
+ `<div class="fpay-actions"></div>` +
+ `<p class="fpay-foot">${footnote}</p>` +
+ `</div>`
+ );
+}
+
+function injectStyles() {
+ if (_stylesInjected || typeof document === 'undefined') return;
+ _stylesInjected = true;
+ const css = `
+ .fpay-overlay{position:fixed;inset:0;z-index:2147483100;display:flex;align-items:center;justify-content:center;
+ padding:20px;background:rgba(4,4,7,.66);backdrop-filter:blur(7px);-webkit-backdrop-filter:blur(7px);
+ opacity:0;transition:opacity .2s ease;font-family:Inter,system-ui,sans-serif;}
+ .fpay-overlay.fpay-in{opacity:1;}
+ .fpay-modal{position:relative;width:min(420px,100%);background:linear-gradient(180deg,#0e0e13,#0a0a0e);
+ border:1px solid #23232c;border-radius:20px;padding:30px 28px 22px;text-align:center;color:#f6f6f8;
+ box-shadow:0 30px 80px -30px rgba(0,0,0,.8);transform:translateY(10px) scale(.985);
+ transition:transform .24s cubic-bezier(.22,1,.36,1);}
+ .fpay-overlay.fpay-in .fpay-modal{transform:none;}
+ .fpay-x{position:absolute;top:12px;right:12px;width:32px;height:32px;border-radius:9px;border:1px solid #23232c;
+ background:transparent;color:#9a9aa4;cursor:pointer;font-size:13px;transition:.15s;}
+ .fpay-x:hover{color:#f6f6f8;border-color:#34343f;}
+ .fpay-badge{font-size:30px;color:#6ee7a8;filter:drop-shadow(0 0 14px rgba(110,231,168,.5));margin-bottom:6px;}
+ .fpay-title{font-size:20px;font-weight:820;letter-spacing:-.02em;margin:2px 0 12px;}
+ .fpay-price{display:flex;flex-direction:column;align-items:center;gap:2px;margin:0 0 16px;padding:13px;
+ background:rgba(110,231,168,.07);border:1px solid rgba(110,231,168,.2);border-radius:12px;}
+ .fpay-price-amt{font-size:26px;font-weight:800;color:#6ee7a8;line-height:1;}
+ .fpay-price-unit{font-size:12px;color:#9a9aa4;}
+ .fpay-status{font-size:13.5px;color:#b6b6c0;line-height:1.5;min-height:20px;margin:0 0 16px;
+ display:flex;align-items:center;justify-content:center;gap:9px;flex-wrap:wrap;}
+ .fpay-status--busy{color:#d6d6de;}
+ .fpay-status--ok{color:#6ee7a8;font-weight:600;}
+ .fpay-status--err{flex-direction:column;gap:3px;}
+ .fpay-err-title{font-size:14px;font-weight:700;color:#f0c2c2;}
+ .fpay-err-detail{font-size:12.5px;color:#a6a6b0;}
+ .fpay-check{color:#6ee7a8;font-weight:800;}
+ .fpay-spinner{width:15px;height:15px;border-radius:50%;border:2px solid rgba(110,231,168,.25);
+ border-top-color:#6ee7a8;animation:fpay-spin .7s linear infinite;flex-shrink:0;}
+ .fpay-actions{display:flex;flex-direction:column;gap:9px;min-height:1px;}
+ .fpay-btn{display:inline-flex;align-items:center;justify-content:center;font:700 14px/1 Inter,system-ui,sans-serif;
+ padding:12px 18px;border-radius:12px;text-decoration:none;cursor:pointer;border:1px solid #2a2a33;
+ background:#13131a;color:#f1f1f4;transition:transform .15s cubic-bezier(.22,1,.36,1),background .15s ease,border-color .15s ease;}
+ .fpay-btn--primary{background:#6ee7a8;color:#06120c;border-color:#6ee7a8;}
+ .fpay-btn--primary:hover{background:#8af0c0;transform:translateY(-1px);}
+ .fpay-btn--ghost:hover{border-color:#3a3a44;background:#181820;transform:translateY(-1px);}
+ .fpay-foot{font-size:11px;color:#6a6a74;margin:16px 0 0;line-height:1.5;}
+ .fpay-btn:focus-visible,.fpay-x:focus-visible{outline:2px solid #6ee7a8;outline-offset:2px;}
+ @keyframes fpay-spin{to{transform:rotate(360deg)}}
+ @media (prefers-reduced-motion: reduce){
+ .fpay-overlay,.fpay-modal,.fpay-btn{transition:none;}
+ .fpay-modal{transform:none;}
+ .fpay-spinner{animation-duration:1.4s;}
+ }`;
+ const el = document.createElement('style');
+ el.id = 'fpay-styles';
+ el.textContent = css;
+ document.head.appendChild(el);
+}
diff --git a/src/forge-studio/forge-prompt-studio.js b/src/forge-studio/forge-prompt-studio.js
new file mode 100644
index 000000000..8f818fd6d
--- /dev/null
+++ b/src/forge-studio/forge-prompt-studio.js
@@ -0,0 +1,264 @@
+// Forge prompt studio — the text-mode authoring aids that sit under the
+// composer: a curated prompt library behind "Surprise me" and "More ideas",
+// a live prompt coach that grades what you typed against how the model
+// actually reconstructs, and an honest character counter.
+//
+// All client-side. The library is hand-authored product content (single
+// isolated subjects with material/lighting cues — the shape Forge meshes
+// cleanest), not sampled data, and nothing here fakes a network call.
+
+const MAXLEN = 1000;
+
+// Curated starters — every one is a single, isolated object with a material
+// and/or lighting cue, mirroring the guidance in the Forge FAQ. Grouped only
+// for authoring clarity; consumed as one flat pool.
+const LIBRARY = [
+ // Creatures & characters
+ 'a low-poly red fox, sitting, soft studio light',
+ 'a chubby axolotl, glossy pink skin, plain background',
+ 'a tiny brass clockwork owl, polished metal',
+ 'a stone golem, mossy granite, weathered',
+ 'a cartoon astronaut, matte white suit, neutral pose',
+ 'a porcelain rabbit figurine, glazed, soft shadows',
+ 'a wooden articulated artist mannequin, light oak',
+ 'a plush felt dinosaur toy, stitched seams',
+ // Props & objects
+ 'a vintage film camera, brushed aluminium and black leather',
+ 'a glazed ceramic teapot, cobalt blue, studio lighting',
+ 'a worn leather armchair, studio lighting, plain background',
+ 'an antique brass compass, weathered patina',
+ 'a mechanical keyboard, translucent keycaps, backlit',
+ 'a hand-forged iron axe, dark steel, leather grip',
+ 'a crystal perfume bottle, faceted glass, gold cap',
+ 'a retro rotary telephone, cream bakelite',
+ 'a stack of hardcover books, aged cloth binding',
+ 'a wireless over-ear headphone, matte charcoal',
+ 'a single running shoe, knit upper, rubber sole',
+ 'a brass desk lamp, articulated arm, enamel shade',
+ 'a treasure chest, dark wood and tarnished iron bands',
+ 'an espresso machine, stainless steel and chrome',
+ // Nature & food
+ 'a potted monstera plant, terracotta pot',
+ 'a bonsai juniper in a shallow stone tray',
+ 'a glazed donut with sprinkles, soft studio light',
+ 'a ripe pomegranate, split open, glossy seeds',
+ 'a cluster of amethyst crystals on raw rock',
+ 'a single autumn maple leaf, deep amber',
+ 'a honey jar with wooden dipper, warm light',
+ 'a coral fan, calcified white, plain background',
+ // Sci-fi & fantasy
+ 'a sci-fi combat helmet, brushed metal, scuffed paint',
+ 'a glowing mana potion in a corked vial, teal liquid',
+ 'a hovering recon drone, white plastic and carbon fibre',
+ 'a wizard staff, gnarled oak with an embedded gem',
+ 'a retro ray gun, chrome with red accents',
+ 'an enchanted spellbook, leather cover, brass clasp',
+ 'a modular space station segment, white panels',
+ 'a knight helm, dark polished steel, plumed crest',
+ // Vehicles & architecture
+ 'a low-poly camper van, pastel teal paint',
+ 'a wooden sailboat model, white canvas sails',
+ 'a vintage scooter, mint green, chrome trim',
+ 'a small lighthouse, red and white stripes',
+ 'a cozy mushroom cottage, thatched roof',
+ 'a hot air balloon, striped canvas, wicker basket',
+];
+
+const $ = (id) => document.getElementById(id);
+
+const els = {
+ prompt: $('prompt'),
+ surprise: $('surprise'),
+ coach: $('prompt-coach'),
+ count: $('prompt-count'),
+ examples: $('examples'),
+ chipsMore: $('chips-more'),
+};
+
+// Heuristic lexicons used by the coach. These describe how TRELLIS-style
+// reconstruction behaves: a named material/finish and a clean isolated
+// subject produce the sharpest mesh; scenes and multi-object prompts
+// compress poorly into a single mesh.
+const MATERIAL_WORDS = [
+ 'metal',
+ 'metallic',
+ 'brass',
+ 'bronze',
+ 'copper',
+ 'steel',
+ 'iron',
+ 'chrome',
+ 'aluminium',
+ 'aluminum',
+ 'gold',
+ 'silver',
+ 'ceramic',
+ 'porcelain',
+ 'glazed',
+ 'glass',
+ 'crystal',
+ 'wood',
+ 'wooden',
+ 'oak',
+ 'leather',
+ 'plastic',
+ 'rubber',
+ 'matte',
+ 'glossy',
+ 'polished',
+ 'brushed',
+ 'velvet',
+ 'felt',
+ 'stone',
+ 'marble',
+ 'granite',
+ 'concrete',
+ 'fabric',
+ 'knit',
+ 'enamel',
+ 'carbon fibre',
+ 'carbon fiber',
+ 'bakelite',
+ 'terracotta',
+ 'weathered',
+ 'rusted',
+ 'patina',
+];
+const LIGHT_WORDS = ['studio', 'lighting', 'light', 'backlit', 'soft shadows', 'soft light', 'neutral'];
+// Signals that the prompt is asking for a scene rather than one object.
+const SCENE_WORDS = [
+ 'scene',
+ 'landscape',
+ 'environment',
+ 'diorama',
+ 'room',
+ 'interior',
+ 'forest',
+ 'city',
+ 'street',
+ 'battlefield',
+ 'background of',
+ 'surrounded by',
+];
+
+function hasAny(text, words) {
+ return words.some((w) => text.includes(w));
+}
+
+// Count subjects loosely — an " and " joining two nouns, or several
+// comma-separated clauses, both push the model toward a multi-object mesh.
+function looksMultiSubject(text) {
+ if (hasAny(text, SCENE_WORDS)) return true;
+ if (/\b(two|three|four|several|a group of|a pair of|a set of)\b/.test(text)) return true;
+ // " x and y " where both sides carry a noun-ish token.
+ if (/\w+\s+and\s+\w+/.test(text) && !/black and white|red and white|salt and pepper/.test(text))
+ return true;
+ return false;
+}
+
+function grade(raw) {
+ const text = raw.trim().toLowerCase();
+ const words = text ? text.split(/\s+/).length : 0;
+
+ if (!text) {
+ return {
+ grade: 'tip',
+ msg: 'Name one object and a material — e.g. “a brass compass, weathered”.',
+ };
+ }
+ if (words < 2) {
+ return { grade: 'tip', msg: 'Add a little detail — a material, colour, or finish.' };
+ }
+ if (looksMultiSubject(text)) {
+ return {
+ grade: 'warn',
+ msg: 'One isolated object reconstructs cleanest — scenes and multiple subjects compress poorly.',
+ };
+ }
+ const material = hasAny(text, MATERIAL_WORDS);
+ const light = hasAny(text, LIGHT_WORDS);
+ if (material && light) {
+ return { grade: 'strong', msg: 'Strong prompt — clear subject, material and lighting cues.' };
+ }
+ if (material) {
+ return { grade: 'strong', msg: 'Good prompt — add “studio lighting” for an even cleaner bake.' };
+ }
+ return {
+ grade: 'tip',
+ msg: 'Add a material or finish — “matte ceramic”, “brushed brass” — for a sharper mesh.',
+ };
+}
+
+function updateCoach() {
+ if (!els.prompt) return;
+ const value = els.prompt.value;
+ if (els.coach) {
+ const { grade: g, msg } = grade(value);
+ els.coach.dataset.grade = g;
+ els.coach.textContent = msg;
+ }
+ if (els.count) {
+ const len = value.length;
+ els.count.textContent = `${len} / ${MAXLEN}`;
+ els.count.dataset.near = String(len >= MAXLEN - 100);
+ }
+}
+
+// Random pick(s) from the library, avoiding a given set of current values so
+// "Surprise me" and "More ideas" never echo what is already on screen.
+function pickDistinct(count, avoid = new Set()) {
+ const pool = LIBRARY.filter((p) => !avoid.has(p));
+ const out = [];
+ while (out.length < count && pool.length) {
+ const i = Math.floor(Math.random() * pool.length);
+ out.push(pool.splice(i, 1)[0]);
+ }
+ return out;
+}
+
+function surprise() {
+ if (!els.prompt) return;
+ const [pick] = pickDistinct(1, new Set([els.prompt.value.trim()]));
+ if (!pick) return;
+ els.prompt.value = pick;
+ updateCoach();
+ els.prompt.focus();
+ const end = els.prompt.value.length;
+ els.prompt.setSelectionRange(end, end);
+ els.surprise?.classList.remove('is-rolling');
+ // reflow so the animation restarts on rapid clicks
+ void els.surprise?.offsetWidth;
+ els.surprise?.classList.add('is-rolling');
+}
+
+function shuffleChips() {
+ if (!els.examples) return;
+ const chips = [...els.examples.querySelectorAll('.chip')];
+ if (!chips.length) return;
+ const current = new Set(chips.map((c) => c.textContent.trim()));
+ const fresh = pickDistinct(chips.length, current);
+ chips.forEach((chip, i) => {
+ const next = fresh[i];
+ if (!next) return;
+ chip.classList.add('is-swapping');
+ });
+ const swap = () => {
+ chips.forEach((chip, i) => {
+ if (fresh[i]) chip.textContent = fresh[i];
+ chip.classList.remove('is-swapping');
+ });
+ };
+ if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) swap();
+ else setTimeout(swap, 180);
+ els.chipsMore?.classList.remove('is-rolling');
+ void els.chipsMore?.offsetWidth;
+ els.chipsMore?.classList.add('is-rolling');
+}
+
+if (els.prompt) {
+ els.prompt.addEventListener('input', updateCoach);
+ els.surprise?.addEventListener('click', surprise);
+ els.chipsMore?.addEventListener('click', shuffleChips);
+ // Reflect any value already present (remix ?prompt= prefill, restored draft).
+ updateCoach();
+}
diff --git a/src/forge-studio/forge-refine.js b/src/forge-studio/forge-refine.js
new file mode 100644
index 000000000..79561d524
--- /dev/null
+++ b/src/forge-studio/forge-refine.js
@@ -0,0 +1,419 @@
+// Refine — local, instant mesh refinement layered onto the forge result viewer.
+//
+// Unlike Stylize (/api/forge-stylize) and Optimize (/api/forge-remesh), which
+// dispatch jobs to GPU workers, Refine runs entirely in the browser: it parses
+// the current GLB with three's GLTFLoader, runs deterministic geometry passes
+// (weld / smooth normals / Laplacian relax / decimate / subdivide) from
+// shared/mesh-refine.js, re-exports with GLTFExporter, and swaps the live
+// <model-viewer> to the result. No worker, no API call, no rate limit — so it
+// works on every deployment and never 429s, which makes it the dependable
+// "improve this model" path when the paid generation lane is throttled.
+//
+// Non-destructive: the original GLB bytes are kept and every preset re-parses
+// from them, so applying a different preset (or reverting) is always clean.
+// Nothing fakes progress — the only timer is an honest elapsed counter, and the
+// geometry work is real synchronous compute behind a busy indicator.
+
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';
+import { refineScene, REFINE_PRESETS, REFINE_PRESET_BY_KEY, specForPreset } from '../shared/mesh-refine.js';
+
+const resultPanel = document.getElementById('state-result');
+const viewer = document.getElementById('viewer');
+
+if (resultPanel && viewer) {
+ // Reuse the forge anonymous client id (set by forge.js) for the source fetch,
+ // so a refine on a first-party CDN URL is attributed consistently. Harmless
+ // if absent; blob: sources ignore it entirely.
+ const CLIENT_HEADERS = (() => {
+ try {
+ const id = localStorage.getItem('forge:cid');
+ return id ? { 'x-forge-client': id } : {};
+ } catch {
+ return {};
+ }
+ })();
+
+ injectStyles();
+ const { panel, gallery, controls, slider, sliderLabel, sliderVal, applyBtn, downloadBtn, revertBtn, stats, status } =
+ injectPanel();
+
+ const loader = new GLTFLoader();
+ const exporter = new GLTFExporter();
+
+ let sourceUrl = ''; // the GLB this panel is refining (the forge result)
+ let sourceBytes = null; // ArrayBuffer of the original, kept for non-destructive re-runs
+ let lastRefinedUrl = ''; // object URL we swapped in; lets the src observer skip our own swap
+ let baseLabel = '';
+ let activeKey = '';
+ let runToken = 0; // bumped per apply/revert/new-source to abort stale work
+ let elapsedTimer = null;
+ let loadingBytes = false;
+
+ const nextFrame = () => new Promise((r) => requestAnimationFrame(() => r()));
+
+ function setStatus(text, kind = '') {
+ status.textContent = text || '';
+ status.dataset.kind = kind;
+ }
+
+ function stopElapsed() {
+ if (elapsedTimer) {
+ clearInterval(elapsedTimer);
+ elapsedTimer = null;
+ }
+ }
+
+ function startElapsed(label) {
+ stopElapsed();
+ const t0 = performance.now();
+ const tick = () => setStatus(`${label} — ${Math.floor((performance.now() - t0) / 1000)}s`, 'busy');
+ tick();
+ elapsedTimer = setInterval(tick, 1000);
+ }
+
+ function setBusy(busy) {
+ for (const card of gallery.querySelectorAll('.refine-card')) card.disabled = busy;
+ applyBtn.disabled = busy;
+ slider.disabled = busy;
+ revertBtn.disabled = busy;
+ panel.dataset.busy = busy ? 'true' : 'false';
+ }
+
+ function buildGallery() {
+ gallery.innerHTML = '';
+ for (const p of REFINE_PRESETS) {
+ const card = document.createElement('button');
+ card.type = 'button';
+ card.className = 'refine-card';
+ card.dataset.preset = p.key;
+ card.setAttribute('aria-pressed', 'false');
+ card.title = p.blurb;
+ card.innerHTML =
+ `<span class="refine-thumb" aria-hidden="true">${p.icon}</span>` +
+ `<span class="refine-name">${p.name}</span>` +
+ `<span class="refine-blurb">${p.blurb}</span>`;
+ card.addEventListener('click', () => selectPreset(p.key, { apply: true }));
+ gallery.appendChild(card);
+ }
+ }
+
+ function markActive(key) {
+ activeKey = key;
+ for (const card of gallery.querySelectorAll('.refine-card')) {
+ card.setAttribute('aria-pressed', String(card.dataset.preset === key));
+ }
+ }
+
+ function syncSlider(key) {
+ const spec = REFINE_PRESET_BY_KEY[key]?.slider;
+ if (!spec) {
+ controls.classList.add('no-slider');
+ slider.disabled = true;
+ sliderLabel.textContent = '';
+ sliderVal.textContent = '';
+ return;
+ }
+ controls.classList.remove('no-slider');
+ slider.disabled = false;
+ slider.min = String(spec.min);
+ slider.max = String(spec.max);
+ slider.step = '1';
+ slider.value = String(spec.def);
+ sliderLabel.textContent = spec.label;
+ sliderVal.textContent = `${spec.def}${spec.unit || ''}`;
+ }
+
+ function selectPreset(key, { apply }) {
+ if (!REFINE_PRESET_BY_KEY[key]) return;
+ markActive(key);
+ syncSlider(key);
+ controls.classList.remove('is-hidden');
+ if (apply) runRefine(key, Number(slider.value));
+ }
+
+ // Parse → refine → export, fully client-side. token guards against a newer
+ // run (or a new source model) superseding this one mid-flight.
+ async function runRefine(key, sliderValue) {
+ if (!sourceUrl) return;
+ const token = ++runToken;
+ const preset = REFINE_PRESET_BY_KEY[key];
+ const spec = specForPreset(key, sliderValue);
+ setBusy(true);
+ startElapsed(`Refining — ${preset.name}`);
+ try {
+ const bytes = await ensureSourceBytes();
+ if (token !== runToken) return;
+ if (!bytes) throw new Error('Could not read the model to refine.');
+
+ await nextFrame(); // let the busy indicator paint before the sync work
+ const gltf = await parseGlb(bytes);
+ if (token !== runToken) return;
+
+ await nextFrame();
+ const { before, after } = refineScene(gltf.scene, spec);
+
+ const glb = await exportGlb(gltf.scene);
+ if (token !== runToken) return;
+
+ const blob = new Blob([glb], { type: 'model/gltf-binary' });
+ const url = URL.createObjectURL(blob);
+ swapViewer(url, `${baseLabel} — ${preset.name} refine`);
+
+ downloadBtn.href = url;
+ downloadBtn.setAttribute('download', `${slugLabel()}-${key}.glb`);
+ downloadBtn.hidden = false;
+ revertBtn.hidden = false;
+
+ stopElapsed();
+ renderStats(before, after, blob.size);
+ setStatus(`${preset.name} applied — instant, on-device. Adjust and re-apply, or revert.`, 'done');
+ } catch (err) {
+ if (token !== runToken) return;
+ stopElapsed();
+ setBusy(false);
+ setStatus(err?.message || 'Refinement failed. Try a different preset.', 'error');
+ return;
+ }
+ if (token === runToken) setBusy(false);
+ }
+
+ function renderStats(before, after, byteSize) {
+ const dTri = after.triangles - before.triangles;
+ const pct = before.triangles > 0 ? Math.round((dTri / before.triangles) * 100) : 0;
+ const arrow = dTri === 0 ? '·' : dTri > 0 ? '▲' : '▼';
+ const triLine = `${fmt(before.triangles)} → ${fmt(after.triangles)} tris ${arrow}${pct ? ` ${Math.abs(pct)}%` : ''}`;
+ stats.innerHTML =
+ `<span class="refine-stat">${triLine}</span>` +
+ `<span class="refine-stat">${fmt(after.vertices)} verts</span>` +
+ `<span class="refine-stat">${fmtBytes(byteSize)}</span>`;
+ stats.hidden = false;
+ }
+
+ function swapViewer(url, alt) {
+ if (lastRefinedUrl && lastRefinedUrl !== sourceUrl) URL.revokeObjectURL(lastRefinedUrl);
+ lastRefinedUrl = url;
+ viewer.setAttribute('src', url);
+ viewer.setAttribute('alt', alt);
+ }
+
+ function revert() {
+ runToken++; // abort any in-flight refine
+ stopElapsed();
+ setBusy(false);
+ if (lastRefinedUrl && lastRefinedUrl !== sourceUrl) {
+ URL.revokeObjectURL(lastRefinedUrl);
+ lastRefinedUrl = '';
+ }
+ viewer.setAttribute('src', sourceUrl);
+ viewer.setAttribute('alt', baseLabel || '3D model');
+ downloadBtn.hidden = true;
+ revertBtn.hidden = true;
+ stats.hidden = true;
+ markActive('');
+ setStatus('Showing the original model.', '');
+ }
+
+ // Fetch the source bytes once and cache them, so re-applying a preset or
+ // switching presets never re-downloads. Both first-party URLs and blob: URLs
+ // (a chained result from Stylize/Optimize) are fetchable here.
+ async function ensureSourceBytes() {
+ if (sourceBytes) return sourceBytes;
+ if (loadingBytes) {
+ // A concurrent call is already fetching — wait for it.
+ while (loadingBytes) await new Promise((r) => setTimeout(r, 30));
+ return sourceBytes;
+ }
+ loadingBytes = true;
+ try {
+ const res = await fetch(sourceUrl, { headers: CLIENT_HEADERS });
+ if (!res.ok) throw new Error(`Couldn't load the model (${res.status}).`);
+ sourceBytes = await res.arrayBuffer();
+ return sourceBytes;
+ } finally {
+ loadingBytes = false;
+ }
+ }
+
+ function parseGlb(arrayBuffer) {
+ // Parse a *copy* of the buffer: GLTFLoader.parse can detach/consume the
+ // ArrayBuffer, and we keep the original for every subsequent re-run.
+ const copy = arrayBuffer.slice(0);
+ return new Promise((resolve, reject) => {
+ loader.parse(copy, '', resolve, reject);
+ });
+ }
+
+ function exportGlb(scene) {
+ return new Promise((resolve, reject) => {
+ exporter.parse(scene, resolve, reject, { binary: true });
+ });
+ }
+
+ function slugLabel() {
+ return (baseLabel || 'forge').replace(/[^a-z0-9]+/gi, '-').slice(0, 40).replace(/^-|-$/g, '') || 'forge';
+ }
+
+ // A new source model became available — reset to the idle gallery for it.
+ // Idempotent: re-firing with the current source (or our own refined swap) is
+ // a no-op so the event and the src observer can both call it safely.
+ function onNewSource(url, label) {
+ if (!url || url === sourceUrl || url === lastRefinedUrl) return;
+ runToken++;
+ stopElapsed();
+ sourceUrl = url;
+ sourceBytes = null;
+ lastRefinedUrl = '';
+ baseLabel = label || '';
+ markActive('');
+ controls.classList.add('is-hidden');
+ downloadBtn.hidden = true;
+ revertBtn.hidden = true;
+ stats.hidden = true;
+ setBusy(false);
+ setStatus('Pick a refinement to perfect this model — instant, on-device, unlimited.', '');
+ panel.hidden = false;
+ }
+
+ // Wiring -------------------------------------------------------------------
+ slider.addEventListener('input', () => {
+ const spec = REFINE_PRESET_BY_KEY[activeKey]?.slider;
+ sliderVal.textContent = `${slider.value}${spec?.unit || ''}`;
+ });
+ // Re-apply only when the user releases the slider, so dragging doesn't fire a
+ // parse+export on every integer step.
+ slider.addEventListener('change', () => {
+ if (activeKey) runRefine(activeKey, Number(slider.value));
+ });
+ applyBtn.addEventListener('click', () => {
+ if (activeKey) runRefine(activeKey, Number(slider.value));
+ });
+ revertBtn.addEventListener('click', revert);
+
+ document.addEventListener('forge:model-ready', (e) => {
+ onNewSource(e.detail?.glbUrl, e.detail?.label);
+ });
+
+ // External request (e.g. the rate-limit error CTA in forge.js) to surface and
+ // focus this panel so the user can refine locally instead of waiting.
+ document.addEventListener('forge:refine-here', () => {
+ if (!sourceUrl) return;
+ panel.hidden = false;
+ panel.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ gallery.querySelector('.refine-card')?.focus();
+ });
+
+ // Resilient fallback: watch the viewer src so the panel reveals on any model
+ // load, even without the explicit event. Our own swaps are ignored.
+ const srcObserver = new MutationObserver(() => {
+ const url = viewer.getAttribute('src');
+ if (!url || url === sourceUrl || url === lastRefinedUrl) return;
+ onNewSource(url, document.getElementById('result-label')?.textContent?.trim() || '');
+ });
+ srcObserver.observe(viewer, { attributes: true, attributeFilter: ['src'] });
+
+ if (viewer.getAttribute('src')) {
+ onNewSource(viewer.getAttribute('src'), document.getElementById('result-label')?.textContent?.trim() || '');
+ }
+
+ buildGallery();
+
+ // ── markup + styles (self-contained so the panel survives template edits) ──
+
+ function injectPanel() {
+ const el = document.createElement('div');
+ el.className = 'refine-panel';
+ el.id = 'refine-panel';
+ el.dataset.busy = 'false';
+ el.hidden = true;
+ el.innerHTML = `
+ <div class="refine-head">
+ <h3>Refine <span class="refine-badge">Instant · on-device · free</span></h3>
+ <p class="refine-sub">
+ Perfect the model you already have — no re-generation, no waiting, no limits.
+ Every preset runs in your browser on the live mesh.
+ </p>
+ </div>
+ <div class="refine-gallery" id="refine-gallery" role="group" aria-label="Refinement presets"></div>
+ <div class="refine-controls is-hidden" id="refine-controls">
+ <div class="refine-slider">
+ <label id="refine-slider-label" for="refine-slider"></label>
+ <input type="range" id="refine-slider" min="1" max="8" value="3" />
+ <output id="refine-slider-val" for="refine-slider"></output>
+ </div>
+ <div class="refine-actions">
+ <button class="btn btn-ghost" type="button" id="refine-apply">Re-apply</button>
+ <a class="btn btn-ghost" id="refine-download" download hidden>Download refined GLB</a>
+ <button class="btn btn-ghost" type="button" id="refine-revert" hidden>Revert to original</button>
+ </div>
+ </div>
+ <div class="refine-stats" id="refine-stats" hidden></div>
+ <div class="refine-status" id="refine-status" role="status" aria-live="polite"></div>
+ `;
+ // Place directly after the Stylize panel when present, else at panel end,
+ // so the three "improve this model" surfaces sit together.
+ const anchor = document.getElementById('stylize-panel');
+ if (anchor && anchor.parentElement === resultPanel) anchor.after(el);
+ else resultPanel.appendChild(el);
+ return {
+ panel: el,
+ gallery: el.querySelector('#refine-gallery'),
+ controls: el.querySelector('#refine-controls'),
+ slider: el.querySelector('#refine-slider'),
+ sliderLabel: el.querySelector('#refine-slider-label'),
+ sliderVal: el.querySelector('#refine-slider-val'),
+ applyBtn: el.querySelector('#refine-apply'),
+ downloadBtn: el.querySelector('#refine-download'),
+ revertBtn: el.querySelector('#refine-revert'),
+ stats: el.querySelector('#refine-stats'),
+ status: el.querySelector('#refine-status'),
+ };
+ }
+
+ function injectStyles() {
+ if (document.getElementById('refine-panel-styles')) return;
+ const style = document.createElement('style');
+ style.id = 'refine-panel-styles';
+ style.textContent = `
+ .refine-panel { margin-top: var(--space-lg, 24px); padding-top: var(--space-md, 16px); border-top: 1px solid var(--stroke, rgba(255,255,255,.08)); }
+ .refine-head h3 { display:flex; align-items:center; gap:8px; flex-wrap:wrap; margin:0 0 4px; font-family: var(--font-display, inherit); font-size: var(--text-lg, 1.1rem); color: var(--ink, #fff); }
+ .refine-badge { font-family: var(--font-mono, monospace); font-size: 10px; letter-spacing:.04em; text-transform:uppercase; color: var(--accent, #7c9cff); background: var(--accent-soft, rgba(124,156,255,.12)); border:1px solid var(--stroke, rgba(255,255,255,.1)); border-radius: 999px; padding: 2px 8px; }
+ .refine-sub { margin:0 0 var(--space-md,16px); font-size: var(--text-sm, .85rem); color: var(--ink-dim, #9aa); line-height: var(--leading-normal, 1.5); max-width: 56ch; }
+ .refine-gallery { display:grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: var(--space-sm, 10px); }
+ .refine-card { display:flex; flex-direction:column; align-items:flex-start; gap:4px; text-align:left; padding: var(--space-sm,10px) var(--space-md,14px); background: var(--surface-1, rgba(255,255,255,.03)); border:1px solid var(--stroke, rgba(255,255,255,.1)); border-radius: var(--radius-md, 10px); color: var(--ink, #fff); cursor:pointer; transition: border-color .15s, background .15s, transform .1s; }
+ .refine-card:hover { border-color: var(--stroke-strong, rgba(255,255,255,.25)); background: var(--surface-2, rgba(255,255,255,.05)); }
+ .refine-card:active { transform: translateY(1px); }
+ .refine-card:focus-visible { outline: 2px solid var(--accent, #7c9cff); outline-offset: 2px; }
+ .refine-card[aria-pressed="true"] { border-color: var(--accent, #7c9cff); background: var(--accent-soft, rgba(124,156,255,.12)); }
+ .refine-card:disabled { opacity:.5; cursor: progress; }
+ .refine-thumb { font-size: 18px; line-height:1; color: var(--accent, #7c9cff); }
+ .refine-name { font-weight:600; font-size: var(--text-sm, .9rem); }
+ .refine-blurb { font-size: var(--text-xs, .72rem); color: var(--ink-dim, #9aa); line-height:1.4; }
+ .refine-controls { margin-top: var(--space-md,16px); display:flex; flex-direction:column; gap: var(--space-sm,10px); }
+ .refine-controls.no-slider .refine-slider { display:none; }
+ .refine-slider { display:flex; align-items:center; gap: var(--space-sm,10px); }
+ .refine-slider label { font-size: var(--text-xs,.72rem); color: var(--ink-dim,#9aa); min-width: 110px; }
+ .refine-slider input[type=range] { flex:1; accent-color: var(--accent, #7c9cff); }
+ .refine-slider output { font-family: var(--font-mono, monospace); font-size: var(--text-xs,.72rem); color: var(--ink,#fff); min-width: 40px; text-align:right; }
+ .refine-actions { display:flex; flex-wrap:wrap; gap: var(--space-sm,8px); }
+ .refine-stats { display:flex; flex-wrap:wrap; gap: var(--space-sm,10px); margin-top: var(--space-sm,10px); }
+ .refine-stat { font-family: var(--font-mono, monospace); font-size: var(--text-xs,.72rem); color: var(--ink-dim,#9aa); background: var(--surface-1, rgba(255,255,255,.03)); border:1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-sm,6px); padding: 3px 8px; }
+ .refine-status { margin-top: var(--space-sm,10px); font-size: var(--text-xs,.72rem); min-height: 1.2em; color: var(--ink-dim,#9aa); }
+ .refine-status[data-kind="busy"] { color: var(--accent, #7c9cff); }
+ .refine-status[data-kind="done"] { color: var(--success, #5fd38a); }
+ .refine-status[data-kind="error"] { color: var(--danger, #ff6b6b); }
+ @media (prefers-reduced-motion: reduce) { .refine-card { transition: none; } }
+ `;
+ document.head.appendChild(style);
+ }
+
+ function fmt(n) {
+ return Number(n || 0).toLocaleString();
+ }
+ function fmtBytes(b) {
+ if (!b) return '—';
+ if (b < 1024) return `${b} B`;
+ if (b < 1024 * 1024) return `${(b / 1024).toFixed(1)} KB`;
+ return `${(b / (1024 * 1024)).toFixed(2)} MB`;
+ }
+}
diff --git a/src/forge-studio/forge-reveal.js b/src/forge-studio/forge-reveal.js
new file mode 100644
index 000000000..92e1349cc
--- /dev/null
+++ b/src/forge-studio/forge-reveal.js
@@ -0,0 +1,353 @@
+// Forge reveal — the cinematic materialize entrance for a forged model.
+//
+// Plays in its own WebGL overlay above the result <model-viewer>: the mesh
+// resolves through a rising noise dissolve whose frontier glows in the page
+// accent while a wireframe ghost fades out, the camera dollies in, and a
+// contact shadow blooms underneath. Once the dissolve lands (and the standing
+// viewer below reports loaded) the overlay crossfades away — same GLB, already
+// in the HTTP cache, so the swap is seamless.
+//
+// Presentation only, never a dependency: any failure (no WebGL, loader error,
+// timeout) resolves immediately and the standing viewer is untouched. Honors
+// prefers-reduced-motion by not playing at all.
+
+const REVEAL_DELAY_MS = 200; // beat before the dissolve starts
+const DISSOLVE_MS = 2100; // wireframe ghost → textured surface
+const MIN_HOLD_MS = 450; // settle time after the dissolve completes
+const MAX_WAIT_MS = 6000; // cap on waiting for the viewer underneath
+const LOAD_TIMEOUT_MS = 12000; // give up on the GLB fetch beyond this
+const FADE_OUT_MS = 420; // overlay crossfade duration (mirrored in CSS)
+const TURNTABLE_DEG_PER_S = 14; // continuous yaw across the whole sequence
+
+// One reveal at a time — opening another creation mid-sequence cancels the
+// running one before its overlay can fight the new one for the same shell.
+let activeCancel = null;
+
+function accentColor() {
+ const v = getComputedStyle(document.documentElement).getPropertyValue('--accent').trim();
+ return v || '#4fc3ff';
+}
+
+const easeInOut = (t) => (t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2);
+const easeOut = (t) => 1 - (1 - t) ** 3;
+
+// GLSL injected into every material of the loaded model via onBeforeCompile:
+// a world-space value noise drives a discard threshold (the dissolve) and an
+// additive emissive band right at the frontier (the glow).
+const NOISE_GLSL = /* glsl */ `
+ uniform float uDissolve;
+ uniform vec3 uEdgeColor;
+ uniform float uEdgeWidth;
+ varying vec3 vForgeWorld;
+ float forgeHash( vec3 p ) {
+ p = fract( p * 0.3183099 + vec3( 0.71, 0.113, 0.419 ) );
+ p *= 17.0;
+ return fract( p.x * p.y * p.z * ( p.x + p.y + p.z ) );
+ }
+ float forgeNoise( vec3 x ) {
+ vec3 i = floor( x );
+ vec3 f = fract( x );
+ f = f * f * ( 3.0 - 2.0 * f );
+ return mix(
+ mix( mix( forgeHash( i ), forgeHash( i + vec3( 1, 0, 0 ) ), f.x ),
+ mix( forgeHash( i + vec3( 0, 1, 0 ) ), forgeHash( i + vec3( 1, 1, 0 ) ), f.x ), f.y ),
+ mix( mix( forgeHash( i + vec3( 0, 0, 1 ) ), forgeHash( i + vec3( 1, 0, 1 ) ), f.x ),
+ mix( forgeHash( i + vec3( 0, 1, 1 ) ), forgeHash( i + vec3( 1, 1, 1 ) ), f.x ), f.y ),
+ f.z );
+ }
+`;
+
+function patchMaterial(material, uniforms) {
+ material.onBeforeCompile = (shader) => {
+ shader.uniforms.uDissolve = uniforms.uDissolve;
+ shader.uniforms.uEdgeColor = uniforms.uEdgeColor;
+ shader.uniforms.uEdgeWidth = uniforms.uEdgeWidth;
+ shader.vertexShader = shader.vertexShader
+ .replace('void main() {', 'varying vec3 vForgeWorld;\nvoid main() {')
+ .replace(
+ '#include <project_vertex>',
+ '#include <project_vertex>\n\tvForgeWorld = ( modelMatrix * vec4( transformed, 1.0 ) ).xyz;',
+ );
+ shader.fragmentShader = shader.fragmentShader
+ .replace('void main() {', `${NOISE_GLSL}\nvoid main() {`)
+ .replace(
+ '#include <clipping_planes_fragment>',
+ [
+ '#include <clipping_planes_fragment>',
+ '\tfloat forgeN = forgeNoise( vForgeWorld * 3.2 );',
+ '\tfloat forgeReveal = uDissolve * ( 1.0 + uEdgeWidth * 2.0 ) - uEdgeWidth;',
+ '\tif ( forgeN > forgeReveal + uEdgeWidth ) discard;',
+ ].join('\n'),
+ )
+ .replace(
+ '#include <dithering_fragment>',
+ [
+ '\tfloat forgeBand = smoothstep( forgeReveal - uEdgeWidth, forgeReveal + uEdgeWidth, forgeN );',
+ '\tgl_FragColor.rgb += uEdgeColor * forgeBand * 2.2;',
+ '#include <dithering_fragment>',
+ ].join('\n'),
+ );
+ };
+ // Distinct cache key so three doesn't reuse the unpatched program.
+ material.customProgramCacheKey = () => 'forge-dissolve';
+ material.needsUpdate = true;
+}
+
+// Soft radial contact shadow — a canvas gradient on a ground plane, no
+// shadow-map pass needed for a single hero object.
+function makeContactShadow(THREE) {
+ const c = document.createElement('canvas');
+ c.width = c.height = 256;
+ const ctx = c.getContext('2d');
+ const g = ctx.createRadialGradient(128, 128, 8, 128, 128, 124);
+ g.addColorStop(0, 'rgba(0,0,0,0.62)');
+ g.addColorStop(0.6, 'rgba(0,0,0,0.22)');
+ g.addColorStop(1, 'rgba(0,0,0,0)');
+ ctx.fillStyle = g;
+ ctx.fillRect(0, 0, 256, 256);
+ const tex = new THREE.CanvasTexture(c);
+ const mat = new THREE.MeshBasicMaterial({
+ map: tex,
+ transparent: true,
+ opacity: 0,
+ depthWrite: false,
+ });
+ const mesh = new THREE.Mesh(new THREE.PlaneGeometry(4.2, 4.2), mat);
+ mesh.rotation.x = -Math.PI / 2;
+ mesh.position.y = 0.001;
+ mesh.renderOrder = -1;
+ return mesh;
+}
+
+/**
+ * Play the materialize sequence over `container` (made position:relative if
+ * static). `waitFor` is an optional promise the overlay holds its turntable
+ * for before fading — pass the underlying model-viewer's load so the swap
+ * never reveals an empty viewer. Resolves with the final camera orbit
+ * ({ azimuthDeg, polarDeg }) for handoff, or null when skipped/cancelled.
+ */
+export async function playForgeReveal({ container, glbUrl, waitFor }) {
+ if (!container || !glbUrl) return null;
+ if (typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches) {
+ return null;
+ }
+ if (activeCancel) activeCancel();
+
+ let cancelled = false;
+ let cleanupFns = [];
+ const cancel = () => {
+ cancelled = true;
+ for (const fn of cleanupFns.splice(0)) {
+ try {
+ fn();
+ } catch {
+ /* disposal best-effort */
+ }
+ }
+ };
+ activeCancel = cancel;
+
+ try {
+ const [THREE, { GLTFLoader }, { RoomEnvironment }] = await Promise.all([
+ import('three'),
+ import('three/addons/loaders/GLTFLoader.js'),
+ import('three/addons/environments/RoomEnvironment.js'),
+ ]);
+ if (cancelled) return null;
+
+ // Fetch + parse the GLB first — the overlay only ever appears with a
+ // model in hand, so a slow or failed load degrades to the plain viewer.
+ const gltf = await Promise.race([
+ new GLTFLoader().loadAsync(glbUrl),
+ new Promise((resolve) => setTimeout(() => resolve(null), LOAD_TIMEOUT_MS)),
+ ]);
+ if (!gltf || cancelled) return null;
+
+ // Overlay scaffold ----------------------------------------------------
+ if (getComputedStyle(container).position === 'static') {
+ container.style.position = 'relative';
+ }
+ const overlay = document.createElement('div');
+ overlay.className = 'forge-reveal-overlay';
+ overlay.setAttribute('aria-hidden', 'true');
+ container.appendChild(overlay);
+ cleanupFns.push(() => overlay.remove());
+
+ const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
+ renderer.toneMappingExposure = 1.6;
+ overlay.appendChild(renderer.domElement);
+ cleanupFns.push(() => renderer.dispose());
+
+ const scene = new THREE.Scene();
+ const pmrem = new THREE.PMREMGenerator(renderer);
+ const envTex = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
+ pmrem.dispose();
+ scene.environment = envTex;
+ cleanupFns.push(() => envTex.dispose());
+
+ // TRELLIS models can bake in dark textures; supplement IBL with explicit
+ // lights so the mesh reads clearly regardless of how dark the bake is.
+ const hemi = new THREE.HemisphereLight(0xffffff, 0x8899bb, 1.8);
+ scene.add(hemi);
+ const key = new THREE.DirectionalLight(0xffffff, 2.5);
+ key.position.set(1, 1.5, 1.2);
+ scene.add(key);
+ const fill = new THREE.DirectionalLight(0xddeeff, 0.8);
+ fill.position.set(-1, 0.5, -0.5);
+ scene.add(fill);
+
+ const camera = new THREE.PerspectiveCamera(32, 1, 0.05, 60);
+ const target = new THREE.Vector3(0, 0.62, 0);
+
+ const sizeToContainer = () => {
+ const w = Math.max(1, container.clientWidth);
+ const h = Math.max(1, container.clientHeight);
+ renderer.setSize(w, h, false);
+ camera.aspect = w / h;
+ camera.updateProjectionMatrix();
+ };
+ sizeToContainer();
+ const ro = new ResizeObserver(sizeToContainer);
+ ro.observe(container);
+ cleanupFns.push(() => ro.disconnect());
+
+ // Model: center on origin, ground at y=0, fit to a ~2-unit frame.
+ const model = gltf.scene;
+ const box = new THREE.Box3().setFromObject(model);
+ const size = box.getSize(new THREE.Vector3());
+ const center = box.getCenter(new THREE.Vector3());
+ const scale = 2 / Math.max(size.x, size.y, size.z, 0.0001);
+ model.scale.setScalar(scale);
+ model.position.set(-center.x * scale, -box.min.y * scale, -center.z * scale);
+
+ const uniforms = {
+ uDissolve: { value: 0 },
+ uEdgeColor: { value: new THREE.Color(accentColor()) },
+ uEdgeWidth: { value: 0.045 },
+ };
+ model.traverse((node) => {
+ if (!node.isMesh) return;
+ const mats = Array.isArray(node.material) ? node.material : [node.material];
+ for (const m of mats) if (m) patchMaterial(m, uniforms);
+ });
+
+ // Wireframe ghost — the model's silhouette before it has a surface.
+ const ghostMat = new THREE.MeshBasicMaterial({
+ color: new THREE.Color(accentColor()),
+ wireframe: true,
+ transparent: true,
+ opacity: 0,
+ depthWrite: false,
+ });
+ const ghost = model.clone(true);
+ ghost.traverse((node) => {
+ if (node.isMesh) node.material = ghostMat;
+ });
+ ghost.scale.multiplyScalar(1.002);
+
+ const shadow = makeContactShadow(THREE);
+ scene.add(model, ghost, shadow);
+ cleanupFns.push(() => {
+ scene.traverse((node) => {
+ if (node.isMesh) {
+ node.geometry?.dispose?.();
+ const mats = Array.isArray(node.material) ? node.material : [node.material];
+ for (const m of mats) m?.dispose?.();
+ }
+ });
+ });
+
+ // Timeline --------------------------------------------------------------
+ const startAzimuth = -0.7; // radians; drifts continuously from here
+ let azimuth = startAzimuth;
+ let polar = Math.PI / 2.6;
+
+ const animateUntil = (predicate, onFrame) =>
+ new Promise((resolve) => {
+ const t0 = performance.now();
+ const frame = (now) => {
+ if (cancelled) return resolve();
+ const t = now - t0;
+ onFrame(t, now);
+ if (predicate(t)) return resolve();
+ requestAnimationFrame(frame);
+ };
+ requestAnimationFrame(frame);
+ });
+
+ const renderFrame = (t) => {
+ const total = (t + REVEAL_DELAY_MS) / 1000;
+ azimuth = startAzimuth + THREE.MathUtils.degToRad(TURNTABLE_DEG_PER_S) * total;
+ const dolly = easeOut(Math.min(1, t / (DISSOLVE_MS + MIN_HOLD_MS)));
+ const radius = 4.4 - 1.15 * dolly;
+ polar = Math.PI / 2.6 + 0.12 * dolly;
+ camera.position.set(
+ target.x + radius * Math.sin(polar) * Math.sin(azimuth),
+ target.y + radius * Math.cos(polar),
+ target.z + radius * Math.sin(polar) * Math.cos(azimuth),
+ );
+ camera.lookAt(target);
+ renderer.render(scene, camera);
+ };
+
+ // Beat 1: the ghost rises out of nothing.
+ await animateUntil(
+ (t) => t >= REVEAL_DELAY_MS,
+ (t) => {
+ ghostMat.opacity = 0.3 * easeOut(Math.min(1, t / REVEAL_DELAY_MS));
+ renderFrame(t - REVEAL_DELAY_MS);
+ },
+ );
+ if (cancelled) return null;
+
+ // Beat 2: the dissolve sweeps the surface in; the ghost yields to it.
+ await animateUntil(
+ (t) => t >= DISSOLVE_MS,
+ (t) => {
+ const d = easeInOut(Math.min(1, t / DISSOLVE_MS));
+ uniforms.uDissolve.value = d;
+ ghostMat.opacity = 0.3 * (1 - d);
+ shadow.material.opacity = 0.62 * d;
+ renderFrame(t);
+ },
+ );
+ if (cancelled) return null;
+ uniforms.uDissolve.value = 1;
+ ghostMat.opacity = 0;
+
+ // Beat 3: hold the turntable until the viewer underneath is ready.
+ const ready = Promise.race([
+ Promise.resolve(waitFor).catch(() => {}),
+ new Promise((resolve) => setTimeout(resolve, MAX_WAIT_MS)),
+ ]);
+ let viewerReady = false;
+ ready.then(() => {
+ viewerReady = true;
+ });
+ await animateUntil(
+ (t) => t >= MIN_HOLD_MS && viewerReady,
+ (t) => renderFrame(DISSOLVE_MS + t),
+ );
+ if (cancelled) return null;
+
+ // Beat 4: crossfade out — keep rendering through the fade so the
+ // turntable never freezes mid-swap.
+ overlay.classList.add('is-fading');
+ await animateUntil(
+ (t) => t >= FADE_OUT_MS,
+ (t) => renderFrame(DISSOLVE_MS + MIN_HOLD_MS + t),
+ );
+
+ const azimuthDeg = THREE.MathUtils.radToDeg(azimuth) % 360;
+ const polarDeg = THREE.MathUtils.radToDeg(polar);
+ cancel();
+ return { azimuthDeg, polarDeg };
+ } catch {
+ cancel();
+ return null;
+ } finally {
+ if (activeCancel === cancel) activeCancel = null;
+ }
+}
diff --git a/src/forge-studio/forge-showcase.js b/src/forge-studio/forge-showcase.js
new file mode 100644
index 000000000..01b7dda46
--- /dev/null
+++ b/src/forge-studio/forge-showcase.js
@@ -0,0 +1,424 @@
+// Forge community showcase — "Fresh from the Forge".
+//
+// Renders the newest finished models across all Forge users into the
+// #showcase section on /forge (GET /api/forge-gallery?scope=community).
+// Two affordances per card:
+// • click the card → opens the model in the page's main viewer via the
+// `forge:open-creation` hook in src/forge.js, so the full result bar
+// (download, share, stylize, optimize, split) works on it
+// • Remix → copies the creation's prompt into the composer and
+// focuses it, so a visitor starts from something that demonstrably works
+//
+// The section stays hidden when the deployment has no durable store or the
+// feed is empty — a first-time visitor never sees a broken or hollow strip.
+
+import { skeletonHTML, errorStateHTML, ensureStateKitStyles } from '../shared/state-kit.js';
+ensureStateKitStyles();
+
+const ENGINE_LABELS = { nvidia: 'Free', trellis: 'Fast', meshy: 'Meshy', tripo: 'Tripo', hunyuan3d: 'Hunyuan3D', triposg: 'TripoSG' };
+
+const MODEL_CAT_LABELS = {
+ avatar: 'Avatar', accessory: 'Accessory', item: 'Item',
+ scene: 'Scene', creature: 'Creature', vehicle: 'Vehicle', other: 'Other',
+};
+
+// ── Thumbnail fallback chain ──────────────────────────────────────────────────
+// Plan A: preview_image_url from DB → <img>
+// Plan B: img onerror or no preview_image_url + has glb_url → capture a frame
+// from a hidden <model-viewer> (queued, max 1 concurrent load so we
+// don't slam the network with a dozen 10MB GLBs simultaneously)
+// Plan C: model-viewer fails / times out → gradient card generated from prompt
+// Plan D: no glb_url at all → gradient card
+
+const CAPTURE_TIMEOUT_MS = 20_000;
+const captureQueue = [];
+let captureActive = false;
+
+function drainCaptureQueue() {
+ if (captureActive || captureQueue.length === 0) return;
+ captureActive = true;
+ const { card, glbUrl, resolve } = captureQueue.shift();
+ captureFromGlb(card, glbUrl)
+ .then(resolve)
+ .catch(() => resolve(null))
+ .finally(() => {
+ captureActive = false;
+ drainCaptureQueue();
+ });
+}
+
+function enqueueCaptureFromGlb(card, glbUrl) {
+ return new Promise((resolve) => {
+ captureQueue.push({ card, glbUrl, resolve });
+ drainCaptureQueue();
+ });
+}
+
+async function captureFromGlb(card, glbUrl) {
+ if (!window.customElements?.get('model-viewer')) return null;
+ return new Promise((resolve) => {
+ const viewer = document.createElement('model-viewer');
+ // Render at a real resolution off-screen — model-viewer sizes its WebGL
+ // canvas to the element box, so a 1px element would capture a 1px frame
+ // (a solid block once stretched over the 200px thumb). 384px gives a
+ // crisp, retina-ish thumbnail. position:fixed keeps it out of layout;
+ // opacity:0 + negative z-index keep it invisible while it still paints.
+ viewer.style.cssText =
+ 'position:fixed;left:0;top:0;width:384px;height:384px;opacity:0;pointer-events:none;z-index:-1;';
+ viewer.setAttribute('src', glbUrl);
+ viewer.setAttribute('shadow-intensity', '0');
+ viewer.setAttribute('exposure', '0.9');
+ viewer.setAttribute('environment-image', 'neutral');
+ viewer.setAttribute('aria-hidden', 'true');
+
+ let done = false;
+ const finish = (dataUrl) => {
+ if (done) return;
+ done = true;
+ clearTimeout(timer);
+ viewer.remove();
+ resolve(dataUrl);
+ };
+
+ const timer = setTimeout(() => finish(null), CAPTURE_TIMEOUT_MS);
+
+ viewer.addEventListener(
+ 'load',
+ async () => {
+ try {
+ // Brief settle so the mesh textures are uploaded to GPU.
+ await new Promise((r) => setTimeout(r, 800));
+ const url = viewer.toDataURL?.('image/webp') ?? null;
+ // A real 384px model render encodes to several KB; a blank or
+ // transparent frame compresses to a few hundred bytes. Reject
+ // the near-empty case so the readable gradient+prompt fallback
+ // wins instead of an invisible card.
+ finish(url && url.length > 1024 ? url : null);
+ } catch {
+ finish(null);
+ }
+ },
+ { once: true },
+ );
+ viewer.addEventListener('error', () => finish(null), { once: true });
+
+ document.body.appendChild(viewer);
+ });
+}
+
+// Deterministic gradient from a string — same prompt always gets the same colours.
+function promptGradient(str) {
+ let h = 0;
+ for (let i = 0; i < (str || '').length; i++) h = (Math.imul(31, h) + str.charCodeAt(i)) | 0;
+ const hue = Math.abs(h) % 360;
+ const hue2 = (hue + 40) % 360;
+ return `linear-gradient(135deg, hsl(${hue},28%,14%) 0%, hsl(${hue2},22%,10%) 100%)`;
+}
+
+function applyGradientFallback(card, prompt) {
+ const existing = card.querySelector('.thumb');
+ if (existing) existing.remove();
+ if (card.querySelector('.thumb.gradient-ph')) return;
+ const ph = document.createElement('span');
+ ph.className = 'thumb gradient-ph';
+ ph.style.background = promptGradient(prompt);
+ // Show the prompt text as the visual — makes the card feel intentional, not broken.
+ if (prompt) {
+ const label = document.createElement('span');
+ label.className = 'gradient-ph-text';
+ label.textContent = prompt;
+ ph.appendChild(label);
+ }
+ card.prepend(ph);
+}
+
+// IntersectionObserver: only attempt GLB capture when the card is actually
+// visible — no wasted work on cards the user never scrolls to.
+const captureObserver =
+ 'IntersectionObserver' in window
+ ? new IntersectionObserver(
+ (entries) => {
+ entries.forEach((e) => {
+ if (!e.isIntersecting) return;
+ captureObserver.unobserve(e.target);
+ const card = e.target;
+ const glbUrl = card.dataset.glbUrl;
+ if (!glbUrl) return;
+ enqueueCaptureFromGlb(card, glbUrl).then((dataUrl) => {
+ if (dataUrl) {
+ const img = document.createElement('img');
+ img.className = 'thumb';
+ img.loading = 'lazy';
+ img.alt = '';
+ img.src = dataUrl;
+ img.onerror = () => applyGradientFallback(card, card.title);
+ const existing = card.querySelector('.thumb');
+ existing ? existing.replaceWith(img) : card.prepend(img);
+ } else {
+ applyGradientFallback(card, card.title);
+ }
+ });
+ });
+ },
+ { rootMargin: '200px' },
+ )
+ : null;
+
+const els = {
+ section: document.getElementById('showcase'),
+ grid: document.getElementById('showcase-grid'),
+ count: document.getElementById('showcase-count'),
+ refresh: document.getElementById('showcase-refresh'),
+};
+
+// "3m ago" / "2h ago" / "5d ago" — compact, no library.
+function timeAgo(iso) {
+ const t = Date.parse(iso);
+ if (!Number.isFinite(t)) return '';
+ const s = Math.max(0, (Date.now() - t) / 1000);
+ if (s < 60) return 'just now';
+ if (s < 3600) return `${Math.floor(s / 60)}m ago`;
+ if (s < 86400) return `${Math.floor(s / 3600)}h ago`;
+ return `${Math.floor(s / 86400)}d ago`;
+}
+
+function buildCard(c) {
+ const card = document.createElement('div');
+ card.className = 'creation showcase-card';
+ card.tabIndex = 0;
+ card.setAttribute('role', 'button');
+ card.title = c.prompt || 'Forged model';
+ card.setAttribute('aria-label', `Open in viewer: ${c.prompt || 'forged model'}`);
+
+ if (c.preview_image_url) {
+ // Plan A: stored thumbnail
+ const img = document.createElement('img');
+ img.className = 'thumb';
+ img.loading = 'lazy';
+ img.alt = '';
+ img.src = c.preview_image_url;
+ img.onerror = () => {
+ // Plan B: image URL broken → try GLB capture, then gradient
+ if (c.glb_url) {
+ card.dataset.glbUrl = c.glb_url;
+ captureObserver ? captureObserver.observe(card) : applyGradientFallback(card, c.prompt);
+ } else {
+ applyGradientFallback(card, c.prompt);
+ }
+ };
+ card.appendChild(img);
+ } else if (c.glb_url) {
+ // Plan B: no thumbnail yet → gradient placeholder now, GLB capture when visible
+ applyGradientFallback(card, c.prompt);
+ card.dataset.glbUrl = c.glb_url;
+ captureObserver ? captureObserver.observe(card) : undefined;
+ } else {
+ // Plan C: no assets at all → gradient placeholder
+ applyGradientFallback(card, c.prompt);
+ }
+
+ // Engine · tier provenance, same convention as "Your creations".
+ if (c.backend || c.tier) {
+ const prov = document.createElement('span');
+ prov.className = 'badge';
+ prov.style.left = '6px';
+ prov.style.right = 'auto';
+ prov.textContent = [ENGINE_LABELS[c.backend] || c.backend, c.tier].filter(Boolean).join(' · ');
+ card.appendChild(prov);
+ }
+
+ attachHoverPreview(card, c);
+ if (Number(c.views_used) > 1) {
+ const mv = document.createElement('span');
+ mv.className = 'badge';
+ mv.textContent = `${c.views_used}×`;
+ mv.title = `${c.views_used} reference views`;
+ card.appendChild(mv);
+ }
+
+ const meta = document.createElement('span');
+ meta.className = 'meta';
+ meta.textContent = c.prompt || 'Untitled';
+ card.appendChild(meta);
+
+ const foot = document.createElement('div');
+ foot.className = 'showcase-foot';
+
+ const when = document.createElement('span');
+ when.className = 'showcase-when';
+ when.textContent = timeAgo(c.created_at);
+ foot.appendChild(when);
+
+ // Model category badge — shows what type of 3D model was forged.
+ const cat = c.model_category || 'other';
+ const catLabel = MODEL_CAT_LABELS[cat] || cat;
+ if (cat !== 'other') {
+ const catBadge = document.createElement('span');
+ catBadge.className = `showcase-cat-badge model-cat-${cat}`;
+ catBadge.textContent = catLabel;
+ catBadge.title = `Model category: ${catLabel}`;
+ foot.appendChild(catBadge);
+ }
+
+ // Remix — only meaningful when there is a prompt to start from.
+ if (c.prompt) {
+ const remix = document.createElement('button');
+ remix.type = 'button';
+ remix.className = 'showcase-remix';
+ remix.textContent = 'Remix';
+ remix.title = 'Copy this prompt into the composer';
+ remix.setAttribute('aria-label', `Remix prompt: ${c.prompt}`);
+ remix.addEventListener('click', (e) => {
+ e.stopPropagation();
+ remixPrompt(c.prompt);
+ });
+ foot.appendChild(remix);
+ }
+ card.appendChild(foot);
+
+ const open = () =>
+ document.dispatchEvent(new CustomEvent('forge:open-creation', { detail: { creation: c } }));
+ card.addEventListener('click', open);
+ card.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ open();
+ }
+ });
+
+ return card;
+}
+
+// Hover a card for a beat → its actual model spins in the thumb. One live
+// mini-viewer at a time (GLBs are megabytes; a grid of twelve would jank the
+// page), created only on real intent (300ms dwell) and torn down on leave.
+// <model-viewer> is already registered on this page. Pointer-only by design:
+// on touch, tapping the card opens the full viewer anyway.
+let activePreview = null; // { card, viewer }
+let previewTimer = null;
+
+function teardownHoverPreview() {
+ clearTimeout(previewTimer);
+ previewTimer = null;
+ if (activePreview) {
+ activePreview.viewer.remove();
+ activePreview.card.classList.remove('is-previewing');
+ activePreview = null;
+ }
+}
+
+function attachHoverPreview(card, c) {
+ if (!c.glb_url || !window.customElements?.get('model-viewer')) return;
+ if (matchMedia('(hover: none)').matches) return;
+
+ card.addEventListener('mouseenter', () => {
+ teardownHoverPreview();
+ previewTimer = setTimeout(() => {
+ const thumb = card.querySelector('.thumb');
+ if (!thumb) return;
+ const viewer = document.createElement('model-viewer');
+ viewer.className = 'showcase-preview';
+ viewer.setAttribute('src', c.glb_url);
+ viewer.setAttribute('auto-rotate', '');
+ viewer.setAttribute('auto-rotate-delay', '0');
+ viewer.setAttribute('rotation-per-second', '24deg');
+ viewer.setAttribute('interaction-prompt', 'none');
+ viewer.setAttribute('disable-zoom', '');
+ viewer.setAttribute('shadow-intensity', '0');
+ viewer.setAttribute('exposure', '0.9');
+ viewer.setAttribute('environment-image', 'neutral');
+ viewer.setAttribute('aria-hidden', 'true');
+ // Fade in only once the GLB is actually ready — no pop, no void.
+ viewer.addEventListener('load', () => card.classList.add('is-previewing'), { once: true });
+ thumb.insertAdjacentElement('afterend', viewer);
+ activePreview = { card, viewer };
+ }, 300);
+ });
+ card.addEventListener('mouseleave', teardownHoverPreview);
+}
+
+// Put the prompt in the composer, in text mode, ready to edit-and-Generate.
+function remixPrompt(prompt) {
+ document.querySelector('#mode-switch [data-mode="text"]')?.click();
+ const box = document.getElementById('prompt');
+ if (!box) return;
+ box.value = prompt;
+ box.dispatchEvent(new Event('input', { bubbles: true }));
+ box.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ // Delay focus + flash until after the scroll settles.
+ setTimeout(() => {
+ box.focus();
+ box.setSelectionRange(box.value.length, box.value.length);
+ // Flash the border so the user clearly sees the prompt landed.
+ box.classList.remove('remix-flash');
+ void box.offsetWidth; // force reflow to restart animation if clicked twice
+ box.classList.add('remix-flash');
+ box.addEventListener('animationend', () => box.classList.remove('remix-flash'), { once: true });
+ }, 300);
+ showRemixToast();
+}
+
+function showRemixToast() {
+ const existing = document.querySelector('.remix-toast');
+ if (existing) existing.remove();
+ const toast = document.createElement('div');
+ toast.className = 'remix-toast';
+ const dot = document.createElement('span');
+ dot.className = 'toast-dot';
+ dot.setAttribute('aria-hidden', 'true');
+ toast.appendChild(dot);
+ toast.appendChild(document.createTextNode('Prompt loaded — edit and Generate'));
+ document.body.appendChild(toast);
+ setTimeout(() => toast.classList.add('fade-out'), 2400);
+ setTimeout(() => toast.remove(), 2800);
+}
+
+async function loadShowcase() {
+ if (!els.section || !els.grid) return;
+
+ els.grid.setAttribute('aria-busy', 'true');
+ els.grid.innerHTML = skeletonHTML(4, 'card');
+ els.section.classList.remove('is-hidden');
+
+ let data;
+ try {
+ // Over-fetch, then dedupe near-identical prompts client-side — people
+ // re-roll the same prompt, and a feed of six teapots sells nothing.
+ const res = await fetch('/api/forge-gallery?scope=community&limit=24');
+ data = await res.json().catch(() => ({}));
+ } catch {
+ els.grid.removeAttribute('aria-busy');
+ els.grid.innerHTML = errorStateHTML({
+ title: "Couldn't load the community feed",
+ body: 'Check your connection and retry — generation itself is unaffected.',
+ });
+ els.grid.querySelector('[data-sk-retry]')?.addEventListener('click', loadShowcase);
+ return;
+ }
+
+ els.grid.removeAttribute('aria-busy');
+ const all = Array.isArray(data?.creations) ? data.creations : [];
+ const seen = new Set();
+ const creations = all
+ .filter((c) => {
+ const key = (c.prompt || c.id || '').toLowerCase().replace(/\s+/g, ' ').trim();
+ if (seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ })
+ .slice(0, 12);
+ if (!data?.enabled || creations.length === 0) {
+ // No durable store, or nothing forged yet — no hollow strip.
+ els.section.classList.add('is-hidden');
+ return;
+ }
+
+ teardownHoverPreview();
+ els.grid.innerHTML = '';
+ for (const c of creations) els.grid.appendChild(buildCard(c));
+ if (els.count) els.count.textContent = `${creations.length} recent`;
+}
+
+els.refresh?.addEventListener('click', loadShowcase);
+
+loadShowcase();
diff --git a/src/forge-studio/forge-stylize.js b/src/forge-studio/forge-stylize.js
new file mode 100644
index 000000000..3941bf3e4
--- /dev/null
+++ b/src/forge-studio/forge-stylize.js
@@ -0,0 +1,265 @@
+// Forge — Stylize panel (browser client).
+//
+// One-click geometric stylization layered onto the forge result viewer. When a
+// model becomes available (forge.js dispatches `forge:model-ready`), this panel
+// reveals a gallery of filters; clicking one runs a real geometry pass on
+// workers/stylize via /api/forge-stylize, polls to completion, and swaps the
+// live <model-viewer> to the stylized GLB. A density slider re-applies the
+// active filter; "Revert" restores the original. Nothing fakes progress — the
+// only timer is an honest elapsed counter.
+
+import { STYLIZE_FILTERS, STYLIZE_FILTER_BY_KEY } from '../shared/stylize-filters.js';
+
+const POLL_INTERVAL_MS = 2000;
+const MAX_POLL_MS = 3 * 60 * 1000;
+
+const panel = document.getElementById('stylize-panel');
+const viewer = document.getElementById('viewer');
+if (panel && viewer) {
+ const gallery = document.getElementById('stylize-gallery');
+ const controls = document.getElementById('stylize-controls');
+ const slider = document.getElementById('stylize-res');
+ const resLabel = document.getElementById('stylize-res-label');
+ const resVal = document.getElementById('stylize-res-val');
+ const applyBtn = document.getElementById('stylize-apply');
+ const downloadBtn = document.getElementById('stylize-download');
+ const revertBtn = document.getElementById('stylize-revert');
+ const status = document.getElementById('stylize-status');
+
+ let originalGlbUrl = '';
+ let lastStylizedUrl = ''; // the GLB we swapped in; lets the src observer skip our own change
+ let baseLabel = '';
+ let activeKey = '';
+ let runToken = 0; // bumped on each apply/revert to abort stale polls
+ let elapsedTimer = null;
+ let unconfigured = false;
+
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+ function setStatus(text, kind = '') {
+ status.textContent = text || '';
+ status.dataset.kind = kind;
+ }
+
+ function stopElapsed() {
+ if (elapsedTimer) {
+ clearInterval(elapsedTimer);
+ elapsedTimer = null;
+ }
+ }
+
+ function startElapsed(label) {
+ stopElapsed();
+ const t0 = performance.now();
+ const tick = () => {
+ const s = Math.floor((performance.now() - t0) / 1000);
+ setStatus(`${label} — ${s}s`, 'busy');
+ };
+ tick();
+ elapsedTimer = setInterval(tick, 1000);
+ }
+
+ function setBusy(busy) {
+ for (const card of gallery.querySelectorAll('.stylize-card')) card.disabled = busy;
+ applyBtn.disabled = busy;
+ slider.disabled = busy;
+ revertBtn.disabled = busy;
+ panel.dataset.busy = busy ? 'true' : 'false';
+ }
+
+ // Build the filter gallery once. Cards are real buttons — keyboard reachable,
+ // with hover/active/focus states defined in the page stylesheet.
+ function buildGallery() {
+ gallery.innerHTML = '';
+ for (const f of STYLIZE_FILTERS) {
+ const card = document.createElement('button');
+ card.type = 'button';
+ card.className = 'stylize-card';
+ card.dataset.style = f.key;
+ card.setAttribute('aria-pressed', 'false');
+ card.title = f.blurb;
+ card.innerHTML =
+ `<span class="stylize-thumb" aria-hidden="true">${f.icon}</span>` +
+ `<span class="stylize-name">${f.name}</span>` +
+ `<span class="stylize-blurb">${f.blurb}</span>`;
+ card.addEventListener('click', () => selectFilter(f.key, { apply: true }));
+ gallery.appendChild(card);
+ }
+ }
+
+ function markActive(key) {
+ activeKey = key;
+ for (const card of gallery.querySelectorAll('.stylize-card')) {
+ card.setAttribute('aria-pressed', String(card.dataset.style === key));
+ }
+ }
+
+ function syncSlider(key) {
+ const spec = STYLIZE_FILTER_BY_KEY[key].resolution;
+ slider.min = String(spec.min);
+ slider.max = String(spec.max);
+ slider.step = '1';
+ slider.value = String(spec.def);
+ resLabel.textContent = spec.label;
+ resVal.textContent = String(spec.def);
+ controls.classList.remove('is-hidden');
+ }
+
+ function selectFilter(key, { apply }) {
+ if (unconfigured || !STYLIZE_FILTER_BY_KEY[key]) return;
+ markActive(key);
+ syncSlider(key);
+ if (apply) runStylize(key, Number(slider.value));
+ }
+
+ async function startJob(meshUrl, style, resolution) {
+ const res = await fetch('/api/forge-stylize', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ mesh_url: meshUrl, style, resolution }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (res.status === 503 || data.error === 'unconfigured') {
+ const e = new Error(data.message || 'Stylization is not configured on this deployment.');
+ e.kind = 'unconfigured';
+ throw e;
+ }
+ if (res.status === 429 || data.error === 'rate_limited') {
+ const secs = Number(data.retry_after) > 0 ? Math.ceil(Number(data.retry_after)) : 10;
+ throw new Error(`The stylizer is busy. Try again in about ${secs}s.`);
+ }
+ if (!res.ok || !data.job_id) {
+ throw new Error(data.message || `The stylizer returned ${res.status}.`);
+ }
+ return data;
+ }
+
+ async function pollUntilDone(jobId, token) {
+ const deadline = performance.now() + MAX_POLL_MS;
+ while (token === runToken && performance.now() < deadline) {
+ await sleep(POLL_INTERVAL_MS);
+ if (token !== runToken) return null;
+ const res = await fetch(`/api/forge-stylize?job=${encodeURIComponent(jobId)}`);
+ const data = await res.json().catch(() => ({}));
+ if (data.error === 'unconfigured') {
+ const e = new Error(data.message || 'unconfigured');
+ e.kind = 'unconfigured';
+ throw e;
+ }
+ if (data.status === 'done' && data.result_url) return data;
+ if (data.status === 'failed') throw new Error(data.error || 'Stylization failed.');
+ }
+ if (token !== runToken) return null;
+ throw new Error('Stylization timed out. Try a lower resolution.');
+ }
+
+ async function runStylize(style, resolution) {
+ if (!originalGlbUrl) return;
+ const token = ++runToken;
+ const filter = STYLIZE_FILTER_BY_KEY[style];
+ setBusy(true);
+ startElapsed(`Stylizing — ${filter.name}`);
+ try {
+ const job = await startJob(originalGlbUrl, style, resolution);
+ const done = await pollUntilDone(job.job_id, token);
+ if (token !== runToken || !done) return; // superseded or reverted
+ stopElapsed();
+ lastStylizedUrl = done.result_url; // so the src observer ignores our own swap
+ viewer.setAttribute('src', done.result_url);
+ viewer.setAttribute('alt', `${baseLabel} — ${filter.name} stylization`);
+ downloadBtn.href = done.result_url;
+ downloadBtn.setAttribute(
+ 'download',
+ `${(baseLabel || 'forge').replace(/[^a-z0-9]+/gi, '-').slice(0, 40).replace(/^-|-$/g, '') || 'forge'}-${style}.glb`,
+ );
+ downloadBtn.hidden = false;
+ revertBtn.hidden = false;
+ const faces = Number(done.face_count) > 0 ? ` · ${Number(done.face_count).toLocaleString()} faces` : '';
+ setStatus(`${filter.name} applied${faces}. Adjust ${filter.resolution.label.toLowerCase()} and re-apply, or revert.`, 'done');
+ } catch (err) {
+ if (token !== runToken) return;
+ stopElapsed();
+ if (err.kind === 'unconfigured') {
+ unconfigured = true;
+ panel.dataset.state = 'unconfigured';
+ setStatus(
+ 'Stylization needs the stylize worker configured on this deployment (GCP_STYLIZE_URL). The filters above light up once it’s set.',
+ 'error',
+ );
+ // Permanently disable the gallery (nothing to apply) without leaving
+ // the thumbs in the busy spin state.
+ for (const card of gallery.querySelectorAll('.stylize-card')) card.disabled = true;
+ applyBtn.disabled = true;
+ slider.disabled = true;
+ panel.dataset.busy = 'false';
+ return;
+ }
+ setStatus(err.message || 'Stylization failed. Try another filter or a lower resolution.', 'error');
+ } finally {
+ if (token === runToken && !unconfigured) setBusy(false);
+ }
+ }
+
+ function revert() {
+ runToken++; // abort any in-flight poll
+ stopElapsed();
+ setBusy(false);
+ viewer.setAttribute('src', originalGlbUrl);
+ viewer.setAttribute('alt', baseLabel || '3D model');
+ downloadBtn.hidden = true;
+ revertBtn.hidden = true;
+ markActive('');
+ setStatus('Showing the original model.', '');
+ }
+
+ // A new source model became available (freshly forged or opened from the
+ // gallery): reset the panel to its idle gallery state for that mesh. Idempotent
+ // — re-firing with the current source is a no-op, so the event and the src
+ // observer below can both call it without double-resetting.
+ function onNewSource(glbUrl, label) {
+ if (!glbUrl || glbUrl === originalGlbUrl) return;
+ originalGlbUrl = glbUrl;
+ baseLabel = label || '';
+ runToken++; // abort polls tied to the previous model
+ stopElapsed();
+ controls.classList.add('is-hidden');
+ downloadBtn.hidden = true;
+ revertBtn.hidden = true;
+ markActive('');
+ setStatus(unconfigured ? '' : 'Pick a filter to restyle this model.', '');
+ if (!unconfigured) setBusy(false);
+ panel.hidden = false;
+ }
+
+ // Wiring -------------------------------------------------------------------
+ slider.addEventListener('input', () => {
+ resVal.textContent = slider.value;
+ });
+ applyBtn.addEventListener('click', () => {
+ if (activeKey) runStylize(activeKey, Number(slider.value));
+ });
+ revertBtn.addEventListener('click', revert);
+
+ // Primary signal: forge.js announces the model explicitly.
+ document.addEventListener('forge:model-ready', (e) => {
+ onNewSource(e.detail?.glbUrl, e.detail?.label);
+ });
+
+ // Resilient fallback: watch the live viewer's `src` directly so the panel
+ // reveals whenever a model loads, even if the explicit event isn't emitted.
+ // Our own stylize swaps (lastStylizedUrl) and reverts (== originalGlbUrl) are
+ // ignored so they don't get mistaken for a new source mesh.
+ const srcObserver = new MutationObserver(() => {
+ const url = viewer.getAttribute('src');
+ if (!url || url === originalGlbUrl || url === lastStylizedUrl) return;
+ onNewSource(url, document.getElementById('result-label')?.textContent?.trim() || '');
+ });
+ srcObserver.observe(viewer, { attributes: true, attributeFilter: ['src'] });
+
+ // Pick up a model that was already shown before this module finished loading.
+ if (viewer.getAttribute('src')) {
+ onNewSource(viewer.getAttribute('src'), document.getElementById('result-label')?.textContent?.trim() || '');
+ }
+
+ buildGallery();
+}
diff --git a/src/forge-studio/forge.js b/src/forge-studio/forge.js
new file mode 100644
index 000000000..26aaee970
--- /dev/null
+++ b/src/forge-studio/forge.js
@@ -0,0 +1,2512 @@
+// Forge — text / image / multi-view → 3D generator (browser client).
+import { skeletonHTML, errorStateHTML, ensureStateKitStyles } from '../shared/state-kit.js';
+import { showSharePanel } from '../shared/share.js';
+import { stampGlbAttribution } from '../shared/glb-attribution.js';
+import { primeTierPass, attachTierPass, getTierPass, getAccess, onGate } from '../three-access.js';
+import { renderLock, lockStateFromAccess } from '../three-lock.js';
+import { payForHighGeneration } from './forge-pay.js';
+import { initWalletButton, getConnectedWalletAddress } from '../wallet.js';
+ensureStateKitStyles();
+//
+// Drives /api/forge. Three paths share one polling loop:
+// • Text → 3D — POST a prompt; FLUX paints a reference image, then TRELLIS
+// reconstructs the mesh.
+// • Image / multi-view → 3D — the user adds 1–4 photos of one object from
+// different angles. Each photo is uploaded straight to object storage via a
+// presigned URL (/api/forge-upload), then their public URLs are POSTed as
+// image_urls. With >1 view the backend fuses them (multi-view conditioning)
+// and reports how many views it used + which backend handled it.
+// • Sketch → 3D — one drawing + a required prompt naming what it depicts,
+// generated by the self-host TripoSG scribble engine (path: 'sketch').
+// The mode tab only appears when the catalog reports that engine live.
+//
+// State transitions are driven by real API responses; the only timer is the
+// honest elapsed counter. Nothing fakes progress.
+
+const POLL_INTERVAL_MS = 2500;
+const MAX_POLL_MS = 5 * 60 * 1000; // generous ceiling for reconstruction
+const MAX_VIEWS = 4;
+const VIEW_LABELS = ['Front', 'Back', 'Left', 'Right'];
+const MAX_UPLOAD_BYTES = 8 * 1024 * 1024;
+const ACCEPTED_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp']);
+
+const els = {
+ form: document.getElementById('composer'),
+ prompt: document.getElementById('prompt'),
+ aspect: document.getElementById('aspect'),
+ generate: document.getElementById('generate'),
+ generateLabel: document.getElementById('generate-label'),
+ examples: document.getElementById('examples'),
+ stage: document.getElementById('stage'),
+ modeSwitch: document.getElementById('mode-switch'),
+ textPane: document.getElementById('text-pane'),
+ imagePane: document.getElementById('image-pane'),
+ viewsGrid: document.getElementById('views-grid'),
+ fileInput: document.getElementById('view-file-input'),
+ imagePrompt: document.getElementById('image-prompt'),
+ sketchPane: document.getElementById('sketch-pane'),
+ sketchGrid: document.getElementById('sketch-grid'),
+ sketchFileInput: document.getElementById('sketch-file-input'),
+ sketchPrompt: document.getElementById('sketch-prompt'),
+ states: {
+ empty: document.getElementById('state-empty'),
+ generating: document.getElementById('state-generating'),
+ result: document.getElementById('state-result'),
+ error: document.getElementById('state-error'),
+ unconfigured: document.getElementById('state-unconfigured'),
+ },
+ genPreview: document.getElementById('gen-preview'),
+ genMeta: document.getElementById('gen-meta'),
+ genProgress: document.getElementById('gen-progress'),
+ genProgressFill: document.getElementById('gen-progress-fill'),
+ steps: {
+ image: document.getElementById('step-image'),
+ mesh: document.getElementById('step-mesh'),
+ finish: document.getElementById('step-finish'),
+ },
+ cancel: document.getElementById('cancel'),
+ viewer: document.getElementById('viewer'),
+ viewerShell: document.getElementById('viewer-shell'),
+ cinema: document.getElementById('cinema'),
+ resultLabel: document.getElementById('result-label'),
+ resultViews: document.getElementById('result-views'),
+ verdict: document.getElementById('verdict'),
+ download: document.getElementById('download'),
+ again: document.getElementById('again'),
+ refine: document.getElementById('refine'),
+ refineLabel: document.getElementById('refine-label'),
+ retry: document.getElementById('retry'),
+ viewsCounter: document.getElementById('views-counter'),
+ viewsCounterText: document.getElementById('views-counter-text'),
+ viewsPips: document.getElementById('views-pips'),
+ sketchReqTag: document.getElementById('sketch-req-tag'),
+ generateAnyway: document.getElementById('generate-anyway'),
+ refineLocally: document.getElementById('refine-locally'),
+ errorMessage: document.getElementById('error-message'),
+ forgeShareBtn: document.getElementById('forge-share-btn'),
+ segmentBtn: document.getElementById('forge-segment-btn'),
+ openInComposer: document.getElementById('open-in-composer'),
+ categoryPicker: document.getElementById('forge-category-picker'),
+ savedChip: document.getElementById('result-saved'),
+ creations: document.getElementById('creations'),
+ creationsGrid: document.getElementById('creations-grid'),
+ creationsCount: document.getElementById('creations-count'),
+ // Quality tier + generation engine + BYOK key.
+ tier: document.getElementById('tier'),
+ // Persistent inline hint under the Quality row — advertises that High is a
+ // $THREE holder feature (toggled locked/unlocked by the live access read).
+ holderNote: document.getElementById('fq-holder-note'),
+ engine: document.getElementById('engine'),
+ byokRow: document.getElementById('byok-row'),
+ byokLabel: document.getElementById('byok-label'),
+ byokHint: document.getElementById('byok-hint'),
+ providerKey: document.getElementById('provider-key'),
+ estimate: document.getElementById('estimate'),
+ // Holder free-quota perk line + the Forge-local wallet-connect chip (Part A).
+ perkRow: document.getElementById('forge-perk-row'),
+ perkLine: document.getElementById('forge-perk-line'),
+ connectBtn: document.getElementById('connect-wallet-btn'),
+};
+
+let aspectRatio = '1:1';
+let elapsedTimer = null;
+let pollAbort = false;
+let mode = 'text'; // 'text' | 'image' | 'sketch' — input mode (prompt vs photos vs drawing)
+let lastJob = null; // { prompt, imageUrls } — for retry
+let currentCreationId = null;
+// The quality tier the on-screen result was produced at — drives the "Refine"
+// affordance, which re-runs the same job exactly one tier higher.
+let currentResultTier = null;
+// The GLB currently shown in the viewer (set on every result). Lets the
+// rate-limit state know a model exists to refine locally as a fallback.
+let lastShownGlb = '';
+
+// Quality tiers, lowest → highest. Refine walks one step up this ladder.
+const TIER_ORDER = ['draft', 'standard', 'high'];
+const TIER_LABELS = { draft: 'Draft', standard: 'Standard', high: 'High' };
+function nextTierAfter(tier) {
+ const i = TIER_ORDER.indexOf(tier);
+ return i >= 0 && i < TIER_ORDER.length - 1 ? TIER_ORDER[i + 1] : null;
+}
+
+// Generation route + quality. `genPath` is the task's image|geometry axis;
+// `genBackend` names the provider; both come from the selected engine button.
+// The catalog (tiers + backends + cost/time matrix) is fetched once on load.
+let catalog = null;
+// Live backend health (/api/forge?health) — probed upstream auth/quota, not
+// just env presence. Null until the probe returns; the buttons render
+// optimistically from the catalog and tighten when health lands.
+let health = null;
+let selectedTier = 'standard';
+let selectedEngine = {
+ id: 'trellis',
+ path: 'image',
+ backend: 'trellis',
+ byok: null,
+ polyControl: false,
+};
+// Once the user deliberately picks an engine we stop auto-selecting the
+// catalog's per-tier default (e.g. the free NVIDIA lane on draft) under them.
+let userPickedEngine = false;
+// BYOK key held only in memory for this session — sent per request, never stored
+// by the page. Signed-in users can instead save it server-side in Account.
+let providerKey = '';
+
+// Cinema mode — distraction-free fullscreen turntable for recording/sharing.
+// Toggled by the result-bar button or F; Esc always exits. Rotation slows so
+// the loop reads as deliberate, not busy.
+let cinemaOn = false;
+function setCinema(on) {
+ if (!els.cinema || on === cinemaOn) return;
+ cinemaOn = on;
+ els.states.result.classList.toggle('is-cinema', on);
+ document.body.classList.toggle('forge-cinema', on);
+ els.cinema.setAttribute('aria-pressed', String(on));
+ els.viewer.setAttribute('rotation-per-second', on ? '10deg' : '18deg');
+}
+
+// Inline key glyph appended to BYOK engine buttons. Stroke = currentColor so it
+// tracks the button's text color through hover/selected/disabled states.
+const ENGINE_KEY_SVG =
+ '<svg class="eng-key" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="7.5" cy="15.5" r="4.5"/><path d="M10.7 12.3 21 2"/><path d="m15 7 3 3"/><path d="m18 4 3 3"/></svg>';
+
+// Inline "FREE" pill appended to zero-cost engine buttons (catalog `free:true`).
+// The free lanes are named by engine like every other button; this pill — not
+// the label — is what marks them free, so two free lanes never both read "Free".
+const ENGINE_FREE_PILL = '<span class="eng-free" aria-hidden="true">FREE</span>';
+
+// Short engine labels for the picker buttons, keyed by backend id. Free lanes
+// carry the FREE pill above, so they are labelled by engine name like the rest.
+const ENGINE_LABELS = {
+ nvidia: 'NVIDIA',
+ huggingface: 'Hunyuan3D',
+ trellis: 'Fast',
+ meshy: 'Meshy',
+ tripo: 'Tripo',
+ rodin: 'Rodin',
+ stability: 'Stability',
+ replicate_byok: 'Replicate',
+ hunyuan3d: 'Hunyuan3D',
+ triposg: 'TripoSG',
+};
+
+// Where to mint a key per BYOK provider, keyed by the backend's `byok` name.
+// Mirrors the canonical registry in api/_lib/provider-keys.js (BYOK_PROVIDERS)
+// and the Account key manager (dashboard-next/pages/account.js) — keep in sync.
+const KEY_HINTS = {
+ meshy: { label: 'Meshy AI', url: 'https://www.meshy.ai/settings/api' },
+ tripo: { label: 'Tripo AI', url: 'https://platform.tripo3d.ai/api-keys' },
+ rodin: { label: 'Rodin (Hyper3D)', url: 'https://developer.hyper3d.ai' },
+ stability: { label: 'Stability AI', url: 'https://platform.stability.ai/account/keys' },
+ replicate: { label: 'Replicate', url: 'https://replicate.com/account/api-tokens' },
+};
+
+// One entry per reference-view slot. `state` drives the slot's rendered region;
+// `url` is the durable public URL (what we send); `objectUrl` is the local
+// preview blob, revoked when the slot is cleared.
+const slots = VIEW_LABELS.map(() => ({
+ state: 'empty',
+ url: null,
+ objectUrl: null,
+ errorMsg: '',
+}));
+
+// File picker target: the slot index the picker was opened for, or null to fill
+// from the first free slot.
+let pickerTarget = null;
+
+// Sketch mode input — one drawing, same lifecycle as a view slot.
+const sketch = { state: 'empty', url: null, objectUrl: null, errorMsg: '' };
+
+// Stable anonymous handle for this browser. /forge has no login, so durable
+// creations + the gallery are scoped to this id (hashed server-side). Sent on
+// every request via the x-forge-client header.
+const CLIENT_ID = (() => {
+ const KEY = 'forge:cid';
+ try {
+ let id = localStorage.getItem(KEY);
+ if (!id) {
+ id =
+ crypto?.randomUUID?.() ||
+ `c-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
+ localStorage.setItem(KEY, id);
+ }
+ return id;
+ } catch {
+ // Private mode / storage blocked — fall back to an ephemeral per-load id.
+ return `c-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
+ }
+})();
+
+const CLIENT_HEADERS = { 'x-forge-client': CLIENT_ID };
+
+const REDUCED_MOTION =
+ typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
+
+function showState(name) {
+ for (const [key, node] of Object.entries(els.states)) {
+ node.classList.toggle('is-hidden', key !== name);
+ }
+ // Leaving the result state always leaves cinema mode with it.
+ if (name !== 'result' && cinemaOn) setCinema(false);
+}
+
+function setStep(step, state) {
+ if (els.steps[step]) els.steps[step].dataset.state = state;
+ // The scanline sweep runs exactly while the mesh step is live.
+ if (step === 'mesh') els.genPreview.classList.toggle('is-reconstructing', state === 'active');
+}
+
+function setStepLabel(step, text) {
+ const node = els.steps[step]?.querySelector('span:last-child');
+ if (node) node.textContent = text;
+}
+
+// The typical end-to-end time for the current engine+tier, straight from the
+// catalog's real estimate matrix (estimateEtaSeconds). Null when no catalog or
+// estimate exists — the meter then runs indeterminate rather than inventing a
+// duration.
+function currentEtaSeconds() {
+ if (!catalog) return null;
+ const backend = catalog.backends?.find((b) => b.id === selectedEngine.backend);
+ const est = (backend?.estimates?.[selectedEngine.path] || []).find(
+ (e) => e.tier === selectedTier,
+ );
+ return Number(est?.eta_seconds) > 0 ? Number(est.eta_seconds) : null;
+}
+
+// Map real elapsed seconds onto an honest fill fraction. The curve approaches
+// 1 asymptotically and is capped below it, so the bar can never reach full on
+// time alone — only a real finished GLB sets it to 100% (see markDone). At
+// elapsed = typical the fill sits ~0.78; it keeps creeping past that but never
+// claims completion.
+function honestFill(elapsedS, typicalS) {
+ const frac = 1 - Math.exp(-elapsedS / (typicalS * 0.66));
+ return Math.min(frac, 0.95);
+}
+
+function setProgress(pct) {
+ if (!els.genProgressFill || !els.genProgress) return;
+ const clamped = Math.max(0, Math.min(100, pct));
+ els.genProgressFill.style.width = `${clamped}%`;
+ els.genProgress.setAttribute('aria-valuenow', String(Math.round(clamped)));
+}
+
+function startElapsed() {
+ const started = performance.now();
+ stopElapsed();
+ const typical = currentEtaSeconds();
+ // Reset the meter to a clean running state for this job.
+ if (els.genProgress) {
+ els.genProgress.dataset.done = 'false';
+ els.genProgress.dataset.over = 'false';
+ els.genProgress.dataset.indeterminate = typical ? 'false' : 'true';
+ }
+ setProgress(0);
+ const tick = () => {
+ const s = Math.floor((performance.now() - started) / 1000);
+ if (typical) {
+ const over = s > typical;
+ setProgress(honestFill(s, typical) * 100);
+ if (els.genProgress) els.genProgress.dataset.over = String(over);
+ els.genMeta.innerHTML = over
+ ? `Elapsed <strong>${s}s</strong> · longer than usual, still working`
+ : `Elapsed <strong>${s}s</strong> · ~${Math.max(1, typical - s)}s left`;
+ } else {
+ // Unknown duration — the bar travels (indeterminate) and we report only
+ // the honest elapsed count.
+ els.genMeta.innerHTML = `Elapsed <strong>${s}s</strong>`;
+ }
+ };
+ tick();
+ elapsedTimer = window.setInterval(tick, 1000);
+}
+
+// Snap the meter to a finished, successful state — the only path to 100%.
+function markProgressDone() {
+ if (!els.genProgress) return;
+ els.genProgress.dataset.indeterminate = 'false';
+ els.genProgress.dataset.over = 'false';
+ els.genProgress.dataset.done = 'true';
+ setProgress(100);
+}
+
+function stopElapsed() {
+ if (elapsedTimer) {
+ window.clearInterval(elapsedTimer);
+ elapsedTimer = null;
+ }
+}
+
+function setBusy(busy) {
+ els.generate.dataset.busy = busy ? '1' : '0';
+ els.generate.disabled = busy;
+ els.generateLabel.textContent = busy ? 'Forging…' : 'Generate';
+ // When returning to idle, re-assert the High-tier $THREE gate (if active) so a
+ // finished/cancelled job doesn't leave the Generate button enabled for a tier
+ // the user can't use.
+ if (!busy) applyHighGate();
+}
+
+function sleep(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+// Mode switching --------------------------------------------------------------
+
+function setMode(next) {
+ if (next !== 'text' && next !== 'image' && next !== 'sketch') return;
+ mode = next;
+ els.textPane.classList.toggle('is-hidden', mode !== 'text');
+ els.imagePane.classList.toggle('is-hidden', mode !== 'image');
+ els.sketchPane?.classList.toggle('is-hidden', mode !== 'sketch');
+ els.examples.classList.toggle('is-hidden', mode !== 'text');
+ for (const b of els.modeSwitch.querySelectorAll('button')) {
+ b.setAttribute('aria-selected', String(b.dataset.mode === mode));
+ }
+ // Sketch serves through its own engine set (TripoSG) — rebuild the selector
+ // so each mode only offers engines that can actually take its input.
+ if (catalog) buildEngineButtons();
+ updateAspectVisibility();
+ if (mode === 'text') els.prompt.focus();
+ if (mode === 'sketch' && sketch.state === 'empty') sketchSlotEl()?.focus();
+}
+
+// Aspect ratio only shapes the synthesized reference image — irrelevant when
+// the user supplies their own photos OR uses the geometry-first path (which
+// never paints an intermediate image).
+function updateAspectVisibility() {
+ if (!els.aspect) return;
+ const relevant = mode === 'text' && selectedEngine.path === 'image';
+ els.aspect.classList.toggle('is-hidden', !relevant);
+}
+
+// Quality tier + engine ------------------------------------------------------
+
+// Fetch the tier/backend/cost catalog once, then build the engine selector from
+// the backends that are live (platform-configured) or BYOK (always selectable).
+async function loadCatalog() {
+ try {
+ const res = await fetch('/api/forge?catalog=1', { headers: CLIENT_HEADERS });
+ catalog = await res.json().catch(() => null);
+ } catch {
+ catalog = null;
+ }
+ if (!catalog || !Array.isArray(catalog.backends)) {
+ // No catalog (older deploy) — hide the controls; defaults still work.
+ els.engine?.closest('#forge-quality')?.classList.add('is-hidden');
+ return;
+ }
+ buildEngineButtons();
+ selectTier(selectedTier);
+ revealSketchMode();
+ loadHealth();
+}
+
+// Sketch→3D needs the self-host TripoSG worker — the tab stays hidden unless
+// the catalog reports that engine configured, so there is no dead mode on
+// deployments without it.
+function revealSketchMode() {
+ const tab = els.modeSwitch?.querySelector('button[data-mode="sketch"]');
+ if (!tab) return;
+ const live = catalog.backends.some((b) => b.paths?.includes('sketch') && b.configured);
+ tab.hidden = !live;
+ if (live) buildSketchSlot();
+}
+
+// Live-probe the backends in the background, then tighten the engine buttons:
+// a lane whose upstream is down gets disabled with the real reason instead of
+// failing after the user has already typed a prompt and clicked Generate.
+// On failure, retries twice (at 30s then 60s) before giving up.
+let healthRetryCount = 0;
+async function loadHealth() {
+ try {
+ const res = await fetch('/api/forge?health=1', { headers: CLIENT_HEADERS });
+ const body = await res.json().catch(() => null);
+ health = body && body.backends ? body : null;
+ } catch {
+ health = null;
+ }
+ if (health) {
+ healthRetryCount = 0;
+ updateEngineAvailability();
+ } else if (healthRetryCount < 2) {
+ healthRetryCount += 1;
+ setTimeout(loadHealth, healthRetryCount * 30_000);
+ }
+}
+
+function buildEngineButtons() {
+ if (!els.engine) return;
+ // Each mode offers only the engines that take its input: sketch mode shows
+ // the sketch-path engines (TripoSG); text/photo modes hide sketch-only ones.
+ const usable = catalog.backends.filter((b) => {
+ if (!(b.configured || b.byok)) return false;
+ const sketchOnly = Array.isArray(b.paths) && b.paths.every((p) => p === 'sketch');
+ return mode === 'sketch' ? b.paths.includes('sketch') : !sketchOnly;
+ });
+ els.engine.innerHTML = '';
+ for (const b of usable) {
+ // Each backend exposes the geometry-first path when it supports it; the
+ // image-intermediate engines (TRELLIS, Hunyuan3D) keep the image path.
+ const path =
+ mode === 'sketch' ? 'sketch' : b.paths.includes('geometry') ? 'geometry' : 'image';
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.dataset.engine = b.id;
+ btn.dataset.path = path;
+ btn.dataset.backend = b.id;
+ btn.dataset.byok = b.byok || '';
+ btn.dataset.poly = String(Boolean(b.poly_control));
+ // Text-only engines (the free NVIDIA TRELLIS preview) can't take photos;
+ // updateEngineAvailability() disables them while reference views are set.
+ btn.dataset.userimages = String(b.user_images !== false);
+ // BYOK engines carry a small key glyph so the picker shows at a glance
+ // which lanes run on the user's own API key vs the free/included ones.
+ const short = ENGINE_LABELS[b.id] || b.label;
+ btn.innerHTML = `<span class="eng-label">${short}</span>${b.free ? ENGINE_FREE_PILL : ''}${b.byok ? ENGINE_KEY_SVG : ''}`;
+ const keyNote = b.byok ? ` · uses your own ${KEY_HINTS[b.byok]?.label || b.byok} key` : '';
+ const freeNote = b.free ? ' · free, no API key' : '';
+ btn.title = `${b.label} — ${b.blurb}${freeNote}${keyNote}`;
+ // aria-label survives the dynamic title rewrites in updateEngineAvailability.
+ btn.setAttribute('aria-label', `${b.label}${freeNote}${keyNote}`);
+ btn.setAttribute('aria-pressed', String(b.id === selectedEngine.backend));
+ els.engine.appendChild(btn);
+ }
+ // If the previously-selected engine isn't usable, fall back to the first.
+ if (!usable.some((b) => b.id === selectedEngine.backend)) {
+ const first = els.engine.querySelector('button');
+ if (first) selectEngine(first, true);
+ }
+ updateEngineAvailability();
+}
+
+// Keep the engine buttons honest about the current input mode, and keep the
+// selection on the catalog's per-tier default until the user picks one.
+// • With reference photos attached, text-only engines are disabled (the free
+// NVIDIA TRELLIS preview rejects user images) and a selected one bounces to
+// the default photo engine.
+// • With no photos and no explicit user choice, the tier's default engine is
+// applied — which is what routes draft prompts onto the free lane.
+function updateEngineAvailability() {
+ if (!els.engine || !catalog) return;
+ const hasPhotos = slots.some((s) => s.state === 'uploaded' || s.state === 'uploading');
+ let bounceTo = null;
+ for (const btn of els.engine.querySelectorAll('button')) {
+ const textOnly = btn.dataset.userimages === 'false';
+ const b = catalog.backends?.find((x) => x.id === btn.dataset.backend);
+ // Live health beats the catalog's env-presence flag: a lane whose
+ // upstream auth/billing probe failed is disabled with the real reason.
+ const lane = health?.backends?.[btn.dataset.backend];
+ const laneDown = lane && (lane.status === 'down' || lane.status === 'unconfigured');
+ const laneBusy = lane && lane.status === 'degraded';
+ const blocked = (textOnly && hasPhotos) || laneDown;
+ btn.disabled = blocked;
+ btn.setAttribute('aria-disabled', String(blocked));
+ btn.dataset.health = lane ? lane.status : '';
+ if (laneDown) {
+ btn.title = `${b?.label || btn.dataset.backend} — temporarily unavailable: ${lane.message}`;
+ } else if (blocked) {
+ btn.title =
+ 'This engine generates from text prompts only — clear the reference views to use it.';
+ } else if (b) {
+ btn.title = laneBusy
+ ? `${b.label} — busy right now: ${lane.message}`
+ : `${b.label} — ${b.blurb}`;
+ }
+ if (blocked && btn.dataset.backend === selectedEngine.backend) bounceTo = true;
+ }
+ const defaultId =
+ catalog.default_backend_for_tier?.[selectedTier]?.[selectedEngine.path] ?? null;
+ if (bounceTo) {
+ // Forced move: the selected engine can't serve photos. Prefer the standing
+ // photo default, else the first enabled button.
+ const fallbackId = catalog.default_backend?.image || 'trellis';
+ const target =
+ els.engine.querySelector(`button[data-backend="${fallbackId}"]:not(:disabled)`) ||
+ els.engine.querySelector('button:not(:disabled)');
+ if (target) selectEngine(target);
+ } else if (
+ !userPickedEngine &&
+ !hasPhotos &&
+ defaultId &&
+ defaultId !== selectedEngine.backend
+ ) {
+ const target = els.engine.querySelector(
+ `button[data-backend="${defaultId}"]:not(:disabled)`,
+ );
+ if (target) selectEngine(target);
+ }
+}
+
+function selectEngine(btn, silent) {
+ if (!btn) return;
+ selectedEngine = {
+ id: btn.dataset.engine,
+ path: btn.dataset.path,
+ backend: btn.dataset.backend,
+ byok: btn.dataset.byok || null,
+ polyControl: btn.dataset.poly === 'true',
+ };
+ for (const b of els.engine.querySelectorAll('button')) {
+ b.setAttribute('aria-pressed', String(b === btn));
+ }
+ updateByokRow();
+ updateAspectVisibility();
+ if (!silent) updateEstimate();
+ // The engine decides whether High is $THREE-gated (platform) or exempt (BYOK), so
+ // re-evaluate the lock whenever the engine changes under High. Reuses the cached
+ // access verdict — no extra round-trip, no loading flash.
+ if (selectedTier === 'high') reflectHighAccess('high', { silent: true });
+}
+
+// Show the key field only for BYOK engines, with provider-specific hint + link.
+function updateByokRow() {
+ if (!els.byokRow) return;
+ const byok = selectedEngine.byok;
+ els.byokRow.classList.toggle('is-hidden', !byok);
+ if (!byok) return;
+ const hint = KEY_HINTS[byok];
+ const name = hint?.label || byok;
+ els.byokLabel.textContent = `${name} key`;
+ els.providerKey.placeholder = `Your ${name} API key (kept in this browser)`;
+ els.byokHint.innerHTML = hint
+ ? `This engine runs on your own ${hint.label} key. <a href="${hint.url}" target="_blank" rel="noopener">Get a key →</a> Signed-in users can save it once in Account instead.`
+ : `This engine runs on your own ${name} key, kept in this browser. Signed-in users can save it in Account instead.`;
+}
+
+function selectTier(tierId) {
+ if (!['draft', 'standard', 'high'].includes(tierId)) return;
+ selectedTier = tierId;
+ for (const b of els.tier.querySelectorAll('button')) {
+ b.setAttribute('aria-pressed', String(b.dataset.tier === tierId));
+ }
+ // Tier changes can move the default engine (draft prefers the free lane).
+ updateEngineAvailability();
+ updateEstimate();
+ reflectHighAccess(tierId);
+}
+
+// The High tier is a $THREE holder perk (gated server-side). When the user picks
+// it, surface their access up front — a frosted lock with a Get $THREE path for
+// non-holders (and the Generate button disabled for High), an "Unlocked" ribbon
+// for holders (pass primed so their request clears the gate without a round-trip
+// stall). Draft and Standard clear the lock (they're free, never gated). Degrades
+// safely: if the access read fails we show a retry but DON'T trap the user — the
+// server stays the final authority and a 403 falls back to the upsell modal.
+let _accessHost = null;
+let highLocked = false; // true → High is selected but the holder isn't eligible
+let _highAccess = null; // last resolved forge.high access payload (for the gate modal)
+
+// The only combination the server actually $THREE-gates: High tier on a PLATFORM-keyed
+// backend. BYOK engines run on the caller's own vendor key, so the server exempts BYOK
+// High (key-gated, not hold-gated) — and so must the client, or a non-holder with their
+// own Meshy/Tripo/Rodin key would be wrongly blocked from High. Draft/Standard are never
+// gated. Every client gate check keys on this, so the lock can never engage outside it.
+function highTierNeedsPass() {
+ return selectedTier === 'high' && !selectedEngine.byok;
+}
+
+function accessHost() {
+ if (_accessHost || !els.tier) return _accessHost;
+ const host = document.createElement('div');
+ host.className = 'fq-access';
+ host.hidden = true;
+ (els.estimate || els.tier).insertAdjacentElement('afterend', host);
+ _accessHost = host;
+ return host;
+}
+
+// Reflect the High-tier gate onto the Generate button: disabled + relabelled
+// while High is selected and the user is ineligible. Only touches the button when
+// not mid-job (setBusy owns the busy label).
+function applyHighGate() {
+ if (!els.generate || els.generate.dataset.busy === '1') return;
+ const locked = highTierNeedsPass() && highLocked;
+ els.generate.disabled = locked;
+ els.generate.classList.toggle('is-gated', locked);
+ if (els.generateLabel) {
+ els.generateLabel.textContent = locked ? 'Hold $THREE for High' : 'Generate';
+ }
+}
+
+async function reflectHighAccess(tierId, { silent = false } = {}) {
+ const host = accessHost();
+ if (!host) return;
+ if (tierId !== 'high') {
+ highLocked = false;
+ _highAccess = null;
+ renderLock(host, { clear: true });
+ // High isn't selected — let the persistent hint advertise it again.
+ if (els.holderNote) els.holderNote.hidden = false;
+ applyHighGate();
+ return;
+ }
+ // High on a BYOK engine is server-exempt (the caller's own vendor key pays), so it's
+ // never $THREE-gated here either: clear any lock, drop the holder note, and let the
+ // BYOK key flow take over. This is the path that keeps BYOK High byte-for-byte free.
+ if (!highTierNeedsPass()) {
+ highLocked = false;
+ renderLock(host, { clear: true });
+ if (els.holderNote) els.holderNote.hidden = true;
+ applyHighGate();
+ return;
+ }
+ // Platform-keyed High — the real $THREE gate. The in-place lock panel takes over, so
+ // the small persistent hint stands down to avoid stacking two "holder feature" notes.
+ if (els.holderNote) els.holderNote.hidden = true;
+ // Re-evaluating after an engine switch (silent) reuses the last resolved verdict so
+ // the panel doesn't flash a loading state for a check we already made.
+ let access = silent && _highAccess ? _highAccess : null;
+ if (!access) {
+ renderLock(host, { loading: true });
+ const data = await getAccess('forge.high');
+ // User moved off High, or switched to a BYOK engine, while we fetched.
+ if (!highTierNeedsPass()) return;
+ access = data?.access || null;
+ }
+ if (!access) {
+ // Access read failed — show a retry, but don't lock (fail open; the server
+ // enforces and a real holder isn't trapped behind a transient hiccup).
+ _highAccess = null;
+ highLocked = false;
+ renderLock(host, { error: true, onRetry: () => reflectHighAccess('high') });
+ applyHighGate();
+ return;
+ }
+ _highAccess = access;
+ highLocked = !access.eligible;
+ renderLock(
+ host,
+ lockStateFromAccess(access, {
+ getThreeUrl: '/three-token',
+ onUseFree: () => selectTier('standard'),
+ useFreeLabel: 'Use Standard (free)',
+ // Working Pay-per-use CTA: pay $THREE for one High generation in place.
+ onPayPerUse: (pay) => payThenGenerate(pay),
+ }),
+ );
+ applyHighGate();
+ // Keep the persistent button pill + note in sync with the fresh verdict.
+ applyHighAffordances(access);
+ // Reflect the resolved hold in the cost line too — High flips to "Free" for a
+ // holder without a reload.
+ updateEstimate();
+ if (access.eligible) primeTierPass();
+}
+
+// Small lock glyph for the High-tier button pill. Stroke = currentColor so it
+// tracks the pill's locked (gold) / unlocked (green) tone.
+const TIER_LOCK_SVG =
+ '<svg class="tier-lock-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="5" y="11" width="14" height="9" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg>';
+
+// Paint the persistent High-tier affordances — the lock pill on the High button
+// and the inline holder note under the Quality row — from a single-feature access
+// payload (the `.access` from getAccess('forge.high'), or a 403 gate body, which
+// both carry `eligible`/`required`/`held`). Holders get the quiet unlocked
+// treatment; everyone else (and the null/unknown case) keeps the $THREE lock so
+// High reads as the premium lane before it's ever selected. Purely cosmetic — the
+// server stays the only authority on eligibility.
+function applyHighAffordances(access) {
+ const eligible = Boolean(access?.eligible);
+ const state = eligible ? 'unlocked' : 'locked';
+ const btn = els.tier?.querySelector('button[data-tier="high"]');
+ if (btn) {
+ btn.dataset.access = state;
+ btn.setAttribute(
+ 'aria-label',
+ eligible ? 'High quality — unlocked, you hold $THREE' : 'High quality — $THREE holder feature',
+ );
+ const pill = btn.querySelector('.tier-lock');
+ if (pill) {
+ pill.dataset.state = state;
+ pill.title = eligible ? 'Unlocked — you hold $THREE' : 'High quality is a $THREE holder feature';
+ pill.innerHTML = eligible
+ ? '<span class="tier-lock-ico" aria-hidden="true">✓</span><span class="tier-lock-txt">$THREE</span>'
+ : `${TIER_LOCK_SVG}<span class="tier-lock-txt">$THREE</span>`;
+ }
+ }
+ const note = els.holderNote;
+ if (note) {
+ note.dataset.state = state;
+ note.innerHTML = eligible
+ ? '<span class="fq-holder-ico" aria-hidden="true">◆</span> High quality is unlocked — you hold <a href="/three-token">$THREE</a>.'
+ : '<span class="fq-holder-ico" aria-hidden="true">◆</span> High quality is a <a href="/three-token">$THREE holder</a> feature — hold to unlock, or pay per generation.';
+ }
+}
+
+// One-time read on load: reflect the viewer's forge.high access onto the High
+// button pill + the inline note so the holder gate is legible before the tier is
+// even selected. Seeds the gate cache and primes the tier pass for real holders so
+// their first High submit clears the server gate without an RPC stall.
+async function reflectHighButtonAccess() {
+ const data = await getAccess('forge.high');
+ const access = data?.access || null;
+ if (access) _highAccess = access;
+ applyHighAffordances(access);
+ if (access?.eligible) primeTierPass();
+}
+
+// $THREE holder free-generation multiplier by tier level — mirrors api/_lib/three-tier.js
+// (rateMultiplier), which the free lane applies to a holder's quota via the tier pass.
+const FREE_MULT_BY_LEVEL = { 1: 2, 2: 3, 3: 5, 4: 10 };
+
+// The quiet holder line under Generate (Part A): a holder sees their active free-quota
+// multiplier; everyone else sees a non-blocking upsell plus a reachable wallet-connect so
+// a holder who hasn't connected can reveal their perk. Reads the shared, wallet-aware
+// access matrix — never nags, never blocks the free base lane.
+async function updatePerkLine() {
+ if (!els.perkRow || !els.perkLine) return;
+ const data = await getAccess();
+ const level = Number(data?.tier?.level) || 0;
+ const connected = Boolean(getConnectedWalletAddress());
+ els.perkRow.hidden = false;
+ if (level >= 1) {
+ const mult = FREE_MULT_BY_LEVEL[level] || 1;
+ els.perkLine.dataset.state = 'perk';
+ els.perkLine.innerHTML =
+ '<span class="fq-perk-ico" aria-hidden="true">⚡</span> Holder perk: ' +
+ `<strong>${mult}× free quota</strong> · <a href="/three#tiers">your $THREE tier</a>`;
+ if (els.connectBtn) els.connectBtn.hidden = true;
+ } else {
+ els.perkLine.dataset.state = 'upsell';
+ els.perkLine.innerHTML =
+ '<a href="/three#tiers">Hold $THREE for up to 10× free generations →</a>';
+ // Offer connect only when there's no wallet in hand to read a tier from.
+ if (els.connectBtn) els.connectBtn.hidden = connected;
+ }
+}
+
+// The honest price for the current engine + tier, as a styled segment. The web
+// gate charges only High tier (hold $THREE or pay per generation); Draft and
+// Standard run free on the platform's rate-limited lanes; BYOK engines bill the
+// caller's own provider key. `_highAccess.eligible` reflects a resolved $THREE
+// hold, so a holder sees High as already unlocked.
+function costSegment(backend, tierMeta) {
+ if (backend.byok) return 'billed to your own key';
+ if (tierMeta.id === 'high') {
+ return _highAccess?.eligible
+ ? '<span class="est-free">Free</span> · you hold $THREE'
+ : `<span class="est-cost">$${tierMeta.price_usdc}</span> or hold $THREE`;
+ }
+ return '<span class="est-free">Free</span>';
+}
+
+// Render the honest time/cost/poly estimate for the current engine + tier from
+// the catalog. No fabricated numbers — everything comes from /api/forge?catalog.
+function updateEstimate() {
+ if (!els.estimate || !catalog) return;
+ const backend = catalog.backends.find((b) => b.id === selectedEngine.backend);
+ const tierMeta = catalog.tiers.find((t) => t.id === selectedTier);
+ if (!backend || !tierMeta) {
+ els.estimate.textContent = '';
+ return;
+ }
+ const est = (backend.estimates?.[selectedEngine.path] || []).find(
+ (e) => e.tier === selectedTier,
+ );
+ // Holder-readable, not pipeline-internal: say how long it usually takes and
+ // what the engine does, in plain words. The mechanism ("builds from a
+ // reference image") replaces jargon like "image-intermediate · fast path".
+ const parts = [`<strong>${tierMeta.label}</strong>`, costSegment(backend, tierMeta)];
+ if (est?.eta_seconds) parts.push(`usually ~${est.eta_seconds}s`);
+ if (est && est.credits != null) parts.push(`~${est.credits} credits`);
+ if (backend.poly_control) parts.push(`up to ${tierMeta.polycount.toLocaleString()} polygons`);
+ if (selectedEngine.path === 'geometry') parts.push('shapes geometry straight from the prompt');
+ else if (selectedEngine.path === 'sketch') parts.push('untextured geometry from your sketch');
+ else parts.push('builds from a reference image');
+ els.estimate.innerHTML = parts.join(' · ');
+}
+
+// View slots ------------------------------------------------------------------
+
+function buildSlots() {
+ els.viewsGrid.innerHTML = '';
+ slots.forEach((_, i) => {
+ const slot = document.createElement('div');
+ slot.className = 'view-slot';
+ slot.dataset.index = String(i);
+ slot.tabIndex = 0;
+ slot.setAttribute('role', 'button');
+
+ slot.innerHTML = `
+ <div class="vs-empty">
+ <span class="vs-icon" aria-hidden="true">+</span>
+ <span class="vs-label">${VIEW_LABELS[i]}</span>
+ </div>
+ <div class="vs-uploading">
+ <div class="shimmer" aria-hidden="true"></div>
+ <span>Uploading…</span>
+ </div>
+ <img loading="lazy" decoding="async" class="vs-thumb" alt="" />
+ <span class="vs-badge">${VIEW_LABELS[i]}</span>
+ <button type="button" class="vs-remove" aria-label="Remove ${VIEW_LABELS[i]} view">×</button>
+ <div class="vs-error">
+ <span class="vs-error-msg">Upload failed</span>
+ <button type="button" class="vs-retry">Retry</button>
+ </div>`;
+
+ // Remove (stop click from also re-opening the picker).
+ slot.querySelector('.vs-remove').addEventListener('click', (e) => {
+ e.stopPropagation();
+ clearSlot(i);
+ });
+ // Retry re-opens the picker for this slot.
+ slot.querySelector('.vs-retry').addEventListener('click', (e) => {
+ e.stopPropagation();
+ openPicker(i);
+ });
+
+ // Click empty/error → browse for this slot.
+ slot.addEventListener('click', () => {
+ if (slots[i].state === 'empty' || slots[i].state === 'error') openPicker(i);
+ });
+ slot.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ if (slots[i].state === 'empty' || slots[i].state === 'error') openPicker(i);
+ }
+ });
+
+ // Drag to reorder (uploaded slots only).
+ slot.addEventListener('dragstart', (e) => {
+ if (slots[i].state !== 'uploaded') {
+ e.preventDefault();
+ return;
+ }
+ e.dataTransfer.setData('application/x-forge-slot', String(i));
+ e.dataTransfer.effectAllowed = 'move';
+ slot.classList.add('dragging');
+ });
+ slot.addEventListener('dragend', () => slot.classList.remove('dragging'));
+
+ // Drop target — accepts files OR a dragged thumbnail (reorder).
+ slot.addEventListener('dragover', (e) => {
+ e.preventDefault();
+ e.dataTransfer.dropEffect = e.dataTransfer.types.includes('application/x-forge-slot')
+ ? 'move'
+ : 'copy';
+ slot.classList.add('drop-target');
+ });
+ slot.addEventListener('dragleave', () => slot.classList.remove('drop-target'));
+ slot.addEventListener('drop', (e) => {
+ e.preventDefault();
+ slot.classList.remove('drop-target');
+ const from = e.dataTransfer.getData('application/x-forge-slot');
+ if (from !== '') {
+ swapSlots(Number(from), i);
+ } else if (e.dataTransfer.files?.length) {
+ handleFiles(i, e.dataTransfer.files);
+ }
+ });
+
+ els.viewsGrid.appendChild(slot);
+ renderSlot(i);
+ });
+}
+
+function slotEl(i) {
+ return els.viewsGrid.querySelector(`.view-slot[data-index="${i}"]`);
+}
+
+// One pip per possible reference view — filled as photos upload.
+function buildViewsPips() {
+ if (!els.viewsPips || els.viewsPips.childElementCount) return;
+ for (let i = 0; i < MAX_VIEWS; i++) {
+ const pip = document.createElement('i');
+ pip.dataset.filled = 'false';
+ els.viewsPips.appendChild(pip);
+ }
+}
+
+// Live "N of 4 views" readout + pips. Teaches that more views sharpen the mesh,
+// so users don't stop at a single photo thinking it's enough.
+function updateViewsCounter() {
+ if (!els.viewsCounter || !els.viewsCounterText) return;
+ const n = slots.filter((s) => s.state === 'uploaded').length;
+ const pips = els.viewsPips ? els.viewsPips.children : [];
+ for (let i = 0; i < pips.length; i++) pips[i].dataset.filled = String(i < n);
+ let tail;
+ if (n === 0) tail = ' — add a photo to begin';
+ else if (n < MAX_VIEWS) tail = ' · <span class="vc-quality">more views = sharper</span>';
+ else tail = ' · <span class="vc-quality">full coverage</span>';
+ els.viewsCounterText.innerHTML = `<strong>${n}</strong> of ${MAX_VIEWS} views${tail}`;
+}
+
+function renderSlot(i) {
+ const el = slotEl(i);
+ if (!el) return;
+ const s = slots[i];
+ el.dataset.state = s.state;
+ el.draggable = s.state === 'uploaded';
+ // Slot changes flip the input mode (prompt-only ↔ photo), which changes
+ // which engines may serve — keep the selector honest in the same frame.
+ updateEngineAvailability();
+ updateViewsCounter();
+
+ const img = el.querySelector('.vs-thumb');
+ if (s.objectUrl) {
+ img.src = s.objectUrl;
+ img.alt = `${VIEW_LABELS[i]} view`;
+ } else {
+ img.removeAttribute('src');
+ img.alt = '';
+ }
+ el.querySelector('.vs-error-msg').textContent = s.errorMsg || 'Upload failed';
+
+ const labels = {
+ empty: `${VIEW_LABELS[i]} view, empty — add a photo`,
+ uploading: `${VIEW_LABELS[i]} view, uploading`,
+ uploaded: `${VIEW_LABELS[i]} view, uploaded — drag to reorder`,
+ error: `${VIEW_LABELS[i]} view, upload failed`,
+ };
+ el.setAttribute('aria-label', labels[s.state] || VIEW_LABELS[i]);
+}
+
+function clearSlot(i) {
+ const s = slots[i];
+ if (s.objectUrl) URL.revokeObjectURL(s.objectUrl);
+ slots[i] = { state: 'empty', url: null, objectUrl: null, errorMsg: '' };
+ renderSlot(i);
+}
+
+function swapSlots(a, b) {
+ if (a === b) return;
+ const tmp = slots[a];
+ slots[a] = slots[b];
+ slots[b] = tmp;
+ renderSlot(a);
+ renderSlot(b);
+}
+
+function firstFreeSlot() {
+ return slots.findIndex((s) => s.state === 'empty' || s.state === 'error');
+}
+
+function nextFreeAfter(i) {
+ for (let j = i + 1; j < MAX_VIEWS; j++) {
+ if (slots[j].state === 'empty' || slots[j].state === 'error') return j;
+ }
+ return -1;
+}
+
+function openPicker(index) {
+ pickerTarget = index;
+ els.fileInput.value = '';
+ els.fileInput.click();
+}
+
+// Distribute dropped/picked files into slots, starting at `startIndex` (or the
+// first free slot when null), filling free slots up to MAX_VIEWS.
+function handleFiles(startIndex, fileList) {
+ const files = Array.from(fileList).filter((f) => f && f.type && f.type.startsWith('image/'));
+ if (!files.length) return;
+ let idx = startIndex == null ? firstFreeSlot() : startIndex;
+ for (const file of files) {
+ if (idx < 0 || idx >= MAX_VIEWS) idx = firstFreeSlot();
+ if (idx < 0) break; // all slots taken
+ uploadToSlot(idx, file);
+ idx = nextFreeAfter(idx);
+ }
+}
+
+// Presign → PUT to object storage → public URL. Shared by the view slots and
+// the sketch uploader. Returns { ok: true, url } or { ok: false, message }.
+async function presignAndPut(file) {
+ try {
+ const presignRes = await fetch('/api/forge-upload', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', ...CLIENT_HEADERS },
+ body: JSON.stringify({ content_type: file.type, size_bytes: file.size }),
+ });
+ const presign = await presignRes.json().catch(() => ({}));
+ if (presignRes.status === 503)
+ return { ok: false, message: 'Uploads unavailable — paste a URL.' };
+ if (presignRes.status === 429)
+ return { ok: false, message: 'Rate limited — retry shortly.' };
+ if (!presignRes.ok || !presign.upload_url || !presign.public_url) {
+ return { ok: false, message: presign.message || 'Upload failed.' };
+ }
+
+ const putRes = await fetch(presign.upload_url, {
+ method: 'PUT',
+ headers: { 'content-type': file.type },
+ body: file,
+ });
+ if (!putRes.ok)
+ return { ok: false, message: `Storage rejected the file (${putRes.status}).` };
+ return { ok: true, url: presign.public_url };
+ } catch {
+ return { ok: false, message: 'Network error during upload.' };
+ }
+}
+
+// Upload one file into a slot: presign → PUT to object storage → record the
+// public URL. The slot moves empty/error → uploading → uploaded|error, each a
+// real, designed state. The local blob preview shows immediately.
+async function uploadToSlot(index, file) {
+ if (!ACCEPTED_TYPES.has(file.type)) {
+ setSlotError(index, 'Use PNG, JPG, or WebP.');
+ return;
+ }
+ if (file.size === 0) {
+ setSlotError(index, 'File is empty.');
+ return;
+ }
+ if (file.size > MAX_UPLOAD_BYTES) {
+ setSlotError(index, 'Too large (max 8 MB).');
+ return;
+ }
+
+ const prev = slots[index];
+ if (prev.objectUrl) URL.revokeObjectURL(prev.objectUrl);
+ const objectUrl = URL.createObjectURL(file);
+ slots[index] = { state: 'uploading', url: null, objectUrl, errorMsg: '' };
+ renderSlot(index);
+
+ const up = await presignAndPut(file);
+ if (!up.ok) {
+ setSlotError(index, up.message);
+ return;
+ }
+ // Success — keep the local blob preview, remember the public URL.
+ slots[index] = { state: 'uploaded', url: up.url, objectUrl, errorMsg: '' };
+ renderSlot(index);
+}
+
+function setSlotError(index, message) {
+ const s = slots[index];
+ // Keep any local preview so the user sees what failed.
+ slots[index] = {
+ state: 'error',
+ url: null,
+ objectUrl: s.objectUrl || null,
+ errorMsg: message,
+ };
+ renderSlot(index);
+}
+
+function uploadedUrls() {
+ return slots.filter((s) => s.state === 'uploaded' && s.url).map((s) => s.url);
+}
+
+// Sketch slot ------------------------------------------------------------------
+// One drawing, built from the same .view-slot kit as the photo slots so every
+// state (empty / uploading / uploaded / error) is already designed.
+
+function sketchSlotEl() {
+ return els.sketchGrid?.querySelector('.view-slot') || null;
+}
+
+function buildSketchSlot() {
+ if (!els.sketchGrid || els.sketchGrid.childElementCount) return;
+ const slot = document.createElement('div');
+ slot.className = 'view-slot';
+ slot.tabIndex = 0;
+ slot.setAttribute('role', 'button');
+ slot.innerHTML = `
+ <div class="vs-empty">
+ <span class="vs-icon" aria-hidden="true">✎</span>
+ <span class="vs-label">Sketch</span>
+ </div>
+ <div class="vs-uploading">
+ <div class="shimmer" aria-hidden="true"></div>
+ <span>Uploading…</span>
+ </div>
+ <img loading="lazy" decoding="async" class="vs-thumb" alt="" />
+ <span class="vs-badge">Sketch</span>
+ <button type="button" class="vs-remove" aria-label="Remove sketch">×</button>
+ <div class="vs-error">
+ <span class="vs-error-msg">Upload failed</span>
+ <button type="button" class="vs-retry">Retry</button>
+ </div>`;
+
+ slot.querySelector('.vs-remove').addEventListener('click', (e) => {
+ e.stopPropagation();
+ clearSketch();
+ });
+ slot.querySelector('.vs-retry').addEventListener('click', (e) => {
+ e.stopPropagation();
+ openSketchPicker();
+ });
+ slot.addEventListener('click', () => {
+ if (sketch.state === 'empty' || sketch.state === 'error') openSketchPicker();
+ });
+ slot.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ if (sketch.state === 'empty' || sketch.state === 'error') openSketchPicker();
+ }
+ });
+ slot.addEventListener('dragover', (e) => {
+ e.preventDefault();
+ e.dataTransfer.dropEffect = 'copy';
+ slot.classList.add('drop-target');
+ });
+ slot.addEventListener('dragleave', () => slot.classList.remove('drop-target'));
+ slot.addEventListener('drop', (e) => {
+ e.preventDefault();
+ slot.classList.remove('drop-target');
+ const file = e.dataTransfer.files?.[0];
+ if (file) uploadSketch(file);
+ });
+
+ els.sketchGrid.appendChild(slot);
+ renderSketchSlot();
+}
+
+function openSketchPicker() {
+ if (!els.sketchFileInput) return;
+ els.sketchFileInput.value = '';
+ els.sketchFileInput.click();
+}
+
+function renderSketchSlot() {
+ const el = sketchSlotEl();
+ if (!el) return;
+ el.dataset.state = sketch.state;
+ const img = el.querySelector('.vs-thumb');
+ if (sketch.objectUrl) {
+ img.src = sketch.objectUrl;
+ img.alt = 'Your sketch';
+ } else {
+ img.removeAttribute('src');
+ img.alt = '';
+ }
+ el.querySelector('.vs-error-msg').textContent = sketch.errorMsg || 'Upload failed';
+ const labels = {
+ empty: 'Sketch, empty — add a drawing',
+ uploading: 'Sketch, uploading',
+ uploaded: 'Sketch, uploaded',
+ error: 'Sketch, upload failed',
+ };
+ el.setAttribute('aria-label', labels[sketch.state] || 'Sketch');
+}
+
+function clearSketch() {
+ if (sketch.objectUrl) URL.revokeObjectURL(sketch.objectUrl);
+ Object.assign(sketch, { state: 'empty', url: null, objectUrl: null, errorMsg: '' });
+ renderSketchSlot();
+}
+
+async function uploadSketch(file) {
+ if (!ACCEPTED_TYPES.has(file.type)) {
+ Object.assign(sketch, { state: 'error', url: null, errorMsg: 'Use PNG, JPG, or WebP.' });
+ renderSketchSlot();
+ return;
+ }
+ if (file.size === 0) {
+ Object.assign(sketch, { state: 'error', url: null, errorMsg: 'File is empty.' });
+ renderSketchSlot();
+ return;
+ }
+ if (file.size > MAX_UPLOAD_BYTES) {
+ Object.assign(sketch, { state: 'error', url: null, errorMsg: 'Too large (max 8 MB).' });
+ renderSketchSlot();
+ return;
+ }
+ if (sketch.objectUrl) URL.revokeObjectURL(sketch.objectUrl);
+ Object.assign(sketch, {
+ state: 'uploading',
+ url: null,
+ objectUrl: URL.createObjectURL(file),
+ errorMsg: '',
+ });
+ renderSketchSlot();
+
+ const up = await presignAndPut(file);
+ if (up.ok) Object.assign(sketch, { state: 'uploaded', url: up.url, errorMsg: '' });
+ else Object.assign(sketch, { state: 'error', url: null, errorMsg: up.message });
+ renderSketchSlot();
+}
+
+function firstPreviewUrl() {
+ const s = slots.find((x) => x.state === 'uploaded' && (x.objectUrl || x.url));
+ return s ? s.objectUrl || s.url : null;
+}
+
+// Job submission --------------------------------------------------------------
+
+// Headers for a forge request, including the BYOK provider key (geometry path)
+// when the user has entered one. The key rides a header, never the URL.
+function forgeHeaders(extra) {
+ const h = { ...CLIENT_HEADERS, ...extra };
+ if (providerKey) h['x-forge-provider-key'] = providerKey;
+ // Carry the holder's $THREE tier pass so an eligible holder clears the High-tier
+ // gate (and gets their free-lane multiplier). No-op for anonymous users — the
+ // request simply proceeds at the base entitlement.
+ attachTierPass(h);
+ return h;
+}
+
+async function startJob({ prompt, imageUrls, skipValidation, payment }) {
+ const base = { path: selectedEngine.path, tier: selectedTier, backend: selectedEngine.backend };
+ const body =
+ Array.isArray(imageUrls) && imageUrls.length
+ ? { image_urls: imageUrls, prompt: prompt || undefined, ...base }
+ : { prompt, aspect_ratio: aspectRatio, ...base };
+ // Caller already saw the vision warning and chose to proceed (Consumer 1).
+ if (skipValidation) body.skip_validation = true;
+ // Pay-per-use proof: a non-holder who paid $THREE for this High generation
+ // presents the settled payment so the server's gate is satisfied per use.
+ if (payment?.paymentId && payment?.refId) {
+ body.payment_id = payment.paymentId;
+ body.ref_id = payment.refId;
+ }
+
+ // Platform-keyed High is the $THREE-gated combination — mint/refresh the holder's tier
+ // pass and AWAIT it so forgeHeaders attaches a fresh, RPC-free proof on this very
+ // request. An eligible holder then clears the server gate even if a live on-chain read
+ // would hiccup, and even when they submit faster than the background primeTierPass()
+ // could finish. An eligible *connected* wallet (no signed-in account) signs once here to
+ // prove ownership — interactive only when eligible so a non-holder is never popped a
+ // signature; a signed-in holder still mints silently via their session. No-op for
+ // anonymous callers, the free tiers, and BYOK High (server-exempt — no pass needed).
+ if (highTierNeedsPass()) await getTierPass({ interactive: Boolean(_highAccess?.eligible) });
+
+ const res = await fetch('/api/forge', {
+ method: 'POST',
+ headers: forgeHeaders({ 'content-type': 'application/json' }),
+ body: JSON.stringify(body),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (res.status === 503 || data.error === 'unconfigured') {
+ const e = new Error(data.message || 'unconfigured');
+ e.kind = 'unconfigured';
+ throw e;
+ }
+ // Geometry path needs a BYOK key we don't have — a recoverable, designed state.
+ if (data.error === 'needs_key') {
+ const e = new Error(data.message || 'An API key is required for this engine.');
+ e.kind = 'needs_key';
+ e.provider = data.provider;
+ throw e;
+ }
+ if (data.error === 'invalid_key') {
+ const e = new Error(data.message || 'The provider rejected this API key.');
+ e.kind = 'invalid_key';
+ throw e;
+ }
+ if (data.error === 'insufficient_credits') {
+ const e = new Error(data.message || 'The provider account is out of credits.');
+ e.kind = 'credits';
+ throw e;
+ }
+ // Vision pre-check rejected the reference photo (Consumer 1). Recoverable:
+ // the user can swap the photo (Try again) or override (Generate anyway).
+ if (res.status === 422 && data.error === 'image_not_usable') {
+ const e = new Error(data.message || 'That photo doesn’t look usable for 3D.');
+ e.kind = 'not_usable';
+ throw e;
+ }
+ if (res.status === 429 || data.error === 'rate_limited') {
+ const headerReset = Number(res.headers.get('ratelimit-reset'));
+ const secs =
+ Number(data.retry_after) > 0
+ ? Math.ceil(Number(data.retry_after))
+ : headerReset > 0
+ ? Math.ceil(headerReset)
+ : 10;
+ // `rate_limiter_unavailable` means the distributed limiter (Redis) is down
+ // and the paid lane is failing closed — not that the user spent their quota.
+ const unavailable = data.reason === 'rate_limiter_unavailable';
+ const e = new Error(
+ data.message ||
+ (unavailable
+ ? 'The generator is temporarily unavailable. Refine your current model locally, or try again shortly.'
+ : `You've hit the generation limit. It resets in about ${secs}s.`),
+ );
+ e.kind = 'rate_limited';
+ e.retryAfter = secs;
+ e.unavailable = unavailable;
+ throw e;
+ }
+ // High-tier hold-to-access gate ($THREE) — a hold-OR-pay 402 (three_hold_required).
+ // Recoverable: the user can hold $THREE (Get $THREE) or drop to Draft/Standard.
+ // Carries the full gate payload (held vs required, usd_to_go, acquire, pay_per_use)
+ // straight to the upsell modal.
+ if (res.status === 402 && data.error === 'three_hold_required') {
+ const e = new Error(data.message || 'High-quality generation is a $THREE holder perk.');
+ e.kind = 'hold_required';
+ e.gate = data;
+ throw e;
+ }
+ // Pay-per-use proof was rejected (bad/expired payment) or already spent — both
+ // recoverable by paying again. payment_invalid/expired re-offer Pay; an already
+ // used payment also clears the stale proof so a retry doesn't replay it.
+ if (
+ res.status === 402 &&
+ (data.error === 'payment_invalid' || data.error === 'payment_expired')
+ ) {
+ const e = new Error(data.message || 'That $THREE payment could not be verified.');
+ e.kind = 'payment_invalid';
+ e.gate = data;
+ throw e;
+ }
+ if (res.status === 409 && data.error === 'payment_already_used') {
+ const e = new Error(data.message || 'That payment was already used. Pay again to generate.');
+ e.kind = 'payment_used';
+ e.gate = data;
+ throw e;
+ }
+ // Free lane shed this request at the fleet concurrency cap — an influx of
+ // demand, not the user's quota. Recoverable with a short auto-retry, framed as
+ // "high demand" rather than a failure the user caused. (provider_busy comes
+ // from an explicit free-engine pick at capacity; free_lane_unavailable from the
+ // Spaces chain being briefly all-down.)
+ if (data.error === 'provider_busy' || data.error === 'free_lane_unavailable') {
+ const e = new Error(data.message || 'The free 3D engines are at capacity right now.');
+ e.kind = 'busy';
+ e.retryAfter = Number(data.retry_after) > 0 ? Math.ceil(Number(data.retry_after)) : 15;
+ throw e;
+ }
+ if (!res.ok) {
+ throw new Error(data.message || `The generator returned ${res.status}.`);
+ }
+ return data;
+}
+
+async function pollUntilDone(jobId) {
+ const deadline = performance.now() + MAX_POLL_MS;
+ while (!pollAbort && performance.now() < deadline) {
+ await sleep(POLL_INTERVAL_MS);
+ if (pollAbort) return null;
+ const res = await fetch(`/api/forge?job=${encodeURIComponent(jobId)}`, {
+ headers: forgeHeaders(),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (data.error === 'unconfigured') {
+ const e = new Error(data.message || 'unconfigured');
+ e.kind = 'unconfigured';
+ throw e;
+ }
+ if (data.status === 'done' && data.glb_url) return data;
+ if (data.status === 'failed') throw new Error(data.error || 'Generation failed.');
+ if (data.status === 'running') setStep('mesh', 'active');
+ }
+ if (pollAbort) return null;
+ throw new Error(
+ 'Generation timed out. The model may be too complex — try fewer views or a simpler prompt.',
+ );
+}
+
+// Post the human verdict on a creation — the labeled half of the data flywheel.
+function sendFeedback(payload) {
+ if (!currentCreationId) return;
+ fetch('/api/forge-feedback', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', ...CLIENT_HEADERS },
+ body: JSON.stringify({ creation_id: currentCreationId, ...payload }),
+ keepalive: true,
+ }).catch(() => {});
+}
+
+function resetVerdict() {
+ if (!els.verdict) return;
+ for (const b of els.verdict.querySelectorAll('button')) {
+ b.setAttribute('aria-pressed', 'false');
+ }
+}
+
+function resetCategoryPicker() {
+ if (!els.categoryPicker) return;
+ els.categoryPicker.querySelectorAll('.forge-cat-btn').forEach((b) => b.classList.remove('active'));
+}
+
+function sendCategory(modelCategory) {
+ if (!currentCreationId) return;
+ fetch('/api/forge-categorize', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', ...CLIENT_HEADERS },
+ body: JSON.stringify({ creation_id: currentCreationId, model_category: modelCategory }),
+ keepalive: true,
+ }).catch(() => {});
+}
+
+// Poster capture — the visual half of every creation card. Image-intermediate
+// engines store their flux reference image as the preview, but geometry-first
+// and sketch lanes paint no image at all, so their gallery/showcase cards used
+// to render as glyph placeholders. Once the finished mesh is standing in the
+// viewer, render it onto a small studio-backdrop canvas and attach it to the
+// creation row (POST /api/forge-poster — fill-only, owner-scoped, best-effort).
+const POSTER_MAX_DIM = 640;
+const postedPosters = new Set();
+
+function renderPosterFrame(sourceDataUrl) {
+ return new Promise((resolve) => {
+ const img = new Image();
+ img.onload = () => {
+ const scale = Math.min(1, POSTER_MAX_DIM / Math.max(img.width, img.height, 1));
+ const w = Math.max(1, Math.round(img.width * scale));
+ const h = Math.max(1, Math.round(img.height * scale));
+ const canvas = document.createElement('canvas');
+ canvas.width = w;
+ canvas.height = h;
+ const ctx = canvas.getContext('2d');
+ if (!ctx) return resolve(null);
+ // Same studio backdrop as the live viewer, so mesh posters read as a
+ // consistent set next to flux reference images in the galleries.
+ const backdrop = ctx.createRadialGradient(w / 2, 0, 0, w / 2, 0, Math.max(w, h) * 1.2);
+ backdrop.addColorStop(0, '#1a1612');
+ backdrop.addColorStop(0.7, '#0b0a09');
+ backdrop.addColorStop(1, '#0b0a09');
+ ctx.fillStyle = backdrop;
+ ctx.fillRect(0, 0, w, h);
+ ctx.drawImage(img, 0, 0, w, h);
+ const webp = canvas.toDataURL('image/webp', 0.85);
+ // Browsers without webp encoding silently hand back PNG — send what we got.
+ resolve(webp.startsWith('data:image/webp') ? webp : canvas.toDataURL('image/png'));
+ };
+ img.onerror = () => resolve(null);
+ img.src = sourceDataUrl;
+ });
+}
+
+async function capturePoster(creationId) {
+ if (!creationId || postedPosters.has(creationId) || !els.viewer?.toDataURL) return;
+ postedPosters.add(creationId);
+ try {
+ if (!els.viewer.loaded) {
+ await new Promise((resolve) =>
+ els.viewer.addEventListener('load', resolve, { once: true }),
+ );
+ }
+ // Let the materialize entrance settle so the capture is a steady frame.
+ await sleep(REDUCED_MOTION ? 300 : 1500);
+ // A newer generation or an opened creation replaced the model — skip.
+ if (currentCreationId !== creationId) return;
+ const frame = await renderPosterFrame(els.viewer.toDataURL('image/png'));
+ if (!frame) return;
+ const res = await fetch('/api/forge-poster', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', ...CLIENT_HEADERS },
+ body: JSON.stringify({ creation_id: creationId, image: frame }),
+ });
+ const data = await res.json().catch(() => ({}));
+ // The card for this creation is already on screen with a placeholder —
+ // refresh the strip so the new poster shows without a reload.
+ if (data?.stored) loadGallery();
+ } catch {
+ // Best-effort: a missed poster never disturbs the result flow.
+ }
+}
+
+// Render the provenance badge from job metadata: how the mesh was produced
+// (engine + tier + path) plus any multi-view conditioning. Shows whatever is
+// known — the geometry-first path has no reference views, the image path does.
+function setViewsBadge(meta) {
+ if (!els.resultViews) return;
+ const parts = [];
+ const used = Number(meta?.views_used);
+ if (Number.isFinite(used) && used >= 1) {
+ parts.push(`${used} ${used === 1 ? 'view' : 'views'}`);
+ if (meta.multiview) parts.push('multi-view');
+ }
+ if (meta?.backend) parts.push(ENGINE_LABELS[meta.backend] || meta.backend);
+ if (meta?.tier) parts.push(meta.tier);
+ if (meta?.path === 'geometry') parts.push('geometry-first');
+ if (meta?.path === 'sketch') parts.push('sketch→3D');
+ if (parts.length === 0) {
+ els.resultViews.classList.add('is-hidden');
+ els.resultViews.textContent = '';
+ return;
+ }
+ els.resultViews.textContent = parts.join(' · ');
+ els.resultViews.classList.remove('is-hidden');
+}
+
+// Materialize entrance — conceal the standing viewer, play the WebGL dissolve
+// reveal over it (src/forge-reveal.js), then crossfade back and hand the
+// final camera angle to model-viewer so the turntable continues seamlessly.
+// Presentation only: any failure restores the viewer immediately.
+let revealSeq = 0;
+async function playMaterialize(glbUrl) {
+ if (REDUCED_MOTION || !els.viewerShell) return;
+ const seq = ++revealSeq;
+ els.viewer.style.opacity = '0';
+ try {
+ const { playForgeReveal } = await import('./forge-reveal.js');
+ const viewerLoaded = new Promise((resolve) => {
+ if (els.viewer.loaded) return resolve();
+ els.viewer.addEventListener('load', resolve, { once: true });
+ });
+ const end = await playForgeReveal({
+ container: els.viewerShell,
+ glbUrl,
+ waitFor: viewerLoaded,
+ });
+ if (seq === revealSeq && end && Number.isFinite(end.azimuthDeg)) {
+ els.viewer.cameraOrbit = `${end.azimuthDeg.toFixed(1)}deg ${end.polarDeg.toFixed(1)}deg auto`;
+ }
+ } catch {
+ // The standing viewer is the fallback — nothing to surface.
+ } finally {
+ if (seq === revealSeq) els.viewer.style.opacity = '1';
+ }
+}
+
+// Show "Refine → <next tier>" only when a higher tier exists and the current
+// result came from a job we can re-run (a prompt and/or reference images).
+function updateRefineButton() {
+ if (!els.refine) return;
+ const next = nextTierAfter(currentResultTier);
+ const reRunnable =
+ lastJob &&
+ (lastJob.prompt || (Array.isArray(lastJob.imageUrls) && lastJob.imageUrls.length));
+ const show = Boolean(next && reRunnable);
+ els.refine.classList.toggle('is-hidden', !show);
+ if (show) {
+ els.refineLabel.textContent = `Refine → ${TIER_LABELS[next]}`;
+ els.refine.title = `Re-run this exact ${
+ lastJob.imageUrls?.length ? 'reconstruction' : 'prompt'
+ } at ${TIER_LABELS[next]} quality`;
+ }
+}
+
+function showResult(glbUrl, label, meta, { autoSaved = false } = {}) {
+ stopElapsed();
+ resetVerdict();
+ resetCategoryPicker();
+ if (els.categoryPicker) els.categoryPicker.hidden = false;
+ els.viewerShell?.classList.remove('has-load-error');
+ // Show the load skeleton over the dark viewport until the GLB paints. The
+ // persistent 'load'/'error' listeners below clear it.
+ els.viewerShell?.classList.add('is-loading');
+ els.viewer.setAttribute('src', glbUrl);
+ els.viewer.setAttribute('alt', `3D model: ${label}`);
+ lastShownGlb = glbUrl;
+ els.resultLabel.textContent = label;
+ // Hide the saved chip by default; caller re-shows it for fresh generations.
+ if (els.savedChip) els.savedChip.classList.add('is-hidden');
+ setViewsBadge(meta);
+ if (autoSaved && els.savedChip) {
+ // Re-trigger the animation by forcing a reflow.
+ els.savedChip.classList.remove('is-hidden');
+ void els.savedChip.offsetWidth;
+ els.savedChip.style.animation = 'none';
+ void els.savedChip.offsetWidth;
+ els.savedChip.style.animation = '';
+ // Hide after animation completes (3s).
+ setTimeout(() => els.savedChip?.classList.add('is-hidden'), 3100);
+ }
+ els.download.href = glbUrl;
+ els.download.setAttribute(
+ 'download',
+ `${
+ label
+ .replace(/[^a-z0-9]+/gi, '-')
+ .slice(0, 48)
+ .replace(/^-|-$/g, '') || 'forge'
+ }.glb`,
+ );
+ // Cross-link into Parts Studio with this exact model pre-loaded.
+ if (els.segmentBtn) els.segmentBtn.href = `/segment?mesh=${encodeURIComponent(glbUrl)}`;
+ if (els.openInComposer) els.openInComposer.href = `/compose?glb=${encodeURIComponent(glbUrl)}`;
+ // Offer "Refine" when a higher tier exists and this job can be re-run. Use the
+ // tier the result was actually produced at (meta), falling back to the current
+ // selection for re-opened gallery models that don't carry tier metadata.
+ currentResultTier = meta?.tier || selectedTier;
+ updateRefineButton();
+ showState('result');
+ playMaterialize(glbUrl);
+ // Hand the live model to the Stylize panel (src/forge-stylize.js) so its
+ // one-click geometric filters operate on the current source mesh.
+ document.dispatchEvent(new CustomEvent('forge:model-ready', { detail: { glbUrl, label } }));
+ document.dispatchEvent(
+ new CustomEvent('tws:feature-done', {
+ detail: { feature: 'forge', model: { glbUrl, label } },
+ }),
+ );
+ if (els.forgeShareBtn) {
+ els.forgeShareBtn.dataset.sharePrompt = label;
+ }
+}
+
+// Deterministic gradient from prompt text — same prompt → same colours.
+function promptGradient(str) {
+ let h = 0;
+ for (let i = 0; i < (str || '').length; i++) h = (Math.imul(31, h) + str.charCodeAt(i)) | 0;
+ const hue = Math.abs(h) % 360;
+ return `linear-gradient(135deg,hsl(${hue},28%,14%) 0%,hsl(${(hue + 40) % 360},22%,10%) 100%)`;
+}
+
+function makeGradientThumb(prompt) {
+ const ph = document.createElement('span');
+ ph.className = 'thumb gradient-ph';
+ ph.style.background = promptGradient(prompt);
+ if (prompt) {
+ const label = document.createElement('span');
+ label.className = 'gradient-ph-text';
+ label.textContent = prompt;
+ ph.appendChild(label);
+ }
+ return ph;
+}
+
+// Load (or reload) the "Your creations" strip from durable storage.
+async function loadGallery() {
+ if (!els.creations) return;
+
+ els.creations.classList.remove('is-hidden');
+ els.creationsGrid.setAttribute('aria-busy', 'true');
+ els.creationsGrid.innerHTML = skeletonHTML(4, 'card');
+
+ let data;
+ try {
+ const res = await fetch('/api/forge-gallery?limit=24', { headers: CLIENT_HEADERS });
+ data = await res.json().catch(() => ({}));
+ } catch {
+ els.creationsGrid.removeAttribute('aria-busy');
+ els.creationsGrid.innerHTML = errorStateHTML({
+ title: "Couldn't load your creations",
+ body: 'Check your connection — your models are still saved.',
+ });
+ els.creationsGrid.querySelector('[data-sk-retry]')?.addEventListener('click', loadGallery);
+ return;
+ }
+
+ els.creationsGrid.removeAttribute('aria-busy');
+ const creations = Array.isArray(data?.creations) ? data.creations : [];
+ if (!data?.enabled || creations.length === 0) {
+ els.creations.classList.add('is-hidden');
+ return;
+ }
+ els.creationsGrid.innerHTML = '';
+ for (const c of creations) {
+ const card = document.createElement('button');
+ card.type = 'button';
+ card.className = 'creation';
+ card.title = c.prompt || 'Forged model';
+ card.setAttribute('aria-label', `Open: ${c.prompt || 'forged model'}`);
+ if (c.id) card.dataset.creationId = c.id;
+
+ if (c.preview_image_url) {
+ const img = document.createElement('img');
+ img.className = 'thumb';
+ img.loading = 'lazy';
+ img.alt = '';
+ img.src = c.preview_image_url;
+ img.onerror = () => {
+ // Thumbnail URL broken — show gradient fallback.
+ img.replaceWith(makeGradientThumb(c.prompt));
+ };
+ card.appendChild(img);
+ } else {
+ card.appendChild(makeGradientThumb(c.prompt));
+ }
+
+ if (c.outcome === 'accepted' || c.outcome === 'rejected') {
+ const badge = document.createElement('span');
+ badge.className = 'badge';
+ badge.dataset.outcome = c.outcome;
+ badge.textContent = c.outcome === 'accepted' ? '👍' : '👎';
+ card.appendChild(badge);
+ }
+
+ // Surface multi-view provenance so the gallery reflects how each model
+ // was conditioned.
+ if (Number(c.views_used) > 1) {
+ const mv = document.createElement('span');
+ mv.className = 'badge';
+ mv.style.left = '6px';
+ mv.style.right = 'auto';
+ mv.textContent = `${c.views_used}×`;
+ mv.title = `${c.views_used} reference views`;
+ card.appendChild(mv);
+ }
+
+ // Engine · tier provenance, so the gallery reflects how each was made.
+ if (c.backend || c.tier) {
+ const prov = document.createElement('span');
+ prov.className = 'badge';
+ prov.style.left = '6px';
+ prov.style.right = 'auto';
+ prov.style.top = Number(c.views_used) > 1 ? '28px' : '6px';
+ prov.textContent = [ENGINE_LABELS[c.backend] || c.backend, c.tier]
+ .filter(Boolean)
+ .join(' ');
+ prov.title =
+ `${c.path === 'geometry' ? 'Geometry-first' : c.path === 'sketch' ? 'Sketch→3D' : 'Image path'} · ${c.backend || ''} · ${c.tier || ''}`.trim();
+ card.appendChild(prov);
+ }
+
+ const meta = document.createElement('span');
+ meta.className = 'meta';
+ meta.textContent = c.prompt || 'Untitled';
+ card.appendChild(meta);
+
+ card.addEventListener('click', () => openCreation(c));
+
+ els.creationsGrid.appendChild(card);
+ }
+ els.creationsCount.textContent = `${creations.length} saved`;
+ els.creations.classList.remove('is-hidden');
+}
+
+// Load a creation into the viewer — shared by gallery card clicks and the
+// share-link path. `c` is a creation row from /api/forge-gallery or
+// /api/forge-creation; both return the same shape.
+function openCreation(c, { scroll = true } = {}) {
+ currentCreationId = c.id;
+ lastJob = { prompt: c.prompt || '', imageUrls: [] };
+ showResult(c.glb_url, c.prompt || 'Forged model', {
+ views_used: c.views_used,
+ multiview: c.multiview,
+ backend: c.backend,
+ tier: c.tier,
+ path: c.path,
+ });
+ if (els.verdict) {
+ for (const b of els.verdict.querySelectorAll('button')) {
+ b.setAttribute('aria-pressed', String(b.dataset.outcome === c.outcome));
+ }
+ }
+ if (scroll) els.stage.scrollIntoView({ behavior: 'smooth', block: 'start' });
+}
+
+// Open a creation from a share link. The model belongs to whoever forged it, so
+// it won't be in this browser's gallery — fetch it directly by id. If the card
+// is already present (the owner re-opening their own share link), reuse it.
+async function openSharedCreation(shareId) {
+ const card = els.creationsGrid?.querySelector(`[data-creation-id="${shareId}"]`);
+ if (card) {
+ card.click();
+ card.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ return;
+ }
+ let creation = null;
+ try {
+ const res = await fetch(`/api/forge-creation?id=${encodeURIComponent(shareId)}`, {
+ headers: CLIENT_HEADERS,
+ });
+ const data = await res.json().catch(() => ({}));
+ creation = data?.creation || null;
+ } catch {
+ creation = null;
+ }
+ if (creation?.glb_url) {
+ openCreation(creation);
+ } else {
+ showError(
+ "This shared creation isn't available — it may have been removed or is still generating.",
+ );
+ }
+}
+
+function showError(message, { allowOverride = false } = {}) {
+ stopElapsed();
+ stopRateLimitCountdown();
+ els.errorMessage.textContent = message;
+ // The "Generate anyway" affordance only exists for the vision pre-check
+ // rejection; every other error hides it so it can't leak across states.
+ if (els.generateAnyway) els.generateAnyway.classList.toggle('is-hidden', !allowOverride);
+ // The local-refine escape hatch belongs only to the rate-limit state.
+ if (els.refineLocally) els.refineLocally.classList.add('is-hidden');
+ if (els.retry) els.retry.disabled = false;
+ showState('error');
+}
+
+// Rate-limit state: a designed, recoverable treatment for a 429. Instead of a
+// dead-end "busy, try again", we (1) show a live countdown to the reset and
+// re-enable Retry automatically when it elapses, and (2) — when a model is
+// already on screen — offer the local Refine path, which needs no API and never
+// throttles, so the user is never fully blocked. Distinguishes a genuine quota
+// hit from a temporarily-unavailable limiter (Redis degraded → fail-closed).
+let rateLimitTimer = null;
+function stopRateLimitCountdown() {
+ if (rateLimitTimer) {
+ clearInterval(rateLimitTimer);
+ rateLimitTimer = null;
+ }
+}
+
+function showRateLimited({ retryAfter = 10, unavailable = false, busy = false }) {
+ stopElapsed();
+ stopRateLimitCountdown();
+ if (els.generateAnyway) els.generateAnyway.classList.add('is-hidden');
+
+ // Offer local refinement whenever a model is already loaded — that's exactly
+ // the case after the Refine button 429s, and the one moment the user most
+ // wants to keep improving without waiting on the paid lane.
+ const canRefineLocally = Boolean(lastShownGlb && els.viewer.getAttribute('src'));
+ if (els.refineLocally) els.refineLocally.classList.toggle('is-hidden', !canRefineLocally);
+
+ let remaining = Math.max(1, Math.ceil(retryAfter));
+ const base = busy
+ ? 'High demand — the free 3D engines are all busy right now.'
+ : unavailable
+ ? 'The generator is temporarily unavailable.'
+ : 'You’ve hit the generation limit.';
+ const tail = canRefineLocally ? ' Or refine your current model now — instant and unlimited.' : '';
+
+ const render = () => {
+ els.errorMessage.textContent =
+ remaining > 0 ? `${base} Retrying is available in ${remaining}s.${tail}` : `${base} You can try again now.${tail}`;
+ };
+ // While counting down, Retry is disabled (it would just 429 again); it
+ // re-enables the moment the window resets.
+ if (els.retry) els.retry.disabled = remaining > 0;
+ render();
+ showState('error');
+
+ rateLimitTimer = setInterval(() => {
+ remaining -= 1;
+ if (remaining <= 0) {
+ stopRateLimitCountdown();
+ if (els.retry) els.retry.disabled = false;
+ }
+ render();
+ }, 1000);
+}
+
+// Run a job (text or image/multi-view). `cfg` = { prompt, imageUrls }.
+async function run(cfg) {
+ lastJob = cfg;
+ pollAbort = false;
+ currentCreationId = null;
+ setBusy(true);
+
+ const isImage = Array.isArray(cfg.imageUrls) && cfg.imageUrls.length > 0;
+ const isGeometry = selectedEngine.path === 'geometry';
+ const isSketch = selectedEngine.path === 'sketch';
+ const meshLabel = `Generating ${selectedTier} mesh`;
+
+ // Reset the generating panel to its real starting state for this run.
+ if (isSketch) {
+ // The drawing IS the reference — no synthesis step, straight to geometry.
+ setStepLabel('image', 'Sketch uploaded');
+ setStepLabel('mesh', `Generating ${selectedTier} geometry from the sketch`);
+ setStep('image', 'done');
+ setStep('mesh', 'active');
+ const preview = sketch.objectUrl || sketch.url;
+ els.genPreview.innerHTML = preview ? '' : '<div class="shimmer" aria-hidden="true"></div>';
+ if (preview) {
+ const img = new Image();
+ img.alt = 'Your sketch';
+ img.src = preview;
+ els.genPreview.appendChild(img);
+ }
+ } else if (isImage) {
+ const n = cfg.imageUrls.length;
+ setStepLabel('image', `Conditioning on ${n} ${n === 1 ? 'view' : 'views'}`);
+ setStepLabel('mesh', isGeometry ? meshLabel : 'Reconstructing textured mesh');
+ setStep('image', 'done');
+ setStep('mesh', 'active');
+ const preview = firstPreviewUrl();
+ els.genPreview.innerHTML = preview ? '' : '<div class="shimmer" aria-hidden="true"></div>';
+ if (preview) {
+ const img = new Image();
+ img.alt = 'Reference view';
+ img.src = preview;
+ els.genPreview.appendChild(img);
+ }
+ } else if (isGeometry) {
+ // Geometry-first: no reference image is painted — the model emits geometry
+ // straight from the prompt, so the first step is already complete.
+ setStepLabel('image', 'Geometry-first — no reference image');
+ setStepLabel('mesh', meshLabel);
+ setStep('image', 'done');
+ setStep('mesh', 'active');
+ els.genPreview.innerHTML = '<div class="shimmer" aria-hidden="true"></div>';
+ } else {
+ setStepLabel('image', 'Painting reference image');
+ setStepLabel('mesh', 'Reconstructing textured mesh');
+ els.genPreview.innerHTML = '<div class="shimmer" aria-hidden="true"></div>';
+ setStep('image', 'active');
+ setStep('mesh', 'pending');
+ }
+ setStep('finish', 'pending');
+ startElapsed();
+ showState('generating');
+
+ const label = cfg.prompt || (isImage ? 'Multi-view reconstruction' : '');
+
+ try {
+ const job = await startJob(cfg);
+ if (job.creation_id) currentCreationId = job.creation_id;
+
+ // Text→3D: the reference image resolved before the POST returned — show it.
+ if (!isImage && job.preview_image_url) {
+ setStep('image', 'done');
+ setStep('mesh', 'active');
+ const img = new Image();
+ img.alt = 'Reference image';
+ img.src = job.preview_image_url;
+ img.onload = () => {
+ els.genPreview.innerHTML = '';
+ els.genPreview.appendChild(img);
+ };
+ }
+
+ // The free draft lane (NVIDIA NIM) completes synchronously — the POST
+ // itself returns the finished model with a null job_id. Polling that
+ // null id would loop on invalid_job until the timeout, losing a result
+ // that already succeeded.
+ const done = job.status === 'done' && job.glb_url ? job : await pollUntilDone(job.job_id);
+ if (pollAbort || !done) return; // cancelled
+
+ // A pay-per-use proof is single-use and now redeemed on the server — drop it
+ // so a later Retry/Refine of this job never replays a spent payment.
+ if (lastJob) delete lastJob.payment;
+
+ if (done.creation_id) currentCreationId = done.creation_id;
+ setStep('mesh', 'done');
+ setStep('finish', 'done');
+ markProgressDone();
+ // Prefer the poll's recorded meta; fall back to the submit response.
+ showResult(
+ done.glb_url,
+ label || 'Forged model',
+ {
+ views_used: done.views_used ?? job.views_used,
+ multiview: done.multiview ?? job.multiview,
+ backend: done.backend ?? job.backend,
+ tier: done.tier ?? job.tier,
+ path: done.path ?? job.path,
+ },
+ { autoSaved: !!done.creation_id },
+ );
+ loadGallery();
+ // Geometry-first and sketch lanes have no reference image — render the
+ // finished mesh itself as the creation's card visual.
+ if (!(done.preview_image_url ?? job.preview_image_url)) {
+ capturePoster(currentCreationId);
+ }
+ } catch (err) {
+ if (pollAbort) return;
+ if (err.kind === 'unconfigured') {
+ stopElapsed();
+ showState('unconfigured');
+ return;
+ }
+ // Recoverable BYOK problems — reveal + focus the key field so the user can
+ // fix it and hit Retry, rather than hitting a dead end.
+ if (err.kind === 'needs_key' || err.kind === 'invalid_key') {
+ stopElapsed();
+ els.byokRow?.classList.remove('is-hidden');
+ if (els.providerKey) {
+ els.providerKey.setAttribute('aria-invalid', 'true');
+ els.providerKey.focus();
+ }
+ showError(err.message || 'Add your API key to use this engine, then retry.');
+ return;
+ }
+ if (err.kind === 'credits') {
+ stopElapsed();
+ showError(err.message || 'The provider account is out of credits.');
+ return;
+ }
+ // The reference photo failed the vision pre-check. Offer "Generate anyway"
+ // so a confident user is never permanently blocked by a cautious verdict.
+ if (err.kind === 'not_usable') {
+ showError(err.message, { allowOverride: true });
+ return;
+ }
+ // Rate limited (or the limiter is temporarily unavailable). Designed,
+ // recoverable state with a live countdown + the local-refine escape hatch.
+ if (err.kind === 'rate_limited') {
+ showRateLimited({ retryAfter: err.retryAfter, unavailable: err.unavailable });
+ return;
+ }
+ // Free lane at capacity under load — same recoverable countdown UI, framed as
+ // high demand. Auto-retry lands the user in line as slots free up, and the
+ // local-refine escape hatch still applies when a model is already on screen.
+ if (err.kind === 'busy') {
+ showRateLimited({ retryAfter: err.retryAfter, busy: true });
+ return;
+ }
+ // High-tier $THREE gate: open the designed upsell (Get $THREE / what you hold
+ // vs. need — plus the working Pay-per-use CTA) and reset to the idle composer
+ // so the user can switch tier, hold, or pay.
+ if (err.kind === 'hold_required') {
+ stopElapsed();
+ showState('empty');
+ // Reflect the server's verdict back onto the composer (lock the High
+ // option + the button pill/note) before opening the upsell, so the gate is
+ // felt in place too — not only in the modal.
+ highLocked = true;
+ _highAccess = err.gate || _highAccess;
+ applyHighGate();
+ applyHighAffordances(err.gate);
+ onGate(err.gate, gateOpts());
+ return;
+ }
+ // A presented pay-per-use proof was already spent — drop the stale payment so
+ // Retry doesn't replay it, and re-open the pay flow for a fresh generation.
+ if (err.kind === 'payment_used') {
+ stopElapsed();
+ if (lastJob) delete lastJob.payment;
+ showState('empty');
+ showError(err.message || 'That payment was already used. Pay again to generate.');
+ return;
+ }
+ // The proof was rejected (bad/expired) before any model — drop it and surface
+ // the gate's Pay-per-use path again so the user can pay cleanly.
+ if (err.kind === 'payment_invalid') {
+ stopElapsed();
+ if (lastJob) delete lastJob.payment;
+ showState('empty');
+ if (err.gate) onGate(err.gate, gateOpts());
+ else showError(err.message || 'That $THREE payment could not be verified.');
+ return;
+ }
+ showError(
+ err.message ||
+ 'Something went wrong. Try a simpler, single-subject prompt or cleaner photos.',
+ );
+ } finally {
+ setBusy(false);
+ }
+}
+
+// Gather + validate the active mode's composer inputs into a run cfg, or null
+// when something's missing (focusing/flagging the offending field as a side
+// effect, exactly as submit always has). Shared by the Generate button and the
+// pay-per-use path so both build the job identically.
+function collectComposerCfg() {
+ if (mode === 'text') {
+ const prompt = els.prompt.value.trim();
+ if (prompt.length < 3) {
+ els.prompt.focus();
+ return null;
+ }
+ return { prompt, imageUrls: [] };
+ }
+
+ // Sketch mode — one drawing + a required prompt naming what it depicts.
+ if (mode === 'sketch') {
+ if (sketch.state === 'uploading') {
+ els.generateLabel.textContent = 'Waiting for upload…';
+ setTimeout(() => {
+ if (!els.generate.disabled) els.generateLabel.textContent = 'Generate';
+ }, 1600);
+ return null;
+ }
+ if (sketch.state !== 'uploaded' || !sketch.url) {
+ const slot = sketchSlotEl();
+ slot?.focus();
+ slot?.classList.add('drop-target');
+ setTimeout(() => slot?.classList.remove('drop-target'), 600);
+ return null;
+ }
+ const prompt = els.sketchPrompt.value.trim();
+ if (prompt.length < 3) {
+ // Make the required-input contract unmissable: flag the field and tint
+ // the "Required" tag until the user types a description.
+ els.sketchPrompt.setAttribute('aria-invalid', 'true');
+ if (els.sketchReqTag) els.sketchReqTag.dataset.missing = 'true';
+ els.sketchPrompt.focus();
+ return null;
+ }
+ return { prompt, imageUrls: [sketch.url] };
+ }
+
+ // Image / multi-view mode.
+ if (slots.some((s) => s.state === 'uploading')) {
+ els.generateLabel.textContent = 'Waiting for uploads…';
+ setTimeout(() => {
+ if (!els.generate.disabled) els.generateLabel.textContent = 'Generate';
+ }, 1600);
+ return null;
+ }
+ const urls = uploadedUrls();
+ if (urls.length === 0) {
+ const first = slotEl(0);
+ first?.focus();
+ first?.classList.add('drop-target');
+ setTimeout(() => first?.classList.remove('drop-target'), 600);
+ return null;
+ }
+ return { prompt: els.imagePrompt.value.trim(), imageUrls: urls };
+}
+
+function submit() {
+ // Platform-keyed High is a $THREE holder perk. The Generate button is disabled
+ // when locked, but a keyboard submit (⌘↵) can still reach here — open the upsell
+ // (with the working Pay-per-use path) instead of firing a request the server will
+ // gate. BYOK High is exempt, so highTierNeedsPass() lets it through untouched.
+ if (highTierNeedsPass() && highLocked) {
+ if (_highAccess) onGate(_highAccess, gateOpts());
+ else reflectHighAccess('high');
+ return;
+ }
+ const cfg = collectComposerCfg();
+ if (cfg) run(cfg);
+}
+
+// Options handed to the gate modal / in-place lock so their "Pay per generation"
+// CTA actually works: pay $THREE for one High generation, then run the current
+// composer inputs with the settled proof attached.
+function gateOpts() {
+ return { onPayPerUse: (pay) => payThenGenerate(pay) };
+}
+
+// The consumption lever, end to end: price comes from the gate's pay_per_use (or
+// the resolved access), the user pays $THREE through the designed modal, and the
+// generation re-fires immediately with { paymentId, refId } so the server's gate
+// is satisfied per use. No-op if the composer inputs are incomplete (the field is
+// focused) or the user cancels the payment.
+async function payThenGenerate(pay) {
+ const usd = Number(pay?.usd) || Number(_highAccess?.pay_per_use?.usd) || 0;
+ if (!(usd > 0)) return;
+ const cfg = collectComposerCfg();
+ if (!cfg) return;
+ // Ensure the job runs at High (the tier the payment buys) even if the click
+ // came from the in-place lock before any submit.
+ if (selectedTier !== 'high') selectTier('high');
+ const result = await payForHighGeneration({ usd });
+ if (!result?.ok) return; // cancelled or failed — the modal explained why
+ run({ ...cfg, payment: { paymentId: result.paymentId, refId: result.refId } });
+}
+
+// Wiring ----------------------------------------------------------------------
+
+els.viewer.addEventListener('error', () => {
+ if (els.viewerShell) {
+ els.viewerShell.classList.add('has-load-error');
+ els.viewerShell.classList.remove('is-loading');
+ }
+});
+// Retry a failed GLB fetch in place — a transient network blip on the file (the
+// common cause) shouldn't dead-end at download-only. Clearing then re-setting src
+// on the next frame forces model-viewer to refetch the same URL.
+document.getElementById('viewer-retry')?.addEventListener('click', () => {
+ const src = els.viewer.getAttribute('src');
+ if (!src) return;
+ els.viewerShell?.classList.remove('has-load-error');
+ els.viewerShell?.classList.add('is-loading');
+ els.viewer.setAttribute('src', '');
+ requestAnimationFrame(() => els.viewer.setAttribute('src', src));
+});
+// The GLB finished painting — drop the load skeleton.
+els.viewer.addEventListener('load', () => {
+ els.viewerShell?.classList.remove('is-loading');
+});
+
+buildSlots();
+buildViewsPips();
+updateViewsCounter();
+
+els.modeSwitch.addEventListener('click', (e) => {
+ const btn = e.target.closest('button[data-mode]');
+ if (btn) setMode(btn.dataset.mode);
+});
+
+els.fileInput.addEventListener('change', () => {
+ handleFiles(pickerTarget, els.fileInput.files);
+ pickerTarget = null;
+ els.fileInput.value = '';
+});
+
+els.form.addEventListener('submit', (e) => {
+ e.preventDefault();
+ submit();
+});
+
+// Cmd/Ctrl+Enter submits from either text box.
+function submitOnModifierEnter(e) {
+ if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
+ e.preventDefault();
+ submit();
+ }
+}
+els.prompt.addEventListener('keydown', submitOnModifierEnter);
+els.imagePrompt.addEventListener('keydown', submitOnModifierEnter);
+els.sketchPrompt?.addEventListener('keydown', submitOnModifierEnter);
+
+// Typing into the sketch prompt clears the "required" warning state.
+els.sketchPrompt?.addEventListener('input', () => {
+ els.sketchPrompt.removeAttribute('aria-invalid');
+ if (els.sketchReqTag) els.sketchReqTag.dataset.missing = 'false';
+});
+
+els.sketchFileInput?.addEventListener('change', () => {
+ const file = els.sketchFileInput.files?.[0];
+ if (file) uploadSketch(file);
+ els.sketchFileInput.value = '';
+});
+
+els.aspect.addEventListener('click', (e) => {
+ const btn = e.target.closest('button[data-aspect]');
+ if (!btn) return;
+ aspectRatio = btn.dataset.aspect;
+ for (const b of els.aspect.querySelectorAll('button')) {
+ b.setAttribute('aria-pressed', String(b === btn));
+ }
+});
+
+els.examples.addEventListener('click', (e) => {
+ const chip = e.target.closest('.chip');
+ if (!chip) return;
+ setMode('text');
+ els.prompt.value = chip.textContent.trim();
+ els.prompt.focus();
+ submit();
+});
+
+// Quality tier + engine + BYOK key wiring.
+els.tier?.addEventListener('click', (e) => {
+ const btn = e.target.closest('button[data-tier]');
+ if (btn) selectTier(btn.dataset.tier);
+});
+els.engine?.addEventListener('click', (e) => {
+ const btn = e.target.closest('button[data-engine]');
+ if (btn && !btn.disabled) {
+ userPickedEngine = true;
+ selectEngine(btn);
+ }
+});
+els.providerKey?.addEventListener('input', () => {
+ providerKey = els.providerKey.value.trim();
+ els.providerKey.removeAttribute('aria-invalid');
+});
+
+els.cancel.addEventListener('click', () => {
+ pollAbort = true;
+ stopElapsed();
+ setBusy(false);
+ if (els.categoryPicker) els.categoryPicker.hidden = true;
+ showState('empty');
+});
+
+els.again.addEventListener('click', () => {
+ stopRateLimitCountdown();
+ if (els.categoryPicker) els.categoryPicker.hidden = true;
+ showState('empty');
+ if (mode === 'text') {
+ els.prompt.focus();
+ els.prompt.select();
+ } else if (mode === 'sketch') {
+ (sketch.state === 'uploaded' ? els.sketchPrompt : sketchSlotEl())?.focus();
+ } else {
+ slotEl(0)?.focus();
+ }
+});
+
+els.retry.addEventListener('click', () => {
+ if (els.retry.disabled) return; // mid-countdown; Retry re-enables at reset
+ stopRateLimitCountdown();
+ if (els.categoryPicker) els.categoryPicker.hidden = true;
+ if (lastJob && (lastJob.prompt || (lastJob.imageUrls && lastJob.imageUrls.length))) {
+ run(lastJob);
+ } else {
+ showState('empty');
+ els.prompt.focus();
+ }
+});
+
+// Rate-limit escape hatch: drop straight back to the loaded model and open the
+// local Refine panel — no API, no waiting on the throttled generation lane.
+els.refineLocally?.addEventListener('click', () => {
+ stopRateLimitCountdown();
+ showState('result');
+ els.stage?.scrollIntoView({ behavior: 'smooth', block: 'start' });
+ document.dispatchEvent(new CustomEvent('forge:refine-here'));
+});
+
+// Refine — re-run the same prompt/views one quality tier higher. Bumping the
+// tier syncs the selector (and the tier's default engine), then replays the
+// stored job, so the higher-fidelity model lands in the same viewer.
+els.refine?.addEventListener('click', async () => {
+ const next = nextTierAfter(currentResultTier);
+ if (!next || !lastJob) return;
+ selectTier(next);
+ // Refining into platform-keyed High runs the same $THREE pre-flight as selecting
+ // it: resolve the holder's eligibility first and open the upsell instead of firing
+ // a job the server would 402. BYOK High is exempt (highTierNeedsPass() is false);
+ // a transient access failure leaves highLocked false so the request proceeds and
+ // the server stays the authority.
+ if (highTierNeedsPass()) {
+ await reflectHighAccess('high', { silent: true });
+ if (highLocked) {
+ if (_highAccess) onGate(_highAccess, gateOpts());
+ return;
+ }
+ }
+ run(lastJob);
+});
+
+// "Generate anyway" — re-run the same job with the vision pre-check bypassed.
+els.generateAnyway?.addEventListener('click', () => {
+ if (!lastJob) return;
+ run({ ...lastJob, skipValidation: true });
+});
+
+if (els.verdict) {
+ els.verdict.addEventListener('click', (e) => {
+ const btn = e.target.closest('button[data-outcome]');
+ if (!btn || !currentCreationId) return;
+ const outcome = btn.dataset.outcome;
+ for (const b of els.verdict.querySelectorAll('button')) {
+ b.setAttribute('aria-pressed', String(b === btn));
+ }
+ sendFeedback({ outcome });
+ });
+}
+
+if (els.categoryPicker) {
+ els.categoryPicker.addEventListener('click', (e) => {
+ const btn = e.target.closest('.forge-cat-btn[data-cat]');
+ if (!btn || !currentCreationId) return;
+ const cat = btn.dataset.cat;
+ // Toggle: click the active cat again to deselect (back to 'other').
+ const isActive = btn.classList.contains('active');
+ els.categoryPicker.querySelectorAll('.forge-cat-btn').forEach((b) => b.classList.remove('active'));
+ if (!isActive) {
+ btn.classList.add('active');
+ sendCategory(cat);
+ } else {
+ sendCategory('other');
+ }
+ });
+}
+
+// Downloads route through a provenance pass: fetch the GLB, stamp
+// asset.generator + asset.extras (source, prompt) into the JSON chunk, and
+// hand the user the stamped file. Any failure falls back to the raw provider
+// file — stamping must never block a download.
+els.download.addEventListener('click', async (e) => {
+ sendFeedback({ downloaded: true });
+ const glbUrl = els.download.href;
+ if (!glbUrl || glbUrl.startsWith('blob:') || els.download.dataset.stamping) return;
+ e.preventDefault();
+ els.download.dataset.stamping = '1';
+ els.download.setAttribute('aria-busy', 'true');
+ const originalText = els.download.textContent;
+ els.download.textContent = 'Preparing…';
+ const filename = els.download.getAttribute('download') || 'forge.glb';
+ try {
+ const res = await fetch(glbUrl);
+ if (!res.ok) throw new Error(`fetch ${res.status}`);
+ const stamped = stampGlbAttribution(await res.arrayBuffer(), {
+ prompt: els.resultLabel?.textContent || '',
+ });
+ const blobUrl = URL.createObjectURL(new Blob([stamped], { type: 'model/gltf-binary' }));
+ const a = document.createElement('a');
+ a.href = blobUrl;
+ a.download = filename;
+ a.click();
+ setTimeout(() => URL.revokeObjectURL(blobUrl), 30_000);
+ } catch {
+ const a = document.createElement('a');
+ a.href = glbUrl;
+ a.download = filename;
+ a.click();
+ } finally {
+ delete els.download.dataset.stamping;
+ els.download.removeAttribute('aria-busy');
+ els.download.textContent = originalText;
+ }
+});
+
+els.cinema?.addEventListener('click', () => setCinema(!cinemaOn));
+
+document.addEventListener('keydown', (e) => {
+ if (e.key === 'Escape' && cinemaOn) {
+ setCinema(false);
+ return;
+ }
+ if (e.metaKey || e.ctrlKey || e.altKey) return;
+ const active = document.activeElement;
+ if (active?.tagName === 'INPUT' || active?.tagName === 'TEXTAREA' || active?.isContentEditable)
+ return;
+ // "/" jumps to the prompt for the current mode — the standard quick-focus.
+ if (e.key === '/') {
+ e.preventDefault();
+ const box =
+ mode === 'sketch' ? els.sketchPrompt : mode === 'image' ? els.imagePrompt : els.prompt;
+ box?.focus();
+ return;
+ }
+ if (e.key !== 'f' && e.key !== 'F') return;
+ if (els.states.result.classList.contains('is-hidden')) return;
+ e.preventDefault();
+ setCinema(!cinemaOn);
+});
+
+if (els.forgeShareBtn) {
+ els.forgeShareBtn.addEventListener('click', () => {
+ const origin = location.origin;
+ const prompt = els.forgeShareBtn.dataset.sharePrompt || lastJob?.prompt || '';
+ const id = currentCreationId;
+ const shareUrl = id ? `${origin}/forge/share/${id}` : `${origin}/forge`;
+ const remixUrl = prompt
+ ? `${origin}/forge?prompt=${encodeURIComponent(prompt)}`
+ : `${origin}/forge`;
+ showSharePanel(
+ {
+ kind: 'forge',
+ id: id || '',
+ title: prompt || 'Forged creation',
+ description: 'A 3D model generated with text / image → 3D on three.ws',
+ shareUrl,
+ remixUrl,
+ },
+ els.forgeShareBtn,
+ );
+ });
+}
+
+// Handle ?prompt= (pre-fill from a remix link) and ?share= (open a creation).
+(function handleQueryParams() {
+ const params = new URLSearchParams(location.search);
+ const promptParam = params.get('prompt');
+ const shareParam = params.get('share');
+ if (promptParam && els.prompt) {
+ setMode('text');
+ els.prompt.value = decodeURIComponent(promptParam).slice(0, 300);
+ els.prompt.focus();
+ }
+ if (shareParam) {
+ window.__forgeShareId = shareParam;
+ }
+})();
+
+// Hooks for the companion modules (forge-dropzone.js, forge-showcase.js) —
+// a CustomEvent contract keeps them decoupled from this file's internals.
+
+// Images captured anywhere on the page (clipboard paste, page-level drop).
+// In sketch mode a single image becomes the sketch; otherwise we switch to
+// photo mode and distribute into free view slots.
+document.addEventListener('forge:add-images', (e) => {
+ const files = Array.isArray(e.detail?.files) ? e.detail.files : [];
+ if (!files.length) return;
+ if (mode === 'sketch' && files.length === 1) {
+ uploadSketch(files[0]);
+ return;
+ }
+ if (mode !== 'image') setMode('image');
+ handleFiles(null, files);
+});
+
+// A community-showcase card asks to open its creation in the main viewer, so
+// the full result bar (download, share, stylize, optimize, split) works on it.
+document.addEventListener('forge:open-creation', (e) => {
+ const creation = e.detail?.creation;
+ if (creation?.glb_url) openCreation(creation);
+});
+
+// Build the quality/engine controls from the live catalog (tiers, backends,
+// cost/time matrix). Falls back silently to the defaults if it can't load.
+loadCatalog();
+
+// Surface the $THREE holder gate on the High control up front (pill + note),
+// independent of the catalog so the affordance lands even on older deploys.
+reflectHighButtonAccess();
+
+// Forge-local wallet connect (Part A): wire the connect chip + auto-connect a trusted
+// wallet so a connected holder's High unlock + free-quota perk surface with no reload.
+// Re-read the gate + perk line whenever the wallet connects or disconnects.
+initWalletButton();
+updatePerkLine();
+window.addEventListener('wallet:changed', () => {
+ reflectHighButtonAccess();
+ if (selectedTier === 'high') reflectHighAccess('high');
+ updatePerkLine();
+});
+
+// Surface any previously forged models for this browser on load.
+loadGallery().then(() => {
+ const shareId = window.__forgeShareId;
+ if (shareId) openSharedCreation(shareId);
+});
diff --git a/src/studio/agent-studio-store.js b/src/studio/agent-studio-store.js
index 126c98cd9..fc840db7d 100644
--- a/src/studio/agent-studio-store.js
+++ b/src/studio/agent-studio-store.js
@@ -226,6 +226,8 @@ class AgentStudioStore {
this._optimistic = this._optimistic ? deepMerge(this._optimistic, clean) : deepMerge({}, clean);
this._notify();
this._scheduleFlush();
+ // Any domain editing the agent drives the shell's single save indicator.
+ this.emit('save:pending');
}
_scheduleFlush() {
@@ -269,6 +271,7 @@ class AgentStudioStore {
}
const { agent } = await resp.json();
this._reconcile(agent, optimisticRecord);
+ this.emit('save:ok');
return this._record;
} catch (err) {
// Roll back the optimistic edit; re-queue nothing (the edit is lost on
diff --git a/src/studio/brain/brain-studio.js b/src/studio/brain/brain-studio.js
index d6c27e094..0769e3d9c 100644
--- a/src/studio/brain/brain-studio.js
+++ b/src/studio/brain/brain-studio.js
@@ -83,6 +83,8 @@ class BrainStudio {
<button class="studio__btn" id="bsFit" title="Frame the graph">Fit</button>
<button class="studio__btn" id="bsDiff" title="See how this brain reads">Behavior</button>
<button class="studio__btn" id="bsTpl" title="Fork a template">Templates</button>
+ <button class="studio__btn" id="bsSave" title="Save now (⌘/Ctrl + S)">Save</button>
+ <button class="studio__btn studio__btn-primary" id="bsDone" title="Save and continue to Memory">Done →</button>
</div>
</div>
<div class="brainstudio__main">
@@ -113,11 +115,71 @@ class BrainStudio {
this.el.querySelector('#bsFit').addEventListener('click', () => this.graph?.fit());
this.el.querySelector('#bsDiff').addEventListener('click', () => this._showBehavior());
this.el.querySelector('#bsTpl').addEventListener('click', () => this._showTemplateModal());
+ this.el.querySelector('#bsSave').addEventListener('click', () => this._saveNow());
+ this.el.querySelector('#bsDone').addEventListener('click', () => this._done());
this.el.querySelector('#bsCompose').addEventListener('submit', (e) => { e.preventDefault(); this._send(); });
const input = this.el.querySelector('#bsInput');
input.addEventListener('keydown', (e) => { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); this._send(); } });
input.addEventListener('input', () => { input.style.height = 'auto'; input.style.height = `${Math.min(120, input.scrollHeight)}px`; });
this.el.querySelector('#bsModal').addEventListener('click', (e) => { if (e.target.id === 'bsModal') this._closeModal(); });
+
+ // Keyboard: ⌘/Ctrl+S saves the graph immediately; Escape always dismisses an
+ // open modal so it can never become a dead-end that blocks the editor beneath.
+ this._keyHandler = (e) => {
+ const modal = this.el.querySelector('#bsModal');
+ if (e.key === 'Escape' && modal && !modal.hidden) { e.preventDefault(); this._closeModal(); return; }
+ if ((e.metaKey || e.ctrlKey) && (e.key === 's' || e.key === 'S') && this._isVisible()) {
+ e.preventDefault();
+ this._saveNow();
+ }
+ };
+ document.addEventListener('keydown', this._keyHandler);
+ }
+
+ // True only when the Brain tab is the active (non-hidden) studio panel — keeps
+ // the global ⌘S handler from firing while the user is editing another tab.
+ _isVisible() {
+ const panel = this.el.closest('.studio-tabpanel');
+ return !!panel && !panel.hidden && this.root?.dataset.view === 'editor';
+ }
+
+ // ── Save + continue ───────────────────────────────────────────────────────
+
+ // Flush the debounced graph persist to the server right now and confirm it on
+ // the Save button. The shell's header indicator also tracks the underlying
+ // store write (save:pending → save:ok), so the user gets two honest signals.
+ async _saveNow({ silent = false } = {}) {
+ // Push the latest graph through the normal persist path (immediate, no debounce)
+ // then flush the store so the write lands before we confirm or navigate.
+ if (this.graph) this._onGraphChange(this.graph.toGraph(), { immediate: true });
+ const btn = this.el.querySelector('#bsSave');
+ if (btn && !silent) { btn.disabled = true; btn.textContent = 'Saving…'; }
+ try {
+ await this.studio.commit();
+ if (btn && !silent) this._flashSaved(btn);
+ return true;
+ } catch {
+ if (btn && !silent) { btn.disabled = false; btn.textContent = 'Retry save'; }
+ return false;
+ }
+ }
+
+ _flashSaved(btn) {
+ btn.disabled = false;
+ btn.textContent = 'Saved ✓';
+ btn.classList.add('is-saved');
+ clearTimeout(this._savedFlash);
+ this._savedFlash = setTimeout(() => { btn.textContent = 'Save'; btn.classList.remove('is-saved'); }, 1600);
+ }
+
+ // Save, then hand off to the next studio section so building a brain flows
+ // naturally into Memory rather than dead-ending on the graph.
+ async _done() {
+ // Only advance once the write actually lands — a failed save rolls back in the
+ // store, so navigating away on failure would silently drop the user's edits.
+ if (await this._saveNow()) {
+ document.dispatchEvent(new CustomEvent('studio:navigate', { detail: { tab: 'memory' } }));
+ }
}
_renderPalette() {
diff --git a/src/studio/studio-shell.js b/src/studio/studio-shell.js
index 7a3da5447..16945c0a5 100644
--- a/src/studio/studio-shell.js
+++ b/src/studio/studio-shell.js
@@ -229,31 +229,32 @@ class StudioShell {
const tagEl = this.root.querySelector('#studio-tagline');
const saveEl = this.root.querySelector('#studio-save');
- // Save indicator. The store debounces (~600ms) then PUTs; it surfaces a
- // failure via the 'error' event but no explicit success signal, so we show
- // "Saving…" on edit and settle to "Saved" shortly after the write window
- // (unless an error fires first). Honest within a frame of the real write.
- const markSaving = () => {
+ // Save indicator. Every domain (identity here, Brain/Memory sub-studios, …)
+ // edits through the same store, which emits 'save:pending' on each patch and
+ // 'save:ok' once the debounced PUT reconciles. Driving the indicator off those
+ // events — rather than per-field timers — means any edit anywhere in the studio
+ // honestly reflects the real write, and the Brain graph's saves finally show.
+ nameEl?.addEventListener('input', () => studio.patch({ name: nameEl.value }));
+ tagEl?.addEventListener('input', () => studio.patch({ description: tagEl.value }));
+ this._unsubSaving = studio.on('save:pending', () => {
if (!saveEl) return;
saveEl.textContent = 'Saving…';
saveEl.dataset.state = 'pending';
- clearTimeout(this._saveTimer);
- this._saveTimer = setTimeout(() => {
- if (saveEl.dataset.state === 'pending') {
- saveEl.textContent = 'Saved';
- saveEl.dataset.state = 'saved';
- }
- }, 1100);
- };
- nameEl?.addEventListener('input', () => {
- studio.patch({ name: nameEl.value });
- markSaving();
});
- tagEl?.addEventListener('input', () => {
- studio.patch({ description: tagEl.value });
- markSaving();
+ this._unsubSaved = studio.on('save:ok', () => {
+ if (!saveEl || saveEl.dataset.state === 'error') return;
+ saveEl.textContent = 'Saved';
+ saveEl.dataset.state = 'saved';
});
+ // Sub-studios (e.g. the Brain graph's "Done →") request an onward jump
+ // through a DOM event so they stay decoupled from the shell instance.
+ this._navHandler = (e) => {
+ const key = e.detail?.tab;
+ if (key && TABS.some((t) => t.key === key)) this._selectTab(key, { focus: true });
+ };
+ document.addEventListener('studio:navigate', this._navHandler);
+
// Keep the header in sync if another surface edits the same agent.
this._unsub = studio.subscribe((agent) => {
if (!agent) return;
@@ -265,7 +266,6 @@ class StudioShell {
}
});
this._unsubErr = studio.on('error', () => {
- clearTimeout(this._saveTimer);
if (saveEl) {
saveEl.textContent = 'Save failed — retrying';
saveEl.dataset.state = 'error';
diff --git a/vercel.json b/vercel.json
index d238a196b..c3bd3abe4 100644
--- a/vercel.json
+++ b/vercel.json
@@ -762,6 +762,10 @@
"src": "/forge/?",
"dest": "/forge.html"
},
+ {
+ "src": "/forge-studio/?",
+ "dest": "/forge-studio.html"
+ },
{
"src": "/scene/?",
"dest": "/scene.html"
diff --git a/vite.config.js b/vite.config.js
index d37393126..984d00318 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -309,6 +309,7 @@ const appConfig = {
create: resolve(__dirname, 'pages/create.html'),
'create-agent': resolve(__dirname, 'pages/create-agent.html'),
forge: resolve(__dirname, 'pages/forge.html'),
+ 'forge-studio': resolve(__dirname, 'pages/forge-studio.html'),
'forge-embed': resolve(__dirname, 'pages/forge-embed.html'),
scene: resolve(__dirname, 'pages/scene.html'),
segment: resolve(__dirname, 'pages/segment.html'),