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.

feat(ar): shared AR Studio rooms — build one scene together, live

nirholas15845db7f882
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 775952d3d..128e7fbfc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **AR Studio** (`/ar/studio`) — A live multi-model AR scene through your camera: place any number of 3D models and avatars in your real space, pull in your forge creations, community models, or any GLB link, and generate new models by prompt without leaving the view.
- **Image to 3D — Turn a Photo into a 3D Model** (`/image-to-3d`) — Upload a photo (or up to 4 angles) and get a downloadable textured 3D model (GLB). The Forge's photo lane, opened directly — for objects and props; for faces, use Selfie to Avatar.
- **A new way to generate avatars: modular, and no two look alike** — The studio avatar generator used to recolor one of five fixed body meshes, so a whole gallery of them read as the same handful of people in different colors. It now composes each avatar from modular parts: a hairstyle, top, bottom, footwear, and glasses mixed across the base bodies onto one shared skeleton, then recolored per part and scaled for height. This is the same one-skeleton-many-parts approach the best avatar platforms use, built in-house with no external service. Every generated avatar is fully rigged and carries facial expression blendshapes, and two of them almost never look the same. All platform-generated avatars continue to appear across the galleries. (`/gallery`) `[feature, improvement]`
+- **AR Studio goes multiplayer: build a scene together in real time** — The AR Studio can now be a shared space. Tap Share live to open a room with a short code, send it to a friend, and you both see the same scene update live: every model one of you adds, moves, resizes, rotates, or removes appears for everyone in the room instantly, with a running count of who's building alongside you. Forge a new model from a prompt and it drops into the shared room for everyone. Open the same room on two phones pointed at the same QR marker and the models pin to the same spot on your real table. It runs on the same realtime servers as our live worlds, with each person only able to edit their own models. (`/ar/studio`) `[feature]`
- **AR Studio: fill your room with 3D models, and forge new ones without leaving the camera** — Until now AR on three.ws was one model at a time: generate, view, exit. The new AR Studio at three.ws/ar/studio is a live scene through your camera where you can place as many models and avatars as you like together in your real space. Pull in your own forge creations, the community feed, or any GLB link; type a prompt and a brand-new model is generated behind the live view and drops into the room when ready. Drag to move, pinch to resize, twist to rotate, duplicate or remove any model, with keyboard shortcuts on desktop. The models look like they belong: on supported Android phones they are lit by your actual room light and reflect it on metal and glass, and they hide correctly behind your real furniture; on every phone the lighting matches your room's brightness and colour. On Android each model also gets its own world anchor; on iPhone the camera view with gyro look works out of the box; on desktop you arrange the scene and send it to your phone with a QR code that carries the exact arrangement, not just the model list. Your scene survives a refresh, humanoid avatars idle naturally instead of standing frozen, and a photo button captures the whole composition. (`/ar/studio`) `[feature]`
- **Avatar gallery previews now read clearly at a glance** — Gallery previews used to be shot dead-on against a near-black background, so dark models vanished and every card looked the same. Previews are now framed from a natural three-quarter angle, fill the card, and stand on a subtly tinted stage unique to each avatar. Prompt-created avatars also got more distinctive: sparse prompts like 'a knight' now commit to a specific look (age, build, hairstyle, palette, one signature detail) instead of converging on the same generic person. Every platform-generated avatar still appears in the galleries. (`/gallery`) `[improvement, fix]`
- **Avatar renders look studio-lit, not murky** — Every generated avatar and 3D identity is now rendered with real studio lighting. The image-based lighting the renderer was missing is the reason materials like leather, fabric, and metal used to crush to near-black; adding it, plus faithful color tone mapping, makes those surfaces read the way they look in a real 3D viewer. Faces are lit, boots and belts look like leather again, and the whole character stands out from the backdrop. This lifts the profile pictures and full-body shots the Agent Identity Studio produces, and the avatar thumbnails across the site. `[improvement]`
@@ -20,9 +21,11 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Embeddable 3D viewer now shows loading, progress, and errors on its own** — The lightweight <three-ws-viewer> web component (the one you drop on any site for a 3D preview) used to render a blank canvas while a model loaded and a blank canvas if it failed. It now ships its own designed states: a spinner with a live download percentage, an error card with Try again and Download GLB, a friendly empty placeholder, and a fade-in when the model appears with a one-time 'drag to rotate' cue. A new optional auto-rotate attribute gently spins the model, and a progress event lets your page track loading. The hosted three.ws/viewer page also shows a real download percentage instead of an endless spinner and restores the swipe-to-rotate hint. `[sdk, improvement]`
- **Every free 3D generation now gets an automatic quality check** — The Forge already re-rolled broken meshes, but the deeper "looks nothing like what I asked for" check only ran on the paid High tier, so the free Draft and Standard lanes could still hand back a valid-but-wrong model. Now a smart adaptive gate covers the free lanes too: a clean, textured result ships instantly, and only an uncertain one is sent to the vision quality check and re-generated if it falls short. The result bar shows the outcome as a Verified, Checked, or Low confidence chip so you can see at a glance whether a model passed. (`/forge`) `[improvement, feature]`
- **Faster, clearer wallet sign-in (one tap on Solana Seeker)** — Connecting a wallet now gives real feedback: the button shows a Connecting state, a success confirmation when it links, and a plain-language message with a one-tap retry when something goes wrong instead of failing silently. If you have no wallet installed, you get a clear Get Phantom prompt rather than a surprise browser tab. On a Solana Seeker, signing in now takes a single tap instead of two: both login and wallet-linking use the Mobile Wallet Adapter's built-in Sign-In-With-Solana, so authorization and the signature happen in one Seed Vault prompt, and backing out is recognized as a clean cancel. Phantom, Backpack, and Solflare work exactly as before. The whole wallet layer is now covered by an automated test suite. `[improvement]`
+- **Forge a 3D model right from the homepage** — The homepage now leads with a prompt bar: type what you want and a real textured 3D model starts building the moment you hit Enter, no navigation and no sign-up. The live generator that used to sit far down the page now sits directly under the headline, so you type at the top and watch your model take shape right below. Three one-tap example prompts and a rotating set of ideas make it easy to start. (`/`) `[feature, improvement]`
- **Forge prompt ideas are now endless, and every one forges beautifully** — The example chips, empty-stage starters, and the Surprise me button on the Forge used to rotate through a fixed list of 48 prompts. They now draw from a curated prompt generator with thousands of combinations: statues, figurines, potted plants, crystals, food, crafted props, and cozy miniatures, each paired only with materials and finishes the 3D engine renders well. Every visit opens with a fresh set, and the prompt coach no longer mistakes words like mushroom for a scene request. (`/forge`) `[improvement]`
- **Forge-Off: upvote community models and win the weekly board** — The 'Fresh from the Forge' strip on the Forge is now a live board. Every community model has an upvote button (no login — one vote per browser), and a Fresh / Top this week toggle re-sorts the strip between newest and most-voted. Each Monday the top-voted model of the week is crowned permanently, and those winners now feed the models that get published to our official Sketchfab account. Your own upvotes light up across the strip. (`/forge`) `[feature]`
- **Forge: one-click "Roll & Forge" and a clearer free-to-start welcome** — The Forge now greets you with a Roll & Forge button that picks a great random prompt and generates a model in a single click, so you can reach a finished 3D object without thinking of what to type. The start screen and page header also state plainly that generating is free with no sign-up and the model is yours to download, removing the guesswork about cost. Roll & Forge draws from the same curated prompt library as Surprise me, so every random model is one that reconstructs cleanly. (`/forge`) `[feature, improvement]`
+- **Forge: one-tap variations of any model** — Every model you forge now shows a "More like this" row: one tap re-forges the same subject in a different material or finish (brushed brass, translucent glass, carved oak, and more), so you can explore a whole design space without retyping anything. A reshuffle button deals a fresh set of ideas. It appears for text prompts and runs on the free lane, so exploring costs nothing. `[feature]`
- **Free 3D API tells agents exactly when to check back** — When a text-to-3D generation needs a moment and hands back a job to poll, the free /api/3d/generate API now includes how long to wait before checking again (a retryAfter value, also sent as the standard Retry-After header) plus an estimated time-to-ready and a stable creation id. Agents that honor the hint poll on a sensible schedule instead of hammering the endpoint, so they stop tripping the rate limit and the shared free GPU lane carries less needless traffic. Fully backward-compatible: existing callers keep working unchanged. (`/docs/3d-api`) `[improvement]`
- **Image to 3D gets its own front door** — Turning a photo into a 3D model has worked in the Forge for a while, but it hid behind a page titled Text to 3D, and the only photo surface people could find was Selfie to Avatar. There is now a dedicated Image to 3D page (three.ws/image-to-3d) that opens the Forge with the photo tab already selected, an Image to 3D link in the main navigation and footers, and clear pointers between the selfie tools (for making an avatar of you) and Image to 3D (for making a model of any object). The Forge and its feature page are also retitled to say what they actually do: text and images. (`/image-to-3d`) `[improvement]`
- **Image-to-3D leaps forward: true PBR materials on a flagship GPU** — The Forge realism engine (Hunyuan3D 2.1) is now live on a new flagship-class GPU (NVIDIA RTX PRO 6000 Blackwell, 96 GB). High-tier image-to-3D generations now come out with true physically-based materials: real metal, roughness, and color maps that catch light like photographed objects instead of flat plastic. The new hardware is also dramatically faster; the full shape-plus-texture pass finished in about a minute in our live verification, where the previous GPU class could not even load the model. Alongside it, every 3D generation service is healthy again and all of yesterday’s reliability fixes are fully rolled out across the fleet. (`/forge`) `[feature, improvement, infra]`
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 0d6f68ec9..73cfa7e50 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -46,7 +46,7 @@ bottom.
| Spatial MCP (3D as a native response type) | Spec [specs/SPATIAL_MCP.md](specs/SPATIAL_MCP.md), pure validator/builder [api/_lib/spatial-mcp.js](api/_lib/spatial-mcp.js), validator tool [api/_mcp3d/tools/spatial.js](api/_mcp3d/tools/spatial.js) (`validate_spatial_response`, free), reference renderer [public/spatial-mcp/spatial-renderer.js](public/spatial-mcp/spatial-renderer.js) + demo [public/spatial-mcp/index.html](public/spatial-mcp/index.html) `→ /spatial-mcp`, docs [docs/spatial-mcp.md](docs/spatial-mcp.md). | Live · both stores | Open (CC0) shape for returning a live, interactive 3D scene as a first-class MCP tool result (scene GLB, camera, environment, animation, AR handoff, affordances) instead of a URL. Every three.ws 3D generator emits a conformant artifact under `structuredContent.spatial`; the validator returns actionable errors, not a boolean; the framework-free reference renderer displays any conformant payload — including one transformed from a foreign tool result (portability proof at `/spatial-mcp`). Zero coin surface — reusable in the OpenAI free app. Tests: [tests/spatial-mcp.test.js](tests/spatial-mcp.test.js). Evidence: [prompts/store-submissions/_generated/spatial-mcp/](prompts/store-submissions/_generated/spatial-mcp/). Store-submission prompt 20. |
| AR-ready exports ("View in your space") | Device-routing core [api/_lib/ar-launch.js](api/_lib/ar-launch.js), UA-branched launch endpoint [api/ar.js](api/ar.js) `→ /api/ar`, MCP tool [api/_mcp3d/tools/ar.js](api/_mcp3d/tools/ar.js) (`export_ar`, free), in-viewer AR button [public/viewer.html](public/viewer.html), docs [docs/ar.md](docs/ar.md). | Live · both stores | `GET /api/ar?src=<glb>` branches on the request User-Agent server-side: iOS → Apple Quick Look (USDZ generated from the GLB on the fly by model-viewer's three.js USDZExporter — real conversion, no server USD tooling), Android → 302 Google Scene Viewer ARCore intent with browser fallback, desktop → WebGL viewer. Bad input rejected at the boundary with a designed error page. `export_ar` returns the AR launch link + a conformant Spatial-MCP artifact; response is OpenAI-clean (no ids/coin surface). `kind=avatar` is the living-agent lane: the launch page leads with a "Bring it to life" handoff into `/irl?avatar=<glb>` (avatar-producing tools return `irlUrl` automatically), and Android serves the launch page instead of the blind Scene Viewer redirect so the living path stays visible. Shared links unfurl: the launch page's `og:image` points at `GET /api/render/glb?glbUrl=` ([api/render/glb.js](api/render/glb.js), server-side PNG of the actual model, CDN-cached a day) and the page carries "Create your own" → `/ar` conversion CTAs. Tests: [tests/ar-export.test.js](tests/ar-export.test.js). Evidence: [prompts/store-submissions/_generated/ar/](prompts/store-submissions/_generated/ar/). Store-submission prompt 21. |
| AR Forge (prompt → model → your room) | [public/ar-forge.html](public/ar-forge.html) `→ /ar` (self-contained page, CDN model-viewer + local meshopt decoder, no Vite registration needed; vercel route sets `xr-spatial-tracking` permissions-policy) | Live | Mobile-first app: one prompt hits the free NVIDIA lane (`POST /api/forge {backend:"nvidia"}`, poll `?job=`), the result renders in an AR-capable `<model-viewer>` with "View in your space" (WebXR / Scene Viewer / Quick Look). Non-AR devices get a QR handoff to `GET /api/ar?src=` (server-side UA routing) plus a copyable `/viewer?src=` share link. Deep link `/ar?src=<glb>&title=` reopens any shared model; recent forges persist in localStorage. Designed idle/working/failed/result states; https-only GLB guard. |
-| AR Studio (multi-model live camera scene) | [pages/ar-studio.html](pages/ar-studio.html) `→ /ar/studio` + [src/ar-studio.js](src/ar-studio.js), multi-anchor WebXR session [src/ar/multi-place.js](src/ar/multi-place.js), pure scene math [src/ar/studio-scene.js](src/ar/studio-scene.js) | Live | The standalone multi-model AR surface: place ANY number of models/avatars into one live camera view (every earlier AR lane was single-model). Model sources: in-view forge (`POST /api/forge {backend:"nvidia"}` runs behind the live camera, result drops into the room), the forge gallery (`/api/forge-gallery` — yours + community tabs), recent forges (localStorage, shared with `/ar`), a pasted GLB link, or repeatable `?src=` deep links (https/relative only). Rendering ladder: WebXR immersive-ar with one XRAnchor per placed model + always-armed reticle (Android), getUserMedia passthrough + gyro world-lock (iOS/everywhere), grid preview + drag-look + QR handoff (desktop). Gestures: tap select, drag move, pinch resize, two-finger twist rotate; per-model duplicate/rotate/remove, clear-with-undo. Humanoids with no baked clips idle via the universal retarget ([src/irl/pin-idle.js](src/irl/pin-idle.js)); scene persists in localStorage and the whole ARRANGEMENT (models + transforms) round-trips through a base64url `#s=` hash on the share/QR URL, so a composed scene reopens exactly on any device. **Presence realism:** WebXR placements are lit by the real room via lighting-estimation ([src/ar/estimated-lighting.js](src/ar/estimated-lighting.js), three's `XREstimatedLight` — real primary-light direction/colour + a live environment cube map so metal/glass reflect the actual room, reverting to baked lights when the device isn't estimating) and occluded by real geometry via depth-sensing ([src/ar/depth-occlusion.js](src/ar/depth-occlusion.js)); the passthrough path matches room brightness AND colour by sampling the camera feed. Desktop keyboard controls (arrows nudge / R rotate / D duplicate / Delete). Photo capture composites camera + WebGL ([src/irl/share-frame.js](src/irl/share-frame.js)). Reachable from `/ar`, the forge AR panel, and the `/viewer` action sheet. Tests: [tests/ar-studio-scene.test.js](tests/ar-studio-scene.test.js), [tests/ar-estimated-lighting.test.js](tests/ar-estimated-lighting.test.js). |
+| AR Studio (multi-model live camera scene) | [pages/ar-studio.html](pages/ar-studio.html) `→ /ar/studio` + [src/ar-studio.js](src/ar-studio.js), multi-anchor WebXR session [src/ar/multi-place.js](src/ar/multi-place.js), pure scene math [src/ar/studio-scene.js](src/ar/studio-scene.js) | Live | The standalone multi-model AR surface: place ANY number of models/avatars into one live camera view (every earlier AR lane was single-model). Model sources: in-view forge (`POST /api/forge {backend:"nvidia"}` runs behind the live camera, result drops into the room), the forge gallery (`/api/forge-gallery` — yours + community tabs), recent forges (localStorage, shared with `/ar`), a pasted GLB link, or repeatable `?src=` deep links (https/relative only). Rendering ladder: WebXR immersive-ar with one XRAnchor per placed model + always-armed reticle (Android), getUserMedia passthrough + gyro world-lock (iOS/everywhere), grid preview + drag-look + QR handoff (desktop). Gestures: tap select, drag move, pinch resize, two-finger twist rotate; per-model duplicate/rotate/remove, clear-with-undo. Humanoids with no baked clips idle via the universal retarget ([src/irl/pin-idle.js](src/irl/pin-idle.js)); scene persists in localStorage and the whole ARRANGEMENT (models + transforms) round-trips through a base64url `#s=` hash on the share/QR URL, so a composed scene reopens exactly on any device. **Presence realism:** WebXR placements are lit by the real room via lighting-estimation ([src/ar/estimated-lighting.js](src/ar/estimated-lighting.js), three's `XREstimatedLight` — real primary-light direction/colour + a live environment cube map so metal/glass reflect the actual room, reverting to baked lights when the device isn't estimating) and occluded by real geometry via depth-sensing ([src/ar/depth-occlusion.js](src/ar/depth-occlusion.js)); the passthrough path matches room brightness AND colour by sampling the camera feed. Desktop keyboard controls (arrows nudge / R rotate / D duplicate / Delete). Photo capture composites camera + WebGL ([src/irl/share-frame.js](src/irl/share-frame.js)). Reachable from `/ar`, the forge AR panel, and the `/viewer` action sheet. **Shared rooms (build together, live):** "Share live" opens a room with a 6-char code; anyone who opens `/ar/studio?room=CODE` joins the same scene and every add / move / scale / rotate / remove delta-syncs in real time, with a live "N here" presence pill. New Colyseus room [multiplayer/src/rooms/StudioRoom.js](multiplayer/src/rooms/StudioRoom.js) + schema [multiplayer/src/studio-schemas.js](multiplayer/src/studio-schemas.js) (owner-gated edits, per-room/per-owner caps, per-client rate limit, https-only src validation — same discipline as WalkRoom's object channel), client wrapper [src/ar/studio-net.js](src/ar/studio-net.js), and a shared logical coordinate frame [src/ar/studio-coords.js](src/ar/studio-coords.js) (relEast/relNorth/yawDeg) so every device agrees on placement; QR-marker colocalization ([src/irl/marker-anchor.js](src/irl/marker-anchor.js)) is the co-located "same physical table" upgrade. Runs on the same Colyseus host as /walk and /irl (a new room, not a new process). Tests: [tests/ar-studio-scene.test.js](tests/ar-studio-scene.test.js), [tests/ar-studio-coords.test.js](tests/ar-studio-coords.test.js), [tests/ar-estimated-lighting.test.js](tests/ar-estimated-lighting.test.js), [tests/studio-room.test.js](tests/studio-room.test.js). |
| IRL (agents in the real world) | [pages/irl.html](pages/irl.html) `→ /irl` + [src/irl.js](src/irl.js), WebXR placement [src/ar/webxr.js](src/ar/webxr.js) + pinch [src/ar/pinch-scale.js](src/ar/pinch-scale.js), animated Quick Look bake [src/usdz-animated.js](src/usdz-animated.js) (static fallback [src/usdz-pipeline.js](src/usdz-pipeline.js)), backend [api/irl/](api/irl) | Live | Pin an agent at a real GPS spot; discovery is presence-proof-gated ([docs/irl/THREAT-MODEL.md](docs/irl/THREAT-MODEL.md)). **Place in AR** leads the dock on AR-capable devices: WebXR hit-test anchoring on Android with two-finger pinch resize (25%..400%) persisted to the pin (`anchor_scale`; the pinch lands as a follow-up `PATCH /api/irl/pins {id, scale}` after the placement tap), and ARKit Quick Look on iOS with the idle clip baked into the USDZ so the agent moves instead of standing in a T-pose. Discovered pins are equally alive in the in-page camera view: every mounted humanoid GLB plays the retargeted idle clip via a per-pin mixer ([src/irl/pin-idle.js](src/irl/pin-idle.js), phase-randomized, LOD-bounded), camera-aware gaze composes on top of the running animation, and the scene renders with ACES tone mapping + IBL + soft shadows (e2e: [tests/e2e/irl-pin-idle.spec.js](tests/e2e/irl-pin-idle.spec.js)). Inbound `/irl?avatar=<glb>` is the living-agent handoff from `GET /api/ar?…&kind=avatar` (explicit `?avatar=` wins over a saved session). Money Drops and World Lines: [docs/irl.md](docs/irl.md). SDK: [packages/irl/](packages/irl). **Share** ([src/irl/share-frame.js](src/irl/share-frame.js), [api/irl/share.js](api/irl/share.js), [api/irl/share/[token].js](api/irl/share/%5Btoken%5D.js)) mints a permanent, unfurlable `/irl/s/:token` link from the captured AR photo for the pin you just placed — never a coordinate, owner-gated, falls back to the plain native share sheet with no active pin. **Analytics** ([api/_lib/irl-analytics.js](api/_lib/irl-analytics.js), [api/irl/analytics.js](api/irl/analytics.js)) is the first site-wide usage rollup for the feature — pins placed, nearby reads, placement method, shares, drop claims — rendered at [/admin/irl-analytics](pages/admin/irl-analytics.html), aged out by the existing hourly reaper. |
| Verifiable 3D provenance (content credentials) | Spec [specs/PROVENANCE_3D.md](specs/PROVENANCE_3D.md), pure core [api/_lib/provenance-3d.js](api/_lib/provenance-3d.js), Solana anchor [api/_lib/provenance-anchor.js](api/_lib/provenance-anchor.js), MCP tools [api/_mcp3d/tools/provenance.js](api/_mcp3d/tools/provenance.js) (`verify_provenance` free, `anchor_provenance` paid $0.05), free REST verify [api/provenance.js](api/provenance.js) `→ /api/provenance`, viewer badge [public/viewer.html](public/viewer.html), docs [docs/provenance.md](docs/provenance.md). | Live (verify) · anchor gated on issuer key + devnet funds | C2PA-style signed content credentials for AI 3D: creator, prompt, model/provider, lineage, timestamp, and the GLB's sha256, ed25519-signed by the three.ws issuer with the credential hash anchored on Solana. Free public `verify_provenance` / `GET /api/provenance?src=…` recompute the hash and return `verified | tampered | unknown` (a single changed byte → tampered); the verify path and response are coin-clean (both stores). `anchor_provenance` signs + writes the SPL Memo anchor + stores the credential in R2. Tests: [tests/provenance-3d.test.js](tests/provenance-3d.test.js). Evidence: [prompts/store-submissions/_generated/provenance/](prompts/store-submissions/_generated/provenance/). Store-submission prompt 19. |
| Sperax partnership + SperaxOS plugin | [pages/sperax.html](pages/sperax.html) `→ /sperax`, plugin [public/sperax/](public/sperax/README.md), manifest `→ /.well-known/sperax-plugin.json`, tools [api/chat-plugin/[tool].js](api/chat-plugin/%5Btool%5D.js) `→ /api/chat-plugin/*`, panel `→ /sperax/iframe/` | In-repo · Live | Partnership landing for the SperaxOS integration: three.ws ships as a standalone `plugin.delivery` plugin that gives a SperaxOS agent an embodied 3D avatar (speak/gesture/emote/render_agent), bound to an ERC-8004 identity, settling over Base x402. Launch offer: free AI credits for three.ws users on [chat.sperax.io](https://chat.sperax.io) — page explains what it is and how to claim. Blog: [/blog/three-ws-speraxusd-integration](blog/three-ws-speraxusd-integration.html) |
diff --git a/data/changelog.json b/data/changelog.json
index 9810c6c6f..440b92b0d 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$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-07-17",
+ "title": "AR Studio goes multiplayer: build a scene together in real time",
+ "summary": "The AR Studio can now be a shared space. Tap Share live to open a room with a short code, send it to a friend, and you both see the same scene update live: every model one of you adds, moves, resizes, rotates, or removes appears for everyone in the room instantly, with a running count of who's building alongside you. Forge a new model from a prompt and it drops into the shared room for everyone. Open the same room on two phones pointed at the same QR marker and the models pin to the same spot on your real table. It runs on the same realtime servers as our live worlds, with each person only able to edit their own models.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/ar/studio"
+ },
{
"date": "2026-07-17",
"title": "Forge: one-tap variations of any model",
diff --git a/multiplayer/src/index.js b/multiplayer/src/index.js
index 1971894cb..16e90535f 100644
--- a/multiplayer/src/index.js
+++ b/multiplayer/src/index.js
@@ -24,6 +24,7 @@ import { AgoraRoom } from './rooms/AgoraRoom.js';
import { IrlRoom } from './rooms/IrlRoom.js';
import { ClashRoom } from './rooms/ClashRoom.js';
import { StageRoom } from './rooms/StageRoom.js';
+import { StudioRoom } from './rooms/StudioRoom.js';
import { getStageRoom } from './stage-registry.js';
import { blockStore } from './block-store.js';
import { worldPersistence } from './persistence.js';
@@ -256,12 +257,18 @@ gameServer.define('clash_arena', ClashRoom).filterBy(['matchKey']);
// loads its host/title/format from /api/stage and reacts to real $THREE tips the
// API injects over /internal/stage. See rooms/StageRoom.js + src/stage.js.
gameServer.define('stage_world', StageRoom).filterBy(['stageId']);
+// Shared AR Studio (/ar/studio "Shared room"). One instance per roomKey — a
+// shared code or a QR-marker id — so everyone holding the same key builds one
+// live scene together: placed models delta-sync and a late joiner receives the
+// whole scene on join. An opted-into collaborative world (WalkRoom side of the
+// privacy line), never a broadcast of private irl pins. See rooms/StudioRoom.js.
+gameServer.define('studio_world', StudioRoom).filterBy(['roomKey']);
gameServer
.listen(PORT, HOST)
.then(() => {
console.log(`[multiplayer] listening on ws://${HOST}:${PORT}`);
- console.log(`[multiplayer] rooms: walk_world, agora_world, irl_world, clash_arena, stage_world`);
+ console.log(`[multiplayer] rooms: walk_world, agora_world, irl_world, clash_arena, stage_world, studio_world`);
console.log(`[multiplayer] allowed origins: ${ALLOWED_ORIGINS.join(', ')}`);
})
.catch((err) => {
diff --git a/multiplayer/src/rooms/StudioRoom.js b/multiplayer/src/rooms/StudioRoom.js
new file mode 100644
index 000000000..9b7265e67
--- /dev/null
+++ b/multiplayer/src/rooms/StudioRoom.js
@@ -0,0 +1,225 @@
+// StudioRoom — the realtime shared scene for the AR Studio (studio_world room).
+//
+// A studio room is an INTENTIONAL collaborative session: two or more people opt
+// in by holding the same room key (a shared code, or the same QR marker they both
+// scan). Unlike irl_world (presence only; pins are private-by-location, REST-
+// gated), the placed models here ARE the synced state — every add / move / scale
+// / rotate / remove delta-broadcasts to the room, and a late joiner gets the whole
+// scene on join. This sits on the WalkRoom side of the privacy line (an opted-into
+// shared world), and reuses that room's discipline: finite-only payloads, owner-
+// gated edits, per-client rate limiting, and per-room / per-owner caps.
+//
+// Transforms ride in the room's shared LOGICAL frame (relEast / relNorth metres,
+// yawDeg) — see studio-schemas.js. The client maps them to its own local floor,
+// or, when co-located via a QR marker, to the same physical spot.
+
+import { Room } from '@colyseus/core';
+
+import { StudioModel, StudioViewer, StudioState } from '../studio-schemas.js';
+import { installUnknownMessageGuard } from '../room-compat.js';
+
+const PATCH_RATE_MS = 100; // 10 Hz delta flush
+const MAX_CLIENTS = 32; // a friendly shared build session, not a crowd
+const MAX_MODELS = 48; // per-room ceiling — keeps late-joiner load sane
+const MAX_MODELS_PER_OWNER = 24; // one person can't fill the room alone
+const OPS_PER_SEC = 25; // per-client message budget (spawn/update/remove)
+const HEARTBEAT_STALE_MS = 30_000; // reap a participant silent this long
+const REAPER_INTERVAL_MS = 10_000;
+const MAX_VIEWERS = MAX_CLIENTS;
+
+const SRC_MAX = 512; // GLB url length cap
+const STR_MAX = 120; // title / name length cap
+const OWNER_MAX = 80;
+const ID_RE = /^[A-Za-z0-9_-]{1,48}$/;
+const SCALE_MIN = 0.25;
+const SCALE_MAX = 4;
+const COORD_BOUND = 60; // clamp placements to ±60 m of the shared origin
+
+// Accept only a GLB the client could also load: an https URL or a site-relative
+// path. Everything else (http, data:, blob:, javascript:, protocol-relative) is
+// rejected — these arrive over the wire and are re-broadcast to every peer, so
+// they are untrusted input. Mirrors normalizeGlbUrl in src/ar/studio-scene.js.
+function validSrc(raw) {
+ const s = String(raw || '').trim();
+ if (!s || s.length > SRC_MAX) return '';
+ if (s.startsWith('/') && !s.startsWith('//')) return s;
+ try {
+ const u = new URL(s);
+ return u.protocol === 'https:' ? u.href : '';
+ } catch {
+ return '';
+ }
+}
+
+const clamp = (n, lo, hi) => Math.min(hi, Math.max(lo, n));
+const num = (v, d = 0) => (Number.isFinite(v) ? v : d);
+
+export class StudioRoom extends Room {
+ constructor() {
+ super();
+ this.maxClients = MAX_CLIENTS;
+ this.roomKey = '';
+ this._modelSeq = 0;
+ // Per-session op-rate ledger: sessionId → { windowStart, count }.
+ this._opLedger = new Map();
+ }
+
+ onCreate(options) {
+ this.roomKey = String(options?.roomKey || '').slice(0, 64);
+ this.setState(new StudioState());
+ this.state.roomKey = this.roomKey;
+ this.setPatchRate(PATCH_RATE_MS);
+ this.autoDispose = true;
+ installUnknownMessageGuard(this, 'studio');
+
+ this.onMessage('model:spawn', this._guard('model:spawn', (c, p) => this._handleSpawn(c, p)));
+ this.onMessage('model:update', this._guard('model:update', (c, p) => this._handleUpdate(c, p)));
+ this.onMessage('model:remove', this._guard('model:remove', (c, p) => this._handleRemove(c, p)));
+ this.onMessage('heartbeat', this._guard('heartbeat', (c) => this._handleHeartbeat(c)));
+
+ this.clock.setInterval(() => this._reapStaleViewers(), REAPER_INTERVAL_MS);
+ console.log(`${this._tag()} created (shared scene)`);
+ }
+
+ _tag() {
+ return `[studio_world ${this.roomId} key=${this.roomKey || '?'}]`;
+ }
+
+ // Contain a malformed payload: log the message, never the payload (which could
+ // carry a client id), and keep the room loop alive.
+ _guard(label, fn) {
+ return (client, payload) => {
+ try {
+ fn(client, payload);
+ } catch (err) {
+ console.error(`${this._tag()} ${label} handler error:`, err?.message || err);
+ }
+ };
+ }
+
+ // Stable owner key: the browser's persistent studio client id when supplied,
+ // else the ephemeral session id. Lets a reconnecting author keep ownership of
+ // the models they placed.
+ _ownerKey(client) {
+ return client.userData?.ownerId || client.sessionId;
+ }
+
+ // Token-bucket-ish per-second op gate. Returns false (drop) when a client
+ // exceeds OPS_PER_SEC in the current 1 s window — a flood can't spam the room.
+ _opOk(sessionId) {
+ const now = Date.now();
+ let rec = this._opLedger.get(sessionId);
+ if (!rec || now - rec.windowStart >= 1000) {
+ rec = { windowStart: now, count: 0 };
+ this._opLedger.set(sessionId, rec);
+ }
+ rec.count++;
+ return rec.count <= OPS_PER_SEC;
+ }
+
+ _handleSpawn(client, payload) {
+ if (!this.state.viewers.has(client.sessionId)) return;
+ if (!this._opOk(client.sessionId)) return;
+ if (!payload || typeof payload !== 'object') return;
+
+ const src = validSrc(payload.src);
+ if (!src) return; // never re-broadcast an unvetted URL
+ if (!Number.isFinite(payload.relEast) || !Number.isFinite(payload.relNorth)) return;
+ if (this.state.models.size >= MAX_MODELS) {
+ client.send('model:reject', { reason: 'room_full' });
+ return;
+ }
+ const owner = this._ownerKey(client);
+ let owned = 0;
+ for (const [, m] of this.state.models) if (m.ownerId === owner) owned++;
+ if (owned >= MAX_MODELS_PER_OWNER) {
+ client.send('model:reject', { reason: 'owner_full' });
+ return;
+ }
+
+ const m = new StudioModel();
+ // Accept a sane, unused client id, else mint a collision-free one — ids stay
+ // server-controlled so a client can't overwrite a peer's model by id.
+ let id = (typeof payload.id === 'string' && ID_RE.test(payload.id)) ? payload.id : '';
+ if (!id || this.state.models.has(id)) id = `m_${client.sessionId.slice(0, 6)}_${++this._modelSeq}`;
+ m.id = id;
+ m.src = src;
+ m.title = String(payload.title || '').slice(0, STR_MAX);
+ m.relEast = clamp(num(payload.relEast), -COORD_BOUND, COORD_BOUND);
+ m.relNorth = clamp(num(payload.relNorth), -COORD_BOUND, COORD_BOUND);
+ m.yawDeg = ((num(payload.yawDeg) % 360) + 360) % 360;
+ m.scale = clamp(num(payload.scale, 1), SCALE_MIN, SCALE_MAX);
+ m.height = clamp(num(payload.height, 0), 0, 20);
+ m.ownerId = owner;
+ m.ts = Date.now();
+ this.state.models.set(m.id, m);
+ }
+
+ _handleUpdate(client, payload) {
+ if (!this._opOk(client.sessionId)) return;
+ if (!payload || typeof payload.id !== 'string') return;
+ const m = this.state.models.get(payload.id);
+ if (!m) return;
+ if (m.ownerId !== this._ownerKey(client)) return; // owner-only moves
+ if (Number.isFinite(payload.relEast)) m.relEast = clamp(payload.relEast, -COORD_BOUND, COORD_BOUND);
+ if (Number.isFinite(payload.relNorth)) m.relNorth = clamp(payload.relNorth, -COORD_BOUND, COORD_BOUND);
+ if (Number.isFinite(payload.yawDeg)) m.yawDeg = ((payload.yawDeg % 360) + 360) % 360;
+ if (Number.isFinite(payload.scale)) m.scale = clamp(payload.scale, SCALE_MIN, SCALE_MAX);
+ m.ts = Date.now();
+ }
+
+ _handleRemove(client, payload) {
+ if (!this._opOk(client.sessionId)) return;
+ if (!payload || typeof payload.id !== 'string') return;
+ const m = this.state.models.get(payload.id);
+ if (!m) return;
+ if (m.ownerId !== this._ownerKey(client)) return; // owner-only removes
+ this.state.models.delete(payload.id);
+ }
+
+ _handleHeartbeat(client) {
+ const v = this.state.viewers.get(client.sessionId);
+ if (v) v.tsServer = Date.now();
+ }
+
+ onJoin(client, options) {
+ client.userData = {
+ ownerId: typeof options?.clientId === 'string' ? options.clientId.slice(0, OWNER_MAX) : '',
+ };
+ if (this.state.viewers.size >= MAX_VIEWERS) {
+ console.warn(`${this._tag()} viewer cap reached (${MAX_VIEWERS})`);
+ return;
+ }
+ const v = new StudioViewer();
+ v.id = client.sessionId;
+ v.name = String(options?.name || '').slice(0, STR_MAX);
+ v.ownerId = client.userData.ownerId;
+ v.tsServer = Date.now();
+ this.state.viewers.set(client.sessionId, v);
+ console.log(`${this._tag()} +join (viewers=${this.state.viewers.size}, models=${this.state.models.size})`);
+ }
+
+ onLeave(client) {
+ // Presence goes; the models a departing author placed STAY for the room's
+ // life so a shared scene doesn't collapse when one person drops (they can
+ // rejoin and still own them). autoDispose clears everything once empty.
+ const had = this.state.viewers.delete(client.sessionId);
+ this._opLedger.delete(client.sessionId);
+ if (had) console.log(`${this._tag()} -leave (viewers=${this.state.viewers.size})`);
+ }
+
+ _reapStaleViewers() {
+ const cutoff = Date.now() - HEARTBEAT_STALE_MS;
+ for (const [id, v] of this.state.viewers) {
+ if (v.tsServer < cutoff) {
+ this.state.viewers.delete(id);
+ this._opLedger.delete(id);
+ }
+ }
+ }
+
+ onDispose() {
+ this._opLedger.clear();
+ console.log(`${this._tag()} disposed`);
+ }
+}
diff --git a/multiplayer/src/studio-schemas.js b/multiplayer/src/studio-schemas.js
new file mode 100644
index 000000000..b9c94742c
--- /dev/null
+++ b/multiplayer/src/studio-schemas.js
@@ -0,0 +1,96 @@
+// Schema definitions for the shared AR Studio world (studio_world room), shared
+// between StudioRoom (server) and src/ar/studio-net.js (client, bundled by Vite
+// the same way it bundles the irl/walk schemas).
+//
+// Unlike irl_world (presence + reactions only, pins are private-by-location and
+// REST-gated), studio_world IS a shared scene transport by design: a studio room
+// is an INTENTIONAL collaborative session two or more people opt into by holding
+// the same room key (a shared code, or the same QR marker they both scan). So the
+// placed models ARE the synced state — every add/move/scale/rotate/remove
+// delta-broadcasts to everyone in the room, and a late joiner receives the whole
+// current scene on join. This lives on the WalkRoom side of the privacy line
+// (an opted-into shared world), never by loosening irl_world.
+//
+// Coordinate frame: relEast / relNorth are shared LOGICAL metres from the room's
+// common origin, decoupled from any one device's camera. A plain (non-co-located)
+// viewer maps them to their own local floor (origin = where they started); two
+// phones that scanned the same QR marker map them to the SAME physical spot via
+// the marker frame (src/irl/marker-anchor.js). Yaw is degrees. This is the one
+// schema-level difference from WalkRoom's world-frame x/z — everything else
+// (owner gating, caps, rate limits, delta sync) mirrors it.
+//
+// IMPORTANT: @colyseus/schema's binary protocol is POSITIONAL. Field indices are
+// load-bearing across a rolling deploy — always APPEND new fields at the end,
+// never insert in the middle, or an older still-connected client is shifted off
+// the wire format mid-deploy.
+
+import { Schema, MapSchema, defineTypes } from '@colyseus/schema';
+
+// One placed model in the shared scene. `src` is the GLB URL every client loads
+// (validated server-side: https or site-relative, length-capped). Transforms are
+// in the room's shared logical frame (see header). `ownerId` is a stable per-
+// browser key (the studio's forge:cid), so a reconnecting author keeps ownership.
+export class StudioModel extends Schema {
+ constructor() {
+ super();
+ this.id = '';
+ this.src = ''; // GLB url (https or site-relative)
+ this.title = ''; // human label, for the remote-model UI
+ this.relEast = 0; // shared logical metres, +east
+ this.relNorth = 0; // shared logical metres, +north
+ this.yawDeg = 0; // 0–360 heading
+ this.scale = 1; // uniform scale, clamped [0.25, 4]
+ this.height = 0; // fitted model height (m), for spawn-distance parity
+ this.ownerId = ''; // stable browser key of the placer
+ this.ts = 0; // server epoch ms of the last change
+ }
+}
+defineTypes(StudioModel, {
+ id: 'string',
+ src: 'string',
+ title: 'string',
+ relEast: 'float32',
+ relNorth: 'float32',
+ yawDeg: 'float32',
+ scale: 'float32',
+ height: 'float32',
+ ownerId: 'string',
+ ts: 'float64',
+});
+
+// A live participant in the room. Presence only — count + optional display name,
+// so the studio can show "3 people building here." No location ever rides this.
+export class StudioViewer extends Schema {
+ constructor() {
+ super();
+ this.id = ''; // ephemeral session id
+ this.name = ''; // short display name (optional)
+ this.ownerId = ''; // stable browser key (ties a viewer to their models)
+ this.tsServer = 0; // last heartbeat epoch ms (drives the reaper)
+ }
+}
+defineTypes(StudioViewer, {
+ id: 'string',
+ name: 'string',
+ ownerId: 'string',
+ tsServer: 'float64',
+});
+
+export class StudioState extends Schema {
+ constructor() {
+ super();
+ // The room key (shared code or marker id) this instance serves — the
+ // filterBy match key, identical for every participant in the instance.
+ this.roomKey = '';
+ // The shared scene: every placed model, keyed by id. Populated by
+ // StudioRoom on model:spawn and pruned on model:remove / owner cleanup.
+ this.models = new MapSchema();
+ // Live participants, keyed by session id (presence + reaper).
+ this.viewers = new MapSchema();
+ }
+}
+defineTypes(StudioState, {
+ roomKey: 'string',
+ models: { map: StudioModel },
+ viewers: { map: StudioViewer },
+});
diff --git a/pages/ar-studio.html b/pages/ar-studio.html
index 6440482be..583edf4f3 100644
--- a/pages/ar-studio.html
+++ b/pages/ar-studio.html
@@ -307,6 +307,32 @@
.ars-qr-box svg { width: 100%; height: 100%; display: block; }
.ars-qr-link { font-size: 12px; color: var(--accent-ink); word-break: break-all; }
+ /* ── Shared-room modal ── */
+ .ars-room-card { gap: 14px; }
+ .ars-room-card h2 { margin: 0 0 4px; }
+ .ars-room-card p { margin: 0 0 4px; }
+ #ars-room-btn.is-active { background: rgba(110, 231, 183, 0.18); border-color: rgba(110, 231, 183, 0.5); color: var(--good); }
+ .ars-room-start { width: 100%; }
+ .ars-room-or { display: flex; align-items: center; gap: 10px; color: var(--ink-faint); font-size: 12px; margin: 2px 0; width: 100%; }
+ .ars-room-or::before, .ars-room-or::after { content: ""; flex: 1 1 auto; height: 1px; background: var(--line); }
+ .ars-room-join { display: flex; gap: 8px; width: 100%; }
+ .ars-room-join input {
+ flex: 1 1 auto; min-width: 0; font: inherit; font-size: 15px; letter-spacing: 0.14em; text-align: center; text-transform: uppercase;
+ color: var(--ink); background: rgba(255, 255, 255, 0.05); border: 1px solid rgba(255, 255, 255, 0.14);
+ border-radius: 10px; padding: 11px 12px;
+ }
+ .ars-room-join input:focus { outline: none; border-color: rgba(139, 124, 248, 0.6); }
+ .ars-room-code {
+ font: 700 30px/1 ui-monospace, "SF Mono", Menlo, monospace; letter-spacing: 0.22em;
+ color: var(--accent-ink); background: rgba(139, 124, 248, 0.12); border: 1px solid rgba(139, 124, 248, 0.35);
+ border-radius: 12px; padding: 14px 10px; width: 100%; text-align: center; user-select: all;
+ }
+ #ars-room-presence { color: var(--good); font-weight: 650; }
+ .ars-room-actions { display: flex; gap: 8px; width: 100%; }
+ .ars-room-actions .ars-btn { flex: 1 1 auto; justify-content: center; }
+ .ars-room-close { width: 100%; justify-content: center; }
+ body.is-room #ars-room-btn { background: rgba(110, 231, 183, 0.18); border-color: rgba(110, 231, 183, 0.5); color: var(--good); }
+
@media (prefers-reduced-motion: reduce) {
.ars-chip, .ars-status, .ars-selbar, .ars-tray-sheet { animation: none; }
.ars-spinner { animation-duration: 2.4s; }
@@ -330,6 +356,7 @@
<span class="ars-title">AR Studio</span>
<span class="ars-count" id="ars-count" hidden>0 models</span>
<span class="ars-spacer"></span>
+ <button class="ars-icon-btn" id="ars-room-btn" type="button" aria-haspopup="dialog" aria-label="Build together in a shared room">👥 Share live</button>
<button class="ars-icon-btn" id="ars-photo-btn" type="button" disabled aria-label="Capture a photo of your scene">📸</button>
<button class="ars-icon-btn" id="ars-qr-btn" type="button" hidden aria-label="Send this scene to your phone">Phone ↗</button>
</header>
@@ -403,6 +430,35 @@
</div>
</div>
+ <div class="ars-modal" id="ars-room-modal" hidden role="dialog" aria-modal="true" aria-label="Build together in a shared room" data-xr-ui>
+ <div class="ars-modal-card ars-room-card">
+ <!-- Idle: start or join a room -->
+ <div id="ars-room-idle">
+ <h2>Build together, live</h2>
+ <p>Open a shared room and everyone with the code sees the same scene update in real time — add, move, and forge models together.</p>
+ <button class="ars-btn ars-btn-primary ars-room-start" id="ars-room-create" type="button">Start a shared room</button>
+ <div class="ars-room-or"><span>or join one</span></div>
+ <form class="ars-room-join" id="ars-room-join-form">
+ <input id="ars-room-join-input" type="text" inputmode="latin" autocomplete="off" spellcheck="false"
+ maxlength="24" placeholder="Enter room code" aria-label="Room code to join" />
+ <button type="submit" class="ars-btn">Join</button>
+ </form>
+ </div>
+ <!-- Live: show the code + share + leave -->
+ <div id="ars-room-live" hidden>
+ <h2>Room is live</h2>
+ <p id="ars-room-presence">You're the only one here yet.</p>
+ <div class="ars-room-code" id="ars-room-code" aria-label="Room code">------</div>
+ <div class="ars-qr-box" id="ars-room-qr" aria-label="QR code to join this room"></div>
+ <div class="ars-room-actions">
+ <button class="ars-btn ars-btn-primary" id="ars-room-copy" type="button">Copy invite link</button>
+ <button class="ars-btn" id="ars-room-leave" type="button">Leave room</button>
+ </div>
+ </div>
+ <button class="ars-btn ars-room-close" id="ars-room-close" type="button">Close</button>
+ </div>
+ </div>
+
<script type="module">
function webglSupported() {
try {
diff --git a/public/changelog.json b/public/changelog.json
index 2fd110612..6b8055516 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-17T12:08:29.844Z",
+ "generated_at": "2026-07-17T12:22:07.940Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -37,6 +37,16 @@
"improvement"
]
},
+ {
+ "date": "2026-07-17",
+ "type": "update",
+ "title": "AR Studio goes multiplayer: build a scene together in real time",
+ "summary": "The AR Studio can now be a shared space. Tap Share live to open a room with a short code, send it to a friend, and you both see the same scene update live: every model one of you adds, moves, resizes, rotates, or removes appears for everyone in the room instantly, with a running count of who's building alongside you. Forge a new model from a prompt and it drops into the shared room for everyone. Open the same room on two phones pointed at the same QR marker and the models pin to the same spot on your real table. It runs on the same realtime servers as our live worlds, with each person only able to edit their own models.",
+ "link": "/ar/studio",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-07-17",
"type": "update",
@@ -155,6 +165,17 @@
"improvement"
]
},
+ {
+ "date": "2026-07-17",
+ "type": "update",
+ "title": "Forge a 3D model right from the homepage",
+ "summary": "The homepage now leads with a prompt bar: type what you want and a real textured 3D model starts building the moment you hit Enter, no navigation and no sign-up. The live generator that used to sit far down the page now sits directly under the headline, so you type at the top and watch your model take shape right below. Three one-tap example prompts and a rotating set of ideas make it easy to start.",
+ "link": "/",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-07-17",
"type": "update",
@@ -186,6 +207,16 @@
"improvement"
]
},
+ {
+ "date": "2026-07-17",
+ "type": "update",
+ "title": "Forge: one-tap variations of any model",
+ "summary": "Every model you forge now shows a \"More like this\" row: one tap re-forges the same subject in a different material or finish (brushed brass, translucent glass, carved oak, and more), so you can explore a whole design space without retyping anything. A reshuffle button deals a fresh set of ideas. It appears for text prompts and runs on the free lane, so exploring costs nothing.",
+ "link": null,
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-07-17",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 281015e52..54cd1d6cb 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -30,6 +30,14 @@
<category>feature</category>
<description>The studio avatar generator used to recolor one of five fixed body meshes, so a whole gallery of them read as the same handful of people in different colors. It now composes each avatar from modular parts: a hairstyle, top, bottom, footwear, and glasses mixed across the base bodies onto one shared skeleton, then recolored per part and scaled for height. This is the same one-skeleton-many-parts approach the best avatar platforms use, built in-house with no external service. Every generated avatar is fully rigged and carries facial expression blendshapes, and two of them almost never look the same. All platform-generated avatars continue to appear across the galleries.</description>
</item>
+ <item>
+ <title>AR Studio goes multiplayer: build a scene together in real time</title>
+ <link>https://three.ws/ar/studio</link>
+ <guid isPermaLink="false">2026-07-17:AR Studio goes multiplayer: build a scene together in real time</guid>
+ <pubDate>Fri, 17 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The AR Studio can now be a shared space. Tap Share live to open a room with a short code, send it to a friend, and you both see the same scene update live: every model one of you adds, moves, resizes, rotates, or removes appears for everyone in the room instantly, with a running count of who's building alongside you. Forge a new model from a prompt and it drops into the shared room for everyone. Open the same room on two phones pointed at the same QR marker and the models pin to the same spot on your real table. It runs on the same realtime servers as our live worlds, with each person only able to edit their own models.</description>
+ </item>
<item>
<title>AR Studio: fill your room with 3D models, and forge new ones without leaving the camera</title>
<link>https://three.ws/ar/studio</link>
@@ -118,6 +126,14 @@
<category>improvement</category>
<description>Connecting a wallet now gives real feedback: the button shows a Connecting state, a success confirmation when it links, and a plain-language message with a one-tap retry when something goes wrong instead of failing silently. If you have no wallet installed, you get a clear Get Phantom prompt rather than a surprise browser tab. On a Solana Seeker, signing in now takes a single tap instead of two: both login and wallet-linking use the Mobile Wallet Adapter's built-in Sign-In-With-Solana, so authorization and the signature happen in one Seed Vault prompt, and backing out is recognized as a clean cancel. Phantom, Backpack, and Solflare work exactly as before. The whole wallet layer is now covered by an automated test suite.</description>
</item>
+ <item>
+ <title>Forge a 3D model right from the homepage</title>
+ <link>https://three.ws/</link>
+ <guid isPermaLink="false">2026-07-17:Forge a 3D model right from the homepage</guid>
+ <pubDate>Fri, 17 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The homepage now leads with a prompt bar: type what you want and a real textured 3D model starts building the moment you hit Enter, no navigation and no sign-up. The live generator that used to sit far down the page now sits directly under the headline, so you type at the top and watch your model take shape right below. Three one-tap example prompts and a rotating set of ideas make it easy to start.</description>
+ </item>
<item>
<title>Forge prompt ideas are now endless, and every one forges beautifully</title>
<link>https://three.ws/forge</link>
@@ -142,6 +158,14 @@
<category>feature</category>
<description>The Forge now greets you with a Roll &amp; Forge button that picks a great random prompt and generates a model in a single click, so you can reach a finished 3D object without thinking of what to type. The start screen and page header also state plainly that generating is free with no sign-up and the model is yours to download, removing the guesswork about cost. Roll &amp; Forge draws from the same curated prompt library as Surprise me, so every random model is one that reconstructs cleanly.</description>
</item>
+ <item>
+ <title>Forge: one-tap variations of any model</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-07-17:Forge: one-tap variations of any model</guid>
+ <pubDate>Fri, 17 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Every model you forge now shows a &quot;More like this&quot; row: one tap re-forges the same subject in a different material or finish (brushed brass, translucent glass, carved oak, and more), so you can explore a whole design space without retyping anything. A reshuffle button deals a fresh set of ideas. It appears for text prompts and runs on the free lane, so exploring costs nothing.</description>
+ </item>
<item>
<title>Free 3D API tells agents exactly when to check back</title>
<link>https://three.ws/docs/3d-api</link>
diff --git a/public/features.json b/public/features.json
index 69431eefb..c6458841f 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-17T12:08:29.831Z",
+ "generated_at": "2026-07-17T12:22:07.928Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index f95db59df..bbfe9d5b2 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -52,25 +52,6 @@
.sm-badge-auth { background: rgba(255, 200, 80, .15); color: #ffcf66; }
.sm-badge-internal { background: rgba(120,200,255,.12); color: #9ad4ff; }
</style>
-
- <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">
- <meta property="og:type" content="website">
- <meta property="og:site_name" content="three.ws">
- <meta property="og:locale" content="en_US">
- <meta property="og:title" content="Sitemap · three.ws">
- <meta property="og:description" content="Human-readable index of every page on three.ws.">
- <meta property="og:url" content="https://three.ws/sitemap">
- <meta property="og:image" content="https://three.ws/api/page-og?s=main&amp;t=Sitemap&amp;d=Human-readable+index+of+every+page+on+three.ws.&amp;p=%2Fsitemap">
- <meta property="og:image:width" content="1200">
- <meta property="og:image:height" content="630">
- <meta property="og:image:type" content="image/png">
- <meta property="og:image:alt" content="Sitemap — three.ws">
- <meta name="twitter:card" content="summary_large_image">
- <meta name="twitter:site" content="@trythreews">
- <meta name="twitter:title" content="Sitemap · three.ws">
- <meta name="twitter:description" content="Human-readable index of every page on three.ws.">
- <meta name="twitter:image" content="https://three.ws/api/page-og?s=main&amp;t=Sitemap&amp;d=Human-readable+index+of+every+page+on+three.ws.&amp;p=%2Fsitemap">
- <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Sitemap","description":"Human-readable index of every page on three.ws.","url":"https://three.ws/sitemap","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap"}]}</script>
</head>
<body>
<header><div id="nav-container"></div></header>
diff --git a/src/ar-studio.js b/src/ar-studio.js
index 74f44884a..51889124c 100644
--- a/src/ar-studio.js
+++ b/src/ar-studio.js
@@ -32,6 +32,11 @@ import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js';
import { EstimatedLighting } from './ar/estimated-lighting.js';
+import {
+ generateRoomCode, localToShared, normalizeRoomCode, roomKeyForCode,
+ roomShareUrl, sharedToLocal,
+} from './ar/studio-coords.js';
+import { StudioNet } from './ar/studio-net.js';
import { MultiPlaceSession } from './ar/multi-place.js';
import {
createPinchState, pinchEnd, pinchMove, pinchStart, touchDist,
@@ -106,6 +111,8 @@ const trayBody = $('ars-tray-body');
const trayClose = $('ars-tray-close');
const emptyEl = $('ars-empty');
const qrModal = $('ars-qr-modal');
+const roomBtn = $('ars-room-btn');
+const roomModal = $('ars-room-modal');
if (!canvas || !hud) {
throw new Error('AR Studio: page skeleton missing');
@@ -227,6 +234,21 @@ let arTrackH = 0;
let statusTimer = null;
let undoItems = null;
+// ── Shared-room networking (purely additive; null = single-player) ────────────
+/** @type {import('./ar/studio-net.js').StudioNet|null} */
+let net = null;
+let roomCode = '';
+/** netId → placement, for reconciling remote models against local ones. */
+const netModelsById = new Map();
+let roomPresence = { count: 1, names: [] };
+
+// A placement I control: single-player models (no ownerId) and my own room
+// models. Others' room models are visible + live but not editable by me (the
+// server owner-gates edits too — this is the local UX guard).
+function isMine(p) {
+ return !p.ownerId || p.ownerId === CLIENT_ID;
+}
+
// Template cache: one load per GLB source no matter how many copies are placed.
/** @type {Map<string, Promise<{ gltf: any, skinned: boolean, fit: { scale: number, yOffset: number }, radius: number }>>} */
const templates = new Map();
@@ -269,8 +291,7 @@ function setStatus(msg, { warn = false, sticky = false, actionLabel = '', onActi
function updateCount() {
if (!countEl) return;
const n = placements.length;
- countEl.textContent = n === 1 ? '1 model' : `${n} models`;
- countEl.hidden = n === 0;
+ updatePresencePill(); // owns the count-pill text (folds in room presence)
if (clearBtn) clearBtn.hidden = n === 0;
if (emptyEl) emptyEl.hidden = n > 0;
if (photoBtn) photoBtn.disabled = n === 0;
@@ -287,9 +308,11 @@ function logicalScale(p) {
}
// ── Scene persistence ─────────────────────────────────────────────────────────
+// Only MY models persist to localStorage — never another participant's room
+// models, which would otherwise reappear as mine on a later solo visit.
function saveScene() {
try {
- localStorage.setItem(SCENE_KEY, serializeScene(placements.map((p) => ({
+ localStorage.setItem(SCENE_KEY, serializeScene(placements.filter(isMine).map((p) => ({
src: p.src,
title: p.title,
x: p.group.position.x,
@@ -408,7 +431,10 @@ function nudgeSpawn(pt) {
* floor in front of the camera (or at the given transform on restore), selects
* it, and persists. Resolves with the placement or null on failure.
*/
-async function addModel({ src, title = '' }, { x = null, z = null, yaw = null, scale = null, announce = true, persist = true } = {}) {
+async function addModel({ src, title = '' }, {
+ x = null, z = null, yaw = null, scale = null, announce = true, persist = true,
+ remote = false, netId = null, ownerId = null,
+} = {}) {
const url = normalizeGlbUrl(src);
if (!url) {
setStatus('That link is not a loadable https GLB.', { warn: true });
@@ -466,6 +492,13 @@ async function addModel({ src, title = '' }, { x = null, z = null, yaw = null, s
yaw: yawV,
baseRadius: tpl.radius,
spawnT: reducedMotion ? 1 : 0,
+ height: tpl.height || 0,
+ // Room fields: netId is the shared-scene id (null until broadcast); ownerId
+ // null = single-player / mine. Set for remote models so isMine() gates edits.
+ netId: netId || null,
+ ownerId: remote ? ownerId : null,
+ remote,
+ _lastNetSend: 0,
};
idlePromise?.then((mgr) => {
if (!mgr) return;
@@ -476,18 +509,337 @@ async function addModel({ src, title = '' }, { x = null, z = null, yaw = null, s
group.userData._targetScale = group.scale.x;
if (!reducedMotion) group.scale.setScalar(0.001);
placements.push(placement);
- armedSrc = { src: url, title: placement.title };
+ if (placement.netId) netModelsById.set(placement.netId, placement);
+ if (!remote) armedSrc = { src: url, title: placement.title };
updateCount();
- select(placement);
+ if (!remote) select(placement);
if (persist) saveScene();
- if (announce) setStatus('Placed. Drag to move, pinch to resize, twist to rotate.');
+
+ // Broadcast a locally-added model to the shared room (once): mint a wire id,
+ // tag the placement with it, and send its shared-frame transform. Remote adds
+ // (reconciled from the room) never re-broadcast.
+ if (!remote && net && net.status === 'online') {
+ const wireId = `m${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`.slice(0, 40);
+ placement.netId = wireId;
+ placement.ownerId = CLIENT_ID;
+ netModelsById.set(wireId, placement);
+ net.spawn(placementWire(placement, wireId));
+ }
+
+ if (announce) {
+ setStatus(remote
+ ? `${title || 'A model'} was added by someone in the room.`
+ : 'Placed. Drag to move, pinch to resize, twist to rotate.');
+ }
return placement;
}
-function removePlacement(p, { persist = true } = {}) {
+// A placement's transform in the shared logical frame (for the wire).
+function placementShared(p) {
+ return localToShared({
+ x: p.group.position.x,
+ z: p.group.position.z,
+ yaw: p.yaw,
+ scale: logicalScale(p),
+ height: p.height || 0,
+ });
+}
+
+// The full spawn payload for the wire: source + title + shared-frame transform.
+function placementWire(p, wireId) {
+ return { id: wireId, src: p.src, title: p.title, ...placementShared(p) };
+}
+
+// Broadcast a transform change for one of MY room models, throttled to ~12 Hz so
+// a drag doesn't flood the socket. No-op single-player or for others' models.
+function netBroadcastTransform(p) {
+ if (!net || net.status !== 'online' || !p.netId || !isMine(p)) return;
+ const now = Date.now();
+ if (now - (p._lastNetSend || 0) < 80) return;
+ p._lastNetSend = now;
+ const s = placementShared(p);
+ net.update(p.netId, { relEast: s.relEast, relNorth: s.relNorth, yawDeg: s.yawDeg, scale: s.scale });
+}
+
+// Apply a shared-frame transform from the room to a placement's local group.
+function applySharedTransform(p, m) {
+ const l = sharedToLocal(m);
+ p.group.position.set(l.x, 0, l.z);
+ p.yaw = l.yaw;
+ p.group.rotation.y = l.yaw;
+ p.group.scale.setScalar(l.scale);
+ p.group.userData._targetScale = l.scale;
+ p.spawnT = 1; // an update is not a spawn — no scale-in pop
+ if (p.shadow) {
+ p.shadow.position.set(l.x, 0.004, l.z);
+ p.shadow.scale.setScalar(l.scale);
+ }
+ if (selected === p) positionSelRing();
+}
+
+// Reconcile the full shared model list against local placements: add models that
+// appeared (others' or my own from a prior session), drop REMOTE ones that left,
+// and refresh others' transforms. My own live models are authored locally — never
+// overwritten by their own echo.
+function reconcileRemoteModels(models) {
+ const serverIds = new Set(models.map((m) => m.id));
+ // Remove remote placements that vanished from the room (owner deleted / reaped).
+ for (const p of [...placements]) {
+ if (p.remote && p.netId && !serverIds.has(p.netId)) {
+ removePlacement(p, { persist: false, broadcast: false });
+ }
+ }
+ for (const m of models) {
+ const existing = netModelsById.get(m.id);
+ if (existing) {
+ if (!isMine(existing)) applySharedTransform(existing, m);
+ continue;
+ }
+ // New to me: reconcile it in. Mark mine when the server says I own it (a
+ // rejoin) so I keep control; otherwise it's someone else's, view-only.
+ const local = sharedToLocal(m);
+ const mine = !!m.mine || m.ownerId === CLIENT_ID;
+ addModel({ src: m.src, title: m.title }, {
+ x: local.x, z: local.z, yaw: local.yaw, scale: local.scale,
+ remote: true, netId: m.id, ownerId: mine ? CLIENT_ID : m.ownerId,
+ announce: false, persist: false,
+ });
+ }
+ updateCount();
+}
+
+// A single model changed (per-field delta) or was removed. Refresh others' live;
+// ignore echoes of my own.
+function applyRemoteModelChange(m) {
+ const p = netModelsById.get(m.id);
+ if (!p) return;
+ if (m.removed) {
+ if (p.remote) removePlacement(p, { persist: false, broadcast: false });
+ return;
+ }
+ if (!isMine(p)) applySharedTransform(p, m);
+}
+
+// ── Room lifecycle ────────────────────────────────────────────────────────────
+function updatePresencePill() {
+ if (!countEl) return;
+ // The count pill doubles as the presence indicator when in a room.
+ const n = placements.length;
+ if (net && net.status === 'online' && roomPresence.count > 1) {
+ countEl.textContent = `${roomPresence.count} here · ${n} ${n === 1 ? 'model' : 'models'}`;
+ countEl.hidden = false;
+ } else {
+ countEl.textContent = n === 1 ? '1 model' : `${n} models`;
+ countEl.hidden = n === 0;
+ }
+}
+
+function wireNet(n) {
+ n.on('status', ({ status }) => {
+ if (status === 'online') {
+ setStatus(`Shared room ${roomCode} is live — edits sync to everyone here.`);
+ document.body.classList.add('is-room');
+ } else if (status === 'connecting') {
+ setStatus(`Joining room ${roomCode}…`, { sticky: true });
+ } else if (status === 'unavailable' || status === 'failed') {
+ setStatus('Shared rooms are offline right now — you can still build solo.', { warn: true });
+ leaveRoom({ silent: true });
+ } else if (status === 'offline') {
+ setStatus('Reconnecting to the room…', { sticky: true });
+ }
+ updateRoomButton();
+ });
+ n.on('models', (models) => reconcileRemoteModels(models));
+ n.on('model', (m) => applyRemoteModelChange(m));
+ n.on('presence', (p) => { roomPresence = p; updatePresencePill(); });
+ n.on('reject', (msg) => {
+ const why = msg?.reason === 'room_full' ? 'the room is full'
+ : msg?.reason === 'owner_full' ? 'you have the max models in this room'
+ : 'the room declined it';
+ setStatus(`Couldn't share that model — ${why}.`, { warn: true });
+ });
+}
+
+// Push every model I ALREADY have into a freshly joined room, so a solo scene
+// becomes the shared starting point instead of vanishing.
+function seedRoomWithLocalScene() {
+ if (!net || net.status !== 'online') return;
+ for (const p of placements) {
+ if (p.netId) continue; // already shared
+ const wireId = `m${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`.slice(0, 40);
+ p.netId = wireId;
+ p.ownerId = CLIENT_ID;
+ p.remote = false;
+ netModelsById.set(wireId, p);
+ net.spawn(placementWire(p, wireId));
+ }
+}
+
+let _roomHeartbeat = null;
+
+// seed=true pushes my current scene into the room as its starting point — right
+// for CREATE (I'm the first one there). JOIN never seeds: entering a room means
+// entering ITS shared scene, so my solo models stay local (private) and can't
+// duplicate the server's authoritative copies on a refresh-rejoin.
+async function joinRoom(code, { seed = false } = {}) {
+ const norm = normalizeRoomCode(code);
+ if (!norm) {
+ setStatus('That room code looks off — check the 6 characters and try again.', { warn: true });
+ return;
+ }
+ leaveRoom({ silent: true });
+ roomCode = norm;
+ net = new StudioNet({
+ roomKey: roomKeyForCode(norm),
+ clientId: CLIENT_ID,
+ name: '',
+ });
+ wireNet(net);
+ await net.connect();
+ if (net.status === 'online') {
+ if (seed) seedRoomWithLocalScene();
+ _roomHeartbeat = setInterval(() => net?.heartbeat(), 15000);
+ try {
+ const url = new URL(location.href);
+ url.searchParams.set('room', norm);
+ history.replaceState(null, '', url);
+ } catch {}
+ }
+ updateRoomButton();
+}
+
+function createRoom() {
+ // Creating a room shares my current scene as its starting point.
+ joinRoom(generateRoomCode(), { seed: true });
+}
+
+function leaveRoom({ silent = false } = {}) {
+ if (_roomHeartbeat) { clearInterval(_roomHeartbeat); _roomHeartbeat = null; }
+ if (net) {
+ try { net.destroy(); } catch {}
+ net = null;
+ }
+ // Remote models leave with the room; my own stay as a local scene.
+ for (const p of [...placements]) {
+ if (p.remote && !isMine(p)) removePlacement(p, { persist: false, broadcast: false });
+ else { p.netId = null; p.remote = false; }
+ }
+ netModelsById.clear();
+ roomCode = '';
+ roomPresence = { count: 1, names: [] };
+ document.body.classList.remove('is-room');
+ try {
+ const url = new URL(location.href);
+ url.searchParams.delete('room');
+ history.replaceState(null, '', url);
+ } catch {}
+ updatePresencePill();
+ updateRoomButton();
+ if (!silent) setStatus('Left the shared room. Your models are still here.');
+}
+
+// ── Room modal UI ─────────────────────────────────────────────────────────────
+function updateRoomButton() {
+ if (!roomBtn) return;
+ const live = !!net && (net.status === 'online' || net.status === 'connecting');
+ roomBtn.classList.toggle('is-active', live);
+ roomBtn.textContent = live ? `👥 ${roomCode || 'Room'}` : '👥 Share live';
+ // Keep the live modal panel in sync if it's open.
+ if (roomModal && !roomModal.hidden) renderRoomModal();
+}
+
+function renderRoomModal() {
+ const idle = $('ars-room-idle');
+ const liveEl = $('ars-room-live');
+ const online = !!net && net.status === 'online';
+ if (idle) idle.hidden = online;
+ if (liveEl) liveEl.hidden = !online;
+ if (online) {
+ const codeEl = $('ars-room-code');
+ if (codeEl) codeEl.textContent = roomCode;
+ const pres = $('ars-room-presence');
+ if (pres) {
+ pres.textContent = roomPresence.count > 1
+ ? `${roomPresence.count} people are building here.`
+ : "You're the only one here yet — share the code to invite someone.";
+ }
+ const box = $('ars-room-qr');
+ if (box) {
+ try {
+ box.innerHTML = renderQRToSVG(roomShareUrl('https://three.ws', roomCode), {
+ scale: 5, margin: 2, dark: '#0b0b0b', light: '#ffffff',
+ });
+ } catch { box.textContent = roomShareUrl('https://three.ws', roomCode); }
+ }
+ }
+}
+
+function openRoomModal() {
+ if (!roomModal) return;
+ roomModal.hidden = false;
+ renderRoomModal();
+ (net && net.status === 'online' ? $('ars-room-copy') : $('ars-room-create'))?.focus?.();
+}
+
+function closeRoomModal() {
+ if (roomModal) roomModal.hidden = true;
+}
+
+roomBtn?.addEventListener('click', openRoomModal);
+$('ars-room-close')?.addEventListener('click', closeRoomModal);
+roomModal?.addEventListener('click', (e) => { if (e.target === roomModal) closeRoomModal(); });
+
+$('ars-room-create')?.addEventListener('click', async () => {
+ await createRoom();
+ renderRoomModal();
+});
+
+$('ars-room-join-form')?.addEventListener('submit', async (e) => {
+ e.preventDefault();
+ const input = $('ars-room-join-input');
+ const code = normalizeRoomCode(input?.value);
+ if (!code) {
+ setStatus('That room code looks off — check the 6 characters.', { warn: true });
+ input?.focus?.();
+ return;
+ }
+ await joinRoom(code);
+ renderRoomModal();
+});
+
+$('ars-room-copy')?.addEventListener('click', () => {
+ const url = roomShareUrl(location.origin, roomCode);
+ const btn = $('ars-room-copy');
+ const done = () => {
+ if (!btn) return;
+ const old = btn.textContent;
+ btn.textContent = 'Link copied ✓';
+ setTimeout(() => { btn.textContent = old; }, 1600);
+ };
+ if (navigator.share) {
+ navigator.share({ title: 'Build with me in AR Studio', text: `Join my AR Studio room: ${roomCode}`, url }).catch(() => {});
+ } else if (navigator.clipboard) {
+ navigator.clipboard.writeText(url).then(done).catch(() => window.prompt('Copy this invite link:', url));
+ } else {
+ window.prompt('Copy this invite link:', url);
+ }
+});
+
+$('ars-room-leave')?.addEventListener('click', () => {
+ leaveRoom();
+ renderRoomModal();
+});
+
+function removePlacement(p, { persist = true, broadcast = true } = {}) {
const i = placements.indexOf(p);
if (i === -1) return;
placements.splice(i, 1);
+ if (p.netId) {
+ netModelsById.delete(p.netId);
+ // Tell the room, unless this removal CAME from the room (reconcile) or it's
+ // not mine to remove (the server would reject it anyway).
+ if (broadcast && net && net.status === 'online' && isMine(p)) net.remove(p.netId);
+ }
p.idle?.detach();
p.idle = null;
xrSession?.release(p.group);
@@ -509,18 +861,21 @@ function removePlacement(p, { persist = true } = {}) {
// ── Restore + deep links ──────────────────────────────────────────────────────
let armedSrc = null; // { src, title } — what an XR reticle tap places
-async function restoreScene() {
+async function restoreScene({ skipLocal = false } = {}) {
const params = new URLSearchParams(location.search);
const linked = parseSrcParams(params);
// A #s= hash is a FULL shared arrangement (models + transforms) — it opens
// like a document, replacing the working scene rather than merging into it.
- const sharedScene = sceneFromHashParam(
+ // skipLocal (arriving via a ?room= link) means the shared ROOM is the source
+ // of truth, so we don't also restore the local/hash scene (which would
+ // duplicate the server's authoritative copies).
+ const sharedScene = skipLocal ? [] : sceneFromHashParam(
new URLSearchParams(location.hash.replace(/^#/, '')).get('s'),
);
let items = sharedScene;
- if (!items.length) {
+ if (!items.length && !skipLocal) {
try {
items = deserializeScene(localStorage.getItem(SCENE_KEY));
} catch {}
@@ -825,8 +1180,8 @@ canvas.addEventListener('pointermove', (e) => {
if (Math.hypot(dx, dy) > 6) pointerDown.moved = true;
if (!pointerDown.moved) return;
- if (pointerDown.placement) {
- // Drag a model along the floor.
+ if (pointerDown.placement && isMine(pointerDown.placement)) {
+ // Drag a model along the floor (only models I own in a shared room).
const pt = floorPointAt(e.clientX, e.clientY);
if (!pt) return;
const p = pointerDown.placement;
@@ -834,7 +1189,8 @@ canvas.addEventListener('pointermove', (e) => {
p.group.position.z = pt.z;
if (p.shadow) p.shadow.position.set(pt.x, 0.004, pt.z);
if (selected === p) positionSelRing();
- } else if (!(arActive && gyroBase)) {
+ netBroadcastTransform(p);
+ } else if (!pointerDown.placement && !(arActive && gyroBase)) {
// Drag-look: only when the gyro isn't already steering the view.
cameraYaw = pointerDown.lookYaw + dx * 0.0042;
cameraPitch = clampPitch(pointerDown.lookPitch + dy * 0.0032, PITCH_MIN, PITCH_MAX);
@@ -848,7 +1204,9 @@ function endPointer(e) {
&& !pinch.active && performance.now() - pinchEndedAt >= 350;
if (wasTap) {
select(pointerDown.placement); // null = deselect
- } else if (pointerDown.placement && pointerDown.moved) {
+ } else if (pointerDown.placement && pointerDown.moved && isMine(pointerDown.placement)) {
+ pointerDown.placement._lastNetSend = 0; // force the settle broadcast through
+ netBroadcastTransform(pointerDown.placement);
saveScene();
setStatus(null);
}
@@ -857,9 +1215,10 @@ function endPointer(e) {
canvas.addEventListener('pointerup', endPointer);
canvas.addEventListener('pointercancel', () => { pointerDown = null; });
-// Two-finger pinch = scale, twist = rotate — on the selected (or last) model.
+// Two-finger pinch = scale, twist = rotate — on the selected (or last) model I own.
function gestureTarget() {
- return selected ?? placements[placements.length - 1] ?? null;
+ const t = selected ?? placements[placements.length - 1] ?? null;
+ return t && isMine(t) ? t : null;
}
canvas.addEventListener('touchstart', (e) => {
@@ -883,14 +1242,17 @@ canvas.addEventListener('touchmove', (e) => {
}
target.yaw = twist.baseYaw + twistDelta(twist.startAngle, touchAngle(e.touches));
target.group.rotation.y = target.yaw;
+ netBroadcastTransform(target);
}, { passive: true });
canvas.addEventListener('touchend', () => {
const s = pinchEnd(pinch);
+ const target = twist?.placement;
if (s != null) {
pinchEndedAt = performance.now();
saveScene();
}
+ if (target) { target._lastNetSend = 0; netBroadcastTransform(target); }
twist = null;
}, { passive: true });
@@ -900,14 +1262,18 @@ selbar?.addEventListener('click', (e) => {
if (!btn || !selected) return;
const act = btn.dataset.act;
if (act === 'rotate') {
+ if (!isMine(selected)) { setStatus('That model belongs to someone else in the room.', { warn: true }); return; }
selected.yaw += Math.PI / 4;
selected.group.rotation.y = selected.yaw;
+ selected._lastNetSend = 0;
+ netBroadcastTransform(selected);
saveScene();
} else if (act === 'duplicate') {
addModel({ src: selected.src, title: selected.title }, {
yaw: selected.yaw, scale: logicalScale(selected),
});
} else if (act === 'remove') {
+ if (!isMine(selected)) { setStatus('That model belongs to someone else in the room.', { warn: true }); return; }
const removed = selected;
removePlacement(removed);
setStatus('Removed.', {
@@ -1080,6 +1446,7 @@ tray?.addEventListener('click', (e) => {
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
if (tray && !tray.hidden) closeTray();
+ else if (roomModal && !roomModal.hidden) closeRoomModal();
else if (qrModal && !qrModal.hidden) qrModal.hidden = true;
else select(null);
}
@@ -1092,9 +1459,12 @@ document.addEventListener('keydown', (e) => {
if (e.target.closest?.('input, textarea, select')) return;
if ((tray && !tray.hidden) || (qrModal && !qrModal.hidden) || xrSession) return;
if (!selected) return;
+ // Keyboard edits act on the selected model — only if it's mine in a room.
+ const editable = isMine(selected);
const key = e.key;
if (key.startsWith('Arrow')) {
+ if (!editable) return;
e.preventDefault();
const step = e.shiftKey ? 0.02 : 0.1;
const fwd = camera.getWorldDirection(new Vector3());
@@ -1109,10 +1479,14 @@ document.addEventListener('keydown', (e) => {
selected.group.position.addScaledVector(move, step);
selected.shadow?.position.set(selected.group.position.x, 0.004, selected.group.position.z);
positionSelRing();
+ netBroadcastTransform(selected);
saveScene();
} else if (key === 'r' || key === 'R') {
+ if (!editable) return;
selected.yaw += Math.PI / 4;
selected.group.rotation.y = selected.yaw;
+ selected._lastNetSend = 0;
+ netBroadcastTransform(selected);
saveScene();
} else if (key === 'd' || key === 'D') {
e.preventDefault();
@@ -1120,6 +1494,7 @@ document.addEventListener('keydown', (e) => {
yaw: selected.yaw, scale: logicalScale(selected),
});
} else if (key === 'Delete' || key === 'Backspace') {
+ if (!editable) return;
e.preventDefault();
const removed = selected;
removePlacement(removed);
@@ -1497,12 +1872,38 @@ window.addEventListener('resize', () => {
window.addEventListener('pagehide', () => {
stopCamera();
xrSession?.end();
+ net?.destroy();
});
// ── Boot ──────────────────────────────────────────────────────────────────────
updateCount();
+updateRoomButton();
startLoop();
-restoreScene();
+{
+ let bootRoom = '';
+ try { bootRoom = normalizeRoomCode(new URLSearchParams(location.search).get('room') || ''); } catch {}
+ // Arriving via a ?room= link: the shared room is the scene, so skip the local
+ // restore and join straight in (no seed — I'm entering someone else's room).
+ restoreScene({ skipLocal: !!bootRoom }).then(() => {
+ if (bootRoom) joinRoom(bootRoom);
+ });
+}
+
+// Read-only introspection hook, enabled only with ?e2e=1 — used by the shared-
+// room sync test to observe remote model transforms. Never present in normal use.
+try {
+ if (new URLSearchParams(location.search).has('e2e')) {
+ window.__arsDebug = {
+ count: () => placements.length,
+ netStatus: () => net?.status ?? 'none',
+ netIds: () => placements.map((p) => p.netId),
+ remoteX: () => {
+ const p = placements.find((x) => x.remote && !isMine(x));
+ return p ? p.group.position.x : null;
+ },
+ };
+ }
+} catch {}
// Mobile: lead with the camera (one tap, inside a user gesture via the empty
// state CTA). Desktop: preview + QR chip.
diff --git a/src/ar/studio-coords.js b/src/ar/studio-coords.js
new file mode 100644
index 000000000..72bd0be13
--- /dev/null
+++ b/src/ar/studio-coords.js
@@ -0,0 +1,116 @@
+// Pure coordinate + room-key helpers for the shared AR Studio. DOM-free and
+// Three-free so they unit-test directly.
+//
+// Two frames:
+// • LOCAL — the studio's own scene. A model sits at (x, z) metres on the floor
+// with yaw in radians (Three's Y rotation). Origin is where this device's
+// view started; +x is right, −z is "into the scene / forward".
+// • SHARED (logical) — what rides the wire so every device agrees. relEast /
+// relNorth metres from the room's common origin, yaw in degrees. We map
+// forward (−z) → north and right (+x) → east. When two phones are co-located
+// via a QR marker, the marker frame makes these logical coords land on the
+// same physical spot; otherwise each device just re-bases them to its own
+// floor origin, so everyone sees the same ARRANGEMENT in their own space.
+
+const TAU = Math.PI * 2;
+
+/** Normalize any radian angle into [0, 2π). */
+export function normRad(a) {
+ if (!Number.isFinite(a)) return 0;
+ return ((a % TAU) + TAU) % TAU;
+}
+
+/** Normalize any degree angle into [0, 360). */
+export function normDeg(d) {
+ if (!Number.isFinite(d)) return 0;
+ return ((d % 360) + 360) % 360;
+}
+
+/**
+ * Local scene transform → shared logical transform (for sending over the wire).
+ * @param {{ x:number, z:number, yaw:number, scale?:number, height?:number }} t
+ * yaw in RADIANS.
+ * @returns {{ relEast:number, relNorth:number, yawDeg:number, scale:number, height:number }}
+ */
+export function localToShared(t) {
+ return {
+ relEast: Number(t.x) || 0,
+ // `|| 0` also collapses the -0 that negating +0 produces — cleaner on the wire.
+ relNorth: -(Number(t.z) || 0) || 0,
+ yawDeg: normDeg((normRad(t.yaw) * 180) / Math.PI),
+ scale: Number(t.scale) || 1,
+ height: Number(t.height) || 0,
+ };
+}
+
+/**
+ * Shared logical transform (from the wire) → local scene transform.
+ * @param {{ relEast:number, relNorth:number, yawDeg:number, scale?:number }} s
+ * @returns {{ x:number, z:number, yaw:number, scale:number }} yaw in RADIANS.
+ */
+export function sharedToLocal(s) {
+ return {
+ x: Number(s.relEast) || 0,
+ z: -(Number(s.relNorth) || 0),
+ yaw: (normDeg(s.yawDeg) * Math.PI) / 180,
+ scale: Number(s.scale) || 1,
+ };
+}
+
+// ── Room codes ────────────────────────────────────────────────────────────────
+// A human-shareable, URL-safe code. Unambiguous alphabet — no 0/O/1/I/L — so a
+// code read aloud or typed from a screen doesn't collide. Six chars ≈ 32^6 ≈ 1e9
+// combinations, ample for concurrent ephemeral rooms.
+const CODE_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
+const CODE_LEN = 6;
+
+/**
+ * Normalize user-typed room input into a canonical code, or '' if unusable.
+ * Accepts a bare code or a pasted /ar/studio?room=CODE URL. Upper-cases, drops
+ * the separators a human adds (spaces, hyphens), then validates STRICTLY against
+ * the alphabet + length — the generator never emits an ambiguous glyph, so a code
+ * carrying one is a mistype, not a near-miss to silently "fix".
+ * @param {unknown} raw
+ * @returns {string}
+ */
+export function normalizeRoomCode(raw) {
+ let s = String(raw ?? '').trim();
+ if (!s) return '';
+ const m = s.match(/[?&]room=([^&#\s]+)/i);
+ if (m) { try { s = decodeURIComponent(m[1]); } catch { s = m[1]; } }
+ s = s.toUpperCase().replace(/[\s-]+/g, '');
+ if (s.length !== CODE_LEN) return '';
+ for (const ch of s) if (!CODE_ALPHABET.includes(ch)) return '';
+ return s;
+}
+
+/**
+ * Generate a fresh room code. `rand` defaults to Math.random but is injectable
+ * so tests are deterministic (and so this never trips the workflow-script clock
+ * ban — app code only).
+ * @param {() => number} [rand]
+ * @returns {string}
+ */
+export function generateRoomCode(rand = Math.random) {
+ let out = '';
+ for (let i = 0; i < CODE_LEN; i++) {
+ out += CODE_ALPHABET[Math.floor(rand() * CODE_ALPHABET.length) % CODE_ALPHABET.length];
+ }
+ return out;
+}
+
+/**
+ * The Colyseus filterBy key for a room code. A code IS its own key; kept as a
+ * function so a future co-located (marker) key can funnel through one place.
+ * @param {string} code
+ * @returns {string}
+ */
+export function roomKeyForCode(code) {
+ return `c-${normalizeRoomCode(code)}`;
+}
+
+/** Build the shareable join URL for a room code. */
+export function roomShareUrl(origin, code) {
+ const c = normalizeRoomCode(code);
+ return c ? `${origin}/ar/studio?room=${c}` : `${origin}/ar/studio`;
+}
diff --git a/src/ar/studio-net.js b/src/ar/studio-net.js
new file mode 100644
index 000000000..ace65ff89
--- /dev/null
+++ b/src/ar/studio-net.js
@@ -0,0 +1,293 @@
+// Realtime client for the shared AR Studio — wraps colyseus.js with a tiny event
+// API so src/ar-studio.js can join a shared room and live-sync placed models
+// without knowing anything about Colyseus. Mirrors src/irl-net.js in shape
+// (status model, single-retry reconnect, no storms) so the two transports read
+// the same.
+//
+// What it does: joins the `studio_world` room for a given roomKey (a shared code,
+// or a QR-marker id when co-located) and relays the shared scene — every model's
+// add / change / remove — plus live presence (who else is in the room). Local
+// edits are sent up via spawn/update/remove; the server owner-gates, caps, and
+// rate-limits, then delta-broadcasts to every peer.
+//
+// Transforms ride in the room's shared LOGICAL frame (relEast / relNorth metres,
+// yawDeg) — see multiplayer/src/studio-schemas.js. Mapping to/from each device's
+// local scene is the caller's job (src/ar/studio-coords.js).
+//
+// Graceful degradation: no server configured, or the socket can't be reached
+// after one retry → a distinct status (`unavailable` / `failed`) and the studio
+// simply stays single-player. Never loops on a dead endpoint.
+
+import { Client, getStateCallbacks } from 'colyseus.js';
+import { StudioState } from '../../multiplayer/src/studio-schemas.js';
+import { joinRoomWithTimeout } from '../shared/colyseus-connect.js';
+import { log } from '../shared/log.js';
+
+const ROOM_NAME = 'studio_world';
+const MAX_RETRIES = 1;
+
+// Resolve the Colyseus host the same way irl-net does — the studio world runs on
+// the SAME server as /walk and /irl (a new room, not a new process).
+function defaultServerUrl() {
+ if (typeof window !== 'undefined') {
+ if (window.STUDIO_SERVER_URL) return String(window.STUDIO_SERVER_URL).trim().replace(/\/$/, '');
+ if (window.IRL_SERVER_URL) return String(window.IRL_SERVER_URL).trim().replace(/\/$/, '');
+ if (window.WALK_SERVER_URL) return String(window.WALK_SERVER_URL).trim().replace(/\/$/, '');
+ }
+ if (typeof document !== 'undefined') {
+ for (const name of ['studio-server', 'irl-server', 'walk-server']) {
+ const v = document.querySelector(`meta[name="${name}"]`)?.getAttribute('content')?.trim();
+ if (v) return v.replace(/\/$/, '');
+ }
+ }
+ try {
+ const envUrl = import.meta?.env?.VITE_IRL_SERVER_URL || import.meta?.env?.VITE_WALK_SERVER_URL;
+ if (envUrl) return String(envUrl).trim().replace(/\/$/, '');
+ } catch (_) {}
+ if (typeof location !== 'undefined') {
+ const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
+ const host = location.hostname;
+ const fwd = host.match(/^(.*)-(\d+)\.(app\.github\.dev|githubpreview\.dev|gitpod\.io)$/);
+ if (fwd) return `${proto}//${fwd[1]}-2567.${fwd[3]}`;
+ let isProd = false;
+ try { isProd = import.meta?.env?.PROD === true; } catch (_) {}
+ const isLocalHost = host === 'localhost' || host === '127.0.0.1';
+ if (!isProd || isLocalHost) return `${proto}//${host}:2567`;
+ return '';
+ }
+ return '';
+}
+
+export class StudioNet {
+ /**
+ * @param {object} opts
+ * @param {string} opts.roomKey Shared match key (code or marker id).
+ * @param {string} [opts.clientId] Stable per-browser id → model ownership.
+ * @param {string} [opts.name] Optional display name for presence.
+ * @param {string} [opts.url] Override server URL (tests).
+ */
+ constructor({ roomKey, clientId = '', name = '', url } = {}) {
+ this.roomKey = String(roomKey || '').slice(0, 64);
+ this.clientId = String(clientId || '').slice(0, 80);
+ this.name = String(name || '').slice(0, 120);
+ this.url = (url ?? defaultServerUrl()) || '';
+ this.status = 'idle';
+ this.error = '';
+ this.room = null;
+ this.client = null;
+ this._listeners = { status: [], models: [], model: [], presence: [], reject: [] };
+ this._retries = 0;
+ this._reconnectTimer = null;
+ this._connectGen = 0;
+ this._destroyed = false;
+ this._presenceQueued = false;
+ }
+
+ on(event, fn) {
+ (this._listeners[event] ||= []).push(fn);
+ return this;
+ }
+
+ _emit(event, payload) {
+ for (const fn of this._listeners[event] || []) {
+ try { fn(payload); } catch (e) { log.warn(`[studio-net] ${event} listener error:`, e?.message || e); }
+ }
+ }
+
+ _setStatus(status, error = '') {
+ this.status = status;
+ this.error = error;
+ this._emit('status', { status, error });
+ }
+
+ _closeRoom() {
+ const room = this.room;
+ if (!room) return;
+ this.room = null;
+ try { room.removeAllListeners(); } catch {}
+ try { room.leave(); } catch {}
+ }
+
+ async connect() {
+ if (this._destroyed) return;
+ this._closeRoom();
+ if (!this.url) { this._setStatus('unavailable'); return; }
+ if (!this.roomKey) { this._setStatus('unavailable'); return; }
+ const gen = ++this._connectGen;
+ this._setStatus('connecting');
+ try {
+ this.client = new Client(this.url);
+ const room = await joinRoomWithTimeout(this.client, ROOM_NAME, {
+ roomKey: this.roomKey,
+ clientId: this.clientId,
+ name: this.name,
+ }, StudioState);
+ if (this._destroyed || gen !== this._connectGen) {
+ try { room.leave(); } catch {}
+ return;
+ }
+ this.room = room;
+ this._retries = 0;
+
+ const $ = getStateCallbacks(this.room);
+
+ // The shared scene: any model add / per-field change / remove re-emits the
+ // full model list so the studio reconciles its local placements against it.
+ // The join handshake fires onAdd once per existing model, so we coalesce
+ // the burst into a single emit next tick.
+ const $models = $(this.room.state)?.models;
+ if ($models) {
+ $models.onAdd((model, id) => {
+ $(model).onChange(() => this._emit('model', this._modelShape(model, id)));
+ this._queueModels();
+ });
+ $models.onRemove((model, id) => {
+ this._emit('model', { id, removed: true });
+ this._queueModels();
+ });
+ }
+
+ const $viewers = $(this.room.state)?.viewers;
+ if ($viewers) {
+ $viewers.onAdd(() => this._queuePresence());
+ $viewers.onRemove(() => this._queuePresence());
+ }
+
+ // A rejected op (room/owner full) — surface it so the UI can explain.
+ this.room.onMessage('model:reject', (msg) => this._emit('reject', msg));
+
+ this.room.onLeave((code) => {
+ if (this._destroyed || code === 1000) return;
+ this._setStatus('offline');
+ this._scheduleReconnect();
+ });
+ this.room.onError((code, message) => log.warn('[studio-net] room.onError', code, message));
+
+ this._setStatus('online');
+ // Emit the initial scene + presence once the handshake burst settles.
+ this._queueModels();
+ this._queuePresence();
+ } catch (err) {
+ const reason = err?.message || (err?.code != null ? `code ${err.code}` : String(err));
+ log.warn('[studio-net] connect failed:', reason);
+ this._setStatus('failed', reason);
+ this._scheduleReconnect();
+ }
+ }
+
+ _scheduleReconnect() {
+ if (this._reconnectTimer || this._destroyed) return;
+ if (this._retries >= MAX_RETRIES) { this._setStatus('unavailable', this.error); return; }
+ this._retries++;
+ const delay = 2500 + Math.random() * 1500;
+ this._reconnectTimer = setTimeout(() => {
+ this._reconnectTimer = null;
+ if (this._destroyed) return;
+ this.connect();
+ }, delay);
+ }
+
+ _modelShape(m, id) {
+ return {
+ id: id ?? m.id,
+ src: m.src,
+ title: m.title,
+ relEast: m.relEast,
+ relNorth: m.relNorth,
+ yawDeg: m.yawDeg,
+ scale: m.scale,
+ height: m.height,
+ ownerId: m.ownerId,
+ mine: !!this.clientId && m.ownerId === this.clientId,
+ };
+ }
+
+ _queueModels() {
+ if (this._modelsQueued || this._destroyed) return;
+ this._modelsQueued = true;
+ Promise.resolve().then(() => {
+ this._modelsQueued = false;
+ if (this._destroyed || !this.room) return;
+ const map = this.room.state?.models;
+ if (!map) return;
+ const models = [];
+ map.forEach((m, id) => models.push(this._modelShape(m, id)));
+ this._emit('models', models);
+ });
+ }
+
+ _queuePresence() {
+ if (this._presenceQueued || this._destroyed) return;
+ this._presenceQueued = true;
+ Promise.resolve().then(() => {
+ this._presenceQueued = false;
+ if (this._destroyed || !this.room) return;
+ const map = this.room.state?.viewers;
+ if (!map) return;
+ let count = 0;
+ const names = [];
+ map.forEach((v) => { count++; if (v.name) names.push(v.name); });
+ this._emit('presence', { count, names });
+ });
+ }
+
+ _live() {
+ return this.status === 'online' && this.room && this.room.connection?.isOpen === true;
+ }
+
+ /** Add a model to the shared scene. `model` is in the shared logical frame. */
+ spawn(model) {
+ if (!this._live()) return false;
+ try {
+ this.room.send('model:spawn', {
+ id: model.id,
+ src: String(model.src || ''),
+ title: String(model.title || '').slice(0, 120),
+ relEast: Number(model.relEast) || 0,
+ relNorth: Number(model.relNorth) || 0,
+ yawDeg: Number(model.yawDeg) || 0,
+ scale: Number(model.scale) || 1,
+ height: Number(model.height) || 0,
+ });
+ return true;
+ } catch (e) {
+ log.warn('[studio-net] spawn failed:', e?.message || e);
+ return false;
+ }
+ }
+
+ /** Move / resize / rotate a model you own. Partial patch. */
+ update(id, patch) {
+ if (!this._live() || !id) return false;
+ const msg = { id: String(id) };
+ for (const k of ['relEast', 'relNorth', 'yawDeg', 'scale']) {
+ if (Number.isFinite(patch?.[k])) msg[k] = patch[k];
+ }
+ try { this.room.send('model:update', msg); return true; } catch (e) {
+ log.warn('[studio-net] update failed:', e?.message || e);
+ return false;
+ }
+ }
+
+ /** Remove a model you own. */
+ remove(id) {
+ if (!this._live() || !id) return false;
+ try { this.room.send('model:remove', { id: String(id) }); return true; } catch (e) {
+ log.warn('[studio-net] remove failed:', e?.message || e);
+ return false;
+ }
+ }
+
+ heartbeat() {
+ if (!this._live()) return;
+ try { this.room.send('heartbeat', {}); } catch (e) { log.warn('[studio-net] heartbeat failed:', e?.message || e); }
+ }
+
+ destroy() {
+ this._destroyed = true;
+ if (this._reconnectTimer) { clearTimeout(this._reconnectTimer); this._reconnectTimer = null; }
+ this._closeRoom();
+ try { this.client = null; } catch {}
+ this._setStatus('destroyed');
+ }
+}
diff --git a/tests/ar-studio-coords.test.js b/tests/ar-studio-coords.test.js
new file mode 100644
index 000000000..291f03f09
--- /dev/null
+++ b/tests/ar-studio-coords.test.js
@@ -0,0 +1,99 @@
+// Shared-studio coordinate + room-key helpers (src/ar/studio-coords.js).
+//
+// The contract: local scene transforms and shared logical transforms round-trip
+// exactly (so a model placed on one phone lands at the matching spot on another),
+// angles normalize without NaN leaks, and room codes are unambiguous, URL-safe,
+// and strictly validated (a mistyped code is rejected, never silently accepted).
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ generateRoomCode,
+ localToShared,
+ normalizeRoomCode,
+ normDeg,
+ normRad,
+ roomKeyForCode,
+ roomShareUrl,
+ sharedToLocal,
+} from '../src/ar/studio-coords.js';
+
+describe('angle normalization', () => {
+ it('wraps radians into [0, 2π) and degrees into [0, 360)', () => {
+ expect(normRad(-Math.PI / 2)).toBeCloseTo(1.5 * Math.PI, 9);
+ expect(normRad(3 * Math.PI)).toBeCloseTo(Math.PI, 9);
+ expect(normDeg(-90)).toBe(270);
+ expect(normDeg(450)).toBe(90);
+ });
+ it('collapses non-finite input to 0', () => {
+ expect(normRad(NaN)).toBe(0);
+ expect(normDeg(Infinity)).toBe(0);
+ });
+});
+
+describe('local <-> shared frame round trip', () => {
+ it('maps forward (-z) to north and right (+x) to east', () => {
+ const s = localToShared({ x: 2, z: -3, yaw: 0, scale: 1 });
+ expect(s.relEast).toBe(2);
+ expect(s.relNorth).toBe(3); // -z forward → +north
+ });
+
+ it('round-trips a placement exactly (position, yaw, scale)', () => {
+ const local = { x: 1.5, z: -2.25, yaw: Math.PI / 3, scale: 1.4, height: 1.7 };
+ const back = sharedToLocal(localToShared(local));
+ expect(back.x).toBeCloseTo(local.x, 6);
+ expect(back.z).toBeCloseTo(local.z, 6);
+ expect(back.yaw).toBeCloseTo(local.yaw, 6);
+ expect(back.scale).toBeCloseTo(local.scale, 6);
+ });
+
+ it('round-trips a yaw near the wrap boundary without spinning', () => {
+ const local = { x: 0, z: 0, yaw: normRad(-0.05), scale: 1 };
+ const back = sharedToLocal(localToShared(local));
+ expect(Math.cos(back.yaw)).toBeCloseTo(Math.cos(local.yaw), 6);
+ expect(Math.sin(back.yaw)).toBeCloseTo(Math.sin(local.yaw), 6);
+ });
+
+ it('degrades garbage transforms to a valid origin placement', () => {
+ const s = localToShared({ x: NaN, z: undefined, yaw: NaN, scale: 0 });
+ expect(s).toEqual({ relEast: 0, relNorth: 0, yawDeg: 0, scale: 1, height: 0 });
+ });
+});
+
+describe('room codes', () => {
+ it('generates a 6-char code from the unambiguous alphabet', () => {
+ const seq = [0.01, 0.2, 0.4, 0.6, 0.8, 0.99];
+ let i = 0;
+ const code = generateRoomCode(() => seq[i++ % seq.length]);
+ expect(code).toHaveLength(6);
+ expect(code).toMatch(/^[A-HJ-NP-Z2-9]+$/); // no O/I/L/0/1
+ });
+
+ it('normalizes a bare code, ignoring case, spaces, and hyphens', () => {
+ const raw = generateRoomCode(() => 0.5);
+ expect(normalizeRoomCode(` ${raw.toLowerCase()} `)).toBe(raw);
+ expect(normalizeRoomCode(`${raw.slice(0, 3)}-${raw.slice(3)}`)).toBe(raw);
+ });
+
+ it('extracts the code from a pasted share URL', () => {
+ const code = generateRoomCode(() => 0.3);
+ expect(normalizeRoomCode(`https://three.ws/ar/studio?room=${code}&x=1`)).toBe(code);
+ });
+
+ it('rejects wrong length or ambiguous/foreign characters', () => {
+ expect(normalizeRoomCode('ABC')).toBe(''); // too short
+ expect(normalizeRoomCode('ABCDEFG')).toBe(''); // too long
+ expect(normalizeRoomCode('ABCDE0')).toBe(''); // contains 0
+ expect(normalizeRoomCode('ABCDEI')).toBe(''); // contains I
+ expect(normalizeRoomCode('!!!!!!')).toBe('');
+ expect(normalizeRoomCode('')).toBe('');
+ expect(normalizeRoomCode(null)).toBe('');
+ });
+
+ it('derives a stable filterBy key and a valid share URL', () => {
+ const code = generateRoomCode(() => 0.42);
+ expect(roomKeyForCode(code)).toBe(`c-${code}`);
+ expect(roomShareUrl('https://three.ws', code)).toBe(`https://three.ws/ar/studio?room=${code}`);
+ expect(roomShareUrl('https://three.ws', 'bad')).toBe('https://three.ws/ar/studio');
+ });
+});
diff --git a/tests/studio-room.test.js b/tests/studio-room.test.js
new file mode 100644
index 000000000..7c464ecf2
--- /dev/null
+++ b/tests/studio-room.test.js
@@ -0,0 +1,149 @@
+// StudioRoom server-authoritative invariants (multiplayer/src/rooms/StudioRoom.js).
+//
+// The full room needs the Colyseus runtime, so — mirroring walkroom-worldobjects
+// — these drive the message handlers directly against a minimal stand-in
+// (Object.create avoids the Room constructor). They lock what a malicious or
+// buggy client must NOT be able to do over the shared-scene socket: spawn an
+// unvetted (non-https) GLB url, move/remove a model it doesn't own, exceed the
+// per-room or per-owner caps, flood past the rate limit, or slip a NaN/out-of-
+// bounds transform through.
+
+import { beforeEach, describe, expect, it } from 'vitest';
+import { StudioRoom } from '../multiplayer/src/rooms/StudioRoom.js';
+
+function makeRoom() {
+ const room = Object.create(StudioRoom.prototype);
+ room.roomKey = 'c-ABCDEF';
+ room._modelSeq = 0;
+ room._opLedger = new Map();
+ const models = new Map();
+ const viewers = new Map();
+ room.state = { models, viewers, roomKey: room.roomKey };
+ // The reject channel: record what the server tells a client.
+ room._rejects = [];
+ return room;
+}
+
+// A fake client whose send() records reject reasons.
+function makeClient(room, { sessionId = 's_alice', ownerId = 'alice' } = {}) {
+ return {
+ sessionId,
+ userData: { ownerId },
+ send: (type, payload) => room._rejects.push({ type, payload, sessionId }),
+ };
+}
+
+// Register a viewer so spawn's "must be in the room" gate passes.
+function join(room, client) {
+ room.state.viewers.set(client.sessionId, { id: client.sessionId, ownerId: client.userData.ownerId, tsServer: Date.now() });
+}
+
+const HTTPS = 'https://cdn.three.ws/model.glb';
+
+describe('StudioRoom — model:spawn', () => {
+ let room, alice;
+ beforeEach(() => { room = makeRoom(); alice = makeClient(room); join(room, alice); });
+
+ it('accepts a valid https GLB and assigns a server-controlled id + owner', () => {
+ room._handleSpawn(alice, { src: HTTPS, relEast: 1, relNorth: 2, yawDeg: 90, scale: 1.5, title: 'crate' });
+ expect(room.state.models.size).toBe(1);
+ const m = [...room.state.models.values()][0];
+ expect(m.src).toBe(HTTPS);
+ expect(m.ownerId).toBe('alice'); // stable owner key, not sessionId
+ expect(m.relEast).toBe(1);
+ expect(m.scale).toBe(1.5);
+ });
+
+ it('accepts a site-relative GLB path', () => {
+ room._handleSpawn(alice, { src: '/avatars/default.glb', relEast: 0, relNorth: 0 });
+ expect(room.state.models.size).toBe(1);
+ });
+
+ it('never re-broadcasts an unvetted url (http/data/js/protocol-relative)', () => {
+ for (const bad of ['http://x.co/a.glb', 'data:model/gltf-binary;base64,AAAA', 'javascript:alert(1)', '//x.co/a.glb', 'ftp://x/a.glb']) {
+ room._handleSpawn(alice, { src: bad, relEast: 0, relNorth: 0 });
+ }
+ expect(room.state.models.size).toBe(0);
+ });
+
+ it('drops a spawn with a non-finite position (a NaN slips past clamps)', () => {
+ room._handleSpawn(alice, { src: HTTPS, relEast: NaN, relNorth: 0 });
+ room._handleSpawn(alice, { src: HTTPS, relEast: 0, relNorth: undefined });
+ expect(room.state.models.size).toBe(0);
+ });
+
+ it('clamps position to bounds and scale to [0.25, 4]', () => {
+ room._handleSpawn(alice, { src: HTTPS, relEast: 999, relNorth: -999, scale: 50 });
+ const m = [...room.state.models.values()][0];
+ expect(m.relEast).toBe(60);
+ expect(m.relNorth).toBe(-60);
+ expect(m.scale).toBe(4);
+ });
+
+ it('ignores a spawn from a client that has not joined', () => {
+ const ghost = makeClient(room, { sessionId: 's_ghost', ownerId: 'ghost' });
+ room._handleSpawn(ghost, { src: HTTPS, relEast: 0, relNorth: 0 });
+ expect(room.state.models.size).toBe(0);
+ });
+
+ it('rejects when the owner is at their per-owner cap', () => {
+ for (let i = 0; i < 24; i++) room._handleSpawn(alice, { src: HTTPS, relEast: 0, relNorth: 0 });
+ expect(room.state.models.size).toBe(24);
+ room._handleSpawn(alice, { src: HTTPS, relEast: 0, relNorth: 0 });
+ expect(room.state.models.size).toBe(24);
+ expect(room._rejects.some((r) => r.payload?.reason === 'owner_full')).toBe(true);
+ });
+});
+
+describe('StudioRoom — ownership gating', () => {
+ let room, alice, bob;
+ beforeEach(() => {
+ room = makeRoom();
+ alice = makeClient(room, { sessionId: 's_a', ownerId: 'alice' });
+ bob = makeClient(room, { sessionId: 's_b', ownerId: 'bob' });
+ join(room, alice); join(room, bob);
+ room._handleSpawn(alice, { src: HTTPS, relEast: 0, relNorth: 0, id: 'M1' });
+ });
+
+ it('lets the owner move their model', () => {
+ room._handleUpdate(alice, { id: 'M1', relEast: 5 });
+ expect(room.state.models.get('M1').relEast).toBe(5);
+ });
+
+ it('refuses a non-owner move', () => {
+ room._handleUpdate(bob, { id: 'M1', relEast: 5 });
+ expect(room.state.models.get('M1').relEast).toBe(0);
+ });
+
+ it('refuses a non-owner remove, allows the owner', () => {
+ room._handleRemove(bob, { id: 'M1' });
+ expect(room.state.models.has('M1')).toBe(true);
+ room._handleRemove(alice, { id: 'M1' });
+ expect(room.state.models.has('M1')).toBe(false);
+ });
+});
+
+describe('StudioRoom — rate limiting', () => {
+ it('allows 25 ops per session per second, then drops', () => {
+ const room = makeRoom();
+ let ok = 0;
+ for (let i = 0; i < 40; i++) if (room._opOk('s_a')) ok++;
+ expect(ok).toBe(25);
+ });
+
+ it('gives each session its own independent budget', () => {
+ const room = makeRoom();
+ for (let i = 0; i < 25; i++) room._opOk('s_a'); // exhaust alice
+ expect(room._opOk('s_a')).toBe(false);
+ expect(room._opOk('s_b')).toBe(true); // bob unaffected
+ });
+
+ it('blocks a flooding spawn past the budget without touching state', () => {
+ const room = makeRoom();
+ const alice = makeClient(room);
+ join(room, alice);
+ for (let i = 0; i < 25; i++) room._opOk(alice.sessionId); // spend the budget
+ room._handleSpawn(alice, { src: HTTPS, relEast: 0, relNorth: 0 });
+ expect(room.state.models.size).toBe(0); // rate-limited before any write
+ });
+});