| 1 | // Vista «Ciudad 3D» — el proyecto abierto renderizado con el MOTOR REAL de |
| 2 | // VibeCodeViewer (Sendery/VibeCodeViewer, Apache-2.0), vendorizado en js/vcc. |
| 3 | // Aquí solo hacemos de glue: escaneamos la carpeta abierta al árbol empaquetado |
| 4 | // que espera buildModel, montamos el render (cámara + OrbitControls + bloom) y |
| 5 | // conectamos el raycast → abrir fichero en Monaco. La geometría (ciudad anidada |
| 6 | // distrito→edificio→planta→…, cristal fresnel, fachadas con el árbol impreso, |
| 7 | // suelo de circuito, leyenda) es la del builder original, sin tocar. |
| 8 | import * as THREE from 'three'; |
| 9 | import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; |
| 10 | import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js'; |
| 11 | import { RenderPass } from 'three/addons/postprocessing/RenderPass.js'; |
| 12 | import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js'; |
| 13 | import { OutputPass } from 'three/addons/postprocessing/OutputPass.js'; |
| 14 | import * as code from './tools/code.js'; |
| 15 | import { buildModel } from './vcc/model.js'; |
| 16 | import { buildCity } from './vcc/builder.js'; |
| 17 | import { THEME } from './vcc/theme.js'; |
| 18 | import { escuchar } from './actividad.js'; |
| 19 | |
| 20 | const IGNORE = new Set(['node_modules', '.git', 'dist', 'build', 'target', '__pycache__', '.next', 'venv', '.venv', '.DS_Store']); |
| 21 | const MAX_FILES = 8000; // tope de seguridad para no colgar el navegador en monorepos |
| 22 | |
| 23 | let disposer = null; |
| 24 | |
| 25 | // Escanea el handle del proyecto al formato empaquetado de VibeCodeViewer: |
| 26 | // dir = [nombre, [subdirs], [ficheros]] · fichero = [nombre, bytes] |
| 27 | async function scanTree(dir, budget) { |
| 28 | const dirs = [], files = []; |
| 29 | for await (const e of dir.values()) { |
| 30 | if (IGNORE.has(e.name)) continue; |
| 31 | (e.kind === 'directory' ? dirs : files).push(e); |
| 32 | } |
| 33 | dirs.sort((a, b) => a.name.localeCompare(b.name)); |
| 34 | files.sort((a, b) => a.name.localeCompare(b.name)); |
| 35 | const outFiles = []; |
| 36 | for (const f of files) { |
| 37 | if (budget.n >= MAX_FILES) break; |
| 38 | let size = 0; try { size = (await f.getFile()).size; } catch { /* ilegible */ } |
| 39 | outFiles.push([f.name, size]); budget.n++; |
| 40 | } |
| 41 | const outDirs = []; |
| 42 | for (const d of dirs) { if (budget.n >= MAX_FILES) break; outDirs.push(await scanTree(d, budget)); } |
| 43 | return [dir.name, outDirs, outFiles]; |
| 44 | } |
| 45 | |
| 46 | export async function renderCity(container, onOpenFile) { |
| 47 | disposeCity(); |
| 48 | const root = code.handle(); |
| 49 | if (!root) { container.innerHTML = '<div class="view-loading">Abre un proyecto primero.</div>'; return; } |
| 50 | container.innerHTML = '<div class="view-loading">Construyendo la metrópolis del proyecto…</div>'; |
| 51 | |
| 52 | const budget = { n: 0 }; |
| 53 | const tree = await scanTree(root, budget); |
| 54 | const model = buildModel(tree, null); |
| 55 | if (!model.files.length) { container.innerHTML = '<div class="view-loading">Proyecto vacío.</div>'; return; } |
| 56 | |
| 57 | container.innerHTML = |
| 58 | '<canvas id="city-canvas"></canvas>' + |
| 59 | '<div class="view-head">Ciudad 3D · ' + model.files.length + (budget.n >= MAX_FILES ? '+' : '') + |
| 60 | ' ficheros en ' + model.districts.length + ' distritos' + |
| 61 | '<span class="view-hint">arrastra para orbitar · rueda para zoom · clic en un edificio → abrir</span></div>' + |
| 62 | // Pila de actividad: lo que la elfa hace AHORA, línea a línea, como un terminal. |
| 63 | '<pre class="city-log" aria-live="off" style="position:absolute;left:0;right:0;bottom:0;max-height:32%;overflow:auto;margin:0;padding:6px 10px;font:12px/1.4 ui-monospace,monospace;background:rgba(0,0,0,.55);color:#cfe;pointer-events:none;white-space:pre-wrap"></pre>'; |
| 64 | const registro = container.querySelector('.city-log'); |
| 65 | const canvas = container.querySelector('#city-canvas'); |
| 66 | const W = container.clientWidth || 800, H = container.clientHeight || 600; |
| 67 | |
| 68 | const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, powerPreference: 'high-performance' }); |
| 69 | renderer.setPixelRatio(Math.min(devicePixelRatio, 2)); |
| 70 | renderer.setSize(W, H, false); |
| 71 | renderer.toneMapping = THREE.ACESFilmicToneMapping; |
| 72 | renderer.toneMappingExposure = 1.0; |
| 73 | renderer.setClearColor(THEME.background, 1); |
| 74 | |
| 75 | const scene = new THREE.Scene(); |
| 76 | scene.background = new THREE.Color(THEME.background); |
| 77 | const extent = Math.max(model.city.box.sx, model.city.box.sz); |
| 78 | scene.fog = new THREE.FogExp2(THEME.fog, 0.62 / extent); |
| 79 | |
| 80 | const camera = new THREE.PerspectiveCamera(55, W / H, 0.1, extent * 14); |
| 81 | camera.position.set(extent * 0.7, extent * 0.6, extent * 0.7); |
| 82 | |
| 83 | const controls = new OrbitControls(camera, canvas); |
| 84 | controls.enableDamping = true; |
| 85 | controls.dampingFactor = 0.08; |
| 86 | controls.maxPolarAngle = Math.PI * 0.495; // no bajar del suelo |
| 87 | controls.target.set(0, extent * 0.04, 0); |
| 88 | controls.update(); |
| 89 | |
| 90 | // pipeline con bloom (la receta del builder: HDR + bloom solo en lo resaltado) |
| 91 | const composer = new EffectComposer(renderer); |
| 92 | composer.setSize(W, H); |
| 93 | composer.addPass(new RenderPass(scene, camera)); |
| 94 | const bloom = new UnrealBloomPass(new THREE.Vector2(W, H), THEME.bloom.strength, 0.25, THEME.bloom.threshold); |
| 95 | composer.addPass(bloom); |
| 96 | composer.addPass(new OutputPass()); |
| 97 | |
| 98 | const city = buildCity(scene, model, THEME); |
| 99 | |
| 100 | // ── interacción: hover resalta edificios, clic abre el fichero ──────────── |
| 101 | const ray = new THREE.Raycaster(), ptr = new THREE.Vector2(); |
| 102 | let hovered = null, lastHover = 0, downXY = null; |
| 103 | const setPtr = e => { const r = canvas.getBoundingClientRect(); ptr.set(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1); }; |
| 104 | const onMove = e => { |
| 105 | setPtr(e); |
| 106 | const now = performance.now(); if (now - lastHover < 50) return; lastHover = now; |
| 107 | ray.setFromCamera(ptr, camera); |
| 108 | const b = ray.intersectObjects(city.shells)[0]?.object.userData.building ?? null; |
| 109 | if (b !== hovered) { |
| 110 | if (hovered) city.paintNode(hovered, 0); |
| 111 | hovered = b; |
| 112 | if (b) city.paintNode(b, 0.16); |
| 113 | canvas.style.cursor = b ? 'pointer' : 'grab'; |
| 114 | } |
| 115 | }; |
| 116 | const onDown = e => { downXY = [e.clientX, e.clientY]; }; |
| 117 | const onUp = e => { |
| 118 | if (!downXY) return; |
| 119 | const moved = Math.hypot(e.clientX - downXY[0], e.clientY - downXY[1]); downXY = null; |
| 120 | if (moved > 5) return; // fue un arrastre de cámara |
| 121 | setPtr(e); ray.setFromCamera(ptr, camera); |
| 122 | const fileHit = ray.intersectObject(city.filesMesh)[0]; |
| 123 | const shellHit = ray.intersectObjects(city.shells)[0]; |
| 124 | if (fileHit && (!shellHit || fileHit.distance < shellHit.distance + 2)) { |
| 125 | const f = model.files[fileHit.instanceId]; |
| 126 | if (f) onOpenFile(f.rel); |
| 127 | } else if (shellHit) { |
| 128 | // clic en un edificio (carpeta): centra la cámara en él |
| 129 | const b = shellHit.object.userData.building; |
| 130 | controls.target.set(b.box.cx, b.box.cy, b.box.cz); |
| 131 | } |
| 132 | }; |
| 133 | canvas.addEventListener('pointermove', onMove); |
| 134 | canvas.addEventListener('pointerdown', onDown); |
| 135 | canvas.addEventListener('pointerup', onUp); |
| 136 | |
| 137 | const onResize = () => { |
| 138 | const w = container.clientWidth || W, h = container.clientHeight || H; |
| 139 | renderer.setSize(w, h, false); composer.setSize(w, h); bloom.resolution.set(w, h); |
| 140 | camera.aspect = w / h; camera.updateProjectionMatrix(); |
| 141 | }; |
| 142 | window.addEventListener('resize', onResize); |
| 143 | // …y cuando cambia el CONTENEDOR sin que cambie la ventana: abrir, cerrar o |
| 144 | // arrastrar la consola, que ahora convive con la vista debajo de ella. |
| 145 | const ro = 'ResizeObserver' in window ? new ResizeObserver(() => onResize()) : null; |
| 146 | ro?.observe(container); |
| 147 | |
| 148 | let raf = null; |
| 149 | const loop = () => { raf = requestAnimationFrame(loop); controls.update(); composer.render(); }; |
| 150 | loop(); |
| 151 | |
| 152 | // Lo mismo que el lienzo, como lista (la monta main.js al lado): con teclado |
| 153 | // o lector de pantalla una ciudad 3D no se puede recorrer. `locate` centra la |
| 154 | // cámara en el edificio del fichero y lo resalta un momento. |
| 155 | // ── actividad en directo ─────────────────────────────────────────────── |
| 156 | // Cada fichero que la elfa lee o escribe se enciende en la ciudad (escribir |
| 157 | // más fuerte que leer) y se apaga solo, para que se vea la ruta del trabajo. |
| 158 | // El registro muestra cada llamada al empezar y su resultado al acabar. |
| 159 | const idPorRuta = new Map(model.files.map(f => [f.rel, f.id])); |
| 160 | const apagados = new Map(); |
| 161 | const LINEAS_MAX = 80; |
| 162 | const ENCENDIDO = { lee: 0.5, escribe: 1 }; |
| 163 | const apagaTodo = () => { for (const t of apagados.values()) clearTimeout(t); apagados.clear(); }; |
| 164 | |
| 165 | const pinta = (ruta, modo) => { |
| 166 | const id = idPorRuta.get(ruta); |
| 167 | if (id == null) return; // fichero nuevo o fuera del escaneo |
| 168 | try { |
| 169 | city.paintFile?.(id, ENCENDIDO[modo] ?? 0.5); |
| 170 | clearTimeout(apagados.get(id)); |
| 171 | apagados.set(id, setTimeout(() => { |
| 172 | try { city.paintFile?.(id, 0); } catch { /* ya no está */ } |
| 173 | apagados.delete(id); |
| 174 | }, 3000)); |
| 175 | } catch { /* el resaltado es decorativo: no debe romper la vista */ } |
| 176 | }; |
| 177 | const escribeLinea = txt => { |
| 178 | if (!registro) return; |
| 179 | registro.textContent += txt + '\n'; |
| 180 | const lineas = registro.textContent.split('\n'); |
| 181 | if (lineas.length > LINEAS_MAX) registro.textContent = lineas.slice(-LINEAS_MAX).join('\n'); |
| 182 | registro.scrollTop = registro.scrollHeight; |
| 183 | }; |
| 184 | const quitarActividad = escuchar(ev => { |
| 185 | if (ev.fase === 'inicio') { |
| 186 | const donde = ev.ruta ? ' ' + ev.ruta : (ev.args?.query ? ' «' + ev.args.query + '»' : (ev.args?.command ? ' $ ' + ev.args.command : '')); |
| 187 | escribeLinea('› ' + ev.herramienta + donde); |
| 188 | if (ev.ruta) pinta(ev.ruta, ev.modo); |
| 189 | } else { |
| 190 | escribeLinea((ev.ok ? ' ✓ ' : ' ✗ ') + (ev.resumen || '')); |
| 191 | } |
| 192 | }); |
| 193 | |
| 194 | let resaltado = null, apaga = null; |
| 195 | const vista = { |
| 196 | items: model.files.map(f => ({ path: f.rel, bytes: f.size ?? f.bytes ?? null })), |
| 197 | locate(path) { |
| 198 | const f = model.files.find(x => x.rel === path); |
| 199 | if (!f?.box) return false; |
| 200 | controls.target.set(f.box.cx, f.box.cy, f.box.cz); |
| 201 | try { |
| 202 | if (resaltado != null) city.paintFile?.(resaltado, 0); |
| 203 | resaltado = f.id; city.paintFile?.(f.id, 1); |
| 204 | clearTimeout(apaga); apaga = setTimeout(() => { try { city.paintFile?.(f.id, 0); } catch { /* ya no está */ } }, 2500); |
| 205 | } catch { /* sin resaltado: la cámara ya apunta */ } |
| 206 | return true; |
| 207 | }, |
| 208 | }; |
| 209 | |
| 210 | disposer = () => { |
| 211 | quitarActividad(); |
| 212 | apagaTodo(); |
| 213 | clearTimeout(apaga); |
| 214 | if (raf) cancelAnimationFrame(raf); |
| 215 | window.removeEventListener('resize', onResize); |
| 216 | ro?.disconnect(); |
| 217 | canvas.removeEventListener('pointermove', onMove); |
| 218 | canvas.removeEventListener('pointerdown', onDown); |
| 219 | canvas.removeEventListener('pointerup', onUp); |
| 220 | controls.dispose(); |
| 221 | city.dispose(); |
| 222 | composer.dispose?.(); |
| 223 | renderer.dispose(); |
| 224 | }; |
| 225 | return vista; |
| 226 | } |
| 227 | |
| 228 | export function disposeCity() { if (disposer) { disposer(); disposer = null; } } |