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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: AR freezes follow-cam so the avatar walks in world space
nirholasc0c8637d6344
diff --git a/image-to-3d-pipeline/gaussian-splatting-pipeline.ipynb b/image-to-3d-pipeline/gaussian-splatting-pipeline.ipynbnew file mode 100644index 000000000..12d6d1ea5--- /dev/null+++ b/image-to-3d-pipeline/gaussian-splatting-pipeline.ipynb@@ -0,0 +1,122 @@+{+ "cells": [+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "532bfed2",+ "metadata": {},+ "outputs": [],+ "source": []+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "7dd58ef4",+ "metadata": {},+ "outputs": [],+ "source": []+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "4cc7e9d5",+ "metadata": {},+ "outputs": [],+ "source": []+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "8e622545",+ "metadata": {},+ "outputs": [],+ "source": [+ "import vertexai\n",+ "from vertexai.preview.vision_models import ImageGenerationModel\n",+ "import os\n",+ "\n",+ "# --- Configuration ---\n",+ "GCP_PROJECT_ID = \"aerial-vehicle-466722-p5\" # @param {type:\"string\"}\n",+ "GCP_REGION = \"us-central1\" # @param {type:\"string\"}\n",+ "\n",+ "# Initialize Vertex AI\n",+ "vertexai.init(project=GCP_PROJECT_ID, location=GCP_REGION)\n",+ "\n",+ "model = ImageGenerationModel.from_pretrained(\"imagegeneration@006\")\n",+ "\n",+ "# Create a directory to store the generated images\n",+ "output_dir = 'source_images'\n",+ "os.makedirs(output_dir, exist_ok=True)\n",+ "\n",+ "# Define the base prompt for image generation\n",+ "prompt_template = \"A photograph of the meme beach cookout at sunset, Pepe and Wojak characters grilling, volleyball game, POZ towels, no work allowed sign, keep exact style and lighting consistent. Camera angle: {angle}.\"\n",+ "\n",+ "# List of camera angles to generate\n",+ "camera_angles = [\n",+ " \"eye-level, centered\",\n",+ " \"from a low angle, looking up\",\n",+ " \"from a high angle, looking down\",\n",+ " \"from the left side\",\n",+ " \"from the right side\",\n",+ " \"close-up on the grill\",\n",+ " \"wide shot of the whole scene\",\n",+ " \"from behind the volleyball net\"\n",+ "]\n",+ "\n",+ "print(f\"Generating {len(camera_angles)} images...\")\n",+ "\n",+ "# Generate an image for each camera angle\n",+ "for i, angle in enumerate(camera_angles):\n",+ " prompt = prompt_template.format(angle=angle)\n",+ " response = model.generate_images(\n",+ " prompt=prompt,\n",+ " number_of_images=1,\n",+ " )\n",+ " image = response.images[0]\n",+ " image.save(f\"{output_dir}/view_{i+1:03d}.png\")\n",+ " print(f\"Saved view_{i+1:03d}.png\")\n",+ "\n",+ "print(\"Image generation complete.\")"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "8c4bdb35",+ "metadata": {},+ "outputs": [],+ "source": []+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "b95671a8",+ "metadata": {},+ "outputs": [],+ "source": []+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "d96a278c",+ "metadata": {},+ "outputs": [],+ "source": []+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "76967bc6",+ "metadata": {},+ "outputs": [],+ "source": []+ }+ ],+ "metadata": {+ "language_info": {+ "name": "python"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 5+}diff --git a/scripts/repro-blank.mjs b/scripts/repro-blank.mjsnew file mode 100644index 000000000..b5d0bb4c5--- /dev/null+++ b/scripts/repro-blank.mjs@@ -0,0 +1,33 @@+import { chromium } from 'playwright';++const URL = 'http://localhost:5500/aframe-mesh.html';+const browser = await chromium.launch();+const page = await browser.newContext({ viewport: { width: 1280, height: 800 } }).then(c => c.newPage());+await page.goto(URL, { waitUntil: 'networkidle' });+await page.waitForFunction(() => document.querySelector('a-scene')?.hasLoaded);+await page.waitForTimeout(1000);++const positions = [+ ['far', '0 0 4'],+ ['midway', '0 0 -2'],+ ['at-surface', '0 0 -5'],+ ['just-inside', '0 0 -6.5'],+ ['deep-inside', '0 0 -10'],+ ['out-back', '0 0 -16'],+];+for (const [name, pos] of positions) {+ await page.evaluate((p) => document.querySelector('#rig').setAttribute('position', p), pos);+ await page.waitForTimeout(300);+ // Sample a center-pixel color to detect "blank"+ const px = await page.evaluate(() => {+ const c = document.querySelector('a-scene').canvas;+ const ctx = c.getContext('webgl2') || c.getContext('webgl');+ const buf = new Uint8Array(4);+ ctx.readPixels(c.width / 2, c.height / 2, 1, 1, ctx.RGBA, ctx.UNSIGNED_BYTE, buf);+ return [...buf];+ });+ await page.screenshot({ path: `scripts/blank-${name}.png` });+ console.log(`${name.padEnd(12)} rig=${pos.padEnd(8)} center pixel rgba=${JSON.stringify(px)}`);+}++await browser.close();diff --git a/scripts/verify-aframe-mesh-final.mjs b/scripts/verify-aframe-mesh-final.mjsnew file mode 100644index 000000000..3e601e58a--- /dev/null+++ b/scripts/verify-aframe-mesh-final.mjs@@ -0,0 +1,56 @@+import { chromium } from 'playwright';++const URL = 'http://localhost:5500/aframe-mesh.html';+const browser = await chromium.launch();+const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 } });+const page = await ctx.newPage();+const errors = [];+page.on('pageerror', (e) => errors.push('pageerror: ' + e.message));+page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); });++await page.goto(URL, { waitUntil: 'networkidle' });+await page.waitForFunction(() => document.querySelector('a-scene')?.hasLoaded);+await page.waitForTimeout(1500);++// Initial spawn — prompt should be visible+await page.screenshot({ path: 'scripts/final-spawn.png' });+const promptVisible = await page.evaluate(() => {+ const p = document.getElementById('prompt');+ return p && !p.classList.contains('hidden') && getComputedStyle(p).opacity !== '0';+});+console.log('prompt visible on load:', promptVisible);++// Mouse micro-parallax: move cursor to the far-right, then far-left, screenshot+await page.mouse.move(1200, 400);+await page.waitForTimeout(400);+await page.screenshot({ path: 'scripts/final-mouse-right.png' });+await page.mouse.move(80, 400);+await page.waitForTimeout(400);+await page.screenshot({ path: 'scripts/final-mouse-left.png' });++// Walk + look around+await page.evaluate(() => {+ document.querySelector('#rig').setAttribute('position', '0 0 -3');+ document.querySelector('a-camera').setAttribute('rotation', '-5 -15 0');+});+await page.waitForTimeout(400);+await page.screenshot({ path: 'scripts/final-walked.png' });++// Strafe to test parallax + backdrop inpaint pass+await page.evaluate(() => {+ document.querySelector('#rig').setAttribute('position', '3.5 0 0');+ document.querySelector('a-camera').setAttribute('rotation', '0 -25 0');+});+await page.waitForTimeout(400);+await page.screenshot({ path: 'scripts/final-strafe.png' });++// Backdrop visibility check — confirm both depth-mesh entities loaded+const meshCount = await page.evaluate(() => {+ return document.querySelectorAll('[depth-mesh]').length;+});+console.log('depth-mesh entities:', meshCount);++console.log('errors:', errors.length);+errors.forEach((e) => console.log(' !', e));+await browser.close();+process.exit(errors.length ? 1 : 0);diff --git a/scripts/verify-aframe-mesh.mjs b/scripts/verify-aframe-mesh.mjsnew file mode 100644index 000000000..ef2525687--- /dev/null+++ b/scripts/verify-aframe-mesh.mjs@@ -0,0 +1,43 @@+import { chromium } from 'playwright';++const URL = 'http://localhost:5500/aframe-mesh.html';+const browser = await chromium.launch();+const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 } });+const page = await ctx.newPage();+const errors = [];+page.on('pageerror', (e) => errors.push('pageerror: ' + e.message));+page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); });++await page.goto(URL, { waitUntil: 'networkidle' });+await page.waitForFunction(() => document.querySelector('a-scene')?.hasLoaded);+await page.waitForTimeout(1500);++await page.screenshot({ path: 'scripts/mesh-spawn.png' });++// strafe right+await page.evaluate(() => {+ document.querySelector('#rig').setAttribute('position', '3 0 2');+});+await page.waitForTimeout(400);+await page.screenshot({ path: 'scripts/mesh-strafe.png' });++// walk forward into the scene+await page.evaluate(() => {+ document.querySelector('#rig').setAttribute('position', '0 0 -3');+});+await page.waitForTimeout(400);+await page.screenshot({ path: 'scripts/mesh-walk.png' });++// crouch / look from low angle+await page.evaluate(() => {+ document.querySelector('#rig').setAttribute('position', '-2 0 -2');+ const cam = document.querySelector('a-camera');+ cam.setAttribute('rotation', '-10 30 0');+});+await page.waitForTimeout(400);+await page.screenshot({ path: 'scripts/mesh-angle.png' });++console.log('errors:', errors.length);+errors.forEach((e) => console.log(' !', e));+await browser.close();+process.exit(errors.length ? 1 : 0);diff --git a/scripts/verify-aframe-parallax.mjs b/scripts/verify-aframe-parallax.mjsnew file mode 100644index 000000000..72f47315e--- /dev/null+++ b/scripts/verify-aframe-parallax.mjs@@ -0,0 +1,37 @@+import { chromium } from 'playwright';++const URL = 'http://localhost:5500/aframe.html';+const browser = await chromium.launch();+const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 } });+const page = await ctx.newPage();+const errors = [];+page.on('pageerror', (e) => errors.push('pageerror: ' + e.message));+page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); });++await page.goto(URL, { waitUntil: 'networkidle' });+await page.waitForFunction(() => document.querySelector('a-scene')?.hasLoaded);+await page.waitForTimeout(1000);++// Frame 1: at origin+await page.screenshot({ path: 'scripts/aframe-origin.png' });++// Step the rig to the right and forward and re-shoot.+await page.evaluate(() => {+ const rig = document.querySelector('#rig');+ rig.setAttribute('position', '2.5 0 -1.5');+});+await page.waitForTimeout(400);+await page.screenshot({ path: 'scripts/aframe-strafe.png' });++// Forward into the scene.+await page.evaluate(() => {+ const rig = document.querySelector('#rig');+ rig.setAttribute('position', '0 0 -4');+});+await page.waitForTimeout(400);+await page.screenshot({ path: 'scripts/aframe-walked.png' });++console.log('shots written. errors:', errors.length);+errors.forEach((e) => console.log(' !', e));+await browser.close();+process.exit(errors.length ? 1 : 0);diff --git a/scripts/verify-aframe.mjs b/scripts/verify-aframe.mjsnew file mode 100644index 000000000..1b6f9d9b1--- /dev/null+++ b/scripts/verify-aframe.mjs@@ -0,0 +1,48 @@+import { chromium } from 'playwright';++const URL = process.argv[2] || 'http://localhost:5500/aframe.html';+const browser = await chromium.launch();+const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 } });+const page = await ctx.newPage();++const errors = [];+const warnings = [];+page.on('console', (m) => {+ const t = m.type();+ const txt = m.text();+ if (t === 'error') errors.push(txt);+ else if (t === 'warning') warnings.push(txt);+});+page.on('pageerror', (e) => errors.push('pageerror: ' + e.message));++await page.goto(URL, { waitUntil: 'networkidle', timeout: 30000 });+// Let A-Frame finish loading assets + first paint+await page.waitForFunction(() => {+ const s = document.querySelector('a-scene');+ return s && s.hasLoaded;+}, { timeout: 30000 });+await page.waitForTimeout(1500);++const scene = await page.evaluate(() => {+ const s = document.querySelector('a-scene');+ const imgs = [...document.querySelectorAll('a-image')].map((el) => ({+ src: el.getAttribute('src'),+ pos: el.getAttribute('position'),+ width: el.getAttribute('width'),+ visible: !!el.getObject3D('mesh'),+ }));+ return { hasLoaded: s.hasLoaded, imgs };+});+console.log('scene.hasLoaded =', scene.hasLoaded);+console.log('a-images:');+for (const i of scene.imgs) console.log(' ', i);++await page.screenshot({ path: 'scripts/aframe-shot.png', fullPage: false });+console.log('\nscreenshot: scripts/aframe-shot.png');+console.log('errors:', errors.length);+errors.forEach((e) => console.log(' !', e));+console.log('warnings:', warnings.length);+warnings.slice(0, 5).forEach((w) => console.log(' ?', w.slice(0, 200)));++await browser.close();+process.exit(errors.length > 0 ? 1 : 0);diff --git a/src/walk.js b/src/walk.jsindex cf514497f..d950d41a1 100644--- a/src/walk.js+++ b/src/walk.js@@ -191,6 +191,12 @@ const camLookCurrent = new Vector3();let cameraYaw = 0; // user-controlled orbit yaw around avatar (radians)let cameraPitch = 0.05; // small downward tilt by default+// In AR mode the camera is frozen in world space instead of following the+// avatar — the joystick then walks the avatar around physically and natural+// perspective makes it grow/shrink as it approaches/recedes. Captured when+// AR is enabled, cleared when AR is disabled.+let arFrozenCamPos = null;+let arFrozenCamLook = null;const PITCH_MIN = -0.6;const PITCH_MAX = 0.7;@@ -557,7 +563,14 @@ async function enableAR() {// Show blob contact shadow.blobShadow.material.opacity = 1;- setStatus('AR on — point at a floor');+ // Freeze the camera at its current pose so the avatar walks around in+ // world space instead of being chased by a follow cam. With the camera+ // fixed, joystick-forward = avatar walks away (gets smaller), joystick-+ // back = avatar walks toward you (gets bigger).+ arFrozenCamPos = camera.position.clone();+ arFrozenCamLook = camLookCurrent.clone();++ setStatus('AR on — joystick walks your agent');}function disableAR() {@@ -586,6 +599,10 @@ function disableAR() {// Hide blob shadow.blobShadow.material.opacity = 0;+ // Resume follow-camera behavior.+ arFrozenCamPos = null;+ arFrozenCamLook = null;+setStatus('AR off');}@@ -915,16 +932,22 @@ function tick() {avatarLean += (targetLean - avatarLean) * LEAN_LERP;if (avatar) avatar.rotation.x = avatarLean;- // 2. Update camera follow-rig.- const offset = CAM_OFFSET.clone().multiplyScalar(camZoom);- offset.applyAxisAngle(new Vector3(1, 0, 0), -cameraPitch);- offset.applyAxisAngle(upY, cameraYaw);- camDesired.copy(avatarRig.position).add(offset);- camera.position.lerp(camDesired, CAM_LERP);-- camLookTarget.copy(avatarRig.position).add(CAM_LOOK_OFFSET);- camLookCurrent.lerp(camLookTarget, CAM_LERP);- camera.lookAt(camLookCurrent);+ // 2. Update camera — frozen in AR, follow-rig otherwise.+ if (arFrozenCamPos && arFrozenCamLook) {+ camera.position.copy(arFrozenCamPos);+ camLookCurrent.copy(arFrozenCamLook);+ camera.lookAt(camLookCurrent);+ } else {+ const offset = CAM_OFFSET.clone().multiplyScalar(camZoom);+ offset.applyAxisAngle(new Vector3(1, 0, 0), -cameraPitch);+ offset.applyAxisAngle(upY, cameraYaw);+ camDesired.copy(avatarRig.position).add(offset);+ camera.position.lerp(camDesired, CAM_LERP);++ camLookTarget.copy(avatarRig.position).add(CAM_LOOK_OFFSET);+ camLookCurrent.lerp(camLookTarget, CAM_LERP);+ camera.lookAt(camLookCurrent);+ }// AR depth: track sun + blob shadow to the avatar each frame so the// grounding shadow always lands under the feet, and estimate real-worlddiff --git a/test/aframe-mesh.html b/test/aframe-mesh.htmlnew file mode 100644index 000000000..16a2f73f9--- /dev/null+++ b/test/aframe-mesh.html@@ -0,0 +1,426 @@+<!DOCTYPE html>+<html lang="en">+ <head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Beach Meme — Depth Mesh (true 3D)</title>+ <script src="https://aframe.io/releases/1.5.0/aframe.min.js"></script>+ <style>+ body { margin: 0; background: #000; }+ #hud {+ position: fixed; left: 12px; top: 12px; z-index: 10;+ font: 12px/1.4 -apple-system, system-ui, sans-serif;+ color: #fff; background: rgba(0,0,0,0.45);+ padding: 8px 10px; border-radius: 6px; pointer-events: none;+ max-width: 360px;+ }+ #hud b { color: #ffb968; }+ #hud .sub { color:#bbb; font-size:11px; }+ #prompt {+ position: fixed; inset: 0; display: flex; align-items: center;+ justify-content: center; pointer-events: none; z-index: 20;+ font: 600 28px/1.4 -apple-system, system-ui, sans-serif;+ color: rgba(255,255,255,0.95);+ text-shadow: 0 2px 14px rgba(0,0,0,0.55);+ animation: bob 2.6s ease-in-out infinite;+ transition: opacity 0.5s ease;+ }+ #prompt span {+ background: rgba(0,0,0,0.35); padding: 14px 22px; border-radius: 10px;+ backdrop-filter: blur(4px);+ }+ #prompt.hidden { opacity: 0; }+ @keyframes bob {+ 0%, 100% { transform: translateY(0); }+ 50% { transform: translateY(-6px); }+ }+ </style>+ </head>+ <body>+ <div id="hud">+ <b>WASD</b> walk <b>mouse</b> look <b>click</b> capture pointer+ <b>Q / E</b> bend ± <b>M</b> mute<br>+ <span class="sub">depth-map drives real 3D geometry. VR button → Quest / Vision Pro / Cardboard.</span>+ </div>+ <div id="prompt"><span>Click to walk in</span></div>++ <a-scene background="color: #ff7e3a"+ renderer="colorManagement: true"+ fog="type: linear; near: 10; far: 22; color: #ff7e3a">++ <a-assets>+ <img id="photo" src="image.jpg" crossorigin="anonymous">+ <!-- depth_hd.png is the 16-bit pf_disparity.png normalized to 8-bit+ over its full dynamic range — ~256 distinct depth levels actually+ in use, vs ~50 useful levels in the JPEG depth.jpg -->+ <img id="depth" src="depth_hd.png" crossorigin="anonymous">+ <!-- characters removed and replaced with cv2.inpaint extrapolated+ sky/sand — shown through the edge-discard holes of the main mesh+ so silhouettes show real backdrop instead of bare sunset colour -->+ <img id="backdrop" src="image_inpainted.jpg" crossorigin="anonymous">+ </a-assets>++ <!-- Sunset-tinted sky so the mesh boundary blends rather than going to black.+ Same colour as the fog so distant mesh fades into the sky seamlessly. -->+ <a-sky color="#ff7e3a"></a-sky>++ <!-- BACKDROP PASS: inpainted photo on identical depth geometry, sat just+ behind the foreground. edgeStretch huge so nothing discards;+ borderFade tiny so the photo stays opaque all the way to the+ rectangle edge — that way the foreground's border fade reveals real+ inpainted photo content, not the bare sunset sky colour. -->+ <a-entity+ depth-mesh="image: #backdrop; depth: #depth; width: 16; height: 12;+ displacement: 8; segments: 220; edgeStretch: 999;+ borderFade: 0.005"+ position="0 1.6 -6.06">+ </a-entity>++ <!-- FOREGROUND PASS: original photo with UV-space edge-discard.+ edgeFeather gives anti-aliased silhouettes (smooth alpha falloff+ below the discard threshold). shimmer animates the ocean band UV+ so the sun reflection on the water breathes. -->+ <a-entity+ depth-mesh="image: #photo; depth: #depth; width: 16; height: 12;+ displacement: 8; segments: 220;+ edgeStretch: 0.08; edgeFeather: 0.025;+ borderFade: 0.06; shimmer: 1.0"+ position="0 1.6 -6">+ </a-entity>++ <!-- Player rig:+ #rig — WASD walks (wasd-controls owns its position)+ #parallaxWrap — mouse-driven micro-parallax offset (pre-lock only)+ <a-camera> — look-controls owns rotation; eye height 1.6 m+ <a-cursor> — pulses while you're hovering, idle hint -->+ <a-entity id="rig" position="0 0 2"+ wasd-controls="acceleration: 25"+ walk-bounds="minX: -6; maxX: 6; minZ: -3.5; maxZ: 8">+ <a-entity id="parallaxWrap" position="0 0 0">+ <a-camera position="0 1.6 0" look-controls="pointerLockEnabled: true">+ <a-cursor color="#ffb968" raycaster="far: 25"+ animation__pulse="property: scale; from: 0.9 0.9 0.9; to: 1.18 1.18 1.18; dir: alternate; loop: true; dur: 1500; easing: easeInOutSine">+ </a-cursor>+ </a-camera>+ </a-entity>+ </a-entity>++ </a-scene>++ <script>+ /**+ * depth-mesh component+ * Builds a tessellated PlaneGeometry textured with `image` and displaces+ * each vertex along -Z proportional to the depth-map brightness.+ * depth.jpg convention: bright = near, dark = far.+ * Vertex displacement happens in the vertex shader so we don't have to+ * rebuild geometry on parameter changes.+ */+ AFRAME.registerComponent('depth-mesh', {+ schema: {+ image: { type: 'selector' },+ depth: { type: 'selector' },+ width: { type: 'number', default: 16 },+ height: { type: 'number', default: 12 },+ displacement: { type: 'number', default: 6 },+ segments: { type: 'number', default: 200 },+ edgeStretch: { type: 'number', default: 0.08 },+ edgeFeather: { type: 'number', default: 0.025 }, // alpha-falloff band+ borderFade: { type: 'number', default: 0.06 }, // rectangle-edge fade fraction+ shimmer: { type: 'number', default: 0.0 } // 0 = none, >0 = ocean wobble strength+ },++ init() {+ const d = this.data;+ const loader = new THREE.TextureLoader();++ const imageTex = loader.load(d.image.src);+ imageTex.colorSpace = THREE.SRGBColorSpace;+ imageTex.minFilter = THREE.LinearFilter;+ imageTex.magFilter = THREE.LinearFilter;++ const depthTex = loader.load(d.depth.src);+ depthTex.colorSpace = THREE.NoColorSpace;+ depthTex.minFilter = THREE.LinearFilter;+ depthTex.magFilter = THREE.LinearFilter;++ const wSegs = d.segments;+ const hSegs = Math.max(8, Math.floor(d.segments * d.height / d.width));+ const geometry = new THREE.PlaneGeometry(d.width, d.height, wSegs, hSegs);++ // Extend MeshBasicMaterial so three.js handles colour management+ // and fog automatically; we just inject vertex displacement and+ // a fragment-stage discard for stretched edges.+ const material = new THREE.MeshBasicMaterial({+ map: imageTex,+ side: THREE.DoubleSide,+ transparent: true,+ fog: true+ });+ this._uDisplacement = { value: d.displacement };+ this._uEdgeStretch = { value: d.edgeStretch };+ this._uEdgeFeather = { value: d.edgeFeather };+ this._uBorderFade = { value: d.borderFade };+ this._uTime = { value: 0 };+ this._uShimmer = { value: d.shimmer };+ // Depth-texel size in UV space. Populated once the depth image loads+ // so we know its true resolution; until then we use 1/1200,1/900+ // which matches the supplied assets.+ this._uDepthTexel = { value: new THREE.Vector2(1 / 1200, 1 / 900) };+ if (depthTex.image && depthTex.image.width) {+ this._uDepthTexel.value.set(1 / depthTex.image.width, 1 / depthTex.image.height);+ } else {+ depthTex.onUpdate = () => {+ if (depthTex.image)+ this._uDepthTexel.value.set(1 / depthTex.image.width, 1 / depthTex.image.height);+ };+ }+ material.onBeforeCompile = (shader) => {+ shader.uniforms.uDepth = { value: depthTex };+ shader.uniforms.uDisplacement = this._uDisplacement;+ shader.uniforms.uEdgeStretch = this._uEdgeStretch;+ shader.uniforms.uEdgeFeather = this._uEdgeFeather;+ shader.uniforms.uBorderFade = this._uBorderFade;+ shader.uniforms.uTime = this._uTime;+ shader.uniforms.uShimmer = this._uShimmer;+ shader.uniforms.uDepthTexel = this._uDepthTexel;++ shader.vertexShader = shader.vertexShader+ .replace(+ '#include <common>',+ `#include <common>+ uniform sampler2D uDepth;+ uniform float uDisplacement;`+ )+ .replace(+ '#include <begin_vertex>',+ `#include <begin_vertex>+ float _d = texture2D(uDepth, uv).r;+ transformed.z -= (1.0 - _d) * uDisplacement;`+ );++ // UV-space depth-gradient mask with a smoothstep alpha falloff+ // (anti-aliased silhouettes) + a parameterised rectangle border+ // fade. Ocean shimmer warps the UV slightly on the mid-depth band+ // for the colour sample only, so the displaced geometry is stable.+ shader.fragmentShader = shader.fragmentShader+ .replace(+ '#include <common>',+ `#include <common>+ uniform sampler2D uDepth;+ uniform float uEdgeStretch;+ uniform float uEdgeFeather;+ uniform float uBorderFade;+ uniform float uTime;+ uniform float uShimmer;+ uniform vec2 uDepthTexel;`+ )+ .replace(+ '#include <map_fragment>',+ `// --- Silhouette mask in UV space (view-angle independent) ---+ float _dC = texture2D(uDepth, vMapUv).r;+ float _dR = texture2D(uDepth, vMapUv + vec2(uDepthTexel.x, 0.0)).r;+ float _dD = texture2D(uDepth, vMapUv + vec2(0.0, uDepthTexel.y)).r;+ float _stretch = max(abs(_dC - _dR), abs(_dC - _dD));+ // Smooth falloff just below the discard threshold => AA edges+ float _silAlpha = 1.0 - smoothstep(uEdgeStretch - uEdgeFeather,+ uEdgeStretch, _stretch);++ // --- Ocean shimmer: warp the colour-sample UV on the water band ---+ vec2 _uvSample = vMapUv;+ if (uShimmer > 0.0) {+ // weight peaks at depth ~0.18..0.32 (ocean band in this map)+ float _w = smoothstep(0.10, 0.20, _dC) * (1.0 - smoothstep(0.32, 0.42, _dC));+ float _phase = uTime * 0.7 + vMapUv.x * 14.0 + vMapUv.y * 6.0;+ _uvSample.x += sin(_phase) * 0.0018 * uShimmer * _w;+ _uvSample.y += cos(_phase * 0.83) * 0.0010 * uShimmer * _w;+ }+ vec4 sampledDiffuseColor = texture2D(map, _uvSample);+ diffuseColor *= sampledDiffuseColor;+ // (replaces stock <map_fragment>)+ diffuseColor.a *= _silAlpha;++ // --- Rectangle border fade ---+ float _bf = max(uBorderFade, 0.0001);+ float _ex = smoothstep(0.0, _bf, vMapUv.x) * smoothstep(1.0, 1.0 - _bf, vMapUv.x);+ float _ey = smoothstep(0.0, _bf, vMapUv.y) * smoothstep(1.0, 1.0 - _bf, vMapUv.y);+ diffuseColor.a *= _ex * _ey;`+ );+ };++ const mesh = new THREE.Mesh(geometry, material);+ this.material = material;+ this.el.setObject3D('mesh', mesh);+ },++ tick(time) {+ // shader time in seconds, only sent if shimmer is active so we don't+ // force a uniform write every frame on the static backdrop pass+ if (this._uShimmer && this._uShimmer.value > 0.0) {+ this._uTime.value = time * 0.001;+ }+ },++ update(oldData) {+ if (!this.material) return;+ if (oldData.displacement !== this.data.displacement) this._uDisplacement.value = this.data.displacement;+ if (oldData.edgeStretch !== this.data.edgeStretch) this._uEdgeStretch.value = this.data.edgeStretch;+ if (oldData.edgeFeather !== this.data.edgeFeather) this._uEdgeFeather.value = this.data.edgeFeather;+ if (oldData.borderFade !== this.data.borderFade) this._uBorderFade.value = this.data.borderFade;+ if (oldData.shimmer !== this.data.shimmer) this._uShimmer.value = this.data.shimmer;+ }+ });++ // Clamps the rig position every tick so the player can't walk through+ // the mesh and out the back (where the world is just sky colour).+ AFRAME.registerComponent('walk-bounds', {+ schema: {+ minX: { type: 'number', default: -10 },+ maxX: { type: 'number', default: 10 },+ minZ: { type: 'number', default: -3.5 },+ maxZ: { type: 'number', default: 10 }+ },+ tick() {+ const p = this.el.object3D.position;+ const d = this.data;+ if (p.x < d.minX) p.x = d.minX; else if (p.x > d.maxX) p.x = d.maxX;+ if (p.z < d.minZ) p.z = d.minZ; else if (p.z > d.maxZ) p.z = d.maxZ;+ }+ });++ // Q / E to tweak displacement live (useful to feel how the scene bends)+ // M toggles the ambient bed mute.+ window.addEventListener('keydown', (e) => {+ const ents = document.querySelectorAll('[depth-mesh]');+ if (e.key === 'q' || e.key === 'Q') {+ ents.forEach((ent) => {+ const cur = ent.getAttribute('depth-mesh').displacement;+ ent.setAttribute('depth-mesh', 'displacement', Math.max(0, cur - 0.5));+ });+ }+ if (e.key === 'e' || e.key === 'E') {+ ents.forEach((ent) => {+ const cur = ent.getAttribute('depth-mesh').displacement;+ ent.setAttribute('depth-mesh', 'displacement', cur + 0.5);+ });+ }+ if (e.key === 'm' || e.key === 'M') toggleAudio();+ });++ // ===== Mouse micro-parallax =====+ // Before the user clicks to lock pointer, drag the camera wrapper a tiny+ // amount with the cursor so the scene feels alive even when standing still.+ // Once pointer locks, look-controls takes over and we reset the offset.+ const parallaxWrap = document.querySelector('#parallaxWrap');+ let parallaxTarget = { x: 0, y: 0 };+ let parallaxCurrent = { x: 0, y: 0 };+ window.addEventListener('mousemove', (e) => {+ if (document.pointerLockElement) return;+ const nx = (e.clientX / window.innerWidth - 0.5) * 2;+ const ny = (e.clientY / window.innerHeight - 0.5) * 2;+ parallaxTarget.x = -nx * 0.35;+ parallaxTarget.y = ny * 0.18;+ });+ function tickParallax() {+ parallaxCurrent.x += (parallaxTarget.x - parallaxCurrent.x) * 0.08;+ parallaxCurrent.y += (parallaxTarget.y - parallaxCurrent.y) * 0.08;+ if (parallaxWrap) parallaxWrap.object3D.position.set(parallaxCurrent.x, parallaxCurrent.y, 0);+ requestAnimationFrame(tickParallax);+ }+ requestAnimationFrame(tickParallax);++ // ===== Pointer-lock prompt =====+ const promptEl = document.getElementById('prompt');+ document.addEventListener('pointerlockchange', () => {+ const locked = !!document.pointerLockElement;+ promptEl.classList.toggle('hidden', locked);+ if (locked) parallaxTarget = { x: 0, y: 0 };+ });++ // ===== Web Audio ambient bed =====+ // All-synthesised: filtered pink noise modulated by an LFO for waves,+ // plus four detuned oscillators forming a slow minor-pad chord.+ // Browsers block AudioContext until a user gesture, so we wait for click.+ let audioCtx = null;+ let masterGain = null;+ let muted = false;+ function startAudio() {+ if (audioCtx) return;+ const AC = window.AudioContext || window.webkitAudioContext;+ if (!AC) return;+ audioCtx = new AC();+ masterGain = audioCtx.createGain();+ masterGain.gain.value = 0.3;+ masterGain.connect(audioCtx.destination);++ // ---- Waves: pink noise → lowpass → gain, with LFOs on filter + gain ----+ const sr = audioCtx.sampleRate;+ const buf = audioCtx.createBuffer(1, sr * 4, sr);+ const data = buf.getChannelData(0);+ let b0=0,b1=0,b2=0,b3=0,b4=0,b5=0,b6=0;+ for (let i = 0; i < data.length; i++) {+ const w = Math.random() * 2 - 1;+ b0 = 0.99886*b0 + w*0.0555179;+ b1 = 0.99332*b1 + w*0.0750759;+ b2 = 0.96900*b2 + w*0.1538520;+ b3 = 0.86650*b3 + w*0.3104856;+ b4 = 0.55000*b4 + w*0.5329522;+ b5 = -0.7616*b5 - w*0.0168980;+ data[i] = (b0+b1+b2+b3+b4+b5+b6 + w*0.5362) * 0.11;+ b6 = w*0.115926;+ }+ const wavesSrc = audioCtx.createBufferSource();+ wavesSrc.buffer = buf; wavesSrc.loop = true;+ const wavesFilter = audioCtx.createBiquadFilter();+ wavesFilter.type = 'lowpass';+ wavesFilter.frequency.value = 700;+ wavesFilter.Q.value = 0.7;+ const wavesGain = audioCtx.createGain();+ wavesGain.gain.value = 0.0;+ wavesSrc.connect(wavesFilter); wavesFilter.connect(wavesGain); wavesGain.connect(masterGain);+ wavesSrc.start();+ // Wave-crash gain LFO+ const wLfo = audioCtx.createOscillator();+ wLfo.frequency.value = 0.13;+ const wLfoAmt = audioCtx.createGain(); wLfoAmt.gain.value = 0.32;+ wLfo.connect(wLfoAmt); wLfoAmt.connect(wavesGain.gain); wLfo.start();+ // Filter sweep LFO+ const fLfo = audioCtx.createOscillator();+ fLfo.frequency.value = 0.09;+ const fLfoAmt = audioCtx.createGain(); fLfoAmt.gain.value = 350;+ fLfo.connect(fLfoAmt); fLfoAmt.connect(wavesFilter.frequency); fLfo.start();++ // ---- Ambient pad: A minor chord with slow detune drift ----+ const padGain = audioCtx.createGain();+ padGain.gain.value = 0.0;+ padGain.connect(masterGain);+ [110, 164.81, 220, 329.63].forEach((f, i) => {+ const osc = audioCtx.createOscillator();+ osc.type = i < 2 ? 'sine' : 'triangle';+ osc.frequency.value = f;+ const og = audioCtx.createGain();+ og.gain.value = 0.18 / 4;+ osc.connect(og); og.connect(padGain); osc.start();+ const dLfo = audioCtx.createOscillator();+ dLfo.frequency.value = 0.06 + i * 0.014;+ const dAmt = audioCtx.createGain(); dAmt.gain.value = 9;+ dLfo.connect(dAmt); dAmt.connect(osc.detune); dLfo.start();+ });++ const t = audioCtx.currentTime;+ wavesGain.gain.setValueAtTime(0, t);+ wavesGain.gain.linearRampToValueAtTime(0.5, t + 2.0);+ padGain.gain.setValueAtTime(0, t);+ padGain.gain.linearRampToValueAtTime(0.55, t + 4.0);+ }+ function toggleAudio() {+ if (!masterGain || !audioCtx) return;+ muted = !muted;+ masterGain.gain.linearRampToValueAtTime(muted ? 0 : 0.3, audioCtx.currentTime + 0.3);+ }+ // First interaction kicks off audio (browsers require a gesture).+ window.addEventListener('click', startAudio, { once: true });+ window.addEventListener('keydown', startAudio, { once: true });+ </script>+ </body>+</html>diff --git a/test/aframe.html b/test/aframe.htmlnew file mode 100644index 000000000..09555dcaa--- /dev/null+++ b/test/aframe.html@@ -0,0 +1,70 @@+<!DOCTYPE html>+<html lang="en">+ <head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Beach Meme Diorama — WASD + VR</title>+ <script src="https://aframe.io/releases/1.5.0/aframe.min.js"></script>+ <style>+ body { margin: 0; background: #000; }+ #hud {+ position: fixed; left: 12px; top: 12px; z-index: 10;+ font: 12px/1.4 -apple-system, system-ui, sans-serif;+ color: #fff; background: rgba(0,0,0,0.45);+ padding: 8px 10px; border-radius: 6px; pointer-events: none;+ }+ #hud b { color: #ffb968; }+ </style>+ </head>+ <body>+ <div id="hud">+ <b>WASD</b> walk <b>mouse</b> look <b>click</b> capture pointer<br>+ Bottom-right <b>VR</b> button works on Quest / Vision Pro / Cardboard.+ </div>++ <a-scene background="color: #2a1a2e" renderer="colorManagement: true; physicallyCorrectLights: true">++ <a-assets>+ <img id="lyr0" src="layers/layer_0.png" crossorigin="anonymous">+ <img id="lyr1" src="layers/layer_1.png" crossorigin="anonymous">+ <img id="lyr2" src="layers/layer_2.png" crossorigin="anonymous">+ <img id="lyr3" src="layers/layer_3.png" crossorigin="anonymous">+ <img id="lyr4" src="layers/layer_4.png" crossorigin="anonymous">+ </a-assets>++ <!-- Sunset gradient backdrop sphere -->+ <a-sky color="#ff7a32"></a-sky>++ <!-- Sand floor -->+ <a-plane position="0 0 -15" rotation="-90 0 0" width="200" height="200"+ color="#c69968" shader="flat"></a-plane>++ <!--+ Five depth slabs sized so width = 1.33 * |Z| (height = |Z|).+ That gives ~53° vertical angular size at every distance, so they all+ share the same field of view from origin and stack into one image.+ Walking forward gives true parallax between near and far slabs.+ material: flat shading so sunset colours stay vivid; alphaTest hides+ the soft feather edges so layers don't ghost through each other.+ -->+ <a-image src="#lyr0" position="0 1.6 -20" width="26.7" height="20"+ material="shader: flat; transparent: true; alphaTest: 0.05; side: double"></a-image>+ <a-image src="#lyr1" position="0 1.6 -14" width="18.7" height="14"+ material="shader: flat; transparent: true; alphaTest: 0.05; side: double"></a-image>+ <a-image src="#lyr2" position="0 1.6 -9" width="12" height="9"+ material="shader: flat; transparent: true; alphaTest: 0.05; side: double"></a-image>+ <a-image src="#lyr3" position="0 1.6 -5" width="6.67" height="5"+ material="shader: flat; transparent: true; alphaTest: 0.05; side: double"></a-image>+ <a-image src="#lyr4" position="0 1.6 -2.5" width="3.33" height="2.5"+ material="shader: flat; transparent: true; alphaTest: 0.05; side: double"></a-image>++ <!-- Player rig: WASD walk + mouse look, eye height 1.6m -->+ <a-entity id="rig" position="0 0 0" wasd-controls="acceleration: 30">+ <a-camera position="0 1.6 0" look-controls="pointerLockEnabled: true">+ <a-cursor color="#ffb968" raycaster="far: 30"></a-cursor>+ </a-camera>+ </a-entity>++ </a-scene>+ </body>+</html>diff --git a/test/agent-3d-claude-test.html b/test/agent-3d-claude-test.htmlnew file mode 100644index 000000000..9919b9f5a--- /dev/null+++ b/test/agent-3d-claude-test.html@@ -0,0 +1,422 @@+<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="UTF-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>agent-3d · loaded in claude</title>+<link rel="preconnect" href="https://fonts.googleapis.com">+<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>+<link href="https://fonts.googleapis.com/css2?family=Fraunces:ital,opsz,wght@0,9..144,300..900;1,9..144,300..900&family=JetBrains+Mono:wght@400;500;700&display=swap" rel="stylesheet">+<style>+ :root {+ --bg-deep: #0a0512;+ --plum: #2a0e1a;+ --wine: #5c1a3e;+ --ember: #d94d1a;+ --sun: #ffb347;+ --sand: #f4d5a3;+ --cream: #fef0d8;+ --ink: #1a0a0f;+ --ok: #7dd87d;+ --warn: #ffc555;+ --err: #ff6655;+ }+ * { box-sizing: border-box; margin: 0; padding: 0; }+ html, body {+ background: var(--bg-deep);+ color: var(--cream);+ font-family: 'Fraunces', Georgia, serif;+ font-variation-settings: "opsz" 14, "SOFT" 50;+ min-height: 100vh;+ -webkit-font-smoothing: antialiased;+ }+ body {+ background:+ radial-gradient(ellipse at 50% 92%, rgba(255, 179, 71, 0.55) 0%, transparent 45%),+ radial-gradient(ellipse at 30% 25%, rgba(217, 77, 26, 0.25) 0%, transparent 55%),+ linear-gradient(180deg, #0a0512 0%, #2a0e1a 28%, #5c1a3e 58%, #d94d1a 88%, #ffb347 100%);+ background-attachment: fixed;+ padding: 3rem 1.5rem 5rem;+ position: relative;+ overflow-x: hidden;+ }+ body::after {+ content: '';+ position: fixed; inset: 0;+ pointer-events: none;+ opacity: 0.07;+ z-index: 100;+ background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='240' height='240'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2'/></filter><rect width='240' height='240' filter='url(%23n)'/></svg>");+ }+ .container { max-width: 1100px; margin: 0 auto; position: relative; z-index: 2; }++ /* HEADER */+ header {+ display: flex; justify-content: space-between; align-items: baseline;+ border-bottom: 1px solid rgba(254, 240, 216, 0.18);+ padding-bottom: 1.5rem; margin-bottom: 3rem;+ flex-wrap: wrap; gap: 1rem;+ }+ .brand {+ font-family: 'Fraunces', serif;+ font-weight: 900; font-style: italic;+ font-variation-settings: "opsz" 144, "SOFT" 100;+ font-size: 1.55rem; letter-spacing: -0.025em;+ }+ .brand .dot { color: var(--sun); }+ .brand .small { font-style: normal; font-weight: 400; font-size: 0.95rem; opacity: 0.6; margin-left: 0.4rem; }+ .meta {+ font-family: 'JetBrains Mono', monospace;+ font-size: 0.7rem; letter-spacing: 0.18em;+ text-transform: uppercase; opacity: 0.65;+ }+ .meta .pulse {+ display: inline-block; width: 6px; height: 6px;+ background: var(--sun); border-radius: 50%; margin-right: 0.4em;+ animation: pulse 2s ease-in-out infinite;+ }+ @keyframes pulse { 0%, 100% { opacity: 0.4 } 50% { opacity: 1 } }++ /* HERO */+ .hero { text-align: center; margin-bottom: 3rem; max-width: 38rem; margin-left: auto; margin-right: auto; }+ .eyebrow {+ font-family: 'JetBrains Mono', monospace;+ font-size: 0.68rem; letter-spacing: 0.32em;+ text-transform: uppercase; color: var(--sun);+ margin-bottom: 1.5rem;+ }+ .eyebrow::before, .eyebrow::after {+ content: '—'; display: inline-block; margin: 0 0.7em; opacity: 0.6;+ }+ h1 {+ font-family: 'Fraunces', serif;+ font-weight: 350;+ font-variation-settings: "opsz" 144, "SOFT" 100;+ font-size: clamp(2.4rem, 6.5vw, 4.6rem);+ line-height: 0.95; letter-spacing: -0.035em;+ margin-bottom: 1.5rem;+ }+ h1 em {+ font-style: italic; font-weight: 250;+ color: var(--sun);+ font-variation-settings: "opsz" 144, "SOFT" 100;+ }+ .lede {+ font-size: 1.1rem; line-height: 1.55; opacity: 0.88;+ font-weight: 350;+ }++ /* STAGE */+ .stage-wrap { text-align: center; margin: 3rem auto; }+ .stage {+ position: relative;+ width: 100%; max-width: 480px;+ aspect-ratio: 4 / 5;+ margin: 0 auto;+ border-radius: 4px;+ overflow: hidden;+ background: linear-gradient(180deg, #1a0a1f 0%, #3a1428 50%, #5c1a3e 100%);+ box-shadow:+ 0 40px 80px -20px rgba(0, 0, 0, 0.6),+ 0 0 0 1px rgba(254, 240, 216, 0.12),+ 0 0 0 8px rgba(254, 240, 216, 0.03);+ }+ .stage::before {+ content: ''; position: absolute;+ bottom: -10%; left: 50%;+ transform: translateX(-50%);+ width: 75%; aspect-ratio: 1;+ border-radius: 50%;+ background: radial-gradient(circle, var(--sun) 0%, var(--ember) 35%, transparent 65%);+ filter: blur(28px); opacity: 0.55;+ z-index: 0;+ }+ agent-3d {+ position: relative; z-index: 1;+ width: 100%; height: 100%;+ display: block;+ }+ /* Loading placeholder visible until the script + element register */+ .stage[data-state="pending"]::after {+ content: 'waiting for agent-3d.js';+ position: absolute; inset: 0;+ display: flex; align-items: center; justify-content: center;+ font-family: 'JetBrains Mono', monospace;+ font-size: 0.75rem; letter-spacing: 0.2em;+ text-transform: uppercase;+ color: rgba(254, 240, 216, 0.4);+ z-index: 2;+ animation: pulse 1.5s ease-in-out infinite;+ }+ .stage[data-state="error"]::after {+ content: '✕ sandbox blocked load';+ position: absolute; inset: 0;+ display: flex; align-items: center; justify-content: center;+ font-family: 'JetBrains Mono', monospace;+ font-size: 0.8rem; letter-spacing: 0.15em;+ color: var(--err);+ z-index: 2;+ }+ .stage-caption {+ font-family: 'JetBrains Mono', monospace;+ font-size: 0.7rem; letter-spacing: 0.22em;+ text-transform: uppercase; opacity: 0.5;+ margin-top: 1.2rem;+ }++ /* CONTROLS */+ .controls {+ display: flex; gap: 0.6rem;+ justify-content: center; flex-wrap: wrap;+ margin: 2.5rem auto 0; max-width: 480px;+ }+ .ctrl {+ background: transparent;+ border: 1px solid rgba(254, 240, 216, 0.4);+ color: var(--cream);+ font-family: 'JetBrains Mono', monospace;+ font-size: 0.7rem; letter-spacing: 0.14em;+ text-transform: uppercase;+ padding: 0.7rem 1.1rem;+ cursor: pointer; transition: all 0.18s ease;+ border-radius: 2px;+ }+ .ctrl:not(:disabled):hover {+ background: var(--cream); color: var(--ink);+ border-color: var(--cream);+ }+ .ctrl:disabled { opacity: 0.3; cursor: not-allowed; }++ /* STATUS PANEL */+ .status {+ background: rgba(10, 5, 18, 0.5);+ backdrop-filter: blur(8px);+ border: 1px solid rgba(254, 240, 216, 0.15);+ border-radius: 4px;+ padding: 1.4rem 1.6rem;+ font-family: 'JetBrains Mono', monospace;+ font-size: 0.78rem;+ margin: 3.5rem auto;+ max-width: 480px;+ }+ .status-title {+ font-size: 0.65rem; letter-spacing: 0.28em;+ text-transform: uppercase; opacity: 0.55;+ margin-bottom: 1rem; padding-bottom: 0.7rem;+ border-bottom: 1px dashed rgba(254, 240, 216, 0.12);+ }+ .status-row {+ display: flex; justify-content: space-between;+ align-items: center;+ padding: 0.45rem 0;+ }+ .status-key { opacity: 0.65; }+ .status-val { font-weight: 500; }+ .status-val.pending { color: var(--cream); opacity: 0.5; }+ .status-val.ok { color: var(--ok); }+ .status-val.warn { color: var(--warn); }+ .status-val.err { color: var(--err); }+ .status-val::before {+ content: '◦ '; opacity: 0.6;+ }+ .status-val.ok::before { content: '✓ '; opacity: 1; }+ .status-val.err::before { content: '✕ '; opacity: 1; }+ .status-val.warn::before { content: '! '; opacity: 1; }++ /* NOTES */+ .notes {+ max-width: 560px; margin: 4rem auto 0;+ border-top: 1px solid rgba(254, 240, 216, 0.18);+ padding-top: 2.5rem;+ }+ .notes-eye {+ font-family: 'JetBrains Mono', monospace;+ font-size: 0.65rem; letter-spacing: 0.28em;+ text-transform: uppercase; opacity: 0.55;+ margin-bottom: 0.7rem;+ }+ .notes h2 {+ font-family: 'Fraunces', serif;+ font-weight: 350; font-style: italic;+ font-variation-settings: "opsz" 144, "SOFT" 100;+ font-size: 1.7rem; letter-spacing: -0.02em;+ margin-bottom: 1.2rem;+ color: var(--sand);+ }+ .notes p {+ font-size: 1.02rem; line-height: 1.65;+ margin-bottom: 1.1rem; opacity: 0.88;+ font-weight: 350;+ }+ .notes code, .lede code {+ font-family: 'JetBrains Mono', monospace;+ font-size: 0.82em;+ background: rgba(254, 240, 216, 0.09);+ padding: 0.15em 0.45em;+ border-radius: 2px;+ color: var(--sun);+ }+ .notes a { color: var(--sun); text-decoration: none; border-bottom: 1px dotted var(--sun); }+ .notes a:hover { background: var(--sun); color: var(--ink); }++ /* MOTION */+ @keyframes fadeUp {+ from { opacity: 0; transform: translateY(16px); }+ to { opacity: 1; transform: translateY(0); }+ }+ .hero, .stage-wrap, .controls, .status, .notes {+ animation: fadeUp 0.7s cubic-bezier(.2,.7,.3,1) backwards;+ }+ .stage-wrap { animation-delay: 0.15s; }+ .controls { animation-delay: 0.3s; }+ .status { animation-delay: 0.4s; }+ .notes { animation-delay: 0.5s; }+</style>+</head>+<body>+ <div class="container">+ <header>+ <div class="brand">three<span class="dot">.</span>ws<span class="small">— inside claude</span></div>+ <div class="meta"><span class="pulse"></span>SANDBOX PROBE · v1</div>+ </header>++ <section class="hero">+ <div class="eyebrow">Embed Probe</div>+ <h1>An agent, <em>at sunset.</em></h1>+ <p class="lede">Loading <code>agent-3d.js</code> from the three.ws CDN directly into this Claude artifact. If the sandbox allows the external script and the cross-origin GLB fetch, a rotating avatar appears below. The panel under it reports what actually happened.</p>+ </section>++ <div class="stage-wrap">+ <div class="stage" id="stage" data-state="pending">+ <agent-3d id="agent"+ body="https//assets.three.ws/models/sample-avatar.glb"+ mode="view"+ watermark="false"+ eager></agent-3d>+ </div>+ <p class="stage-caption">— sample-avatar · assets.three.ws —</p>++ <div class="controls">+ <button class="ctrl" id="btn-wave" disabled>Wave</button>+ <button class="ctrl" id="btn-look" disabled>Look at camera</button>+ <button class="ctrl" id="btn-reload">Reload</button>+ </div>+ </div>++ <div class="status">+ <div class="status-title">Diagnostic</div>+ <div class="status-row"><span class="status-key">script load</span><span class="status-val pending" id="s-script">pending</span></div>+ <div class="status-row"><span class="status-key">custom element</span><span class="status-val pending" id="s-elem">pending</span></div>+ <div class="status-row"><span class="status-key">agent:ready event</span><span class="status-val pending" id="s-ready">pending</span></div>+ <div class="status-row"><span class="status-key">script URL</span><span class="status-val ok" style="font-size:0.7em;opacity:0.7" id="s-url">three.ws/agent-3d/1.5.1</span></div>+ </div>++ <section class="notes">+ <div class="notes-eye">Reading the result</div>+ <h2>What this tells us.</h2>+ <p>The viewer is the <code><agent-3d></code> custom element from <a href="https://three.ws" target="_blank" rel="noopener">three.ws</a>, loaded as an external module script. The artifact runs in Claude's sandboxed iframe — script-tag loads usually work, but some sandboxes block cross-origin script execution or cross-origin model fetches.</p>+ <p>If <em>script load</em> fails, the sandbox is blocking external module scripts entirely. The fallback is to inline the library or use the <code><iframe src="https://three.ws/a/{chain}/{id}/embed"></code> approach, which runs in its own browsing context with its own CSP.</p>+ <p>If <em>script load</em> succeeds but <em>agent:ready</em> times out, the script ran but the model fetch from <code>assets.three.ws</code> was blocked. Same fallback applies, or host the GLB on a CORS-friendly origin.</p>+ <p>To wire in a brain, set <code>brain="claude-sonnet-4-6"</code> and an <code>instructions</code> attribute. That routes chat through their API, which needs the host origin to be allowed in their CORS config.</p>+ </section>+ </div>++ <script type="module">+ const $ = (id) => document.getElementById(id);+ const setStatus = (id, txt, cls) => {+ const el = $(id);+ el.textContent = txt;+ el.className = 'status-val ' + cls;+ };++ const stage = $('stage');+ const SCRIPT_URL = 'https://three.ws/agent-3d/1.5.1/agent-3d.js';++ setStatus('s-script', 'loading…', 'pending');++ const script = document.createElement('script');+ script.type = 'module';+ script.src = SCRIPT_URL;++ let scriptLoaded = false;+ script.onload = () => {+ scriptLoaded = true;+ setStatus('s-script', 'loaded', 'ok');++ // Custom element may register before or after script onload; whenDefined handles both.+ setStatus('s-elem', 'waiting…', 'pending');+ customElements.whenDefined('agent-3d').then(() => {+ setStatus('s-elem', 'registered', 'ok');++ const agent = $('agent');+ setStatus('s-ready', 'waiting…', 'pending');++ const readyHandler = () => {+ setStatus('s-ready', 'fired', 'ok');+ stage.dataset.state = 'ready';+ $('btn-wave').disabled = false;+ $('btn-look').disabled = false;+ };+ agent.addEventListener('agent:ready', readyHandler, { once: true });++ // Fallback: if the canvas appears inside the element, treat that as visual readiness+ const obs = new MutationObserver(() => {+ if (agent.querySelector('canvas') || agent.shadowRoot?.querySelector('canvas')) {+ stage.dataset.state = 'ready';+ obs.disconnect();+ }+ });+ obs.observe(agent, { childList: true, subtree: true });++ setTimeout(() => {+ if ($('s-ready').textContent === 'waiting…') {+ setStatus('s-ready', 'timeout (12s) · check console', 'warn');+ }+ }, 12000);+ }).catch(err => {+ setStatus('s-elem', 'failed: ' + (err?.message || 'unknown'), 'err');+ stage.dataset.state = 'error';+ });+ };++ script.onerror = (e) => {+ setStatus('s-script', 'blocked or 404', 'err');+ setStatus('s-elem', 'not reached', 'err');+ setStatus('s-ready', 'not reached', 'err');+ stage.dataset.state = 'error';+ };++ // Hard timeout for script load itself+ setTimeout(() => {+ if (!scriptLoaded && $('s-script').textContent === 'loading…') {+ setStatus('s-script', 'still loading after 15s', 'warn');+ }+ }, 15000);++ document.head.appendChild(script);++ // Control wiring (only fires after agent:ready enables them)+ $('btn-wave').addEventListener('click', () => {+ const agent = $('agent');+ if (typeof agent.wave === 'function') agent.wave();+ else if (typeof agent.play === 'function') agent.play('wave');+ });+ $('btn-look').addEventListener('click', () => {+ const agent = $('agent');+ if (typeof agent.lookAt === 'function') agent.lookAt('camera');+ });+ $('btn-reload').addEventListener('click', () => {+ const agent = $('agent');+ const body = agent.getAttribute('body');+ stage.dataset.state = 'pending';+ $('btn-wave').disabled = true;+ $('btn-look').disabled = true;+ setStatus('s-ready', 'reloading…', 'pending');+ agent.removeAttribute('body');+ requestAnimationFrame(() => {+ setTimeout(() => agent.setAttribute('body', body), 60);+ });+ });+ </script>+</body>+</html>diff --git a/test/build_layers.py b/test/build_layers.pynew file mode 100644index 000000000..debc74e95--- /dev/null+++ b/test/build_layers.py@@ -0,0 +1,61 @@+"""+Slice the beach image into depth layers using the depth map.++Strategy: each pixel is assigned to a depth slab by its depth value.+- Layer 0 = farthest = the full original image (acts as the complete backdrop).+- Layers 1..N-1 = each successive near depth slab with the rest transparent.+- Alpha edges are feathered with a small Gaussian blur so seams don't show+ as hard cuts in the A-Frame composite.+"""+import os+from PIL import Image, ImageFilter+import numpy as np++HERE = os.path.dirname(os.path.abspath(__file__))+OUT_DIR = os.path.join(HERE, 'layers')+os.makedirs(OUT_DIR, exist_ok=True)++img = Image.open(os.path.join(HERE, 'image.jpg')).convert('RGB')+depth = Image.open(os.path.join(HERE, 'depth.jpg')).convert('L')+if depth.size != img.size:+ depth = depth.resize(img.size, Image.LANCZOS)++# Also produce a high-detail 8-bit depth from the 16-bit disparity map.+# Disparity convention matches depth.jpg: bright = near, dark = far.+# Normalize across the actual value range so the full 0..255 byte is used.+disp_path = os.path.join(HERE, 'pf_disparity.png')+if os.path.exists(disp_path):+ disp = np.array(Image.open(disp_path)).astype(np.float32)+ lo, hi = float(disp.min()), float(disp.max())+ disp_norm = ((disp - lo) / (hi - lo) * 255.0).clip(0, 255).astype(np.uint8)+ Image.fromarray(disp_norm).save(os.path.join(HERE, 'depth_hd.png'))+ print(f'depth_hd.png written raw range {int(lo)}-{int(hi)} unique={len(np.unique(disp_norm))}')++img_arr = np.array(img) # H, W, 3+depth_arr = np.array(depth) # H, W bright = near, dark = far++N = 5+bounds = np.percentile(depth_arr, np.linspace(0, 100, N + 1))+print(f'Depth percentile bounds (far -> near): {[int(b) for b in bounds]}')++for i in range(N):+ if i == 0:+ # Farthest layer = full opaque backdrop.+ alpha = np.full(depth_arr.shape, 255, dtype=np.uint8)+ else:+ lo, hi = bounds[i], bounds[i + 1]+ if i == N - 1:+ m = (depth_arr >= lo) & (depth_arr <= hi)+ else:+ m = (depth_arr >= lo) & (depth_arr < hi)+ alpha = (m * 255).astype(np.uint8)+ alpha = np.array(+ Image.fromarray(alpha).filter(ImageFilter.GaussianBlur(2.0))+ )++ layer = np.dstack([img_arr, alpha])+ out = os.path.join(OUT_DIR, f'layer_{i}.png')+ Image.fromarray(layer).save(out)+ print(f' layer_{i}.png visible_px={(alpha > 8).sum()}')++print('Done.')diff --git a/test/depth.jpg b/test/depth.jpgnew file mode 100644index 000000000..c4058d292Binary files /dev/null and b/test/depth.jpg differdiff --git a/test/depth_hd.png b/test/depth_hd.pngnew file mode 100644index 000000000..160744eeaBinary files /dev/null and b/test/depth_hd.png differdiff --git a/test/image.jpg b/test/image.jpgnew file mode 100644index 000000000..11926093fBinary files /dev/null and b/test/image.jpg differdiff --git a/test/image_inpainted.jpg b/test/image_inpainted.jpgnew file mode 100644index 000000000..16357e09fBinary files /dev/null and b/test/image_inpainted.jpg differdiff --git a/test/index.html b/test/index.htmlnew file mode 100644index 000000000..364b01a6a--- /dev/null+++ b/test/index.html@@ -0,0 +1,109 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Immersive 3D Beach Meme Experience</title>+ <style>+ body { margin: 0; overflow: hidden; background-color: #000; }+ canvas { display: block; width: 100vw; height: 100vh; }+ #loading {+ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);+ color: white; font-family: sans-serif; font-size: 24px; pointer-events: none;+ }+ </style>+ <!-- Load Three.js -->+ <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>+</head>+<body>+ <div id="loading">Loading 3D Experience...</div>+ <script>+ // 1. Setup Scene, Camera, and Renderer+ const scene = new THREE.Scene();+ const camera = new THREE.OrthographicCamera( -1, 1, 1, -1, 0, 1 );+ const renderer = new THREE.WebGLRenderer({ antialias: true });+ renderer.setSize(window.innerWidth, window.innerHeight);+ document.body.appendChild(renderer.domElement);++ // 2. Load the Images (Original and Depth Map)+ const loader = new THREE.TextureLoader();++ // IMPORTANT: Ensure your images are named exactly like this in the same folder!+ const imgTexture = loader.load('image.jpg');+ const depthTexture = loader.load('depth.jpg', () => {+ document.getElementById('loading').style.display = 'none'; // Hide loading text+ });++ // 3. Create the 3D Shader Material+ const material = new THREE.ShaderMaterial({+ uniforms: {+ u_image: { type: 't', value: imgTexture },+ u_depth: { type: 't', value: depthTexture },+ u_mouse: { type: 'v2', value: new THREE.Vector2(0.5, 0.5) },+ u_intensity: { type: 'f', value: 0.05 } // Adjust for more/less 3D effect+ },+ vertexShader: `+ varying vec2 vUv;+ void main() {+ vUv = uv;+ gl_Position = vec4(position, 1.0);+ }+ `,+ fragmentShader: `+ uniform sampler2D u_image;+ uniform sampler2D u_depth;+ uniform vec2 u_mouse;+ uniform float u_intensity;+ varying vec2 vUv;++ void main() {+ // Read depth (0.0 to 1.0)+ vec4 depthColor = texture2D(u_depth, vUv);+ float depth = depthColor.r;++ // Calculate 3D offset based on mouse position and depth+ vec2 offset = (u_mouse - 0.5) * u_intensity * (1.0 - depth);++ // Apply offset and render+ vec4 color = texture2D(u_image, vUv + offset);+ gl_FragColor = color;+ }+ `+ });++ // 4. Map to a flat plane that fits the screen+ const geometry = new THREE.PlaneGeometry(2, 2);+ const mesh = new THREE.Mesh(geometry, material);+ scene.add(mesh);++ // 5. Track Mouse/Touch for Interactive 3D Parallax+ let targetMouse = new THREE.Vector2(0.5, 0.5);+ let currentMouse = new THREE.Vector2(0.5, 0.5);++ window.addEventListener('mousemove', (e) => {+ targetMouse.x = e.clientX / window.innerWidth;+ targetMouse.y = 1.0 - (e.clientY / window.innerHeight);+ });++ window.addEventListener('touchmove', (e) => {+ targetMouse.x = e.touches[0].clientX / window.innerWidth;+ targetMouse.y = 1.0 - (e.touches[0].clientY / window.innerHeight);+ });++ // Handle Window Resize+ window.addEventListener('resize', () => {+ renderer.setSize(window.innerWidth, window.innerHeight);+ });++ // 6. Animation Loop (Smooth easing)+ function animate() {+ requestAnimationFrame(animate);+ // Ease the mouse movement for a smooth, natural camera feel+ currentMouse.lerp(targetMouse, 0.05);+ material.uniforms.u_mouse.value = currentMouse;+ renderer.render(scene, camera);+ }+ animate();+ </script>+</body>+</html>\ No newline at end of filediff --git a/test/inpaint_backdrop.py b/test/inpaint_backdrop.pynew file mode 100644index 000000000..bbb80965e--- /dev/null+++ b/test/inpaint_backdrop.py@@ -0,0 +1,92 @@+"""+Build the inpainted backdrop image that sits behind the foreground depth-mesh.++The mesh's UV-space discard punches holes at character silhouettes; the backdrop+mesh provides clean pixels visible through those holes.++Approach:+ 1. Detect horizon row from the depth map (steepest sky->ground gradient).+ 2. Build a character mask = mid-depth band, dilated.+ 3. SKY portion of mask (above horizon): cv2.inpaint with NS algorithm — works+ well here because clean sky surrounds the masked pixels.+ 4. GROUND portion (below horizon): per-row HORIZONTAL linear extrapolation —+ lerp between the nearest unmasked pixels left and right on the same row.+ This avoids the vertical "shower curtain" streaks that single-pass+ OpenCV inpainting produces when the mask covers most of the lower half.+"""+import os+import numpy as np+import cv2+from PIL import Image++HERE = os.path.dirname(os.path.abspath(__file__))+img = cv2.imread(os.path.join(HERE, 'image.jpg')) # BGR HxWx3+depth = np.array(Image.open(os.path.join(HERE, 'depth_hd.png')).convert('L'))+H, W = img.shape[:2]++# --- Horizon row ---+row_means = depth.astype(np.float32).mean(axis=1)+row_smooth = np.convolve(row_means, np.ones(20) / 20.0, mode='same')+horizon_y = int(np.argmax(np.gradient(row_smooth)))+print(f'horizon row: {horizon_y} / {H}')++# --- Character mask ---+char_mask = ((depth > 40) & (depth < 215)).astype(np.uint8) * 255+char_mask = cv2.dilate(char_mask, np.ones((5, 5), np.uint8), iterations=2)++band = 25+sky_mask = char_mask.copy()+sky_mask[horizon_y + band:] = 0+gnd_mask = char_mask.copy()+gnd_mask[:horizon_y - band] = 0+print(f'sky-mask px: {int((sky_mask > 0).sum())} '+ f'ground-mask px: {int((gnd_mask > 0).sum())}')++# --- Sky pass: standard NS inpaint ---+out = cv2.inpaint(img, sky_mask, 12, cv2.INPAINT_NS)++# --- Ground pass: per-row horizontal linear extrapolation ---+# For each row, find runs of masked pixels and lerp between the unmasked+# pixels immediately left and right of the run. Falls back to the one side+# that exists when the run is anchored to an edge.+def horizontal_lerp_fill(img_in, mask):+ out_img = img_in.copy()+ H_, W_ = mask.shape[:2]+ for y in range(H_):+ row = mask[y] > 0+ if not row.any():+ continue+ # Boundary deltas: +1 entering a run, -1 leaving+ d = np.diff(row.astype(np.int8), prepend=0, append=0)+ starts = np.where(d == 1)[0]+ ends = np.where(d == -1)[0] - 1+ for s, e in zip(starts, ends):+ lx, rx = s - 1, e + 1+ width = e - s + 1+ if lx < 0 and rx >= W_:+ continue # entire row masked -> leave as inpaint-pass result+ if lx < 0:+ out_img[y, s:e + 1] = img_in[y, rx]+ continue+ if rx >= W_:+ out_img[y, s:e + 1] = img_in[y, lx]+ continue+ left = img_in[y, lx].astype(np.float32)+ right = img_in[y, rx].astype(np.float32)+ # t in (0,1) over the run width, exclusive of the endpoints+ t = (np.arange(1, width + 1) / (width + 1))[:, None]+ out_img[y, s:e + 1] = (left * (1.0 - t) + right * t).astype(np.uint8)+ return out_img++out = horizontal_lerp_fill(out, gnd_mask)++# Light vertical blur on the ground band only so the per-row lerps don't read+# as scanlines when viewed from extreme angles.+y0, y1 = max(0, horizon_y - band), H+strip = out[y0:y1].copy()+strip = cv2.GaussianBlur(strip, (1, 9), 0)+out[y0:y1] = strip++dst = os.path.join(HERE, 'image_inpainted.jpg')+cv2.imwrite(dst, out, [cv2.IMWRITE_JPEG_QUALITY, 92])+print(f'wrote {dst}')diff --git a/test/layers/layer_0.png b/test/layers/layer_0.pngnew file mode 100644index 000000000..d4ad74f93Binary files /dev/null and b/test/layers/layer_0.png differdiff --git a/test/layers/layer_1.png b/test/layers/layer_1.pngnew file mode 100644index 000000000..7f4af642cBinary files /dev/null and b/test/layers/layer_1.png differdiff --git a/test/layers/layer_2.png b/test/layers/layer_2.pngnew file mode 100644index 000000000..82b059e03Binary files /dev/null and b/test/layers/layer_2.png differdiff --git a/test/layers/layer_3.png b/test/layers/layer_3.pngnew file mode 100644index 000000000..cd646e3fcBinary files /dev/null and b/test/layers/layer_3.png differdiff --git a/test/layers/layer_4.png b/test/layers/layer_4.pngnew file mode 100644index 000000000..29960884dBinary files /dev/null and b/test/layers/layer_4.png differdiff --git a/test/pf_disparity.png b/test/pf_disparity.pngnew file mode 100644index 000000000..34ab7ce83Binary files /dev/null and b/test/pf_disparity.png differ