Elffuss BraidHub

utopia-ia/elffuss-code public

17d8624c4d4f · 10.4 KiBRawPermalink
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.
8import * as THREE from 'three';
9import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
10import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
11import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
12import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
13import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
14import * as code from './tools/code.js';
15import { buildModel } from './vcc/model.js';
16import { buildCity } from './vcc/builder.js';
17import { THEME } from './vcc/theme.js';
18import { escuchar } from './actividad.js';
19
20const IGNORE = new Set(['node_modules', '.git', 'dist', 'build', 'target', '__pycache__', '.next', 'venv', '.venv', '.DS_Store']);
21const MAX_FILES = 8000; // tope de seguridad para no colgar el navegador en monorepos
22
23let disposer = null;
24
25// Escanea el handle del proyecto al formato empaquetado de VibeCodeViewer:
26// dir = [nombre, [subdirs], [ficheros]] · fichero = [nombre, bytes]
27async 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
46export 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
144 let raf = null;
145 const loop = () => { raf = requestAnimationFrame(loop); controls.update(); composer.render(); };
146 loop();
147
148 // Lo mismo que el lienzo, como lista (la monta main.js al lado): con teclado
149 // o lector de pantalla una ciudad 3D no se puede recorrer. `locate` centra la
150 // cámara en el edificio del fichero y lo resalta un momento.
151 // ── actividad en directo ───────────────────────────────────────────────
152 // Cada fichero que la elfa lee o escribe se enciende en la ciudad (escribir
153 // más fuerte que leer) y se apaga solo, para que se vea la ruta del trabajo.
154 // El registro muestra cada llamada al empezar y su resultado al acabar.
155 const idPorRuta = new Map(model.files.map(f => [f.rel, f.id]));
156 const apagados = new Map();
157 const LINEAS_MAX = 80;
158 const ENCENDIDO = { lee: 0.5, escribe: 1 };
159 const apagaTodo = () => { for (const t of apagados.values()) clearTimeout(t); apagados.clear(); };
160
161 const pinta = (ruta, modo) => {
162 const id = idPorRuta.get(ruta);
163 if (id == null) return; // fichero nuevo o fuera del escaneo
164 try {
165 city.paintFile?.(id, ENCENDIDO[modo] ?? 0.5);
166 clearTimeout(apagados.get(id));
167 apagados.set(id, setTimeout(() => {
168 try { city.paintFile?.(id, 0); } catch { /* ya no está */ }
169 apagados.delete(id);
170 }, 3000));
171 } catch { /* el resaltado es decorativo: no debe romper la vista */ }
172 };
173 const escribeLinea = txt => {
174 if (!registro) return;
175 registro.textContent += txt + '\n';
176 const lineas = registro.textContent.split('\n');
177 if (lineas.length > LINEAS_MAX) registro.textContent = lineas.slice(-LINEAS_MAX).join('\n');
178 registro.scrollTop = registro.scrollHeight;
179 };
180 const quitarActividad = escuchar(ev => {
181 if (ev.fase === 'inicio') {
182 const donde = ev.ruta ? ' ' + ev.ruta : (ev.args?.query ? ' «' + ev.args.query + '»' : (ev.args?.command ? ' $ ' + ev.args.command : ''));
183 escribeLinea('› ' + ev.herramienta + donde);
184 if (ev.ruta) pinta(ev.ruta, ev.modo);
185 } else {
186 escribeLinea((ev.ok ? ' ✓ ' : ' ✗ ') + (ev.resumen || ''));
187 }
188 });
189
190 let resaltado = null, apaga = null;
191 const vista = {
192 items: model.files.map(f => ({ path: f.rel, bytes: f.size ?? f.bytes ?? null })),
193 locate(path) {
194 const f = model.files.find(x => x.rel === path);
195 if (!f?.box) return false;
196 controls.target.set(f.box.cx, f.box.cy, f.box.cz);
197 try {
198 if (resaltado != null) city.paintFile?.(resaltado, 0);
199 resaltado = f.id; city.paintFile?.(f.id, 1);
200 clearTimeout(apaga); apaga = setTimeout(() => { try { city.paintFile?.(f.id, 0); } catch { /* ya no está */ } }, 2500);
201 } catch { /* sin resaltado: la cámara ya apunta */ }
202 return true;
203 },
204 };
205
206 disposer = () => {
207 quitarActividad();
208 apagaTodo();
209 clearTimeout(apaga);
210 if (raf) cancelAnimationFrame(raf);
211 window.removeEventListener('resize', onResize);
212 canvas.removeEventListener('pointermove', onMove);
213 canvas.removeEventListener('pointerdown', onDown);
214 canvas.removeEventListener('pointerup', onUp);
215 controls.dispose();
216 city.dispose();
217 composer.dispose?.();
218 renderer.dispose();
219 };
220 return vista;
221}
222
223export function disposeCity() { if (disposer) { disposer(); disposer = null; } }